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

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 e801a4e was e801a4e, checked in by Adam Washington <adam.washington@…>, 7 years ago

Test that SESANS files insist on proper headers

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