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