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

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 10ab40e was 10ab40e, checked in by Adam Washington <adam.washington@…>, 7 years ago

Throw an exception if sesans file is missing necessary units

  • Property mode set to 100644
File size: 5.2 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 logging
9import numpy as np
10import os
11from sas.sascalc.dataloader.data_info import Data1D
12
13# Check whether we have a converter available
14has_converter = True
15try:
16    from sas.sascalc.data_util.nxsunit import Converter
17except:
18    has_converter = False
19_ZERO = 1e-16
20
21
22class Reader:
23    """
24    Class to load sesans files (6 columns).
25    """
26    # File type
27    type_name = "SESANS"
28
29    # Wildcards
30    type = ["SESANS files (*.ses)|*.ses",
31            "SESANS files (*..sesans)|*.sesans"]
32    # List of allowed extensions
33    ext = ['.ses', '.SES', '.sesans', '.SESANS']
34
35    # Flag to bypass extension check
36    allow_all = True
37
38    def read(self, path):
39        """
40        Load data file
41
42        :param path: file path
43
44        :return: SESANSData1D object, or None
45
46        :raise RuntimeError: when the file can't be opened
47        :raise ValueError: when the length of the data vectors are inconsistent
48        """
49        if os.path.isfile(path):
50            basename = os.path.basename(path)
51            _, extension = os.path.splitext(basename)
52            if not (self.allow_all or extension.lower() in self.ext):
53                raise RuntimeError("{} has an unrecognized file extension".format(path))
54        else:
55            raise RunetimeError("{} is not a file".format(path))
56        with open(path, 'r') as input_f:
57            # Read in binary mode since GRASP frequently has no-ascii
58            # characters that brakes the open operation
59            line = input_f.readline()
60            params = {}
61            while not line.startswith("BEGIN_DATA"):
62                terms = line.split()
63                if len(terms) >= 2:
64                    params[terms[0]] = " ".join(terms[1:])
65                line = input_f.readline()
66            self.params = params
67
68            if "SpinEchoLength_unit" not in self.params:
69                raise RuntimeError("SpinEchoLength has no units")
70            if "Wavelength_unit" not in self.params:
71                raise RuntimeError("Wavelength has no units")
72
73            headers = input_f.readline().split()
74
75            data = np.loadtxt(input_f)
76            if data.size < 1:
77                raise RuntimeError("{} is empty".format(path))
78            x = data[:, headers.index("SpinEchoLength")]
79            if "SpinEchoLength_error" in headers:
80                dx = data[:, headers.index("SpinEchoLength_error")]
81            else:
82                dx = x*0.05
83            lam = data[:, headers.index("Wavelength")]
84            if "Wavelength_error" in headers:
85                dlam = data[:, headers.index("Wavelength_error")]
86            else:
87                dlam = lam*0.05
88            y = data[:, headers.index("Depolarisation")]
89            dy = data[:, headers.index("Depolarisation_error")]
90
91            lam_unit = self._unit_fetch("Wavelength")
92            x, x_unit = self._unit_conversion(x, "A", self._unit_fetch("SpinEchoLength"))
93            dx, dx_unit = self._unit_conversion(
94                dx, lam_unit,
95                self._unit_fetch("SpinEchoLength"))
96            dlam, dlam_unit = self._unit_conversion(
97                dlam, lam_unit,
98                self._unit_fetch("Wavelength"))
99            y_unit = self._unit_fetch("Depolarisation")
100
101            output = Data1D(x=x, y=y, lam=lam, dy=dy, dx=dx, dlam=dlam,
102                            isSesans=True)
103
104            output.y_unit = y_unit
105            output.x_unit = x_unit
106            output.source.wavelength_unit = lam_unit
107            output.source.wavelength = lam
108            self.filename = output.filename = basename
109            output.xaxis(r"\rm{z}", x_unit)
110            # Adjust label to ln P/(lam^2 t), remove lam column refs
111            output.yaxis(r"\rm{ln(P)/(t \lambda^2)}", y_unit)
112            # Store loading process information
113            output.meta_data['loader'] = self.type_name
114            output.sample.name = params["Sample"]
115            output.sample.ID = params["DataFileTitle"]
116            output.sample.thickness = self._unit_conversion(
117                float(params["Thickness"]), "cm",
118                self._unit_fetch("Thickness"))[0]
119
120            output.sample.zacceptance = (
121                float(params["Theta_zmax"]),
122                self._unit_fetch("Theta_zmax"))
123
124            output.sample.yacceptance = (
125                float(params["Theta_ymax"]),
126                self._unit_fetch("Theta_ymax"))
127            return output
128
129    @staticmethod
130    def _unit_conversion(value, value_unit, default_unit):
131        """
132        Performs unit conversion on a measurement.
133
134        :param value: The magnitude of the measurement
135        :param value_unit: a string containing the final desired unit
136        :param default_unit: a string containing the units of the original measurement
137        :return: The magnitude of the measurement in the new units
138        """
139        # (float, string, string) -> float
140        if has_converter and value_unit != default_unit:
141            data_conv_q = Converter(default_unit)
142            value = data_conv_q(value, units=value_unit)
143            new_unit = default_unit
144        else:
145            new_unit = value_unit
146        return value, new_unit
147
148    def _unit_fetch(self, unit):
149        return self.params[unit+"_unit"]
Note: See TracBrowser for help on using the repository browser.