[d26dea0] | 1 | """ |
---|
| 2 | CanSAS data reader - new recursive cansas_version. |
---|
| 3 | """ |
---|
| 4 | ############################################################################ |
---|
| 5 | #This software was developed by the University of Tennessee as part of the |
---|
| 6 | #Distributed Data Analysis of Neutron Scattering Experiments (DANSE) |
---|
| 7 | #project funded by the US National Science Foundation. |
---|
| 8 | #If you use DANSE applications to do scientific research that leads to |
---|
| 9 | #publication, we ask that you acknowledge the use of the software with the |
---|
| 10 | #following sentence: |
---|
| 11 | #This work benefited from DANSE software developed under NSF award DMR-0520547. |
---|
| 12 | #copyright 2008,2009 University of Tennessee |
---|
| 13 | ############################################################################# |
---|
[0f1e140] | 14 | |
---|
[d26dea0] | 15 | import logging |
---|
[250fec92] | 16 | import numpy as np |
---|
[d26dea0] | 17 | import os |
---|
| 18 | import sys |
---|
| 19 | import datetime |
---|
| 20 | import inspect |
---|
| 21 | # For saving individual sections of data |
---|
[83c09af] | 22 | from sas.sascalc.dataloader.data_info import Data1D, Data2D, DataInfo, \ |
---|
[af08e55] | 23 | plottable_1D, plottable_2D |
---|
[83c09af] | 24 | from sas.sascalc.dataloader.data_info import Collimation, TransmissionSpectrum, \ |
---|
| 25 | Detector, Process, Aperture |
---|
| 26 | from sas.sascalc.dataloader.data_info import \ |
---|
| 27 | combine_data_info_with_plottable as combine_data |
---|
[b699768] | 28 | import sas.sascalc.dataloader.readers.xml_reader as xml_reader |
---|
| 29 | from sas.sascalc.dataloader.readers.xml_reader import XMLreader |
---|
[250fec92] | 30 | from sas.sascalc.dataloader.readers.cansas_constants import CansasConstants, CurrentLevel |
---|
[d26dea0] | 31 | |
---|
[682c432] | 32 | # The following 2 imports *ARE* used. Do not remove either. |
---|
| 33 | import xml.dom.minidom |
---|
| 34 | from xml.dom.minidom import parseString |
---|
| 35 | |
---|
[d26dea0] | 36 | PREPROCESS = "xmlpreprocess" |
---|
| 37 | ENCODING = "encoding" |
---|
| 38 | RUN_NAME_DEFAULT = "None" |
---|
[250fec92] | 39 | INVALID_SCHEMA_PATH_1_1 = "{0}/sas/sascalc/dataloader/readers/schema/cansas1d_invalid_v1_1.xsd" |
---|
| 40 | INVALID_SCHEMA_PATH_1_0 = "{0}/sas/sascalc/dataloader/readers/schema/cansas1d_invalid_v1_0.xsd" |
---|
| 41 | INVALID_XML = "\n\nThe loaded xml file, {0} does not fully meet the CanSAS v1.x specification. SasView loaded " + \ |
---|
| 42 | "as much of the data as possible.\n\n" |
---|
[d26dea0] | 43 | HAS_CONVERTER = True |
---|
| 44 | try: |
---|
[b699768] | 45 | from sas.sascalc.data_util.nxsunit import Converter |
---|
[d26dea0] | 46 | except ImportError: |
---|
| 47 | HAS_CONVERTER = False |
---|
| 48 | |
---|
| 49 | CONSTANTS = CansasConstants() |
---|
| 50 | CANSAS_FORMAT = CONSTANTS.format |
---|
| 51 | CANSAS_NS = CONSTANTS.names |
---|
| 52 | ALLOW_ALL = True |
---|
| 53 | |
---|
| 54 | class Reader(XMLreader): |
---|
| 55 | """ |
---|
| 56 | Class to load cansas 1D XML files |
---|
| 57 | |
---|
| 58 | :Dependencies: |
---|
| 59 | The CanSAS reader requires PyXML 0.8.4 or later. |
---|
| 60 | """ |
---|
[af08e55] | 61 | # CanSAS version - defaults to version 1.0 |
---|
[d26dea0] | 62 | cansas_version = "1.0" |
---|
| 63 | base_ns = "{cansas1d/1.0}" |
---|
[250fec92] | 64 | cansas_defaults = None |
---|
[d26dea0] | 65 | type_name = "canSAS" |
---|
[250fec92] | 66 | invalid = True |
---|
[654e8e0] | 67 | frm = "" |
---|
[af08e55] | 68 | # Log messages and errors |
---|
[250fec92] | 69 | logging = None |
---|
| 70 | errors = set() |
---|
[af08e55] | 71 | # Namespace hierarchy for current xml_file object |
---|
[250fec92] | 72 | names = None |
---|
| 73 | ns_list = None |
---|
[af08e55] | 74 | # Temporary storage location for loading multiple data sets in a single file |
---|
[250fec92] | 75 | current_datainfo = None |
---|
| 76 | current_dataset = None |
---|
| 77 | current_data1d = None |
---|
| 78 | data = None |
---|
[af08e55] | 79 | # List of data1D objects to be sent back to SasView |
---|
[250fec92] | 80 | output = None |
---|
[af08e55] | 81 | # Wildcards |
---|
[d26dea0] | 82 | type = ["XML files (*.xml)|*.xml", "SasView Save Files (*.svs)|*.svs"] |
---|
[af08e55] | 83 | # List of allowed extensions |
---|
[d26dea0] | 84 | ext = ['.xml', '.XML', '.svs', '.SVS'] |
---|
[af08e55] | 85 | # Flag to bypass extension check |
---|
[d26dea0] | 86 | allow_all = True |
---|
| 87 | |
---|
[250fec92] | 88 | def reset_state(self): |
---|
| 89 | """ |
---|
| 90 | Resets the class state to a base case when loading a new data file so previous |
---|
| 91 | data files do not appear a second time |
---|
| 92 | """ |
---|
| 93 | self.current_datainfo = None |
---|
| 94 | self.current_dataset = None |
---|
| 95 | self.current_data1d = None |
---|
| 96 | self.data = [] |
---|
| 97 | self.process = Process() |
---|
| 98 | self.transspectrum = TransmissionSpectrum() |
---|
| 99 | self.aperture = Aperture() |
---|
| 100 | self.collimation = Collimation() |
---|
| 101 | self.detector = Detector() |
---|
| 102 | self.names = [] |
---|
| 103 | self.cansas_defaults = {} |
---|
| 104 | self.output = [] |
---|
| 105 | self.ns_list = None |
---|
[d26dea0] | 106 | self.logging = [] |
---|
| 107 | self.encoding = None |
---|
| 108 | |
---|
[250fec92] | 109 | def read(self, xml_file, schema_path="", invalid=True): |
---|
| 110 | """ |
---|
| 111 | Validate and read in an xml_file file in the canSAS format. |
---|
| 112 | |
---|
| 113 | :param xml_file: A canSAS file path in proper XML format |
---|
| 114 | :param schema_path: A file path to an XML schema to validate the xml_file against |
---|
| 115 | """ |
---|
| 116 | # For every file loaded, reset everything to a base state |
---|
| 117 | self.reset_state() |
---|
| 118 | self.invalid = invalid |
---|
| 119 | # Check that the file exists |
---|
| 120 | if os.path.isfile(xml_file): |
---|
| 121 | basename, extension = os.path.splitext(os.path.basename(xml_file)) |
---|
| 122 | # If the file type is not allowed, return nothing |
---|
| 123 | if extension in self.ext or self.allow_all: |
---|
| 124 | # Get the file location of |
---|
| 125 | self.load_file_and_schema(xml_file, schema_path) |
---|
| 126 | self.add_data_set() |
---|
| 127 | # Try to load the file, but raise an error if unable to. |
---|
| 128 | # Check the file matches the XML schema |
---|
| 129 | try: |
---|
| 130 | self.is_cansas(extension) |
---|
| 131 | self.invalid = False |
---|
| 132 | # Get each SASentry from XML file and add it to a list. |
---|
| 133 | entry_list = self.xmlroot.xpath( |
---|
| 134 | '/ns:SASroot/ns:SASentry', |
---|
| 135 | namespaces={'ns': self.cansas_defaults.get("ns")}) |
---|
| 136 | self.names.append("SASentry") |
---|
| 137 | |
---|
| 138 | # Get all preprocessing events and encoding |
---|
| 139 | self.set_processing_instructions() |
---|
| 140 | |
---|
| 141 | # Parse each <SASentry> item |
---|
| 142 | for entry in entry_list: |
---|
| 143 | # Create a new DataInfo object for every <SASentry> |
---|
| 144 | |
---|
| 145 | # Set the file name and then parse the entry. |
---|
| 146 | self.current_datainfo.filename = basename + extension |
---|
| 147 | self.current_datainfo.meta_data["loader"] = "CanSAS XML 1D" |
---|
| 148 | self.current_datainfo.meta_data[PREPROCESS] = \ |
---|
| 149 | self.processing_instructions |
---|
| 150 | |
---|
| 151 | # Parse the XML SASentry |
---|
| 152 | self._parse_entry(entry) |
---|
| 153 | # Combine datasets with datainfo |
---|
| 154 | self.add_data_set() |
---|
| 155 | except RuntimeError: |
---|
| 156 | # If the file does not match the schema, raise this error |
---|
| 157 | invalid_xml = self.find_invalid_xml() |
---|
| 158 | invalid_xml = INVALID_XML.format(basename + extension) + invalid_xml |
---|
| 159 | self.errors.add(invalid_xml) |
---|
| 160 | # Try again with an invalid CanSAS schema, that requires only a data set in each |
---|
| 161 | base_name = xml_reader.__file__ |
---|
| 162 | base_name = base_name.replace("\\", "/") |
---|
| 163 | base = base_name.split("/sas/")[0] |
---|
| 164 | if self.cansas_version == "1.1": |
---|
| 165 | invalid_schema = INVALID_SCHEMA_PATH_1_1.format(base, self.cansas_defaults.get("schema")) |
---|
| 166 | else: |
---|
| 167 | invalid_schema = INVALID_SCHEMA_PATH_1_0.format(base, self.cansas_defaults.get("schema")) |
---|
| 168 | self.set_schema(invalid_schema) |
---|
| 169 | try: |
---|
| 170 | if self.invalid: |
---|
| 171 | if self.is_cansas(): |
---|
| 172 | self.output = self.read(xml_file, invalid_schema, False) |
---|
| 173 | else: |
---|
| 174 | raise RuntimeError |
---|
| 175 | else: |
---|
| 176 | raise RuntimeError |
---|
| 177 | except RuntimeError: |
---|
| 178 | x = np.zeros(1) |
---|
| 179 | y = np.zeros(1) |
---|
| 180 | self.current_data1d = Data1D(x,y) |
---|
| 181 | self.current_data1d.errors = self.errors |
---|
| 182 | return [self.current_data1d] |
---|
| 183 | else: |
---|
| 184 | self.output.append("Not a valid file path.") |
---|
| 185 | # Return a list of parsed entries that dataloader can manage |
---|
| 186 | return self.output |
---|
| 187 | |
---|
[654e8e0] | 188 | def _parse_entry(self, dom, recurse=False): |
---|
[250fec92] | 189 | """ |
---|
| 190 | Parse a SASEntry - new recursive method for parsing the dom of |
---|
| 191 | the CanSAS data format. This will allow multiple data files |
---|
| 192 | and extra nodes to be read in simultaneously. |
---|
| 193 | |
---|
| 194 | :param dom: dom object with a namespace base of names |
---|
| 195 | """ |
---|
| 196 | |
---|
[654e8e0] | 197 | if not self._is_call_local() and not recurse: |
---|
[1686a333] | 198 | self.reset_state() |
---|
| 199 | self.add_data_set() |
---|
| 200 | self.names.append("SASentry") |
---|
| 201 | self.parent_class = "SASentry" |
---|
[250fec92] | 202 | self._check_for_empty_data() |
---|
| 203 | self.base_ns = "{0}{1}{2}".format("{", \ |
---|
| 204 | CANSAS_NS.get(self.cansas_version).get("ns"), "}") |
---|
| 205 | |
---|
| 206 | # Go through each child in the parent element |
---|
| 207 | for node in dom: |
---|
[5f26aa4] | 208 | attr = node.attrib |
---|
| 209 | name = attr.get("name", "") |
---|
| 210 | type = attr.get("type", "") |
---|
[250fec92] | 211 | # Get the element name and set the current names level |
---|
| 212 | tagname = node.tag.replace(self.base_ns, "") |
---|
| 213 | tagname_original = tagname |
---|
| 214 | # Skip this iteration when loading in save state information |
---|
| 215 | if tagname == "fitting_plug_in" or tagname == "pr_inversion" or tagname == "invariant": |
---|
| 216 | continue |
---|
| 217 | |
---|
| 218 | # Get where to store content |
---|
| 219 | self.names.append(tagname_original) |
---|
| 220 | self.ns_list = CONSTANTS.iterate_namespace(self.names) |
---|
| 221 | # If the element is a child element, recurse |
---|
| 222 | if len(node.getchildren()) > 0: |
---|
| 223 | self.parent_class = tagname_original |
---|
| 224 | if tagname == 'SASdata': |
---|
[af08e55] | 225 | self._initialize_new_data_set(node) |
---|
| 226 | if isinstance(self.current_dataset, plottable_2D): |
---|
| 227 | x_bins = attr.get("x_bins", "") |
---|
| 228 | y_bins = attr.get("y_bins", "") |
---|
| 229 | if x_bins is not "" and y_bins is not "": |
---|
| 230 | self.current_dataset.shape = (x_bins, y_bins) |
---|
| 231 | else: |
---|
| 232 | self.current_dataset.shape = () |
---|
| 233 | # Recursion step to access data within the group |
---|
[654e8e0] | 234 | self._parse_entry(node, True) |
---|
[5f26aa4] | 235 | if tagname == "SASsample": |
---|
| 236 | self.current_datainfo.sample.name = name |
---|
| 237 | elif tagname == "beam_size": |
---|
| 238 | self.current_datainfo.source.beam_size_name = name |
---|
| 239 | elif tagname == "SAScollimation": |
---|
| 240 | self.collimation.name = name |
---|
| 241 | elif tagname == "aperture": |
---|
| 242 | self.aperture.name = name |
---|
| 243 | self.aperture.type = type |
---|
[250fec92] | 244 | self.add_intermediate() |
---|
| 245 | else: |
---|
[1905128] | 246 | if isinstance(self.current_dataset, plottable_2D): |
---|
| 247 | data_point = node.text |
---|
| 248 | unit = attr.get('unit', '') |
---|
| 249 | else: |
---|
| 250 | data_point, unit = self._get_node_value(node, tagname) |
---|
[250fec92] | 251 | |
---|
[af08e55] | 252 | # If this is a dataset, store the data appropriately |
---|
[250fec92] | 253 | if tagname == 'Run': |
---|
[5f26aa4] | 254 | self.current_datainfo.run_name[data_point] = name |
---|
[250fec92] | 255 | self.current_datainfo.run.append(data_point) |
---|
| 256 | elif tagname == 'Title': |
---|
| 257 | self.current_datainfo.title = data_point |
---|
| 258 | elif tagname == 'SASnote': |
---|
| 259 | self.current_datainfo.notes.append(data_point) |
---|
| 260 | |
---|
[af08e55] | 261 | # I and Q - 1D data |
---|
| 262 | elif tagname == 'I' and isinstance(self.current_dataset, plottable_1D): |
---|
[ad4632c] | 263 | unit_list = unit.split(" | ") |
---|
| 264 | if len(unit_list) > 1: |
---|
| 265 | self.current_dataset.yaxis(unit_list[0], unit_list[1]) |
---|
| 266 | else: |
---|
| 267 | self.current_dataset.yaxis("Intensity", unit) |
---|
[250fec92] | 268 | self.current_dataset.y = np.append(self.current_dataset.y, data_point) |
---|
[af08e55] | 269 | elif tagname == 'Idev' and isinstance(self.current_dataset, plottable_1D): |
---|
[250fec92] | 270 | self.current_dataset.dy = np.append(self.current_dataset.dy, data_point) |
---|
| 271 | elif tagname == 'Q': |
---|
[ad4632c] | 272 | unit_list = unit.split(" | ") |
---|
| 273 | if len(unit_list) > 1: |
---|
| 274 | self.current_dataset.xaxis(unit_list[0], unit_list[1]) |
---|
| 275 | else: |
---|
| 276 | self.current_dataset.xaxis("Q", unit) |
---|
[250fec92] | 277 | self.current_dataset.x = np.append(self.current_dataset.x, data_point) |
---|
| 278 | elif tagname == 'Qdev': |
---|
| 279 | self.current_dataset.dx = np.append(self.current_dataset.dx, data_point) |
---|
| 280 | elif tagname == 'dQw': |
---|
| 281 | self.current_dataset.dxw = np.append(self.current_dataset.dxw, data_point) |
---|
| 282 | elif tagname == 'dQl': |
---|
| 283 | self.current_dataset.dxl = np.append(self.current_dataset.dxl, data_point) |
---|
[1686a333] | 284 | elif tagname == 'Qmean': |
---|
| 285 | pass |
---|
| 286 | elif tagname == 'Shadowfactor': |
---|
| 287 | pass |
---|
[ad4632c] | 288 | elif tagname == 'Sesans': |
---|
| 289 | self.current_datainfo.isSesans = bool(data_point) |
---|
| 290 | elif tagname == 'zacceptance': |
---|
| 291 | self.current_datainfo.sample.zacceptance = (data_point, unit) |
---|
[250fec92] | 292 | |
---|
[af08e55] | 293 | # I and Qx, Qy - 2D data |
---|
| 294 | elif tagname == 'I' and isinstance(self.current_dataset, plottable_2D): |
---|
| 295 | self.current_dataset.yaxis("Intensity", unit) |
---|
[1905128] | 296 | self.current_dataset.data = np.fromstring(data_point, dtype=float, sep=",") |
---|
[af08e55] | 297 | elif tagname == 'Idev' and isinstance(self.current_dataset, plottable_2D): |
---|
[1905128] | 298 | self.current_dataset.err_data = np.fromstring(data_point, dtype=float, sep=",") |
---|
[af08e55] | 299 | elif tagname == 'Qx': |
---|
| 300 | self.current_dataset.xaxis("Qx", unit) |
---|
[1905128] | 301 | self.current_dataset.qx_data = np.fromstring(data_point, dtype=float, sep=",") |
---|
[af08e55] | 302 | elif tagname == 'Qy': |
---|
| 303 | self.current_dataset.yaxis("Qy", unit) |
---|
[1905128] | 304 | self.current_dataset.qy_data = np.fromstring(data_point, dtype=float, sep=",") |
---|
[af08e55] | 305 | elif tagname == 'Qxdev': |
---|
| 306 | self.current_dataset.xaxis("Qxdev", unit) |
---|
[1905128] | 307 | self.current_dataset.dqx_data = np.fromstring(data_point, dtype=float, sep=",") |
---|
[af08e55] | 308 | elif tagname == 'Qydev': |
---|
| 309 | self.current_dataset.yaxis("Qydev", unit) |
---|
[1905128] | 310 | self.current_dataset.dqy_data = np.fromstring(data_point, dtype=float, sep=",") |
---|
[af08e55] | 311 | elif tagname == 'Mask': |
---|
[bcabf4e] | 312 | inter = [item == "1" for item in data_point.split(",")] |
---|
[1905128] | 313 | self.current_dataset.mask = np.asarray(inter, dtype=bool) |
---|
[af08e55] | 314 | |
---|
| 315 | # Sample Information |
---|
[250fec92] | 316 | elif tagname == 'ID' and self.parent_class == 'SASsample': |
---|
| 317 | self.current_datainfo.sample.ID = data_point |
---|
| 318 | elif tagname == 'Title' and self.parent_class == 'SASsample': |
---|
| 319 | self.current_datainfo.sample.name = data_point |
---|
| 320 | elif tagname == 'thickness' and self.parent_class == 'SASsample': |
---|
| 321 | self.current_datainfo.sample.thickness = data_point |
---|
| 322 | self.current_datainfo.sample.thickness_unit = unit |
---|
| 323 | elif tagname == 'transmission' and self.parent_class == 'SASsample': |
---|
| 324 | self.current_datainfo.sample.transmission = data_point |
---|
| 325 | elif tagname == 'temperature' and self.parent_class == 'SASsample': |
---|
| 326 | self.current_datainfo.sample.temperature = data_point |
---|
| 327 | self.current_datainfo.sample.temperature_unit = unit |
---|
| 328 | elif tagname == 'details' and self.parent_class == 'SASsample': |
---|
| 329 | self.current_datainfo.sample.details.append(data_point) |
---|
| 330 | elif tagname == 'x' and self.parent_class == 'position': |
---|
| 331 | self.current_datainfo.sample.position.x = data_point |
---|
| 332 | self.current_datainfo.sample.position_unit = unit |
---|
| 333 | elif tagname == 'y' and self.parent_class == 'position': |
---|
| 334 | self.current_datainfo.sample.position.y = data_point |
---|
| 335 | self.current_datainfo.sample.position_unit = unit |
---|
| 336 | elif tagname == 'z' and self.parent_class == 'position': |
---|
| 337 | self.current_datainfo.sample.position.z = data_point |
---|
| 338 | self.current_datainfo.sample.position_unit = unit |
---|
| 339 | elif tagname == 'roll' and self.parent_class == 'orientation' and 'SASsample' in self.names: |
---|
| 340 | self.current_datainfo.sample.orientation.x = data_point |
---|
| 341 | self.current_datainfo.sample.orientation_unit = unit |
---|
| 342 | elif tagname == 'pitch' and self.parent_class == 'orientation' and 'SASsample' in self.names: |
---|
| 343 | self.current_datainfo.sample.orientation.y = data_point |
---|
| 344 | self.current_datainfo.sample.orientation_unit = unit |
---|
| 345 | elif tagname == 'yaw' and self.parent_class == 'orientation' and 'SASsample' in self.names: |
---|
| 346 | self.current_datainfo.sample.orientation.z = data_point |
---|
| 347 | self.current_datainfo.sample.orientation_unit = unit |
---|
| 348 | |
---|
[af08e55] | 349 | # Instrumental Information |
---|
[250fec92] | 350 | elif tagname == 'name' and self.parent_class == 'SASinstrument': |
---|
| 351 | self.current_datainfo.instrument = data_point |
---|
[af08e55] | 352 | # Detector Information |
---|
[250fec92] | 353 | elif tagname == 'name' and self.parent_class == 'SASdetector': |
---|
| 354 | self.detector.name = data_point |
---|
| 355 | elif tagname == 'SDD' and self.parent_class == 'SASdetector': |
---|
| 356 | self.detector.distance = data_point |
---|
| 357 | self.detector.distance_unit = unit |
---|
| 358 | elif tagname == 'slit_length' and self.parent_class == 'SASdetector': |
---|
| 359 | self.detector.slit_length = data_point |
---|
| 360 | self.detector.slit_length_unit = unit |
---|
| 361 | elif tagname == 'x' and self.parent_class == 'offset': |
---|
| 362 | self.detector.offset.x = data_point |
---|
| 363 | self.detector.offset_unit = unit |
---|
| 364 | elif tagname == 'y' and self.parent_class == 'offset': |
---|
| 365 | self.detector.offset.y = data_point |
---|
| 366 | self.detector.offset_unit = unit |
---|
| 367 | elif tagname == 'z' and self.parent_class == 'offset': |
---|
| 368 | self.detector.offset.z = data_point |
---|
| 369 | self.detector.offset_unit = unit |
---|
| 370 | elif tagname == 'x' and self.parent_class == 'beam_center': |
---|
| 371 | self.detector.beam_center.x = data_point |
---|
| 372 | self.detector.beam_center_unit = unit |
---|
| 373 | elif tagname == 'y' and self.parent_class == 'beam_center': |
---|
| 374 | self.detector.beam_center.y = data_point |
---|
| 375 | self.detector.beam_center_unit = unit |
---|
| 376 | elif tagname == 'z' and self.parent_class == 'beam_center': |
---|
| 377 | self.detector.beam_center.z = data_point |
---|
| 378 | self.detector.beam_center_unit = unit |
---|
| 379 | elif tagname == 'x' and self.parent_class == 'pixel_size': |
---|
| 380 | self.detector.pixel_size.x = data_point |
---|
| 381 | self.detector.pixel_size_unit = unit |
---|
| 382 | elif tagname == 'y' and self.parent_class == 'pixel_size': |
---|
| 383 | self.detector.pixel_size.y = data_point |
---|
| 384 | self.detector.pixel_size_unit = unit |
---|
| 385 | elif tagname == 'z' and self.parent_class == 'pixel_size': |
---|
| 386 | self.detector.pixel_size.z = data_point |
---|
| 387 | self.detector.pixel_size_unit = unit |
---|
| 388 | elif tagname == 'roll' and self.parent_class == 'orientation' and 'SASdetector' in self.names: |
---|
| 389 | self.detector.orientation.x = data_point |
---|
| 390 | self.detector.orientation_unit = unit |
---|
| 391 | elif tagname == 'pitch' and self.parent_class == 'orientation' and 'SASdetector' in self.names: |
---|
| 392 | self.detector.orientation.y = data_point |
---|
| 393 | self.detector.orientation_unit = unit |
---|
| 394 | elif tagname == 'yaw' and self.parent_class == 'orientation' and 'SASdetector' in self.names: |
---|
| 395 | self.detector.orientation.z = data_point |
---|
| 396 | self.detector.orientation_unit = unit |
---|
[af08e55] | 397 | # Collimation and Aperture |
---|
[250fec92] | 398 | elif tagname == 'length' and self.parent_class == 'SAScollimation': |
---|
| 399 | self.collimation.length = data_point |
---|
| 400 | self.collimation.length_unit = unit |
---|
| 401 | elif tagname == 'name' and self.parent_class == 'SAScollimation': |
---|
| 402 | self.collimation.name = data_point |
---|
| 403 | elif tagname == 'distance' and self.parent_class == 'aperture': |
---|
| 404 | self.aperture.distance = data_point |
---|
| 405 | self.aperture.distance_unit = unit |
---|
| 406 | elif tagname == 'x' and self.parent_class == 'size': |
---|
| 407 | self.aperture.size.x = data_point |
---|
| 408 | self.collimation.size_unit = unit |
---|
| 409 | elif tagname == 'y' and self.parent_class == 'size': |
---|
| 410 | self.aperture.size.y = data_point |
---|
| 411 | self.collimation.size_unit = unit |
---|
| 412 | elif tagname == 'z' and self.parent_class == 'size': |
---|
| 413 | self.aperture.size.z = data_point |
---|
| 414 | self.collimation.size_unit = unit |
---|
| 415 | |
---|
[af08e55] | 416 | # Process Information |
---|
[250fec92] | 417 | elif tagname == 'name' and self.parent_class == 'SASprocess': |
---|
| 418 | self.process.name = data_point |
---|
| 419 | elif tagname == 'description' and self.parent_class == 'SASprocess': |
---|
| 420 | self.process.description = data_point |
---|
| 421 | elif tagname == 'date' and self.parent_class == 'SASprocess': |
---|
| 422 | try: |
---|
| 423 | self.process.date = datetime.datetime.fromtimestamp(data_point) |
---|
| 424 | except: |
---|
| 425 | self.process.date = data_point |
---|
| 426 | elif tagname == 'SASprocessnote': |
---|
| 427 | self.process.notes.append(data_point) |
---|
| 428 | elif tagname == 'term' and self.parent_class == 'SASprocess': |
---|
[5f26aa4] | 429 | unit = attr.get("unit", "") |
---|
| 430 | dic = {} |
---|
| 431 | dic["name"] = name |
---|
| 432 | dic["value"] = data_point |
---|
| 433 | dic["unit"] = unit |
---|
| 434 | self.process.term.append(dic) |
---|
[250fec92] | 435 | |
---|
[af08e55] | 436 | # Transmission Spectrum |
---|
[250fec92] | 437 | elif tagname == 'T' and self.parent_class == 'Tdata': |
---|
| 438 | self.transspectrum.transmission = np.append(self.transspectrum.transmission, data_point) |
---|
| 439 | self.transspectrum.transmission_unit = unit |
---|
| 440 | elif tagname == 'Tdev' and self.parent_class == 'Tdata': |
---|
| 441 | self.transspectrum.transmission_deviation = np.append(self.transspectrum.transmission_deviation, data_point) |
---|
| 442 | self.transspectrum.transmission_deviation_unit = unit |
---|
| 443 | elif tagname == 'Lambda' and self.parent_class == 'Tdata': |
---|
| 444 | self.transspectrum.wavelength = np.append(self.transspectrum.wavelength, data_point) |
---|
| 445 | self.transspectrum.wavelength_unit = unit |
---|
| 446 | |
---|
[af08e55] | 447 | # Source Information |
---|
[250fec92] | 448 | elif tagname == 'wavelength' and (self.parent_class == 'SASsource' or self.parent_class == 'SASData'): |
---|
| 449 | self.current_datainfo.source.wavelength = data_point |
---|
| 450 | self.current_datainfo.source.wavelength_unit = unit |
---|
| 451 | elif tagname == 'wavelength_min' and self.parent_class == 'SASsource': |
---|
| 452 | self.current_datainfo.source.wavelength_min = data_point |
---|
| 453 | self.current_datainfo.source.wavelength_min_unit = unit |
---|
| 454 | elif tagname == 'wavelength_max' and self.parent_class == 'SASsource': |
---|
| 455 | self.current_datainfo.source.wavelength_max = data_point |
---|
| 456 | self.current_datainfo.source.wavelength_max_unit = unit |
---|
| 457 | elif tagname == 'wavelength_spread' and self.parent_class == 'SASsource': |
---|
| 458 | self.current_datainfo.source.wavelength_spread = data_point |
---|
| 459 | self.current_datainfo.source.wavelength_spread_unit = unit |
---|
| 460 | elif tagname == 'x' and self.parent_class == 'beam_size': |
---|
| 461 | self.current_datainfo.source.beam_size.x = data_point |
---|
| 462 | self.current_datainfo.source.beam_size_unit = unit |
---|
| 463 | elif tagname == 'y' and self.parent_class == 'beam_size': |
---|
| 464 | self.current_datainfo.source.beam_size.y = data_point |
---|
| 465 | self.current_datainfo.source.beam_size_unit = unit |
---|
| 466 | elif tagname == 'z' and self.parent_class == 'pixel_size': |
---|
| 467 | self.current_datainfo.source.data_point.z = data_point |
---|
| 468 | self.current_datainfo.source.beam_size_unit = unit |
---|
| 469 | elif tagname == 'radiation' and self.parent_class == 'SASsource': |
---|
| 470 | self.current_datainfo.source.radiation = data_point |
---|
| 471 | elif tagname == 'beam_shape' and self.parent_class == 'SASsource': |
---|
| 472 | self.current_datainfo.source.beam_shape = data_point |
---|
| 473 | |
---|
[af08e55] | 474 | # Everything else goes in meta_data |
---|
[250fec92] | 475 | else: |
---|
| 476 | new_key = self._create_unique_key(self.current_datainfo.meta_data, tagname) |
---|
| 477 | self.current_datainfo.meta_data[new_key] = data_point |
---|
| 478 | |
---|
| 479 | self.names.remove(tagname_original) |
---|
| 480 | length = 0 |
---|
| 481 | if len(self.names) > 1: |
---|
| 482 | length = len(self.names) - 1 |
---|
| 483 | self.parent_class = self.names[length] |
---|
[654e8e0] | 484 | if not self._is_call_local() and not recurse: |
---|
| 485 | self.frm = "" |
---|
[1686a333] | 486 | self.add_data_set() |
---|
| 487 | empty = None |
---|
| 488 | return self.output[0], empty |
---|
[250fec92] | 489 | |
---|
| 490 | |
---|
[654e8e0] | 491 | def _is_call_local(self): |
---|
[1686a333] | 492 | """ |
---|
| 493 | |
---|
| 494 | """ |
---|
[654e8e0] | 495 | if self.frm == "": |
---|
| 496 | inter = inspect.stack() |
---|
| 497 | self.frm = inter[2] |
---|
| 498 | mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "") |
---|
[1686a333] | 499 | mod_name = mod_name.replace(".py", "") |
---|
| 500 | mod = mod_name.split("sas/") |
---|
| 501 | mod_name = mod[1] |
---|
| 502 | if mod_name != "sascalc/dataloader/readers/cansas_reader": |
---|
| 503 | return False |
---|
| 504 | return True |
---|
| 505 | |
---|
[d26dea0] | 506 | def is_cansas(self, ext="xml"): |
---|
| 507 | """ |
---|
| 508 | Checks to see if the xml file is a CanSAS file |
---|
| 509 | |
---|
| 510 | :param ext: The file extension of the data file |
---|
| 511 | """ |
---|
| 512 | if self.validate_xml(): |
---|
| 513 | name = "{http://www.w3.org/2001/XMLSchema-instance}schemaLocation" |
---|
| 514 | value = self.xmlroot.get(name) |
---|
| 515 | if CANSAS_NS.get(self.cansas_version).get("ns") == \ |
---|
| 516 | value.rsplit(" ")[0]: |
---|
| 517 | return True |
---|
| 518 | if ext == "svs": |
---|
| 519 | return True |
---|
[250fec92] | 520 | raise RuntimeError |
---|
[d26dea0] | 521 | |
---|
[83b6408] | 522 | def load_file_and_schema(self, xml_file, schema_path=""): |
---|
[d26dea0] | 523 | """ |
---|
[250fec92] | 524 | Loads the file and associates a schema, if a schema is passed in or if one already exists |
---|
[d26dea0] | 525 | |
---|
| 526 | :param xml_file: The xml file path sent to Reader.read |
---|
[250fec92] | 527 | :param schema_path: The path to a schema associated with the xml_file, or find one based on the file |
---|
[d26dea0] | 528 | """ |
---|
| 529 | base_name = xml_reader.__file__ |
---|
| 530 | base_name = base_name.replace("\\", "/") |
---|
| 531 | base = base_name.split("/sas/")[0] |
---|
| 532 | |
---|
| 533 | # Load in xml file and get the cansas version from the header |
---|
| 534 | self.set_xml_file(xml_file) |
---|
| 535 | self.cansas_version = self.xmlroot.get("version", "1.0") |
---|
| 536 | |
---|
| 537 | # Generic values for the cansas file based on the version |
---|
[250fec92] | 538 | self.cansas_defaults = CANSAS_NS.get(self.cansas_version, "1.0") |
---|
[83b6408] | 539 | if schema_path == "": |
---|
[250fec92] | 540 | schema_path = "{0}/sas/sascalc/dataloader/readers/schema/{1}".format \ |
---|
| 541 | (base, self.cansas_defaults.get("schema")).replace("\\", "/") |
---|
[d26dea0] | 542 | |
---|
| 543 | # Link a schema to the XML file. |
---|
| 544 | self.set_schema(schema_path) |
---|
| 545 | |
---|
[250fec92] | 546 | def add_data_set(self): |
---|
[d26dea0] | 547 | """ |
---|
[250fec92] | 548 | Adds the current_dataset to the list of outputs after preforming final processing on the data and then calls a |
---|
| 549 | private method to generate a new data set. |
---|
[d26dea0] | 550 | |
---|
[250fec92] | 551 | :param key: NeXus group name for current tree level |
---|
[d26dea0] | 552 | """ |
---|
| 553 | |
---|
[250fec92] | 554 | if self.current_datainfo and self.current_dataset: |
---|
| 555 | self._final_cleanup() |
---|
| 556 | self.data = [] |
---|
| 557 | self.current_datainfo = DataInfo() |
---|
[d26dea0] | 558 | |
---|
[af08e55] | 559 | def _initialize_new_data_set(self, node=None): |
---|
[250fec92] | 560 | """ |
---|
| 561 | A private class method to generate a new 1D data object. |
---|
| 562 | Outside methods should call add_data_set() to be sure any existing data is stored properly. |
---|
| 563 | |
---|
[af08e55] | 564 | :param node: XML node to determine if 1D or 2D data |
---|
[250fec92] | 565 | """ |
---|
| 566 | x = np.array(0) |
---|
| 567 | y = np.array(0) |
---|
[af08e55] | 568 | for child in node: |
---|
| 569 | if child.tag.replace(self.base_ns, "") == "Idata": |
---|
| 570 | for i_child in child: |
---|
| 571 | if i_child.tag.replace(self.base_ns, "") == "Qx": |
---|
| 572 | self.current_dataset = plottable_2D() |
---|
| 573 | return |
---|
[250fec92] | 574 | self.current_dataset = plottable_1D(x, y) |
---|
[d26dea0] | 575 | |
---|
[250fec92] | 576 | def add_intermediate(self): |
---|
| 577 | """ |
---|
| 578 | This method stores any intermediate objects within the final data set after fully reading the set. |
---|
| 579 | |
---|
| 580 | :param parent: The NXclass name for the h5py Group object that just finished being processed |
---|
| 581 | """ |
---|
| 582 | |
---|
| 583 | if self.parent_class == 'SASprocess': |
---|
| 584 | self.current_datainfo.process.append(self.process) |
---|
| 585 | self.process = Process() |
---|
| 586 | elif self.parent_class == 'SASdetector': |
---|
| 587 | self.current_datainfo.detector.append(self.detector) |
---|
| 588 | self.detector = Detector() |
---|
| 589 | elif self.parent_class == 'SAStransmission_spectrum': |
---|
| 590 | self.current_datainfo.trans_spectrum.append(self.transspectrum) |
---|
| 591 | self.transspectrum = TransmissionSpectrum() |
---|
| 592 | elif self.parent_class == 'SAScollimation': |
---|
| 593 | self.current_datainfo.collimation.append(self.collimation) |
---|
| 594 | self.collimation = Collimation() |
---|
[5f26aa4] | 595 | elif self.parent_class == 'aperture': |
---|
[250fec92] | 596 | self.collimation.aperture.append(self.aperture) |
---|
| 597 | self.aperture = Aperture() |
---|
| 598 | elif self.parent_class == 'SASdata': |
---|
| 599 | self._check_for_empty_resolution() |
---|
| 600 | self.data.append(self.current_dataset) |
---|
| 601 | |
---|
| 602 | def _final_cleanup(self): |
---|
[d26dea0] | 603 | """ |
---|
| 604 | Final cleanup of the Data1D object to be sure it has all the |
---|
| 605 | appropriate information needed for perspectives |
---|
| 606 | """ |
---|
[250fec92] | 607 | |
---|
[af08e55] | 608 | # Append errors to dataset and reset class errors |
---|
[250fec92] | 609 | self.current_datainfo.errors = set() |
---|
[d26dea0] | 610 | for error in self.errors: |
---|
[250fec92] | 611 | self.current_datainfo.errors.add(error) |
---|
[d26dea0] | 612 | self.errors.clear() |
---|
[250fec92] | 613 | |
---|
[af08e55] | 614 | # Combine all plottables with datainfo and append each to output |
---|
| 615 | # Type cast data arrays to float64 and find min/max as appropriate |
---|
[250fec92] | 616 | for dataset in self.data: |
---|
[af08e55] | 617 | if isinstance(dataset, plottable_1D): |
---|
| 618 | if dataset.x is not None: |
---|
| 619 | dataset.x = np.delete(dataset.x, [0]) |
---|
| 620 | dataset.x = dataset.x.astype(np.float64) |
---|
| 621 | dataset.xmin = np.min(dataset.x) |
---|
| 622 | dataset.xmax = np.max(dataset.x) |
---|
| 623 | if dataset.y is not None: |
---|
| 624 | dataset.y = np.delete(dataset.y, [0]) |
---|
| 625 | dataset.y = dataset.y.astype(np.float64) |
---|
| 626 | dataset.ymin = np.min(dataset.y) |
---|
| 627 | dataset.ymax = np.max(dataset.y) |
---|
| 628 | if dataset.dx is not None: |
---|
| 629 | dataset.dx = np.delete(dataset.dx, [0]) |
---|
| 630 | dataset.dx = dataset.dx.astype(np.float64) |
---|
| 631 | if dataset.dxl is not None: |
---|
| 632 | dataset.dxl = np.delete(dataset.dxl, [0]) |
---|
| 633 | dataset.dxl = dataset.dxl.astype(np.float64) |
---|
| 634 | if dataset.dxw is not None: |
---|
| 635 | dataset.dxw = np.delete(dataset.dxw, [0]) |
---|
| 636 | dataset.dxw = dataset.dxw.astype(np.float64) |
---|
| 637 | if dataset.dy is not None: |
---|
| 638 | dataset.dy = np.delete(dataset.dy, [0]) |
---|
| 639 | dataset.dy = dataset.dy.astype(np.float64) |
---|
| 640 | np.trim_zeros(dataset.x) |
---|
| 641 | np.trim_zeros(dataset.y) |
---|
| 642 | np.trim_zeros(dataset.dy) |
---|
| 643 | elif isinstance(dataset, plottable_2D): |
---|
| 644 | dataset.data = dataset.data.astype(np.float64) |
---|
| 645 | dataset.qx_data = dataset.qx_data.astype(np.float64) |
---|
| 646 | dataset.xmin = np.min(dataset.qx_data) |
---|
| 647 | dataset.xmax = np.max(dataset.qx_data) |
---|
| 648 | dataset.qy_data = dataset.qy_data.astype(np.float64) |
---|
| 649 | dataset.ymin = np.min(dataset.qy_data) |
---|
| 650 | dataset.ymax = np.max(dataset.qy_data) |
---|
| 651 | dataset.q_data = np.sqrt(dataset.qx_data * dataset.qx_data |
---|
| 652 | + dataset.qy_data * dataset.qy_data) |
---|
| 653 | if dataset.err_data is not None: |
---|
| 654 | dataset.err_data = dataset.err_data.astype(np.float64) |
---|
| 655 | if dataset.dqx_data is not None: |
---|
| 656 | dataset.dqx_data = dataset.dqx_data.astype(np.float64) |
---|
| 657 | if dataset.dqy_data is not None: |
---|
| 658 | dataset.dqy_data = dataset.dqy_data.astype(np.float64) |
---|
| 659 | if dataset.mask is not None: |
---|
| 660 | dataset.mask = dataset.mask.astype(dtype=bool) |
---|
| 661 | |
---|
| 662 | if len(dataset.shape) == 2: |
---|
| 663 | n_rows, n_cols = dataset.shape |
---|
| 664 | dataset.y_bins = dataset.qy_data[0::int(n_cols)] |
---|
| 665 | dataset.x_bins = dataset.qx_data[:int(n_cols)] |
---|
| 666 | dataset.data = dataset.data.flatten() |
---|
| 667 | else: |
---|
| 668 | dataset.y_bins = [] |
---|
| 669 | dataset.x_bins = [] |
---|
| 670 | dataset.data = dataset.data.flatten() |
---|
| 671 | |
---|
[250fec92] | 672 | final_dataset = combine_data(dataset, self.current_datainfo) |
---|
| 673 | self.output.append(final_dataset) |
---|
[d26dea0] | 674 | |
---|
| 675 | def _create_unique_key(self, dictionary, name, numb=0): |
---|
| 676 | """ |
---|
| 677 | Create a unique key value for any dictionary to prevent overwriting |
---|
[250fec92] | 678 | Recurse until a unique key value is found. |
---|
[d26dea0] | 679 | |
---|
| 680 | :param dictionary: A dictionary with any number of entries |
---|
| 681 | :param name: The index of the item to be added to dictionary |
---|
| 682 | :param numb: The number to be appended to the name, starts at 0 |
---|
| 683 | """ |
---|
| 684 | if dictionary.get(name) is not None: |
---|
| 685 | numb += 1 |
---|
| 686 | name = name.split("_")[0] |
---|
| 687 | name += "_{0}".format(numb) |
---|
| 688 | name = self._create_unique_key(dictionary, name, numb) |
---|
| 689 | return name |
---|
| 690 | |
---|
[250fec92] | 691 | def _get_node_value(self, node, tagname): |
---|
| 692 | """ |
---|
| 693 | Get the value of a node and any applicable units |
---|
| 694 | |
---|
| 695 | :param node: The XML node to get the value of |
---|
| 696 | :param tagname: The tagname of the node |
---|
| 697 | """ |
---|
| 698 | #Get the text from the node and convert all whitespace to spaces |
---|
| 699 | units = '' |
---|
| 700 | node_value = node.text |
---|
| 701 | if node_value is not None: |
---|
| 702 | node_value = ' '.join(node_value.split()) |
---|
| 703 | else: |
---|
| 704 | node_value = "" |
---|
| 705 | |
---|
| 706 | # If the value is a float, compile with units. |
---|
| 707 | if self.ns_list.ns_datatype == "float": |
---|
| 708 | # If an empty value is given, set as zero. |
---|
| 709 | if node_value is None or node_value.isspace() \ |
---|
| 710 | or node_value.lower() == "nan": |
---|
| 711 | node_value = "0.0" |
---|
| 712 | #Convert the value to the base units |
---|
| 713 | node_value, units = self._unit_conversion(node, tagname, node_value) |
---|
| 714 | |
---|
| 715 | # If the value is a timestamp, convert to a datetime object |
---|
| 716 | elif self.ns_list.ns_datatype == "timestamp": |
---|
| 717 | if node_value is None or node_value.isspace(): |
---|
| 718 | pass |
---|
| 719 | else: |
---|
| 720 | try: |
---|
| 721 | node_value = \ |
---|
| 722 | datetime.datetime.fromtimestamp(node_value) |
---|
| 723 | except ValueError: |
---|
| 724 | node_value = None |
---|
| 725 | return node_value, units |
---|
| 726 | |
---|
| 727 | def _unit_conversion(self, node, tagname, node_value): |
---|
[d26dea0] | 728 | """ |
---|
| 729 | A unit converter method used to convert the data included in the file |
---|
| 730 | to the default units listed in data_info |
---|
| 731 | |
---|
[250fec92] | 732 | :param node: XML node |
---|
| 733 | :param tagname: name of the node |
---|
[d26dea0] | 734 | :param node_value: The value of the current dom node |
---|
| 735 | """ |
---|
| 736 | attr = node.attrib |
---|
| 737 | value_unit = '' |
---|
| 738 | err_msg = None |
---|
[682c432] | 739 | default_unit = None |
---|
[5f26aa4] | 740 | if not isinstance(node_value, float): |
---|
| 741 | node_value = float(node_value) |
---|
| 742 | if 'unit' in attr and attr.get('unit') is not None: |
---|
[d26dea0] | 743 | try: |
---|
| 744 | local_unit = attr['unit'] |
---|
[250fec92] | 745 | unitname = self.ns_list.current_level.get("unit", "") |
---|
| 746 | if "SASdetector" in self.names: |
---|
| 747 | save_in = "detector" |
---|
| 748 | elif "aperture" in self.names: |
---|
| 749 | save_in = "aperture" |
---|
| 750 | elif "SAScollimation" in self.names: |
---|
| 751 | save_in = "collimation" |
---|
| 752 | elif "SAStransmission_spectrum" in self.names: |
---|
| 753 | save_in = "transspectrum" |
---|
| 754 | elif "SASdata" in self.names: |
---|
| 755 | x = np.zeros(1) |
---|
| 756 | y = np.zeros(1) |
---|
| 757 | self.current_data1d = Data1D(x, y) |
---|
| 758 | save_in = "current_data1d" |
---|
| 759 | elif "SASsource" in self.names: |
---|
| 760 | save_in = "current_datainfo.source" |
---|
| 761 | elif "SASsample" in self.names: |
---|
| 762 | save_in = "current_datainfo.sample" |
---|
| 763 | elif "SASprocess" in self.names: |
---|
| 764 | save_in = "process" |
---|
| 765 | else: |
---|
| 766 | save_in = "current_datainfo" |
---|
| 767 | exec "default_unit = self.{0}.{1}".format(save_in, unitname) |
---|
| 768 | if local_unit and default_unit and local_unit.lower() != default_unit.lower() \ |
---|
[d26dea0] | 769 | and local_unit.lower() != "none": |
---|
| 770 | if HAS_CONVERTER == True: |
---|
[af08e55] | 771 | # Check local units - bad units raise KeyError |
---|
[d26dea0] | 772 | data_conv_q = Converter(local_unit) |
---|
| 773 | value_unit = default_unit |
---|
[682c432] | 774 | node_value = data_conv_q(node_value, units=default_unit) |
---|
[d26dea0] | 775 | else: |
---|
| 776 | value_unit = local_unit |
---|
| 777 | err_msg = "Unit converter is not available.\n" |
---|
| 778 | else: |
---|
| 779 | value_unit = local_unit |
---|
| 780 | except KeyError: |
---|
| 781 | err_msg = "CanSAS reader: unexpected " |
---|
| 782 | err_msg += "\"{0}\" unit [{1}]; " |
---|
| 783 | err_msg = err_msg.format(tagname, local_unit) |
---|
[682c432] | 784 | err_msg += "expecting [{0}]".format(default_unit) |
---|
[d26dea0] | 785 | value_unit = local_unit |
---|
| 786 | except: |
---|
| 787 | err_msg = "CanSAS reader: unknown error converting " |
---|
| 788 | err_msg += "\"{0}\" unit [{1}]" |
---|
| 789 | err_msg = err_msg.format(tagname, local_unit) |
---|
| 790 | value_unit = local_unit |
---|
| 791 | elif 'unit' in attr: |
---|
| 792 | value_unit = attr['unit'] |
---|
| 793 | if err_msg: |
---|
| 794 | self.errors.add(err_msg) |
---|
| 795 | return node_value, value_unit |
---|
| 796 | |
---|
[250fec92] | 797 | def _check_for_empty_data(self): |
---|
[d26dea0] | 798 | """ |
---|
| 799 | Creates an empty data set if no data is passed to the reader |
---|
| 800 | |
---|
| 801 | :param data1d: presumably a Data1D object |
---|
| 802 | """ |
---|
[250fec92] | 803 | if self.current_dataset == None: |
---|
| 804 | x_vals = np.empty(0) |
---|
| 805 | y_vals = np.empty(0) |
---|
| 806 | dx_vals = np.empty(0) |
---|
| 807 | dy_vals = np.empty(0) |
---|
| 808 | dxl = np.empty(0) |
---|
| 809 | dxw = np.empty(0) |
---|
| 810 | self.current_dataset = plottable_1D(x_vals, y_vals, dx_vals, dy_vals) |
---|
| 811 | self.current_dataset.dxl = dxl |
---|
| 812 | self.current_dataset.dxw = dxw |
---|
| 813 | |
---|
| 814 | def _check_for_empty_resolution(self): |
---|
[d26dea0] | 815 | """ |
---|
| 816 | A method to check all resolution data sets are the same size as I and Q |
---|
| 817 | """ |
---|
[af08e55] | 818 | if isinstance(self.current_dataset, plottable_1D): |
---|
| 819 | dql_exists = False |
---|
| 820 | dqw_exists = False |
---|
| 821 | dq_exists = False |
---|
| 822 | di_exists = False |
---|
| 823 | if self.current_dataset.dxl is not None: |
---|
| 824 | dql_exists = True |
---|
| 825 | if self.current_dataset.dxw is not None: |
---|
| 826 | dqw_exists = True |
---|
| 827 | if self.current_dataset.dx is not None: |
---|
| 828 | dq_exists = True |
---|
| 829 | if self.current_dataset.dy is not None: |
---|
| 830 | di_exists = True |
---|
| 831 | if dqw_exists and not dql_exists: |
---|
| 832 | array_size = self.current_dataset.dxw.size - 1 |
---|
| 833 | self.current_dataset.dxl = np.append(self.current_dataset.dxl, |
---|
| 834 | np.zeros([array_size])) |
---|
| 835 | elif dql_exists and not dqw_exists: |
---|
| 836 | array_size = self.current_dataset.dxl.size - 1 |
---|
| 837 | self.current_dataset.dxw = np.append(self.current_dataset.dxw, |
---|
| 838 | np.zeros([array_size])) |
---|
| 839 | elif not dql_exists and not dqw_exists and not dq_exists: |
---|
| 840 | array_size = self.current_dataset.x.size - 1 |
---|
| 841 | self.current_dataset.dx = np.append(self.current_dataset.dx, |
---|
| 842 | np.zeros([array_size])) |
---|
| 843 | if not di_exists: |
---|
| 844 | array_size = self.current_dataset.y.size - 1 |
---|
| 845 | self.current_dataset.dy = np.append(self.current_dataset.dy, |
---|
| 846 | np.zeros([array_size])) |
---|
| 847 | elif isinstance(self.current_dataset, plottable_2D): |
---|
| 848 | dqx_exists = False |
---|
| 849 | dqy_exists = False |
---|
| 850 | di_exists = False |
---|
| 851 | mask_exists = False |
---|
| 852 | if self.current_dataset.dqx_data is not None: |
---|
| 853 | dqx_exists = True |
---|
| 854 | if self.current_dataset.dqy_data is not None: |
---|
| 855 | dqy_exists = True |
---|
| 856 | if self.current_dataset.err_data is not None: |
---|
| 857 | di_exists = True |
---|
| 858 | if self.current_dataset.mask is not None: |
---|
| 859 | mask_exists = True |
---|
| 860 | if not dqy_exists: |
---|
| 861 | array_size = self.current_dataset.qy_data.size - 1 |
---|
| 862 | self.current_dataset.dqy_data = np.append( |
---|
| 863 | self.current_dataset.dqy_data, np.zeros([array_size])) |
---|
| 864 | if not dqx_exists: |
---|
| 865 | array_size = self.current_dataset.qx_data.size - 1 |
---|
| 866 | self.current_dataset.dqx_data = np.append( |
---|
| 867 | self.current_dataset.dqx_data, np.zeros([array_size])) |
---|
| 868 | if not di_exists: |
---|
| 869 | array_size = self.current_dataset.data.size - 1 |
---|
| 870 | self.current_dataset.err_data = np.append( |
---|
| 871 | self.current_dataset.err_data, np.zeros([array_size])) |
---|
| 872 | if not mask_exists: |
---|
| 873 | array_size = self.current_dataset.data.size - 1 |
---|
| 874 | self.current_dataset.mask = np.append( |
---|
| 875 | self.current_dataset.mask, |
---|
| 876 | np.ones([array_size] ,dtype=bool)) |
---|
[250fec92] | 877 | |
---|
| 878 | ####### All methods below are for writing CanSAS XML files ####### |
---|
[d26dea0] | 879 | |
---|
[250fec92] | 880 | def write(self, filename, datainfo): |
---|
[d26dea0] | 881 | """ |
---|
[250fec92] | 882 | Write the content of a Data1D as a CanSAS XML file |
---|
[d26dea0] | 883 | |
---|
[250fec92] | 884 | :param filename: name of the file to write |
---|
| 885 | :param datainfo: Data1D object |
---|
| 886 | """ |
---|
| 887 | # Create XML document |
---|
| 888 | doc, _ = self._to_xml_doc(datainfo) |
---|
| 889 | # Write the file |
---|
| 890 | file_ref = open(filename, 'w') |
---|
| 891 | if self.encoding == None: |
---|
| 892 | self.encoding = "UTF-8" |
---|
| 893 | doc.write(file_ref, encoding=self.encoding, |
---|
| 894 | pretty_print=True, xml_declaration=True) |
---|
| 895 | file_ref.close() |
---|
[d26dea0] | 896 | |
---|
[250fec92] | 897 | def _to_xml_doc(self, datainfo): |
---|
[d26dea0] | 898 | """ |
---|
[250fec92] | 899 | Create an XML document to contain the content of a Data1D |
---|
[d26dea0] | 900 | |
---|
[250fec92] | 901 | :param datainfo: Data1D object |
---|
[d26dea0] | 902 | """ |
---|
[af08e55] | 903 | is_2d = False |
---|
[83c09af] | 904 | if issubclass(datainfo.__class__, Data2D): |
---|
| 905 | is_2d = True |
---|
[d26dea0] | 906 | |
---|
[250fec92] | 907 | # Get PIs and create root element |
---|
| 908 | pi_string = self._get_pi_string() |
---|
| 909 | # Define namespaces and create SASroot object |
---|
| 910 | main_node = self._create_main_node() |
---|
| 911 | # Create ElementTree, append SASroot and apply processing instructions |
---|
| 912 | base_string = pi_string + self.to_string(main_node) |
---|
| 913 | base_element = self.create_element_from_string(base_string) |
---|
| 914 | doc = self.create_tree(base_element) |
---|
| 915 | # Create SASentry Element |
---|
| 916 | entry_node = self.create_element("SASentry") |
---|
| 917 | root = doc.getroot() |
---|
| 918 | root.append(entry_node) |
---|
[d26dea0] | 919 | |
---|
[250fec92] | 920 | # Add Title to SASentry |
---|
| 921 | self.write_node(entry_node, "Title", datainfo.title) |
---|
| 922 | # Add Run to SASentry |
---|
| 923 | self._write_run_names(datainfo, entry_node) |
---|
| 924 | # Add Data info to SASEntry |
---|
[83c09af] | 925 | if is_2d: |
---|
| 926 | self._write_data_2d(datainfo, entry_node) |
---|
| 927 | else: |
---|
| 928 | self._write_data(datainfo, entry_node) |
---|
[250fec92] | 929 | # Transmission Spectrum Info |
---|
| 930 | self._write_trans_spectrum(datainfo, entry_node) |
---|
| 931 | # Sample info |
---|
| 932 | self._write_sample_info(datainfo, entry_node) |
---|
| 933 | # Instrument info |
---|
| 934 | instr = self._write_instrument(datainfo, entry_node) |
---|
| 935 | # Source |
---|
| 936 | self._write_source(datainfo, instr) |
---|
| 937 | # Collimation |
---|
| 938 | self._write_collimation(datainfo, instr) |
---|
| 939 | # Detectors |
---|
| 940 | self._write_detectors(datainfo, instr) |
---|
| 941 | # Processes info |
---|
| 942 | self._write_process_notes(datainfo, entry_node) |
---|
| 943 | # Note info |
---|
| 944 | self._write_notes(datainfo, entry_node) |
---|
| 945 | # Return the document, and the SASentry node associated with |
---|
| 946 | # the data we just wrote |
---|
| 947 | # If the calling function was not the cansas reader, return a minidom |
---|
| 948 | # object rather than an lxml object. |
---|
[654e8e0] | 949 | self.frm = inspect.stack()[1] |
---|
| 950 | doc, entry_node = self._check_origin(entry_node, doc) |
---|
[250fec92] | 951 | return doc, entry_node |
---|
[d26dea0] | 952 | |
---|
[250fec92] | 953 | def write_node(self, parent, name, value, attr=None): |
---|
| 954 | """ |
---|
| 955 | :param doc: document DOM |
---|
| 956 | :param parent: parent node |
---|
| 957 | :param name: tag of the element |
---|
| 958 | :param value: value of the child text node |
---|
| 959 | :param attr: attribute dictionary |
---|
[d26dea0] | 960 | |
---|
[250fec92] | 961 | :return: True if something was appended, otherwise False |
---|
| 962 | """ |
---|
| 963 | if value is not None: |
---|
| 964 | parent = self.ebuilder(parent, name, value, attr) |
---|
| 965 | return True |
---|
| 966 | return False |
---|
[d26dea0] | 967 | |
---|
| 968 | def _get_pi_string(self): |
---|
| 969 | """ |
---|
| 970 | Creates the processing instructions header for writing to file |
---|
| 971 | """ |
---|
| 972 | pis = self.return_processing_instructions() |
---|
| 973 | if len(pis) > 0: |
---|
| 974 | pi_tree = self.create_tree(pis[0]) |
---|
| 975 | i = 1 |
---|
| 976 | for i in range(1, len(pis) - 1): |
---|
| 977 | pi_tree = self.append(pis[i], pi_tree) |
---|
| 978 | pi_string = self.to_string(pi_tree) |
---|
| 979 | else: |
---|
| 980 | pi_string = "" |
---|
| 981 | return pi_string |
---|
| 982 | |
---|
| 983 | def _create_main_node(self): |
---|
| 984 | """ |
---|
| 985 | Creates the primary xml header used when writing to file |
---|
| 986 | """ |
---|
| 987 | xsi = "http://www.w3.org/2001/XMLSchema-instance" |
---|
| 988 | version = self.cansas_version |
---|
| 989 | n_s = CANSAS_NS.get(version).get("ns") |
---|
| 990 | if version == "1.1": |
---|
| 991 | url = "http://www.cansas.org/formats/1.1/" |
---|
| 992 | else: |
---|
| 993 | url = "http://svn.smallangles.net/svn/canSAS/1dwg/trunk/" |
---|
| 994 | schema_location = "{0} {1}cansas1d.xsd".format(n_s, url) |
---|
| 995 | attrib = {"{" + xsi + "}schemaLocation" : schema_location, |
---|
| 996 | "version" : version} |
---|
| 997 | nsmap = {'xsi' : xsi, None: n_s} |
---|
| 998 | |
---|
| 999 | main_node = self.create_element("{" + n_s + "}SASroot", |
---|
| 1000 | attrib=attrib, nsmap=nsmap) |
---|
| 1001 | return main_node |
---|
| 1002 | |
---|
| 1003 | def _write_run_names(self, datainfo, entry_node): |
---|
| 1004 | """ |
---|
| 1005 | Writes the run names to the XML file |
---|
| 1006 | |
---|
| 1007 | :param datainfo: The Data1D object the information is coming from |
---|
| 1008 | :param entry_node: lxml node ElementTree object to be appended to |
---|
| 1009 | """ |
---|
| 1010 | if datainfo.run == None or datainfo.run == []: |
---|
| 1011 | datainfo.run.append(RUN_NAME_DEFAULT) |
---|
| 1012 | datainfo.run_name[RUN_NAME_DEFAULT] = RUN_NAME_DEFAULT |
---|
| 1013 | for item in datainfo.run: |
---|
| 1014 | runname = {} |
---|
| 1015 | if item in datainfo.run_name and \ |
---|
| 1016 | len(str(datainfo.run_name[item])) > 1: |
---|
| 1017 | runname = {'name': datainfo.run_name[item]} |
---|
| 1018 | self.write_node(entry_node, "Run", item, runname) |
---|
| 1019 | |
---|
| 1020 | def _write_data(self, datainfo, entry_node): |
---|
| 1021 | """ |
---|
[83c09af] | 1022 | Writes 1D I and Q data to the XML file |
---|
[d26dea0] | 1023 | |
---|
| 1024 | :param datainfo: The Data1D object the information is coming from |
---|
| 1025 | :param entry_node: lxml node ElementTree object to be appended to |
---|
| 1026 | """ |
---|
| 1027 | node = self.create_element("SASdata") |
---|
| 1028 | self.append(node, entry_node) |
---|
| 1029 | |
---|
| 1030 | for i in range(len(datainfo.x)): |
---|
| 1031 | point = self.create_element("Idata") |
---|
| 1032 | node.append(point) |
---|
| 1033 | self.write_node(point, "Q", datainfo.x[i], |
---|
[ad4632c] | 1034 | {'unit': datainfo._xaxis + " | " + datainfo._xunit}) |
---|
[d26dea0] | 1035 | if len(datainfo.y) >= i: |
---|
| 1036 | self.write_node(point, "I", datainfo.y[i], |
---|
[ad4632c] | 1037 | {'unit': datainfo._yaxis + " | " + datainfo._yunit}) |
---|
[5f26aa4] | 1038 | if datainfo.dy is not None and len(datainfo.dy) > i: |
---|
[d26dea0] | 1039 | self.write_node(point, "Idev", datainfo.dy[i], |
---|
[ad4632c] | 1040 | {'unit': datainfo._yaxis + " | " + datainfo._yunit}) |
---|
[5f26aa4] | 1041 | if datainfo.dx is not None and len(datainfo.dx) > i: |
---|
[d26dea0] | 1042 | self.write_node(point, "Qdev", datainfo.dx[i], |
---|
[ad4632c] | 1043 | {'unit': datainfo._xaxis + " | " + datainfo._xunit}) |
---|
[5f26aa4] | 1044 | if datainfo.dxw is not None and len(datainfo.dxw) > i: |
---|
[d26dea0] | 1045 | self.write_node(point, "dQw", datainfo.dxw[i], |
---|
[ad4632c] | 1046 | {'unit': datainfo._xaxis + " | " + datainfo._xunit}) |
---|
[5f26aa4] | 1047 | if datainfo.dxl is not None and len(datainfo.dxl) > i: |
---|
[d26dea0] | 1048 | self.write_node(point, "dQl", datainfo.dxl[i], |
---|
[ad4632c] | 1049 | {'unit': datainfo._xaxis + " | " + datainfo._xunit}) |
---|
| 1050 | if datainfo.isSesans: |
---|
| 1051 | sesans = self.create_element("Sesans") |
---|
| 1052 | sesans.text = str(datainfo.isSesans) |
---|
| 1053 | node.append(sesans) |
---|
| 1054 | self.write_node(node, "zacceptance", datainfo.sample.zacceptance[0], |
---|
| 1055 | {'unit': datainfo.sample.zacceptance[1]}) |
---|
| 1056 | |
---|
[d26dea0] | 1057 | |
---|
[83c09af] | 1058 | def _write_data_2d(self, datainfo, entry_node): |
---|
| 1059 | """ |
---|
| 1060 | Writes 2D data to the XML file |
---|
| 1061 | |
---|
| 1062 | :param datainfo: The Data2D object the information is coming from |
---|
| 1063 | :param entry_node: lxml node ElementTree object to be appended to |
---|
| 1064 | """ |
---|
[af08e55] | 1065 | attr = {} |
---|
| 1066 | if datainfo.data.shape: |
---|
[1905128] | 1067 | attr["x_bins"] = str(len(datainfo.x_bins)) |
---|
| 1068 | attr["y_bins"] = str(len(datainfo.y_bins)) |
---|
| 1069 | node = self.create_element("SASdata", attr) |
---|
[83c09af] | 1070 | self.append(node, entry_node) |
---|
| 1071 | |
---|
[1905128] | 1072 | point = self.create_element("Idata") |
---|
| 1073 | node.append(point) |
---|
| 1074 | qx = ','.join([str(datainfo.qx_data[i]) for i in xrange(len(datainfo.qx_data))]) |
---|
| 1075 | qy = ','.join([str(datainfo.qy_data[i]) for i in xrange(len(datainfo.qy_data))]) |
---|
| 1076 | intensity = ','.join([str(datainfo.data[i]) for i in xrange(len(datainfo.data))]) |
---|
| 1077 | |
---|
| 1078 | self.write_node(point, "Qx", qx, |
---|
| 1079 | {'unit': datainfo._xunit}) |
---|
| 1080 | self.write_node(point, "Qy", qy, |
---|
| 1081 | {'unit': datainfo._yunit}) |
---|
| 1082 | self.write_node(point, "I", intensity, |
---|
| 1083 | {'unit': datainfo._zunit}) |
---|
| 1084 | if datainfo.err_data is not None: |
---|
[5e6df0e] | 1085 | err = ','.join([str(datainfo.err_data[i]) for i in |
---|
| 1086 | xrange(len(datainfo.err_data))]) |
---|
[1905128] | 1087 | self.write_node(point, "Idev", err, |
---|
[83c09af] | 1088 | {'unit': datainfo._zunit}) |
---|
[1905128] | 1089 | if datainfo.dqy_data is not None: |
---|
[5e6df0e] | 1090 | dqy = ','.join([str(datainfo.dqy_data[i]) for i in |
---|
| 1091 | xrange(len(datainfo.dqy_data))]) |
---|
[1905128] | 1092 | self.write_node(point, "Qydev", dqy, |
---|
| 1093 | {'unit': datainfo._yunit}) |
---|
| 1094 | if datainfo.dqx_data is not None: |
---|
[5e6df0e] | 1095 | dqx = ','.join([str(datainfo.dqx_data[i]) for i in |
---|
| 1096 | xrange(len(datainfo.dqx_data))]) |
---|
[1905128] | 1097 | self.write_node(point, "Qxdev", dqx, |
---|
| 1098 | {'unit': datainfo._xunit}) |
---|
| 1099 | if datainfo.mask is not None: |
---|
[5e6df0e] | 1100 | mask = ','.join( |
---|
[bcabf4e] | 1101 | ["1" if datainfo.mask[i] else "0" |
---|
| 1102 | for i in xrange(len(datainfo.mask))]) |
---|
[1905128] | 1103 | self.write_node(point, "Mask", mask) |
---|
[83c09af] | 1104 | |
---|
[d26dea0] | 1105 | def _write_trans_spectrum(self, datainfo, entry_node): |
---|
| 1106 | """ |
---|
| 1107 | Writes the transmission spectrum data to the XML file |
---|
| 1108 | |
---|
| 1109 | :param datainfo: The Data1D object the information is coming from |
---|
| 1110 | :param entry_node: lxml node ElementTree object to be appended to |
---|
| 1111 | """ |
---|
| 1112 | for i in range(len(datainfo.trans_spectrum)): |
---|
| 1113 | spectrum = datainfo.trans_spectrum[i] |
---|
| 1114 | node = self.create_element("SAStransmission_spectrum", |
---|
| 1115 | {"name" : spectrum.name}) |
---|
| 1116 | self.append(node, entry_node) |
---|
| 1117 | if isinstance(spectrum.timestamp, datetime.datetime): |
---|
| 1118 | node.setAttribute("timestamp", spectrum.timestamp) |
---|
| 1119 | for i in range(len(spectrum.wavelength)): |
---|
| 1120 | point = self.create_element("Tdata") |
---|
| 1121 | node.append(point) |
---|
| 1122 | self.write_node(point, "Lambda", spectrum.wavelength[i], |
---|
| 1123 | {'unit': spectrum.wavelength_unit}) |
---|
| 1124 | self.write_node(point, "T", spectrum.transmission[i], |
---|
| 1125 | {'unit': spectrum.transmission_unit}) |
---|
| 1126 | if spectrum.transmission_deviation != None \ |
---|
| 1127 | and len(spectrum.transmission_deviation) >= i: |
---|
| 1128 | self.write_node(point, "Tdev", |
---|
| 1129 | spectrum.transmission_deviation[i], |
---|
| 1130 | {'unit': |
---|
| 1131 | spectrum.transmission_deviation_unit}) |
---|
| 1132 | |
---|
| 1133 | def _write_sample_info(self, datainfo, entry_node): |
---|
| 1134 | """ |
---|
| 1135 | Writes the sample information to the XML file |
---|
| 1136 | |
---|
| 1137 | :param datainfo: The Data1D object the information is coming from |
---|
| 1138 | :param entry_node: lxml node ElementTree object to be appended to |
---|
| 1139 | """ |
---|
| 1140 | sample = self.create_element("SASsample") |
---|
| 1141 | if datainfo.sample.name is not None: |
---|
| 1142 | self.write_attribute(sample, "name", |
---|
| 1143 | str(datainfo.sample.name)) |
---|
| 1144 | self.append(sample, entry_node) |
---|
| 1145 | self.write_node(sample, "ID", str(datainfo.sample.ID)) |
---|
| 1146 | self.write_node(sample, "thickness", datainfo.sample.thickness, |
---|
| 1147 | {"unit": datainfo.sample.thickness_unit}) |
---|
| 1148 | self.write_node(sample, "transmission", datainfo.sample.transmission) |
---|
| 1149 | self.write_node(sample, "temperature", datainfo.sample.temperature, |
---|
| 1150 | {"unit": datainfo.sample.temperature_unit}) |
---|
| 1151 | |
---|
| 1152 | pos = self.create_element("position") |
---|
| 1153 | written = self.write_node(pos, |
---|
| 1154 | "x", |
---|
| 1155 | datainfo.sample.position.x, |
---|
| 1156 | {"unit": datainfo.sample.position_unit}) |
---|
| 1157 | written = written | self.write_node( \ |
---|
| 1158 | pos, "y", datainfo.sample.position.y, |
---|
| 1159 | {"unit": datainfo.sample.position_unit}) |
---|
| 1160 | written = written | self.write_node( \ |
---|
| 1161 | pos, "z", datainfo.sample.position.z, |
---|
| 1162 | {"unit": datainfo.sample.position_unit}) |
---|
| 1163 | if written == True: |
---|
| 1164 | self.append(pos, sample) |
---|
| 1165 | |
---|
| 1166 | ori = self.create_element("orientation") |
---|
| 1167 | written = self.write_node(ori, "roll", |
---|
| 1168 | datainfo.sample.orientation.x, |
---|
| 1169 | {"unit": datainfo.sample.orientation_unit}) |
---|
| 1170 | written = written | self.write_node( \ |
---|
| 1171 | ori, "pitch", datainfo.sample.orientation.y, |
---|
| 1172 | {"unit": datainfo.sample.orientation_unit}) |
---|
| 1173 | written = written | self.write_node( \ |
---|
| 1174 | ori, "yaw", datainfo.sample.orientation.z, |
---|
| 1175 | {"unit": datainfo.sample.orientation_unit}) |
---|
| 1176 | if written == True: |
---|
| 1177 | self.append(ori, sample) |
---|
| 1178 | |
---|
| 1179 | for item in datainfo.sample.details: |
---|
| 1180 | self.write_node(sample, "details", item) |
---|
| 1181 | |
---|
| 1182 | def _write_instrument(self, datainfo, entry_node): |
---|
| 1183 | """ |
---|
| 1184 | Writes the instrumental information to the XML file |
---|
| 1185 | |
---|
| 1186 | :param datainfo: The Data1D object the information is coming from |
---|
| 1187 | :param entry_node: lxml node ElementTree object to be appended to |
---|
| 1188 | """ |
---|
| 1189 | instr = self.create_element("SASinstrument") |
---|
| 1190 | self.append(instr, entry_node) |
---|
| 1191 | self.write_node(instr, "name", datainfo.instrument) |
---|
| 1192 | return instr |
---|
| 1193 | |
---|
| 1194 | def _write_source(self, datainfo, instr): |
---|
| 1195 | """ |
---|
| 1196 | Writes the source information to the XML file |
---|
| 1197 | |
---|
| 1198 | :param datainfo: The Data1D object the information is coming from |
---|
| 1199 | :param instr: instrument node to be appended to |
---|
| 1200 | """ |
---|
| 1201 | source = self.create_element("SASsource") |
---|
| 1202 | if datainfo.source.name is not None: |
---|
| 1203 | self.write_attribute(source, "name", |
---|
| 1204 | str(datainfo.source.name)) |
---|
| 1205 | self.append(source, instr) |
---|
| 1206 | if datainfo.source.radiation == None or datainfo.source.radiation == '': |
---|
| 1207 | datainfo.source.radiation = "neutron" |
---|
| 1208 | self.write_node(source, "radiation", datainfo.source.radiation) |
---|
| 1209 | |
---|
| 1210 | size = self.create_element("beam_size") |
---|
| 1211 | if datainfo.source.beam_size_name is not None: |
---|
| 1212 | self.write_attribute(size, "name", |
---|
| 1213 | str(datainfo.source.beam_size_name)) |
---|
| 1214 | written = self.write_node( \ |
---|
| 1215 | size, "x", datainfo.source.beam_size.x, |
---|
| 1216 | {"unit": datainfo.source.beam_size_unit}) |
---|
| 1217 | written = written | self.write_node( \ |
---|
| 1218 | size, "y", datainfo.source.beam_size.y, |
---|
| 1219 | {"unit": datainfo.source.beam_size_unit}) |
---|
| 1220 | written = written | self.write_node( \ |
---|
| 1221 | size, "z", datainfo.source.beam_size.z, |
---|
| 1222 | {"unit": datainfo.source.beam_size_unit}) |
---|
| 1223 | if written == True: |
---|
| 1224 | self.append(size, source) |
---|
| 1225 | |
---|
| 1226 | self.write_node(source, "beam_shape", datainfo.source.beam_shape) |
---|
| 1227 | self.write_node(source, "wavelength", |
---|
| 1228 | datainfo.source.wavelength, |
---|
| 1229 | {"unit": datainfo.source.wavelength_unit}) |
---|
| 1230 | self.write_node(source, "wavelength_min", |
---|
| 1231 | datainfo.source.wavelength_min, |
---|
| 1232 | {"unit": datainfo.source.wavelength_min_unit}) |
---|
| 1233 | self.write_node(source, "wavelength_max", |
---|
| 1234 | datainfo.source.wavelength_max, |
---|
| 1235 | {"unit": datainfo.source.wavelength_max_unit}) |
---|
| 1236 | self.write_node(source, "wavelength_spread", |
---|
| 1237 | datainfo.source.wavelength_spread, |
---|
| 1238 | {"unit": datainfo.source.wavelength_spread_unit}) |
---|
| 1239 | |
---|
| 1240 | def _write_collimation(self, datainfo, instr): |
---|
| 1241 | """ |
---|
| 1242 | Writes the collimation information to the XML file |
---|
| 1243 | |
---|
| 1244 | :param datainfo: The Data1D object the information is coming from |
---|
| 1245 | :param instr: lxml node ElementTree object to be appended to |
---|
| 1246 | """ |
---|
| 1247 | if datainfo.collimation == [] or datainfo.collimation == None: |
---|
| 1248 | coll = Collimation() |
---|
| 1249 | datainfo.collimation.append(coll) |
---|
| 1250 | for item in datainfo.collimation: |
---|
| 1251 | coll = self.create_element("SAScollimation") |
---|
| 1252 | if item.name is not None: |
---|
| 1253 | self.write_attribute(coll, "name", str(item.name)) |
---|
| 1254 | self.append(coll, instr) |
---|
| 1255 | |
---|
| 1256 | self.write_node(coll, "length", item.length, |
---|
| 1257 | {"unit": item.length_unit}) |
---|
| 1258 | |
---|
| 1259 | for aperture in item.aperture: |
---|
| 1260 | apert = self.create_element("aperture") |
---|
| 1261 | if aperture.name is not None: |
---|
| 1262 | self.write_attribute(apert, "name", str(aperture.name)) |
---|
| 1263 | if aperture.type is not None: |
---|
| 1264 | self.write_attribute(apert, "type", str(aperture.type)) |
---|
| 1265 | self.append(apert, coll) |
---|
| 1266 | |
---|
| 1267 | size = self.create_element("size") |
---|
| 1268 | if aperture.size_name is not None: |
---|
| 1269 | self.write_attribute(size, "name", |
---|
| 1270 | str(aperture.size_name)) |
---|
| 1271 | written = self.write_node(size, "x", aperture.size.x, |
---|
| 1272 | {"unit": aperture.size_unit}) |
---|
| 1273 | written = written | self.write_node( \ |
---|
| 1274 | size, "y", aperture.size.y, |
---|
| 1275 | {"unit": aperture.size_unit}) |
---|
| 1276 | written = written | self.write_node( \ |
---|
| 1277 | size, "z", aperture.size.z, |
---|
| 1278 | {"unit": aperture.size_unit}) |
---|
| 1279 | if written == True: |
---|
| 1280 | self.append(size, apert) |
---|
| 1281 | |
---|
| 1282 | self.write_node(apert, "distance", aperture.distance, |
---|
| 1283 | {"unit": aperture.distance_unit}) |
---|
| 1284 | |
---|
| 1285 | def _write_detectors(self, datainfo, instr): |
---|
| 1286 | """ |
---|
| 1287 | Writes the detector information to the XML file |
---|
| 1288 | |
---|
| 1289 | :param datainfo: The Data1D object the information is coming from |
---|
| 1290 | :param inst: lxml instrument node to be appended to |
---|
| 1291 | """ |
---|
| 1292 | if datainfo.detector == None or datainfo.detector == []: |
---|
| 1293 | det = Detector() |
---|
| 1294 | det.name = "" |
---|
| 1295 | datainfo.detector.append(det) |
---|
| 1296 | |
---|
| 1297 | for item in datainfo.detector: |
---|
| 1298 | det = self.create_element("SASdetector") |
---|
| 1299 | written = self.write_node(det, "name", item.name) |
---|
| 1300 | written = written | self.write_node(det, "SDD", item.distance, |
---|
| 1301 | {"unit": item.distance_unit}) |
---|
| 1302 | if written == True: |
---|
| 1303 | self.append(det, instr) |
---|
| 1304 | |
---|
| 1305 | off = self.create_element("offset") |
---|
| 1306 | written = self.write_node(off, "x", item.offset.x, |
---|
| 1307 | {"unit": item.offset_unit}) |
---|
| 1308 | written = written | self.write_node(off, "y", item.offset.y, |
---|
| 1309 | {"unit": item.offset_unit}) |
---|
| 1310 | written = written | self.write_node(off, "z", item.offset.z, |
---|
| 1311 | {"unit": item.offset_unit}) |
---|
| 1312 | if written == True: |
---|
| 1313 | self.append(off, det) |
---|
| 1314 | |
---|
| 1315 | ori = self.create_element("orientation") |
---|
| 1316 | written = self.write_node(ori, "roll", item.orientation.x, |
---|
| 1317 | {"unit": item.orientation_unit}) |
---|
| 1318 | written = written | self.write_node(ori, "pitch", |
---|
| 1319 | item.orientation.y, |
---|
| 1320 | {"unit": item.orientation_unit}) |
---|
| 1321 | written = written | self.write_node(ori, "yaw", |
---|
| 1322 | item.orientation.z, |
---|
| 1323 | {"unit": item.orientation_unit}) |
---|
| 1324 | if written == True: |
---|
| 1325 | self.append(ori, det) |
---|
| 1326 | |
---|
| 1327 | center = self.create_element("beam_center") |
---|
| 1328 | written = self.write_node(center, "x", item.beam_center.x, |
---|
| 1329 | {"unit": item.beam_center_unit}) |
---|
| 1330 | written = written | self.write_node(center, "y", |
---|
| 1331 | item.beam_center.y, |
---|
| 1332 | {"unit": item.beam_center_unit}) |
---|
| 1333 | written = written | self.write_node(center, "z", |
---|
| 1334 | item.beam_center.z, |
---|
| 1335 | {"unit": item.beam_center_unit}) |
---|
| 1336 | if written == True: |
---|
| 1337 | self.append(center, det) |
---|
| 1338 | |
---|
| 1339 | pix = self.create_element("pixel_size") |
---|
| 1340 | written = self.write_node(pix, "x", item.pixel_size.x, |
---|
| 1341 | {"unit": item.pixel_size_unit}) |
---|
| 1342 | written = written | self.write_node(pix, "y", item.pixel_size.y, |
---|
| 1343 | {"unit": item.pixel_size_unit}) |
---|
| 1344 | written = written | self.write_node(pix, "z", item.pixel_size.z, |
---|
| 1345 | {"unit": item.pixel_size_unit}) |
---|
| 1346 | if written == True: |
---|
| 1347 | self.append(pix, det) |
---|
[3a9801f] | 1348 | self.write_node(det, "slit_length", item.slit_length, |
---|
| 1349 | {"unit": item.slit_length_unit}) |
---|
| 1350 | |
---|
[d26dea0] | 1351 | |
---|
| 1352 | def _write_process_notes(self, datainfo, entry_node): |
---|
| 1353 | """ |
---|
| 1354 | Writes the process notes to the XML file |
---|
| 1355 | |
---|
| 1356 | :param datainfo: The Data1D object the information is coming from |
---|
| 1357 | :param entry_node: lxml node ElementTree object to be appended to |
---|
| 1358 | |
---|
| 1359 | """ |
---|
| 1360 | for item in datainfo.process: |
---|
| 1361 | node = self.create_element("SASprocess") |
---|
| 1362 | self.append(node, entry_node) |
---|
| 1363 | self.write_node(node, "name", item.name) |
---|
| 1364 | self.write_node(node, "date", item.date) |
---|
| 1365 | self.write_node(node, "description", item.description) |
---|
| 1366 | for term in item.term: |
---|
[1686a333] | 1367 | if isinstance(term, list): |
---|
| 1368 | value = term['value'] |
---|
| 1369 | del term['value'] |
---|
[5f26aa4] | 1370 | elif isinstance(term, dict): |
---|
| 1371 | value = term.get("value") |
---|
| 1372 | del term['value'] |
---|
[1686a333] | 1373 | else: |
---|
| 1374 | value = term |
---|
[d26dea0] | 1375 | self.write_node(node, "term", value, term) |
---|
| 1376 | for note in item.notes: |
---|
| 1377 | self.write_node(node, "SASprocessnote", note) |
---|
| 1378 | if len(item.notes) == 0: |
---|
| 1379 | self.write_node(node, "SASprocessnote", "") |
---|
| 1380 | |
---|
| 1381 | def _write_notes(self, datainfo, entry_node): |
---|
| 1382 | """ |
---|
| 1383 | Writes the notes to the XML file and creates an empty note if none |
---|
| 1384 | exist |
---|
| 1385 | |
---|
| 1386 | :param datainfo: The Data1D object the information is coming from |
---|
| 1387 | :param entry_node: lxml node ElementTree object to be appended to |
---|
| 1388 | |
---|
| 1389 | """ |
---|
| 1390 | if len(datainfo.notes) == 0: |
---|
| 1391 | node = self.create_element("SASnote") |
---|
| 1392 | self.append(node, entry_node) |
---|
| 1393 | else: |
---|
| 1394 | for item in datainfo.notes: |
---|
| 1395 | node = self.create_element("SASnote") |
---|
| 1396 | self.write_text(node, item) |
---|
| 1397 | self.append(node, entry_node) |
---|
| 1398 | |
---|
[654e8e0] | 1399 | def _check_origin(self, entry_node, doc): |
---|
[d26dea0] | 1400 | """ |
---|
| 1401 | Return the document, and the SASentry node associated with |
---|
| 1402 | the data we just wrote. |
---|
| 1403 | If the calling function was not the cansas reader, return a minidom |
---|
| 1404 | object rather than an lxml object. |
---|
| 1405 | |
---|
| 1406 | :param entry_node: lxml node ElementTree object to be appended to |
---|
| 1407 | :param doc: entire xml tree |
---|
| 1408 | """ |
---|
[654e8e0] | 1409 | if not self.frm: |
---|
| 1410 | self.frm = inspect.stack()[1] |
---|
| 1411 | mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "") |
---|
[d26dea0] | 1412 | mod_name = mod_name.replace(".py", "") |
---|
| 1413 | mod = mod_name.split("sas/") |
---|
| 1414 | mod_name = mod[1] |
---|
[45d90b9] | 1415 | if mod_name != "sascalc/dataloader/readers/cansas_reader": |
---|
[d26dea0] | 1416 | string = self.to_string(doc, pretty_print=False) |
---|
| 1417 | doc = parseString(string) |
---|
| 1418 | node_name = entry_node.tag |
---|
| 1419 | node_list = doc.getElementsByTagName(node_name) |
---|
| 1420 | entry_node = node_list.item(0) |
---|
[5ce7f17] | 1421 | return doc, entry_node |
---|
[d26dea0] | 1422 | |
---|
| 1423 | # DO NOT REMOVE - used in saving and loading panel states. |
---|
| 1424 | def _store_float(self, location, node, variable, storage, optional=True): |
---|
| 1425 | """ |
---|
| 1426 | Get the content of a xpath location and store |
---|
| 1427 | the result. Check that the units are compatible |
---|
| 1428 | with the destination. The value is expected to |
---|
| 1429 | be a float. |
---|
| 1430 | |
---|
| 1431 | The xpath location might or might not exist. |
---|
| 1432 | If it does not exist, nothing is done |
---|
| 1433 | |
---|
| 1434 | :param location: xpath location to fetch |
---|
| 1435 | :param node: node to read the data from |
---|
| 1436 | :param variable: name of the data member to store it in [string] |
---|
| 1437 | :param storage: data object that has the 'variable' data member |
---|
| 1438 | :param optional: if True, no exception will be raised |
---|
| 1439 | if unit conversion can't be done |
---|
| 1440 | |
---|
| 1441 | :raise ValueError: raised when the units are not recognized |
---|
| 1442 | """ |
---|
| 1443 | entry = get_content(location, node) |
---|
| 1444 | try: |
---|
| 1445 | value = float(entry.text) |
---|
| 1446 | except: |
---|
| 1447 | value = None |
---|
| 1448 | |
---|
| 1449 | if value is not None: |
---|
| 1450 | # If the entry has units, check to see that they are |
---|
| 1451 | # compatible with what we currently have in the data object |
---|
| 1452 | units = entry.get('unit') |
---|
| 1453 | if units is not None: |
---|
| 1454 | toks = variable.split('.') |
---|
| 1455 | local_unit = None |
---|
| 1456 | exec "local_unit = storage.%s_unit" % toks[0] |
---|
| 1457 | if local_unit != None and units.lower() != local_unit.lower(): |
---|
| 1458 | if HAS_CONVERTER == True: |
---|
| 1459 | try: |
---|
| 1460 | conv = Converter(units) |
---|
| 1461 | exec "storage.%s = %g" % \ |
---|
| 1462 | (variable, conv(value, units=local_unit)) |
---|
| 1463 | except: |
---|
| 1464 | _, exc_value, _ = sys.exc_info() |
---|
| 1465 | err_mess = "CanSAS reader: could not convert" |
---|
| 1466 | err_mess += " %s unit [%s]; expecting [%s]\n %s" \ |
---|
| 1467 | % (variable, units, local_unit, exc_value) |
---|
| 1468 | self.errors.add(err_mess) |
---|
| 1469 | if optional: |
---|
| 1470 | logging.info(err_mess) |
---|
| 1471 | else: |
---|
| 1472 | raise ValueError, err_mess |
---|
| 1473 | else: |
---|
| 1474 | err_mess = "CanSAS reader: unrecognized %s unit [%s];"\ |
---|
| 1475 | % (variable, units) |
---|
| 1476 | err_mess += " expecting [%s]" % local_unit |
---|
| 1477 | self.errors.add(err_mess) |
---|
| 1478 | if optional: |
---|
| 1479 | logging.info(err_mess) |
---|
| 1480 | else: |
---|
| 1481 | raise ValueError, err_mess |
---|
| 1482 | else: |
---|
| 1483 | exec "storage.%s = value" % variable |
---|
| 1484 | else: |
---|
| 1485 | exec "storage.%s = value" % variable |
---|
| 1486 | |
---|
| 1487 | # DO NOT REMOVE - used in saving and loading panel states. |
---|
| 1488 | def _store_content(self, location, node, variable, storage): |
---|
| 1489 | """ |
---|
| 1490 | Get the content of a xpath location and store |
---|
| 1491 | the result. The value is treated as a string. |
---|
| 1492 | |
---|
| 1493 | The xpath location might or might not exist. |
---|
| 1494 | If it does not exist, nothing is done |
---|
| 1495 | |
---|
| 1496 | :param location: xpath location to fetch |
---|
| 1497 | :param node: node to read the data from |
---|
| 1498 | :param variable: name of the data member to store it in [string] |
---|
| 1499 | :param storage: data object that has the 'variable' data member |
---|
| 1500 | |
---|
| 1501 | :return: return a list of errors |
---|
| 1502 | """ |
---|
| 1503 | entry = get_content(location, node) |
---|
| 1504 | if entry is not None and entry.text is not None: |
---|
| 1505 | exec "storage.%s = entry.text.strip()" % variable |
---|
[250fec92] | 1506 | |
---|
| 1507 | |
---|
| 1508 | # DO NOT REMOVE Called by outside packages: |
---|
| 1509 | # sas.sasgui.perspectives.invariant.invariant_state |
---|
| 1510 | # sas.sasgui.perspectives.fitting.pagestate |
---|
| 1511 | def get_content(location, node): |
---|
| 1512 | """ |
---|
| 1513 | Get the first instance of the content of a xpath location. |
---|
| 1514 | |
---|
| 1515 | :param location: xpath location |
---|
| 1516 | :param node: node to start at |
---|
| 1517 | |
---|
| 1518 | :return: Element, or None |
---|
| 1519 | """ |
---|
| 1520 | nodes = node.xpath(location, |
---|
| 1521 | namespaces={'ns': CANSAS_NS.get("1.0").get("ns")}) |
---|
| 1522 | if len(nodes) > 0: |
---|
| 1523 | return nodes[0] |
---|
| 1524 | else: |
---|
| 1525 | return None |
---|
| 1526 | |
---|
| 1527 | # DO NOT REMOVE Called by outside packages: |
---|
| 1528 | # sas.sasgui.perspectives.fitting.pagestate |
---|
| 1529 | def write_node(doc, parent, name, value, attr=None): |
---|
| 1530 | """ |
---|
| 1531 | :param doc: document DOM |
---|
| 1532 | :param parent: parent node |
---|
| 1533 | :param name: tag of the element |
---|
| 1534 | :param value: value of the child text node |
---|
| 1535 | :param attr: attribute dictionary |
---|
| 1536 | |
---|
| 1537 | :return: True if something was appended, otherwise False |
---|
| 1538 | """ |
---|
| 1539 | if attr is None: |
---|
| 1540 | attr = {} |
---|
| 1541 | if value is not None: |
---|
| 1542 | node = doc.createElement(name) |
---|
| 1543 | node.appendChild(doc.createTextNode(str(value))) |
---|
| 1544 | for item in attr: |
---|
| 1545 | node.setAttribute(item, attr[item]) |
---|
| 1546 | parent.appendChild(node) |
---|
| 1547 | return True |
---|
| 1548 | return False |
---|