source: sasview/src/sas/sascalc/dataloader/readers/sesans_reader.py @ d04ac05

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalcmagnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since d04ac05 was 849094a, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

use decoded stream for sesans reader

  • Property mode set to 100644
File size: 6.4 KB
Line 
1"""
2    SESANS reader (based on ASCII reader)
3
4    Reader for .ses or .sesans file format
5
6    Jurrian Bakker
7"""
8import os
9
10import numpy as np
11
12from ..file_reader_base_class import FileReader
13from ..data_info import plottable_1D, DataInfo
14from ..loader_exceptions import FileContentsException, DataReaderException
15
16# Check whether we have a converter available
17has_converter = True
18try:
19    from sas.sascalc.data_util.nxsunit import Converter
20except:
21    has_converter = False
22_ZERO = 1e-16
23
24class Reader(FileReader):
25    """
26    Class to load sesans files (6 columns).
27    """
28    # File type
29    type_name = "SESANS"
30
31    ## Wildcards
32    type = ["SESANS files (*.ses)|*.ses",
33            "SESANS files (*..sesans)|*.sesans"]
34    # List of allowed extensions
35    ext = ['.ses', '.SES', '.sesans', '.SESANS']
36
37    # Flag to bypass extension check
38    allow_all = True
39
40    def get_file_contents(self):
41        self.current_datainfo = DataInfo()
42        self.current_dataset = plottable_1D(np.array([]), np.array([]))
43        self.current_datainfo.isSesans = True
44        self.output = []
45
46        line = self.nextline()
47        params = {}
48        while not line.startswith("BEGIN_DATA"):
49            terms = line.split()
50            if len(terms) >= 2:
51                params[terms[0]] = " ".join(terms[1:])
52            line = self.nextline()
53        self.params = params
54
55        if "FileFormatVersion" not in self.params:
56            raise FileContentsException("SES file missing FileFormatVersion")
57        if float(self.params["FileFormatVersion"]) >= 2.0:
58            raise FileContentsException("SASView only supports SES version 1")
59
60        if "SpinEchoLength_unit" not in self.params:
61            raise FileContentsException("SpinEchoLength has no units")
62        if "Wavelength_unit" not in self.params:
63            raise FileContentsException("Wavelength has no units")
64        if params["SpinEchoLength_unit"] != params["Wavelength_unit"]:
65            raise FileContentsException("The spin echo data has rudely used "
66                               "different units for the spin echo length "
67                               "and the wavelength.  While sasview could "
68                               "handle this instance, it is a violation "
69                               "of the file format and will not be "
70                               "handled by other software.")
71
72        headers = self.nextline().split()
73
74        self._insist_header(headers, "SpinEchoLength")
75        self._insist_header(headers, "Depolarisation")
76        self._insist_header(headers, "Depolarisation_error")
77        self._insist_header(headers, "Wavelength")
78
79        data = np.loadtxt(self.f_open)
80
81        if data.shape[1] != len(headers):
82            raise FileContentsException(
83                "File has {} headers, but {} columns".format(
84                    len(headers),
85                    data.shape[1]))
86
87        if not data.size:
88            raise FileContentsException("{} is empty".format(path))
89        x = data[:, headers.index("SpinEchoLength")]
90        if "SpinEchoLength_error" in headers:
91            dx = data[:, headers.index("SpinEchoLength_error")]
92        else:
93            dx = x * 0.05
94        lam = data[:, headers.index("Wavelength")]
95        if "Wavelength_error" in headers:
96            dlam = data[:, headers.index("Wavelength_error")]
97        else:
98            dlam = lam * 0.05
99        y = data[:, headers.index("Depolarisation")]
100        dy = data[:, headers.index("Depolarisation_error")]
101
102        lam_unit = self._unit_fetch("Wavelength")
103        x, x_unit = self._unit_conversion(x, "A",
104                                          self._unit_fetch(
105                                              "SpinEchoLength"))
106        dx, dx_unit = self._unit_conversion(
107            dx, lam_unit,
108            self._unit_fetch("SpinEchoLength"))
109        dlam, dlam_unit = self._unit_conversion(
110            dlam, lam_unit,
111            self._unit_fetch("Wavelength"))
112        y_unit = self._unit_fetch("Depolarisation")
113
114        self.current_dataset.x = x
115        self.current_dataset.y = y
116        self.current_dataset.lam = lam
117        self.current_dataset.dy = dy
118        self.current_dataset.dx = dx
119        self.current_dataset.dlam = dlam
120        self.current_datainfo.isSesans = True
121
122        self.current_datainfo._yunit = y_unit
123        self.current_datainfo._xunit = x_unit
124        self.current_datainfo.source.wavelength_unit = lam_unit
125        self.current_datainfo.source.wavelength = lam
126        self.current_datainfo.filename = os.path.basename(self.f_open.name)
127        self.current_dataset.xaxis(r"\rm{z}", x_unit)
128        # Adjust label to ln P/(lam^2 t), remove lam column refs
129        self.current_dataset.yaxis(r"\rm{ln(P)/(t \lambda^2)}", y_unit)
130        # Store loading process information
131        self.current_datainfo.meta_data['loader'] = self.type_name
132        self.current_datainfo.sample.name = params["Sample"]
133        self.current_datainfo.sample.ID = params["DataFileTitle"]
134        self.current_datainfo.sample.thickness = self._unit_conversion(
135            float(params["Thickness"]), "cm",
136            self._unit_fetch("Thickness"))[0]
137
138        self.current_datainfo.sample.zacceptance = (
139            float(params["Theta_zmax"]),
140            self._unit_fetch("Theta_zmax"))
141
142        self.current_datainfo.sample.yacceptance = (
143            float(params["Theta_ymax"]),
144            self._unit_fetch("Theta_ymax"))
145
146        self.send_to_output()
147
148    @staticmethod
149    def _insist_header(headers, name):
150        if name not in headers:
151            raise FileContentsException(
152                "Missing {} column in spin echo data".format(name))
153
154    @staticmethod
155    def _unit_conversion(value, value_unit, default_unit):
156        """
157        Performs unit conversion on a measurement.
158
159        :param value: The magnitude of the measurement
160        :param value_unit: a string containing the final desired unit
161        :param default_unit: string with the units of the original measurement
162        :return: The magnitude of the measurement in the new units
163        """
164        # (float, string, string) -> float
165        if has_converter and value_unit != default_unit:
166            data_conv_q = Converter(default_unit)
167            value = data_conv_q(value, units=value_unit)
168            new_unit = default_unit
169        else:
170            new_unit = value_unit
171        return value, new_unit
172
173    def _unit_fetch(self, unit):
174        return self.params[unit+"_unit"]
Note: See TracBrowser for help on using the repository browser.