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