[4a2b054] | 1 | """ |
---|
| 2 | """ |
---|
| 3 | |
---|
[75fbd17] | 4 | #import time |
---|
[4a2b054] | 5 | import os |
---|
| 6 | import sys |
---|
[4e1c362] | 7 | import logging |
---|
| 8 | import copy |
---|
| 9 | import DataLoader |
---|
[890a909b] | 10 | #from xml.dom.minidom import parse |
---|
[4e1c362] | 11 | from lxml import etree |
---|
| 12 | from DataLoader.readers.cansas_reader import Reader as CansasReader |
---|
| 13 | from DataLoader.readers.cansas_reader import get_content |
---|
| 14 | from sans.guiframe.utils import format_number |
---|
[4a2b054] | 15 | from sans.guiframe.dataFitting import Theory1D |
---|
| 16 | from sans.guiframe.dataFitting import Data1D |
---|
| 17 | |
---|
[4e1c362] | 18 | INVNODE_NAME = 'invariant' |
---|
| 19 | CANSAS_NS = "cansas1d/1.0" |
---|
[4a2b054] | 20 | |
---|
[4e1c362] | 21 | # default state |
---|
| 22 | list = {'file': 'None', |
---|
| 23 | 'compute_num':0, |
---|
| 24 | 'state_num':0, |
---|
| 25 | 'is_time_machine':False, |
---|
| 26 | 'background_tcl':0.0, |
---|
| 27 | 'scale_tcl':1.0, |
---|
| 28 | 'contrast_tcl':1.0, |
---|
| 29 | 'porod_constant_tcl':'', |
---|
| 30 | 'npts_low_tcl':10, |
---|
| 31 | 'npts_high_tcl':10, |
---|
| 32 | 'power_high_tcl':4.0, |
---|
| 33 | 'power_low_tcl': 4.0, |
---|
| 34 | 'enable_high_cbox':False, |
---|
| 35 | 'enable_low_cbox':False, |
---|
| 36 | 'guinier': True, |
---|
| 37 | 'power_law_high': False, |
---|
| 38 | 'power_law_low': False, |
---|
| 39 | 'fit_enable_high': False, |
---|
| 40 | 'fit_enable_low': False, |
---|
| 41 | 'fix_enable_high':True, |
---|
| 42 | 'fix_enable_low':True, |
---|
| 43 | 'volume_tcl':'', |
---|
| 44 | 'volume_err_tcl':'', |
---|
| 45 | 'surface_tcl':'', |
---|
| 46 | 'surface_err_tcl':''} |
---|
[4a2b054] | 47 | # list of states: This list will be filled as panel |
---|
| 48 | # init and the number of states increases |
---|
[4e1c362] | 49 | state_list = {} |
---|
| 50 | bookmark_list = {} |
---|
| 51 | # list of input parameters (will be filled up on panel init) used by __str__ |
---|
[cb463b4] | 52 | input_list = {'background_tcl':0, |
---|
| 53 | 'scale_tcl':0, |
---|
| 54 | 'contrast_tcl':0, |
---|
| 55 | 'porod_constant_tcl':'', |
---|
| 56 | 'npts_low_tcl':0, |
---|
| 57 | 'npts_high_tcl':0, |
---|
| 58 | 'power_high_tcl':0, |
---|
| 59 | 'power_low_tcl': 0} |
---|
[4e1c362] | 60 | # list of output parameters (order sensitive) used by __str__ |
---|
[4a2b054] | 61 | output_list = [["qstar_low", "Q* from low Q extrapolation [1/(cm*A)]"], |
---|
[4e1c362] | 62 | ["qstar_low_err", "dQ* from low Q extrapolation"], |
---|
| 63 | ["qstar_low_percent", "Q* percent from low Q extrapolation"], |
---|
[4a2b054] | 64 | ["qstar", "Q* from data [1/(cm*A)]"], |
---|
[4e1c362] | 65 | ["qstar_err", "dQ* from data"], |
---|
| 66 | ["qstar_percent", "Q* percent from data"], |
---|
[4a2b054] | 67 | ["qstar_high", "Q* from high Q extrapolation [1/(cm*A)]"], |
---|
[4e1c362] | 68 | ["qstar_high_err", "dQ* from high Q extrapolation"], |
---|
| 69 | ["qstar_high_percent", "Q* percent from low Q extrapolation"], |
---|
[4a2b054] | 70 | ["qstar_total", "total Q* [1/(cm*A)]"], |
---|
[4e1c362] | 71 | ["qstar_total_err", "total dQ*"], |
---|
| 72 | ["volume", "volume fraction"], |
---|
| 73 | ["volume_err", "volume fraction error"], |
---|
| 74 | ["surface", "specific surface"], |
---|
| 75 | ["surface_err", "specific surface error"]] |
---|
| 76 | |
---|
| 77 | |
---|
| 78 | |
---|
| 79 | class InvariantState(object): |
---|
| 80 | """ |
---|
| 81 | Class to hold the state information of the InversionControl panel. |
---|
| 82 | """ |
---|
| 83 | def __init__(self): |
---|
| 84 | """ |
---|
| 85 | Default values |
---|
| 86 | """ |
---|
| 87 | # Input |
---|
| 88 | self.file = None |
---|
| 89 | self.data = Data1D(x=[], y=[], dx=None, dy=None) |
---|
| 90 | self.theory_lowQ = Theory1D(x=[], y=[], dy=None) |
---|
| 91 | self.theory_highQ = Theory1D(x=[], y=[], dy=None) |
---|
| 92 | #self.is_time_machine = False |
---|
| 93 | self.saved_state = list |
---|
| 94 | self.state_list = state_list |
---|
| 95 | self.bookmark_list = bookmark_list |
---|
| 96 | self.input_list = input_list |
---|
| 97 | self.output_list = output_list |
---|
| 98 | |
---|
| 99 | self.compute_num = 0 |
---|
| 100 | self.state_num = 0 |
---|
[51fb7ab] | 101 | self.timestamp = ('00:00:00', '00/00/0000') |
---|
[4e1c362] | 102 | self.container = None |
---|
[a94c4e1] | 103 | #plot image |
---|
| 104 | self.wximbmp = None |
---|
[cb463b4] | 105 | # report_html strings |
---|
| 106 | import sans.perspectives.invariant as invariant |
---|
| 107 | path = invariant.get_data_path(media='media') |
---|
[4a2b054] | 108 | path_report_html = os.path.join(path,"report_template.html") |
---|
| 109 | html_template = open(path_report_html,"r") |
---|
[cb463b4] | 110 | self.template_str = html_template.read() |
---|
| 111 | self.report_str = self.template_str |
---|
[b281210] | 112 | #self.report_str_save = None |
---|
[cb463b4] | 113 | html_template.close() |
---|
[4e1c362] | 114 | |
---|
| 115 | def __str__(self): |
---|
| 116 | """ |
---|
| 117 | Pretty print |
---|
| 118 | |
---|
| 119 | : return: string representing the state |
---|
| 120 | """ |
---|
| 121 | # Input string |
---|
| 122 | compute_num = self.saved_state['compute_num'] |
---|
| 123 | compute_state = self.state_list[str(compute_num)] |
---|
| 124 | my_time, date = self.timestamp |
---|
| 125 | file_name = self.file |
---|
| 126 | |
---|
| 127 | state_num = int(self.saved_state['state_num']) |
---|
[4a2b054] | 128 | state = "\n[Invariant computation for %s: " % file_name |
---|
| 129 | state += "performed at %s on %s] \n" % (my_time, date) |
---|
| 130 | state += "State No.: %d \n" % state_num |
---|
[4e1c362] | 131 | state += "\n=== Inputs ===\n" |
---|
| 132 | |
---|
| 133 | # text ctl general inputs ( excluding extrapolation text ctl) |
---|
[4a2b054] | 134 | for key, value in self.input_list.iteritems(): |
---|
[4e1c362] | 135 | if value == '': |
---|
| 136 | continue |
---|
| 137 | key_split = key.split('_') |
---|
| 138 | max_ind = len(key_split)-1 |
---|
| 139 | if key_split[max_ind] == 'tcl': |
---|
[4a2b054] | 140 | name = "" |
---|
| 141 | if key_split[1] == 'low' or key_split[1] == 'high': |
---|
[4e1c362] | 142 | continue |
---|
[4a2b054] | 143 | for ind in range(0, max_ind): |
---|
| 144 | name += " %s" % key_split[ind] |
---|
| 145 | state += "%s: %s\n" % (name.lstrip(" "), value) |
---|
[4e1c362] | 146 | |
---|
| 147 | # other input parameters |
---|
| 148 | extra_lo = compute_state['enable_low_cbox'] |
---|
| 149 | if compute_state['enable_low_cbox']: |
---|
| 150 | if compute_state['guinier']: |
---|
| 151 | extra_lo = 'Guinier' |
---|
| 152 | else: |
---|
| 153 | extra_lo = 'Power law' |
---|
| 154 | extra_hi = compute_state['enable_high_cbox'] |
---|
| 155 | if compute_state['enable_high_cbox']: |
---|
| 156 | extra_hi = 'Power law' |
---|
[4a2b054] | 157 | state += "\nExtrapolation: High=%s; Low=%s\n" %(extra_hi, extra_lo) |
---|
[4e1c362] | 158 | low_off = False |
---|
| 159 | high_off = False |
---|
[4a2b054] | 160 | for key, value in self.input_list.iteritems(): |
---|
[4e1c362] | 161 | key_split = key.split('_') |
---|
[4a2b054] | 162 | max_ind = len(key_split) - 1 |
---|
[4e1c362] | 163 | if key_split[max_ind] == 'tcl': |
---|
[4a2b054] | 164 | name = "" |
---|
[4e1c362] | 165 | # check each buttons whether or not ON or OFF |
---|
[4a2b054] | 166 | if key_split[1] == 'low' or key_split[1] == 'high': |
---|
| 167 | if not compute_state['enable_low_cbox'] and \ |
---|
| 168 | key_split[max_ind-1] == 'low': |
---|
[4e1c362] | 169 | low_off = True |
---|
| 170 | continue |
---|
[4a2b054] | 171 | elif not compute_state['enable_high_cbox'] and \ |
---|
| 172 | key_split[max_ind-1] == 'high': |
---|
[4e1c362] | 173 | high_off = True |
---|
| 174 | continue |
---|
[4a2b054] | 175 | elif extra_lo == 'Guinier' and key_split[0] == 'power' and \ |
---|
| 176 | key_split[max_ind-1] == 'low': |
---|
[4e1c362] | 177 | continue |
---|
[4a2b054] | 178 | for ind in range(0, max_ind): |
---|
| 179 | name += " %s" % key_split[ind] |
---|
[4e1c362] | 180 | name = name.lstrip(" ") |
---|
| 181 | if name == "power low" : |
---|
| 182 | if compute_state['fix_enable_low']: |
---|
| 183 | name += ' (Fixed)' |
---|
| 184 | else: |
---|
| 185 | name += ' (Fitted)' |
---|
| 186 | if name == "power high" : |
---|
| 187 | if compute_state['fix_enable_high']: |
---|
| 188 | name += ' (Fixed)' |
---|
| 189 | else: |
---|
| 190 | name += ' (Fitted)' |
---|
[4a2b054] | 191 | state += "%s: %s\n" % (name, value) |
---|
[4e1c362] | 192 | # Outputs |
---|
| 193 | state += "\n=== Outputs ===" |
---|
| 194 | for item in output_list: |
---|
| 195 | item_split = item[0].split('_') |
---|
| 196 | # Exclude the extrapolation that turned off |
---|
[4a2b054] | 197 | if len(item_split) > 1: |
---|
| 198 | if low_off and item_split[1] == 'low': |
---|
| 199 | continue |
---|
| 200 | if high_off and item_split[1] == 'high': |
---|
| 201 | continue |
---|
| 202 | max_ind = len(item_split) - 1 |
---|
[4e1c362] | 203 | value = None |
---|
| 204 | try: |
---|
| 205 | # Q* outputs |
---|
[4a2b054] | 206 | exec "value = self.container.%s\n" % item[0] |
---|
[4e1c362] | 207 | except: |
---|
| 208 | # other outputs than Q* |
---|
[4a2b054] | 209 | name = item[0] + "_tcl" |
---|
[cb69775] | 210 | if name in self.saved_state.keys(): |
---|
| 211 | exec "value = self.saved_state['%s']" % name |
---|
[4e1c362] | 212 | |
---|
| 213 | # Exclude the outputs w/'' |
---|
[4a2b054] | 214 | if value == '': |
---|
| 215 | continue |
---|
[4e1c362] | 216 | # Error outputs |
---|
| 217 | if item_split[max_ind] == 'err': |
---|
[4a2b054] | 218 | state += "+- %s " % format_number(value) |
---|
[4e1c362] | 219 | # Percentage outputs |
---|
| 220 | elif item_split[max_ind] == 'percent': |
---|
| 221 | try: |
---|
[4a2b054] | 222 | value = float(value) * 100 |
---|
[4e1c362] | 223 | except: |
---|
| 224 | pass |
---|
[4a2b054] | 225 | state += "(%s %s)" % (format_number(value), '%') |
---|
[4e1c362] | 226 | # Outputs |
---|
| 227 | else: |
---|
[4a2b054] | 228 | state += "\n%s: %s " % (item[1], |
---|
| 229 | format_number(value, high=True)) |
---|
[4e1c362] | 230 | # Include warning msg |
---|
[cb69775] | 231 | if self.container is not None: |
---|
| 232 | state += "\n\nNote:\n" + self.container.warning_msg |
---|
[4e1c362] | 233 | return state |
---|
| 234 | |
---|
| 235 | def clone_state(self): |
---|
| 236 | """ |
---|
| 237 | deepcopy the state |
---|
| 238 | """ |
---|
| 239 | return copy.deepcopy(self.saved_state) |
---|
| 240 | |
---|
| 241 | def toXML(self, file="inv_state.inv", doc=None, entry_node=None): |
---|
| 242 | """ |
---|
| 243 | Writes the state of the InversionControl panel to file, as XML. |
---|
| 244 | |
---|
| 245 | Compatible with standalone writing, or appending to an |
---|
| 246 | already existing XML document. In that case, the XML document |
---|
[4a2b054] | 247 | is required. An optional entry node in the XML document |
---|
| 248 | may also be given. |
---|
[4e1c362] | 249 | |
---|
| 250 | : param file: file to write to |
---|
| 251 | : param doc: XML document object [optional] |
---|
[4a2b054] | 252 | : param entry_node: XML node within the XML document at which |
---|
| 253 | we will append the data [optional] |
---|
[4e1c362] | 254 | """ |
---|
| 255 | from xml.dom.minidom import getDOMImplementation |
---|
[75fbd17] | 256 | import time |
---|
[4e1c362] | 257 | timestamp = time.time() |
---|
| 258 | # Check whether we have to write a standalone XML file |
---|
| 259 | if doc is None: |
---|
| 260 | impl = getDOMImplementation() |
---|
| 261 | |
---|
| 262 | doc_type = impl.createDocumentType(INVNODE_NAME, "1.0", "1.0") |
---|
| 263 | |
---|
| 264 | newdoc = impl.createDocument(None, INVNODE_NAME, doc_type) |
---|
| 265 | top_element = newdoc.documentElement |
---|
| 266 | else: |
---|
| 267 | # We are appending to an existing document |
---|
| 268 | newdoc = doc |
---|
| 269 | top_element = newdoc.createElement(INVNODE_NAME) |
---|
| 270 | if entry_node is None: |
---|
| 271 | newdoc.documentElement.appendChild(top_element) |
---|
| 272 | else: |
---|
| 273 | entry_node.appendChild(top_element) |
---|
| 274 | |
---|
| 275 | attr = newdoc.createAttribute("version") |
---|
| 276 | attr.nodeValue = '1.0' |
---|
| 277 | top_element.setAttributeNode(attr) |
---|
| 278 | |
---|
| 279 | # File name |
---|
| 280 | element = newdoc.createElement("filename") |
---|
[4a2b054] | 281 | if self.file != None and self.file != '': |
---|
[4e1c362] | 282 | element.appendChild(newdoc.createTextNode(str(self.file))) |
---|
| 283 | else: |
---|
| 284 | element.appendChild(newdoc.createTextNode(str(file))) |
---|
| 285 | top_element.appendChild(element) |
---|
| 286 | |
---|
| 287 | element = newdoc.createElement("timestamp") |
---|
| 288 | element.appendChild(newdoc.createTextNode(time.ctime(timestamp))) |
---|
| 289 | attr = newdoc.createAttribute("epoch") |
---|
| 290 | attr.nodeValue = str(timestamp) |
---|
| 291 | element.setAttributeNode(attr) |
---|
| 292 | top_element.appendChild(element) |
---|
| 293 | |
---|
| 294 | # Current state |
---|
| 295 | state = newdoc.createElement("state") |
---|
| 296 | top_element.appendChild(state) |
---|
| 297 | |
---|
| 298 | for name,value in self.saved_state.iteritems(): |
---|
| 299 | element = newdoc.createElement(str(name)) |
---|
| 300 | element.appendChild(newdoc.createTextNode(str(value))) |
---|
| 301 | state.appendChild(element) |
---|
| 302 | |
---|
| 303 | # State history list |
---|
| 304 | history = newdoc.createElement("history") |
---|
| 305 | top_element.appendChild(history) |
---|
| 306 | |
---|
| 307 | for name, value in self.state_list.iteritems(): |
---|
[4a2b054] | 308 | history_element = newdoc.createElement('state_' + str(name)) |
---|
[4e1c362] | 309 | for state_name,state_value in value.iteritems(): |
---|
| 310 | state_element = newdoc.createElement(str(state_name)) |
---|
[4a2b054] | 311 | child = newdoc.createTextNode(str(state_value)) |
---|
| 312 | state_element.appendChild(child) |
---|
[4e1c362] | 313 | history_element.appendChild(state_element) |
---|
| 314 | #history_element.appendChild(state_list_element) |
---|
| 315 | history.appendChild(history_element) |
---|
| 316 | |
---|
[4a2b054] | 317 | # Bookmarks bookmark_list[self.bookmark_num] = [\ |
---|
| 318 | #my_time,date,state,comp_state] |
---|
[4e1c362] | 319 | bookmark = newdoc.createElement("bookmark") |
---|
| 320 | top_element.appendChild(bookmark) |
---|
| 321 | item_list = ['time','date','state','comp_state'] |
---|
| 322 | for name, value_list in self.bookmark_list.iteritems(): |
---|
| 323 | element = newdoc.createElement('mark_'+ str(name)) |
---|
[ddeeb02] | 324 | _,date,state,comp_state = value_list |
---|
[4e1c362] | 325 | time_element = newdoc.createElement('time') |
---|
| 326 | time_element.appendChild(newdoc.createTextNode(str(value_list[0]))) |
---|
| 327 | date_element = newdoc.createElement('date') |
---|
| 328 | date_element.appendChild(newdoc.createTextNode(str(value_list[1]))) |
---|
| 329 | state_list_element = newdoc.createElement('state') |
---|
| 330 | comp_state_list_element = newdoc.createElement('comp_state') |
---|
[4a2b054] | 331 | for state_name, state_value in value_list[2].iteritems(): |
---|
[4e1c362] | 332 | state_element = newdoc.createElement(str(state_name)) |
---|
[4a2b054] | 333 | child = newdoc.createTextNode(str(state_value)) |
---|
| 334 | state_element.appendChild(child) |
---|
[4e1c362] | 335 | state_list_element.appendChild(state_element) |
---|
[4a2b054] | 336 | for comp_name, comp_value in value_list[3].iteritems(): |
---|
[4e1c362] | 337 | comp_element = newdoc.createElement(str(comp_name)) |
---|
| 338 | comp_element.appendChild(newdoc.createTextNode(str(comp_value))) |
---|
| 339 | comp_state_list_element.appendChild(comp_element) |
---|
| 340 | element.appendChild(time_element) |
---|
| 341 | element.appendChild(date_element) |
---|
| 342 | element.appendChild(state_list_element) |
---|
| 343 | element.appendChild(comp_state_list_element) |
---|
| 344 | bookmark.appendChild(element) |
---|
| 345 | |
---|
| 346 | # Save the file |
---|
| 347 | if doc is None: |
---|
| 348 | fd = open('test000', 'w') |
---|
| 349 | fd.write(newdoc.toprettyxml()) |
---|
| 350 | fd.close() |
---|
| 351 | return None |
---|
| 352 | else: |
---|
| 353 | return newdoc.toprettyxml() |
---|
| 354 | |
---|
| 355 | def fromXML(self, file=None, node=None): |
---|
| 356 | """ |
---|
| 357 | Load invariant states from a file |
---|
| 358 | |
---|
| 359 | : param file: .inv file |
---|
| 360 | : param node: node of a XML document to read from |
---|
| 361 | """ |
---|
| 362 | if file is not None: |
---|
[4a2b054] | 363 | msg = "InvariantSate no longer supports non-CanSAS" |
---|
| 364 | msg += " format for invariant files" |
---|
| 365 | raise RuntimeError, msg |
---|
[4e1c362] | 366 | |
---|
| 367 | if node.get('version')\ |
---|
| 368 | and node.get('version') == '1.0': |
---|
| 369 | |
---|
| 370 | # Get file name |
---|
| 371 | entry = get_content('ns:filename', node) |
---|
| 372 | if entry is not None: |
---|
[b35d3d1] | 373 | file_name = entry.text.strip() |
---|
| 374 | |
---|
[4e1c362] | 375 | # Get time stamp |
---|
| 376 | entry = get_content('ns:timestamp', node) |
---|
| 377 | if entry is not None and entry.get('epoch'): |
---|
| 378 | try: |
---|
| 379 | timestamp = (entry.get('epoch')) |
---|
| 380 | except: |
---|
[4a2b054] | 381 | msg = "InvariantSate.fromXML: Could not read" |
---|
| 382 | msg += " timestamp\n %s" % sys.exc_value |
---|
| 383 | logging.error(msg) |
---|
[4e1c362] | 384 | |
---|
| 385 | # Parse bookmarks |
---|
| 386 | entry_bookmark = get_content('ns:bookmark', node) |
---|
| 387 | |
---|
[4a2b054] | 388 | for ind in range(1, len(entry_bookmark) + 1): |
---|
[4e1c362] | 389 | temp_state = {} |
---|
| 390 | temp_bookmark = {} |
---|
| 391 | entry = get_content('ns:mark_%s' % ind, entry_bookmark) |
---|
| 392 | |
---|
| 393 | if entry is not None: |
---|
[4a2b054] | 394 | time = get_content('ns:time', entry) |
---|
[4e1c362] | 395 | val_time = str(time.text.strip()) |
---|
[4a2b054] | 396 | date = get_content('ns:date', entry) |
---|
[4e1c362] | 397 | val_date = str(date.text.strip()) |
---|
[4a2b054] | 398 | state_entry = get_content('ns:state', entry) |
---|
[4e1c362] | 399 | for item in list: |
---|
| 400 | |
---|
[4a2b054] | 401 | input_field = get_content('ns:%s' % item, state_entry) |
---|
[4e1c362] | 402 | val = str(input_field.text.strip()) |
---|
| 403 | if input_field is not None: |
---|
| 404 | try: |
---|
[4a2b054] | 405 | exec "temp_state['%s'] = %s" % (item, val) |
---|
[4e1c362] | 406 | except: |
---|
[4a2b054] | 407 | exec "temp_state['%s'] = '%s'" % (item, val) |
---|
| 408 | comp_entry = get_content('ns:comp_state', entry) |
---|
[4e1c362] | 409 | |
---|
| 410 | for item in list: |
---|
[4a2b054] | 411 | input_field = get_content('ns:%s' % item, comp_entry) |
---|
[4e1c362] | 412 | val = str(input_field.text.strip()) |
---|
| 413 | if input_field is not None: |
---|
| 414 | try: |
---|
[4a2b054] | 415 | exec "temp_bookmark['%s'] = %s" % (item, val) |
---|
[4e1c362] | 416 | except: |
---|
[4a2b054] | 417 | exec "temp_bookmark['%s'] = '%s'" % (item, val) |
---|
[4e1c362] | 418 | try: |
---|
[4a2b054] | 419 | cmd = "self.bookmark_list[%s] = [val_time," |
---|
| 420 | cmd += "val_date,temp_state,temp_bookmark]" |
---|
| 421 | exec cmd % ind |
---|
[4e1c362] | 422 | except: |
---|
| 423 | raise "missing components of bookmarks..." |
---|
| 424 | # Parse histories |
---|
| 425 | entry_history = get_content('ns:history', node) |
---|
| 426 | |
---|
[4a2b054] | 427 | for ind in range(0, len(entry_history)): |
---|
[4e1c362] | 428 | temp_state = {} |
---|
| 429 | entry = get_content('ns:state_%s' % ind, entry_history) |
---|
| 430 | |
---|
| 431 | if entry is not None: |
---|
| 432 | for item in list: |
---|
| 433 | input_field = get_content('ns:%s' % item, entry ) |
---|
| 434 | val = str(input_field.text.strip()) |
---|
| 435 | |
---|
| 436 | if input_field is not None: |
---|
| 437 | try: |
---|
[4a2b054] | 438 | exec "temp_state['%s'] = %s" % (item, val) |
---|
[4e1c362] | 439 | except: |
---|
[4a2b054] | 440 | exec "temp_state['%s'] = '%s'" % (item, val) |
---|
[4e1c362] | 441 | finally: |
---|
[4a2b054] | 442 | exec "self.state_list['%s'] = temp_state" % ind |
---|
[4e1c362] | 443 | # Parse current state (ie, saved_state) |
---|
| 444 | entry = get_content('ns:state', node) |
---|
| 445 | if entry is not None: |
---|
| 446 | for item in list: |
---|
| 447 | input_field = get_content('ns:%s' % item, entry) |
---|
| 448 | val = str(input_field.text.strip()) |
---|
| 449 | if input_field is not None: |
---|
| 450 | self.set_saved_state(name=item, value=val) |
---|
[b35d3d1] | 451 | self.file = file_name |
---|
| 452 | |
---|
[cb463b4] | 453 | def set_report_string(self): |
---|
| 454 | """ |
---|
| 455 | Get the values (strings) from __str__ for report |
---|
| 456 | """ |
---|
| 457 | strings = self.__str__() |
---|
| 458 | |
---|
| 459 | # default string values |
---|
[4a2b054] | 460 | for num in range (1, 19): |
---|
| 461 | exec "s_%s = 'NA'" % str(num) |
---|
[cb463b4] | 462 | lines = strings.split('\n') |
---|
| 463 | # get all string values from __str__() |
---|
[4a2b054] | 464 | for line in range(0, len(lines)): |
---|
[cb463b4] | 465 | if line == 1: |
---|
| 466 | s_1 = lines[1] |
---|
| 467 | elif line == 2: |
---|
| 468 | s_2 = lines[2] |
---|
| 469 | else: |
---|
| 470 | item = lines[line].split(':') |
---|
| 471 | item[0] = item[0].strip() |
---|
[4a2b054] | 472 | if item[0] == "scale": |
---|
[cb463b4] | 473 | s_3 = item[1] |
---|
| 474 | elif item[0] == "porod constant": |
---|
| 475 | s_4 = item[1] |
---|
| 476 | elif item[0] == "background": |
---|
| 477 | s_5 = item[1] |
---|
| 478 | elif item[0] == "contrast": |
---|
| 479 | s_6 = item[1] |
---|
| 480 | elif item[0] == "Extrapolation": |
---|
| 481 | extra = item[1].split(";") |
---|
| 482 | bool_0 = extra[0].split("=") |
---|
| 483 | bool_1 = extra[1].split("=") |
---|
[5dc6d84] | 484 | s_8 = " " + bool_0[0] + "Q region = " + bool_0[1] |
---|
| 485 | s_7 = " " + bool_1[0] + "Q region = " + bool_1[1] |
---|
[4a2b054] | 486 | elif item[0] == "npts low": |
---|
[cb463b4] | 487 | s_9 = item[1] |
---|
[5dc6d84] | 488 | elif item[0] == "npts high": |
---|
[cb463b4] | 489 | s_10 = item[1] |
---|
| 490 | elif item[0] == "volume fraction": |
---|
[6ca38f3] | 491 | val=item[1].split("+-")[0].strip() |
---|
| 492 | error = item[1].split("+-")[1].strip() |
---|
[4a2b054] | 493 | s_17 = val + " ± " + error |
---|
[cb463b4] | 494 | elif item[0] == "specific surface": |
---|
[4a2b054] | 495 | val = item[1].split("+-")[0].strip() |
---|
[6ca38f3] | 496 | error = item[1].split("+-")[1].strip() |
---|
[4a2b054] | 497 | s_18 = val + " ± " + error |
---|
| 498 | elif item[0].split("(")[0].strip() == "power low": |
---|
[5dc6d84] | 499 | s_11 = item[0]+" ="+item[1] |
---|
| 500 | elif item[0].split("(")[0].strip() == "power high": |
---|
[cb463b4] | 501 | s_12 = item[0]+" ="+item[1] |
---|
[4a2b054] | 502 | elif item[0].split("[")[0].strip() == "Q* from low Q extrapolation": |
---|
[6ca38f3] | 503 | #looks messy but this way the symbols +_ and % work on html |
---|
[4a2b054] | 504 | val = item[1].split("+-")[0].strip() |
---|
[6ca38f3] | 505 | error = item[1].split("+-")[1].strip() |
---|
| 506 | err = error.split("%")[0].strip() |
---|
| 507 | percent = error.split("%")[1].strip() |
---|
[4a2b054] | 508 | s_13 = val + " ± " + err + "%" + percent |
---|
| 509 | elif item[0].split("[")[0].strip() == "Q* from data": |
---|
| 510 | val = item[1].split("+-")[0].strip() |
---|
[6ca38f3] | 511 | error = item[1].split("+-")[1].strip() |
---|
| 512 | err = error.split("%")[0].strip() |
---|
| 513 | percent = error.split("%")[1].strip() |
---|
[4a2b054] | 514 | s_14 = val + " ± " + err + "%" + percent |
---|
| 515 | elif item[0].split("[")[0].strip() == "Q* from high Q extrapolation": |
---|
| 516 | val = item[1].split("+-")[0].strip() |
---|
[6ca38f3] | 517 | error = item[1].split("+-")[1].strip() |
---|
| 518 | err = error.split("%")[0].strip() |
---|
| 519 | percent = error.split("%")[1].strip() |
---|
[4a2b054] | 520 | s_15 = val + " ± " + err + "%" + percent |
---|
| 521 | elif item[0].split("[")[0].strip() == "total Q*": |
---|
| 522 | val = item[1].split("+-")[0].strip() |
---|
[6ca38f3] | 523 | error = item[1].split("+-")[1].strip() |
---|
[4a2b054] | 524 | s_16 = val + " ± " + error |
---|
[cb463b4] | 525 | else: |
---|
| 526 | continue |
---|
| 527 | |
---|
[a94c4e1] | 528 | # make plot image |
---|
| 529 | self.set_plot_state(extra_high=bool_0[1],extra_low=bool_1[1]) |
---|
| 530 | # get ready for report with setting all the html strings |
---|
[4a2b054] | 531 | self.report_str = str(self.template_str) % (s_1, s_2, |
---|
| 532 | s_3, s_4, s_5, s_6, s_7, s_8, |
---|
| 533 | s_9, s_10, s_11, s_12, s_13, s_14, s_15, |
---|
| 534 | s_16, s_17, s_18, self.file, "%s") |
---|
[b281210] | 535 | |
---|
[4e1c362] | 536 | def set_saved_state(self, name, value): |
---|
| 537 | """ |
---|
| 538 | Set the state list |
---|
| 539 | |
---|
| 540 | : param name: name of the state component |
---|
| 541 | : param value: value of the state component |
---|
| 542 | """ |
---|
[4a2b054] | 543 | rb_list = [['power_law_low','guinier'], |
---|
| 544 | ['fit_enable_low','fix_enable_low'], |
---|
| 545 | ['fit_enable_high','fix_enable_high']] |
---|
[4e1c362] | 546 | |
---|
| 547 | try: |
---|
[4a2b054] | 548 | if value == None or value.lstrip().rstrip() == '': |
---|
[4e1c362] | 549 | exec "self.%s = '%s'" % (name, value) |
---|
[4a2b054] | 550 | exec "self.saved_state['%s'] = '%s'" % (name, value) |
---|
[4e1c362] | 551 | else: |
---|
| 552 | exec 'self.%s = %s' % (name, value) |
---|
[4a2b054] | 553 | exec "self.saved_state['%s'] = %s" % (name, value) |
---|
| 554 | # set the count part of radio button clicked |
---|
| 555 | # False for the saved_state |
---|
| 556 | for title, content in rb_list: |
---|
[4e1c362] | 557 | if name == title: |
---|
| 558 | name = content |
---|
| 559 | value = False |
---|
| 560 | elif name == content: |
---|
| 561 | name = title |
---|
| 562 | value = False |
---|
[4a2b054] | 563 | exec "self.saved_state['%s'] = '%s'" % (name, value) |
---|
[4e1c362] | 564 | self.state_num = self.saved_state['state_num'] |
---|
| 565 | except: |
---|
| 566 | pass |
---|
| 567 | |
---|
[4a2b054] | 568 | def set_plot_state(self, extra_high=False, extra_low=False): |
---|
[a94c4e1] | 569 | """ |
---|
| 570 | Build image state that wx.html understand |
---|
| 571 | by plotting, putting it into wx.FileSystem image object |
---|
| 572 | |
---|
[4a2b054] | 573 | : extrap_high,extra_low: low/high extrapolations |
---|
| 574 | are possible extra-plots |
---|
[a94c4e1] | 575 | """ |
---|
| 576 | # some imports |
---|
[5b03122] | 577 | import wx |
---|
[a94c4e1] | 578 | import matplotlib.pyplot as plt |
---|
[f310316] | 579 | from matplotlib.backends.backend_agg import FigureCanvasAgg |
---|
| 580 | |
---|
[a94c4e1] | 581 | #we use simple plot, not plotpanel |
---|
| 582 | #make matlab figure |
---|
| 583 | fig = plt.figure() |
---|
[f310316] | 584 | fig.set_facecolor('w') |
---|
[a94c4e1] | 585 | graph = fig.add_subplot(111) |
---|
[f310316] | 586 | |
---|
[a94c4e1] | 587 | #data plot |
---|
| 588 | graph.errorbar(self.data.x, self.data.y, yerr=self.data.dy, fmt='o') |
---|
| 589 | #low Q extrapolation fit plot |
---|
| 590 | if not extra_low == 'False': |
---|
| 591 | graph.plot(self.theory_lowQ.x,self.theory_lowQ.y) |
---|
| 592 | #high Q extrapolation fit plot |
---|
| 593 | if not extra_high == 'False': |
---|
| 594 | graph.plot(self.theory_highQ.x,self.theory_highQ.y) |
---|
| 595 | graph.set_xscale("log", nonposx='clip') |
---|
| 596 | graph.set_yscale("log", nonposy='clip') |
---|
[f310316] | 597 | graph.set_xlabel('$\\rm{Q}(\\AA^{-1})$', fontsize = 12) |
---|
| 598 | graph.set_ylabel('$\\rm{Intensity}(cm^{-1})$', fontsize = 12) |
---|
| 599 | canvas = FigureCanvasAgg(fig) |
---|
| 600 | #actually make image |
---|
| 601 | canvas.draw() |
---|
| 602 | |
---|
| 603 | #make python.Image object |
---|
| 604 | #size |
---|
[4a2b054] | 605 | w, h = canvas.get_width_height() |
---|
[a94c4e1] | 606 | #convert to wx.Image |
---|
[f310316] | 607 | wximg = wx.EmptyImage(w,h) |
---|
| 608 | #wxim.SetData(img.convert('RGB').tostring() ) |
---|
| 609 | wximg.SetData(canvas.tostring_rgb()) |
---|
[a94c4e1] | 610 | #get the dynamic image for the htmlwindow |
---|
[f310316] | 611 | wximgbmp = wx.BitmapFromImage(wximg) |
---|
[a94c4e1] | 612 | #store the image in wx.FileSystem Object |
---|
| 613 | wx.FileSystem.AddHandler(wx.MemoryFSHandler()) |
---|
| 614 | # use wx.MemoryFSHandler |
---|
| 615 | self.imgRAM = wx.MemoryFSHandler() |
---|
| 616 | #AddFile, image can be retrieved with 'memory:filename' |
---|
[4a2b054] | 617 | self.imgRAM.AddFile('img_inv.png', wximgbmp, wx.BITMAP_TYPE_PNG) |
---|
[a94c4e1] | 618 | |
---|
[f310316] | 619 | self.wximgbmp = 'memory:img_inv.png' |
---|
| 620 | self.image = fig |
---|
[4e1c362] | 621 | |
---|
| 622 | class Reader(CansasReader): |
---|
| 623 | """ |
---|
| 624 | Class to load a .inv invariant file |
---|
| 625 | """ |
---|
| 626 | ## File type |
---|
| 627 | type_name = "Invariant" |
---|
| 628 | |
---|
| 629 | ## Wildcards |
---|
[b35d3d1] | 630 | type = ["Invariant file (*.inv)|*.inv", |
---|
| 631 | "SANSView file (*.svs)|*.svs"] |
---|
[4e1c362] | 632 | ## List of allowed extensions |
---|
[4a2b054] | 633 | ext = ['.inv', '.INV', '.svs', 'SVS'] |
---|
[4e1c362] | 634 | |
---|
| 635 | def __init__(self, call_back, cansas=True): |
---|
| 636 | """ |
---|
| 637 | Initialize the call-back method to be called |
---|
| 638 | after we load a file |
---|
| 639 | |
---|
| 640 | : param call_back: call-back method |
---|
| 641 | : param cansas: True = files will be written/read in CanSAS format |
---|
| 642 | False = write CanSAS format |
---|
| 643 | """ |
---|
| 644 | ## Call back method to be executed after a file is read |
---|
| 645 | self.call_back = call_back |
---|
| 646 | ## CanSAS format flag |
---|
| 647 | self.cansas = cansas |
---|
[75fbd17] | 648 | self.state = None |
---|
[4e1c362] | 649 | |
---|
| 650 | def read(self, path): |
---|
| 651 | """ |
---|
| 652 | Load a new invariant state from file |
---|
| 653 | |
---|
| 654 | : param path: file path |
---|
| 655 | : return: None |
---|
| 656 | """ |
---|
[4a2b054] | 657 | if self.cansas == True: |
---|
[4e1c362] | 658 | return self._read_cansas(path) |
---|
| 659 | else: |
---|
| 660 | return self._read_standalone(path) |
---|
| 661 | |
---|
| 662 | def _read_standalone(self, path): |
---|
| 663 | """ |
---|
| 664 | Load a new invariant state from file. |
---|
| 665 | The invariant node is assumed to be the top element. |
---|
| 666 | |
---|
| 667 | : param path: file path |
---|
| 668 | : return: None |
---|
| 669 | """ |
---|
| 670 | # Read the new state from file |
---|
| 671 | state = InvariantState() |
---|
| 672 | |
---|
| 673 | state.fromXML(file=path) |
---|
| 674 | |
---|
| 675 | # Call back to post the new state |
---|
| 676 | self.call_back(state) |
---|
| 677 | return None |
---|
| 678 | |
---|
| 679 | def _parse_state(self, entry): |
---|
| 680 | """ |
---|
| 681 | Read an invariant result from an XML node |
---|
| 682 | |
---|
| 683 | : param entry: XML node to read from |
---|
| 684 | : return: InvariantState object |
---|
| 685 | """ |
---|
[b35d3d1] | 686 | state = None |
---|
[4e1c362] | 687 | # Locate the invariant node |
---|
| 688 | try: |
---|
[4a2b054] | 689 | nodes = entry.xpath('ns:%s' % INVNODE_NAME, |
---|
| 690 | namespaces={'ns': CANSAS_NS}) |
---|
[b35d3d1] | 691 | # Create an empty state |
---|
[4a2b054] | 692 | if nodes != []: |
---|
[b35d3d1] | 693 | state = InvariantState() |
---|
| 694 | state.fromXML(node=nodes[0]) |
---|
[4e1c362] | 695 | except: |
---|
[4a2b054] | 696 | msg = "XML document does not contain invariant" |
---|
| 697 | msg += " information.\n %s" % sys.exc_value |
---|
| 698 | logging.info(msg) |
---|
[4e1c362] | 699 | return state |
---|
| 700 | |
---|
| 701 | def _read_cansas(self, path): |
---|
| 702 | """ |
---|
| 703 | Load data and invariant information from a CanSAS XML file. |
---|
| 704 | |
---|
| 705 | : param path: file path |
---|
| 706 | : return: Data1D object if a single SASentry was found, |
---|
| 707 | or a list of Data1D objects if multiple entries were found, |
---|
| 708 | or None of nothing was found |
---|
| 709 | : raise RuntimeError: when the file can't be opened |
---|
| 710 | : raise ValueError: when the length of the data vectors are inconsistent |
---|
| 711 | """ |
---|
| 712 | output = [] |
---|
| 713 | if os.path.isfile(path): |
---|
| 714 | basename = os.path.basename(path) |
---|
| 715 | root, extension = os.path.splitext(basename) |
---|
| 716 | |
---|
| 717 | if extension.lower() in self.ext or \ |
---|
| 718 | extension.lower() == '.xml': |
---|
| 719 | tree = etree.parse(path, parser=etree.ETCompatXMLParser()) |
---|
| 720 | |
---|
| 721 | # Check the format version number |
---|
[4a2b054] | 722 | # Specifying the namespace will take care of |
---|
| 723 | # the file format version |
---|
[4e1c362] | 724 | root = tree.getroot() |
---|
| 725 | |
---|
[4a2b054] | 726 | entry_list = root.xpath('/ns:SASroot/ns:SASentry', |
---|
| 727 | namespaces={'ns': CANSAS_NS}) |
---|
[4e1c362] | 728 | |
---|
| 729 | for entry in entry_list: |
---|
| 730 | |
---|
| 731 | sas_entry = self._parse_entry(entry) |
---|
| 732 | invstate = self._parse_state(entry) |
---|
[b35d3d1] | 733 | |
---|
| 734 | #invstate could be None when .svs file is loaded |
---|
| 735 | #in this case, skip appending to output |
---|
| 736 | if invstate != None: |
---|
| 737 | sas_entry.meta_data['invstate'] = invstate |
---|
| 738 | sas_entry.filename = invstate.file |
---|
| 739 | output.append(sas_entry) |
---|
[4e1c362] | 740 | else: |
---|
| 741 | raise RuntimeError, "%s is not a file" % path |
---|
| 742 | |
---|
| 743 | # Return output consistent with the loader's api |
---|
[4a2b054] | 744 | if len(output) == 0: |
---|
[4e1c362] | 745 | return None |
---|
[4a2b054] | 746 | elif len(output) == 1: |
---|
[4e1c362] | 747 | # Call back to post the new state |
---|
[75fbd17] | 748 | self.state = output[0].meta_data['invstate'] |
---|
[cb69775] | 749 | self.call_back(state=output[0].meta_data['invstate'], |
---|
| 750 | datainfo = output[0]) |
---|
[4e1c362] | 751 | return output[0] |
---|
| 752 | else: |
---|
| 753 | return output |
---|
| 754 | |
---|
[75fbd17] | 755 | def get_state(self): |
---|
| 756 | return self.state |
---|
[4e1c362] | 757 | |
---|
| 758 | def write(self, filename, datainfo=None, invstate=None): |
---|
| 759 | """ |
---|
| 760 | Write the content of a Data1D as a CanSAS XML file |
---|
| 761 | |
---|
| 762 | : param filename: name of the file to write |
---|
| 763 | : param datainfo: Data1D object |
---|
| 764 | : param invstate: InvariantState object |
---|
| 765 | """ |
---|
| 766 | # Sanity check |
---|
| 767 | if self.cansas == True: |
---|
[b35d3d1] | 768 | doc = self.write_toXML(datainfo,invstate) |
---|
[4e1c362] | 769 | # Write the XML document |
---|
| 770 | fd = open(filename, 'w') |
---|
| 771 | fd.write(doc.toprettyxml()) |
---|
| 772 | fd.close() |
---|
| 773 | else: |
---|
| 774 | invstate.toXML(file=filename) |
---|
| 775 | |
---|
[b35d3d1] | 776 | def write_toXML(self, datainfo=None, state=None): |
---|
| 777 | """ |
---|
| 778 | Write toXML, a helper for write() |
---|
| 779 | |
---|
| 780 | : return: xml doc |
---|
| 781 | """ |
---|
| 782 | if datainfo is None: |
---|
| 783 | datainfo = DataLoader.data_info.Data1D(x=[], y=[]) |
---|
| 784 | elif not issubclass(datainfo.__class__, DataLoader.data_info.Data1D): |
---|
[4a2b054] | 785 | msg = "The cansas writer expects a Data1D" |
---|
| 786 | msg += " instance: %s" % str(datainfo.__class__.__name__) |
---|
| 787 | raise RuntimeError, msg |
---|
[b35d3d1] | 788 | #make sure title and data run is filled up. |
---|
[4a2b054] | 789 | if datainfo.title == None or datainfo.title == '': |
---|
| 790 | datainfo.title = datainfo.name |
---|
| 791 | if datainfo.run_name == None or datainfo.run_name == {}: |
---|
[b35d3d1] | 792 | datainfo.run = [str(datainfo.name)] |
---|
| 793 | datainfo.run_name[0] = datainfo.name |
---|
| 794 | # Create basic XML document |
---|
| 795 | doc, sasentry = self._to_xml_doc(datainfo) |
---|
| 796 | # Add the invariant information to the XML document |
---|
| 797 | if state is not None: |
---|
[5069a18] | 798 | state.toXML(datainfo.name,doc=doc, entry_node=sasentry) |
---|
[4a2b054] | 799 | return doc |
---|
| 800 | |
---|