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

Last change on this file since 41d6187 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
RevLine 
[5e326a6]1"""
[edfc8ac]2    SESANS reader (based on ASCII reader)
[b2c28a5]3
[edfc8ac]4    Reader for .ses or .sesans file format
[b2c28a5]5
6    Jurrian Bakker
[5e326a6]7"""
8import os
[574adc7]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
[5e326a6]15
16# Check whether we have a converter available
17has_converter = True
18try:
[b699768]19    from sas.sascalc.data_util.nxsunit import Converter
[5e326a6]20except:
21    has_converter = False
22_ZERO = 1e-16
23
[b2c28a5]24class Reader(FileReader):
[5e326a6]25    """
26    Class to load sesans files (6 columns).
27    """
[def97a0]28    # File type
[5e326a6]29    type_name = "SESANS"
[b2c28a5]30
[5e326a6]31    ## Wildcards
32    type = ["SESANS files (*.ses)|*.ses",
33            "SESANS files (*..sesans)|*.sesans"]
[def97a0]34    # List of allowed extensions
[5e326a6]35    ext = ['.ses', '.SES', '.sesans', '.SESANS']
[b2c28a5]36
[def97a0]37    # Flag to bypass extension check
[5e326a6]38    allow_all = True
[26d4864]39
[b2c28a5]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
[849094a]46        line = self.nextline()
[5a8cdbb]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:])
[849094a]52            line = self.nextline()
[5a8cdbb]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
[849094a]72        headers = self.nextline().split()
[5a8cdbb]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
[be43448]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()
[26d4864]147
[2d866370]148    @staticmethod
[e801a4e]149    def _insist_header(headers, name):
150        if name not in headers:
[5a8cdbb]151            raise FileContentsException(
[e801a4e]152                "Missing {} column in spin echo data".format(name))
153
154    @staticmethod
[2d866370]155    def _unit_conversion(value, value_unit, default_unit):
[09a0be5]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
[f6c2555]161        :param default_unit: string with the units of the original measurement
[09a0be5]162        :return: The magnitude of the measurement in the new units
163        """
[bc6532e]164        # (float, string, string) -> float
[def97a0]165        if has_converter and value_unit != default_unit:
[857cc58]166            data_conv_q = Converter(default_unit)
167            value = data_conv_q(value, units=value_unit)
[26d4864]168            new_unit = default_unit
169        else:
170            new_unit = value_unit
[b2c28a5]171        return value, new_unit
[e935ddb1]172
[2b310602]173    def _unit_fetch(self, unit):
174        return self.params[unit+"_unit"]
Note: See TracBrowser for help on using the repository browser.