Changeset 78a205a in sasview for src/sas/perspectives/invariant/invariant_state.py
- Timestamp:
- Mar 5, 2015 10:29:42 AM (9 years ago)
- Branches:
- master, ESS_GUI, ESS_GUI_Docs, ESS_GUI_batch_fitting, ESS_GUI_bumps_abstraction, ESS_GUI_iss1116, ESS_GUI_iss879, ESS_GUI_iss959, ESS_GUI_opencl, ESS_GUI_ordering, ESS_GUI_sync_sascalc, costrafo411, magnetic_scatt, release-4.1.1, release-4.1.2, release-4.2.2, release_4.0.1, ticket-1009, ticket-1094-headless, ticket-1242-2d-resolution, ticket-1243, ticket-1249, ticket885, unittest-saveload
- Children:
- dca6188
- Parents:
- 74f419d
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
src/sas/perspectives/invariant/invariant_state.py
rb9a5f0e r78a205a 1 1 """ 2 State class for the invariant UI 2 3 """ 3 4 4 # import time5 # import time 5 6 import os 6 7 import sys … … 8 9 import copy 9 10 import sas.dataloader 10 # from xml.dom.minidom import parse11 # from xml.dom.minidom import parse 11 12 from lxml import etree 12 13 from sas.dataloader.readers.cansas_reader import Reader as CansasReader … … 20 21 21 22 # 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':''}47 # list of states: This list will be filled as panel 23 DEFAULT_STATE = {'file': 'None', 24 'compute_num':0, 25 'state_num':0, 26 'is_time_machine':False, 27 'background_tcl':0.0, 28 'scale_tcl':1.0, 29 'contrast_tcl':1.0, 30 'porod_constant_tcl':'', 31 'npts_low_tcl':10, 32 'npts_high_tcl':10, 33 'power_high_tcl':4.0, 34 'power_low_tcl': 4.0, 35 'enable_high_cbox':False, 36 'enable_low_cbox':False, 37 'guinier': True, 38 'power_law_high': False, 39 'power_law_low': False, 40 'fit_enable_high': False, 41 'fit_enable_low': False, 42 'fix_enable_high':True, 43 'fix_enable_low':True, 44 'volume_tcl':'', 45 'volume_err_tcl':'', 46 'surface_tcl':'', 47 'surface_err_tcl':''} 48 # list of states: This list will be filled as panel 48 49 # init and the number of states increases 49 50 state_list = {} 50 51 bookmark_list = {} 51 # list of input parameters (will be filled up on panel init) used by __str__ 52 # list of input parameters (will be filled up on panel init) used by __str__ 52 53 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}60 # list of output parameters (order sensitive) used by __str__ 61 output_list = [["qstar_low", 62 ["qstar_low_err", 63 ["qstar_low_percent", 64 ["qstar", 65 ["qstar_err", 66 ["qstar_percent", 67 ["qstar_high", 68 ["qstar_high_err", 54 'scale_tcl':0, 55 'contrast_tcl':0, 56 'porod_constant_tcl':'', 57 'npts_low_tcl':0, 58 'npts_high_tcl':0, 59 'power_high_tcl':0, 60 'power_low_tcl': 0} 61 # list of output parameters (order sensitive) used by __str__ 62 output_list = [["qstar_low", "Q* from low Q extrapolation [1/(cm*A)]"], 63 ["qstar_low_err", "dQ* from low Q extrapolation"], 64 ["qstar_low_percent", "Q* percent from low Q extrapolation"], 65 ["qstar", "Q* from data [1/(cm*A)]"], 66 ["qstar_err", "dQ* from data"], 67 ["qstar_percent", "Q* percent from data"], 68 ["qstar_high", "Q* from high Q extrapolation [1/(cm*A)]"], 69 ["qstar_high_err", "dQ* from high Q extrapolation"], 69 70 ["qstar_high_percent", "Q* percent from low Q extrapolation"], 70 ["qstar_total", 71 ["qstar_total_err", 72 ["volume", 73 ["volume_err", 74 ["surface", 75 ["surface_err", 76 77 71 ["qstar_total", "total Q* [1/(cm*A)]"], 72 ["qstar_total_err", "total dQ*"], 73 ["volume", "volume fraction"], 74 ["volume_err", "volume fraction error"], 75 ["surface", "specific surface"], 76 ["surface_err", "specific surface error"]] 77 78 78 79 79 80 class InvariantState(object): … … 85 86 Default values 86 87 """ 87 # Input 88 self.file 88 # Input 89 self.file = None 89 90 self.data = Data1D(x=[], y=[], dx=None, dy=None) 90 self.theory_lowQ = 91 self.theory_lowQ = Data1D(x=[], y=[], dy=None) 91 92 self.theory_lowQ.symbol = GUIFRAME_ID.CURVE_SYMBOL_NUM 92 93 self.theory_highQ = Data1D(x=[], y=[], dy=None) 93 94 self.theory_highQ.symbol = GUIFRAME_ID.CURVE_SYMBOL_NUM 94 # self.is_time_machine = False95 self.saved_state = list95 # self.is_time_machine = False 96 self.saved_state = DEFAULT_STATE 96 97 self.state_list = state_list 97 98 self.bookmark_list = bookmark_list 98 99 self.input_list = input_list 99 100 self.output_list = output_list 100 101 101 102 self.compute_num = 0 102 103 self.state_num = 0 103 104 self.timestamp = ('00:00:00', '00/00/0000') 104 105 self.container = None 105 # plot image106 # plot image 106 107 self.wximbmp = None 107 108 # report_html strings 108 109 import sas.perspectives.invariant as invariant 109 110 path = invariant.get_data_path(media='media') 110 path_report_html = os.path.join(path, "report_template.html")111 html_template = open(path_report_html, "r")111 path_report_html = os.path.join(path, "report_template.html") 112 html_template = open(path_report_html, "r") 112 113 self.template_str = html_template.read() 113 114 self.report_str = self.template_str 114 # self.report_str_save = None115 # self.report_str_save = None 115 116 html_template.close() 116 117 117 118 def __str__(self): 118 119 """ 119 120 Pretty print 120 121 121 122 : return: string representing the state 122 123 """ … … 132 133 state += "State No.: %d \n" % state_num 133 134 state += "\n=== Inputs ===\n" 134 135 135 136 # text ctl general inputs ( excluding extrapolation text ctl) 136 for key, value in self.input_list.iteritems(): 137 for key, value in self.input_list.iteritems(): 137 138 if value == '': 138 139 continue 139 key_split = key.split('_') 140 max_ind = len(key_split) -1141 if key_split[max_ind] == 'tcl': 140 key_split = key.split('_') 141 max_ind = len(key_split) - 1 142 if key_split[max_ind] == 'tcl': 142 143 name = "" 143 144 if key_split[1] == 'low' or key_split[1] == 'high': … … 146 147 name += " %s" % key_split[ind] 147 148 state += "%s: %s\n" % (name.lstrip(" "), value) 148 149 # other input parameters 149 150 # other input parameters 150 151 extra_lo = compute_state['enable_low_cbox'] 151 152 if compute_state['enable_low_cbox']: … … 157 158 if compute_state['enable_high_cbox']: 158 159 extra_hi = 'Power law' 159 state += "\nExtrapolation: High=%s; Low=%s\n" % (extra_hi, extra_lo)160 state += "\nExtrapolation: High=%s; Low=%s\n" % (extra_hi, extra_lo) 160 161 low_off = False 161 162 high_off = False 162 for key, value in self.input_list.iteritems(): 163 key_split = key.split('_') 164 max_ind = len(key_split) - 1 165 if key_split[max_ind] == 'tcl': 166 name = "" 163 for key, value in self.input_list.iteritems(): 164 key_split = key.split('_') 165 max_ind = len(key_split) - 1 166 if key_split[max_ind] == 'tcl': 167 name = "" 167 168 # check each buttons whether or not ON or OFF 168 169 if key_split[1] == 'low' or key_split[1] == 'high': 169 170 if not compute_state['enable_low_cbox'] and \ 170 key_split[max_ind -1] == 'low':171 key_split[max_ind - 1] == 'low': 171 172 low_off = True 172 continue 173 continue 173 174 elif not compute_state['enable_high_cbox'] and \ 174 key_split[max_ind -1] == 'high':175 key_split[max_ind - 1] == 'high': 175 176 high_off = True 176 177 continue 177 178 elif extra_lo == 'Guinier' and key_split[0] == 'power' and \ 178 key_split[max_ind -1] == 'low':179 key_split[max_ind - 1] == 'low': 179 180 continue 180 181 for ind in range(0, max_ind): 181 182 name += " %s" % key_split[ind] 182 183 name = name.lstrip(" ") 183 if name == "power low" 184 if name == "power low": 184 185 if compute_state['fix_enable_low']: 185 186 name += ' (Fixed)' 186 187 else: 187 188 name += ' (Fitted)' 188 if name == "power high" 189 if name == "power high": 189 190 if compute_state['fix_enable_high']: 190 191 name += ' (Fixed)' … … 195 196 state += "\n=== Outputs ===" 196 197 for item in output_list: 197 item_split = item[0].split('_') 198 item_split = item[0].split('_') 198 199 # Exclude the extrapolation that turned off 199 200 if len(item_split) > 1: … … 204 205 max_ind = len(item_split) - 1 205 206 value = None 206 try:207 if hasattr(self.container, item[0]): 207 208 # Q* outputs 208 exec "value = self.container.%s\n" % item[0]209 e xcept:209 value = getattr(self.container, item[0]) 210 else: 210 211 # other outputs than Q* 211 212 name = item[0] + "_tcl" 212 213 if name in self.saved_state.keys(): 213 exec "value = self.saved_state['%s']" % name214 215 # Exclude the outputs w/'' 214 value = self.saved_state[name] 215 216 # Exclude the outputs w/'' 216 217 if value == '': 217 continue 218 continue 218 219 # Error outputs 219 220 if item_split[max_ind] == 'err': … … 221 222 # Percentage outputs 222 223 elif item_split[max_ind] == 'percent': 223 try: 224 value = float(value) * 100 225 except: 226 pass 224 value = float(value) * 100 227 225 state += "(%s %s)" % (format_number(value), '%') 228 226 # Outputs 229 227 else: 230 state += "\n%s: %s " % (item[1], 231 format_number(value, high=True))228 state += "\n%s: %s " % (item[1], 229 format_number(value, high=True)) 232 230 # Include warning msg 233 231 if self.container is not None: … … 244 242 """ 245 243 Writes the state of the InversionControl panel to file, as XML. 246 244 247 245 Compatible with standalone writing, or appending to an 248 246 already existing XML document. In that case, the XML document 249 is required. An optional entry node in the XML document 247 is required. An optional entry node in the XML document 250 248 may also be given. 251 249 252 250 : param file: file to write to 253 251 : param doc: XML document object [optional] 254 : param entry_node: XML node within the XMLdocument at which we will append the data [optional]252 : param entry_node: XML node within the document at which we will append the data [optional] 255 253 """ 256 254 # TODO: Get this to work … … 261 259 if doc is None: 262 260 impl = getDOMImplementation() 263 264 doc_type = impl.createDocumentType(INVNODE_NAME, "1.0", "1.0") 265 261 262 doc_type = impl.createDocumentType(INVNODE_NAME, "1.0", "1.0") 263 266 264 newdoc = impl.createDocument(None, INVNODE_NAME, doc_type) 267 265 top_element = newdoc.documentElement … … 274 272 else: 275 273 entry_node.appendChild(top_element) 276 274 277 275 attr = newdoc.createAttribute("version") 278 276 attr.nodeValue = '1.0' 279 277 top_element.setAttributeNode(attr) 280 278 281 279 # File name 282 280 element = newdoc.createElement("filename") … … 286 284 element.appendChild(newdoc.createTextNode(str(file))) 287 285 top_element.appendChild(element) 288 286 289 287 element = newdoc.createElement("timestamp") 290 288 element.appendChild(newdoc.createTextNode(time.ctime(timestamp))) … … 293 291 element.setAttributeNode(attr) 294 292 top_element.appendChild(element) 295 293 296 294 # Current state 297 295 state = newdoc.createElement("state") 298 296 top_element.appendChild(state) 299 300 for name, value in self.saved_state.iteritems():297 298 for name, value in self.saved_state.iteritems(): 301 299 element = newdoc.createElement(str(name)) 302 300 element.appendChild(newdoc.createTextNode(str(value))) 303 301 state.appendChild(element) 304 302 305 303 # State history list 306 304 history = newdoc.createElement("history") 307 305 top_element.appendChild(history) 308 306 309 307 for name, value in self.state_list.iteritems(): 310 308 history_element = newdoc.createElement('state_' + str(name)) 311 for state_name, state_value in value.iteritems():309 for state_name, state_value in value.iteritems(): 312 310 state_element = newdoc.createElement(str(state_name)) 313 311 child = newdoc.createTextNode(str(state_value)) 314 312 state_element.appendChild(child) 315 313 history_element.appendChild(state_element) 316 # history_element.appendChild(state_list_element)314 # history_element.appendChild(state_list_element) 317 315 history.appendChild(history_element) 318 316 319 317 # Bookmarks bookmark_list[self.bookmark_num] = [\ 320 # my_time,date,state,comp_state]318 # my_time,date,state,comp_state] 321 319 bookmark = newdoc.createElement("bookmark") 322 320 top_element.appendChild(bookmark) 323 item_list = ['time', 'date','state','comp_state']321 item_list = ['time', 'date', 'state', 'comp_state'] 324 322 for name, value_list in self.bookmark_list.iteritems(): 325 element = newdoc.createElement('mark_' + str(name))326 _, date,state,comp_state = value_list323 element = newdoc.createElement('mark_' + str(name)) 324 _, date, state, comp_state = value_list 327 325 time_element = newdoc.createElement('time') 328 326 time_element.appendChild(newdoc.createTextNode(str(value_list[0]))) … … 354 352 else: 355 353 return newdoc 356 354 357 355 def fromXML(self, file=None, node=None): 358 356 """ 359 357 Load invariant states from a file 360 358 361 359 : param file: .inv file 362 : param node: node of a XML document to read from 360 : param node: node of a XML document to read from 363 361 """ 364 362 if file is not None: … … 366 364 msg += " format for invariant files" 367 365 raise RuntimeError, msg 368 366 369 367 if node.get('version')\ 370 368 and node.get('version') == '1.0': … … 384 382 msg += " timestamp\n %s" % sys.exc_value 385 383 logging.error(msg) 386 384 387 385 # Parse bookmarks 388 386 entry_bookmark = get_content('ns:bookmark', node) … … 391 389 temp_state = {} 392 390 temp_bookmark = {} 393 entry = get_content('ns:mark_%s' % ind, entry_bookmark) 394 391 entry = get_content('ns:mark_%s' % ind, entry_bookmark) 392 395 393 if entry is not None: 396 394 my_time = get_content('ns:time', entry) … … 399 397 val_date = str(date.text.strip()) 400 398 state_entry = get_content('ns:state', entry) 401 for item in list: 402 399 for item in DEFAULT_STATE: 403 400 input_field = get_content('ns:%s' % item, state_entry) 404 401 val = str(input_field.text.strip()) 405 402 if input_field is not None: 406 try: 407 exec "temp_state['%s'] = %s" % (item, val) 408 except: 409 exec "temp_state['%s'] = '%s'" % (item, val) 403 temp_state[item] = val 410 404 comp_entry = get_content('ns:comp_state', entry) 411 412 for item in list:405 406 for item in DEFAULT_STATE: 413 407 input_field = get_content('ns:%s' % item, comp_entry) 414 408 val = str(input_field.text.strip()) 415 409 if input_field is not None: 416 try: 417 exec "temp_bookmark['%s'] = %s" % (item, val) 418 except: 419 exec "temp_bookmark['%s'] = '%s'" % (item, val) 410 temp_bookmark[item] = val 420 411 try: 421 cmd = "self.bookmark_list[%s] = [val_time," 422 cmd += "val_date,temp_state,temp_bookmark]" 423 exec cmd % ind 412 self.bookmark_list[ind] = [val_time, val_date, temp_state, temp_bookmark] 424 413 except: 425 414 raise "missing components of bookmarks..." … … 429 418 for ind in range(0, len(entry_history)): 430 419 temp_state = {} 431 entry = get_content('ns:state_%s' % ind, entry_history) 420 entry = get_content('ns:state_%s' % ind, entry_history) 432 421 433 422 if entry is not None: 434 for item in list:435 input_field = get_content('ns:%s' % item, entry 423 for item in DEFAULT_STATE: 424 input_field = get_content('ns:%s' % item, entry) 436 425 val = str(input_field.text.strip()) 437 438 426 if input_field is not None: 439 try: 440 exec "temp_state['%s'] = %s" % (item, val) 441 except: 442 exec "temp_state['%s'] = '%s'" % (item, val) 443 finally: 444 exec "self.state_list['%s'] = temp_state" % ind 427 temp_state[item] = val 428 self.state_list[ind] = temp_state 429 445 430 # Parse current state (ie, saved_state) 446 entry = get_content('ns:state', node) 431 entry = get_content('ns:state', node) 447 432 if entry is not None: 448 for item in list:433 for item in DEFAULT_STATE: 449 434 input_field = get_content('ns:%s' % item, entry) 450 435 val = str(input_field.text.strip()) … … 452 437 self.set_saved_state(name=item, value=val) 453 438 self.file = file_name 454 439 455 440 def set_report_string(self): 456 441 """ 457 Get the values (strings) from __str__ for report 442 Get the values (strings) from __str__ for report 458 443 """ 459 444 strings = self.__str__() 460 445 461 446 # default string values 462 for num in range 447 for num in range(1, 19): 463 448 exec "s_%s = 'NA'" % str(num) 464 449 lines = strings.split('\n') … … 491 476 s_10 = item[1] 492 477 elif item[0] == "volume fraction": 493 val =item[1].split("+-")[0].strip()478 val = item[1].split("+-")[0].strip() 494 479 error = item[1].split("+-")[1].strip() 495 480 s_17 = val + " ± " + error … … 499 484 s_18 = val + " ± " + error 500 485 elif item[0].split("(")[0].strip() == "power low": 501 s_11 = item[0] +" ="+item[1]486 s_11 = item[0] + " =" + item[1] 502 487 elif item[0].split("(")[0].strip() == "power high": 503 s_12 = item[0] +" ="+item[1]488 s_12 = item[0] + " =" + item[1] 504 489 elif item[0].split("[")[0].strip() == "Q* from low Q extrapolation": 505 # looks messy but this way the symbols +_ and % work on html490 # looks messy but this way the symbols +_ and % work on html 506 491 val = item[1].split("+-")[0].strip() 507 492 error = item[1].split("+-")[1].strip() … … 532 517 533 518 # make plot image 534 self.set_plot_state(extra_high=bool_0[1], extra_low=bool_1[1])519 self.set_plot_state(extra_high=bool_0[1], extra_low=bool_1[1]) 535 520 # get ready for report with setting all the html strings 536 521 self.report_str = str(self.template_str) % (s_1, s_2, 537 s_3, s_4, s_5, s_6, s_7, s_8,538 s_9, s_10, s_11, s_12, s_13, s_14, s_15,539 s_16, s_17, s_18, file_name, "%s")522 s_3, s_4, s_5, s_6, s_7, s_8, 523 s_9, s_10, s_11, s_12, s_13, s_14, s_15, 524 s_16, s_17, s_18, file_name, "%s") 540 525 541 526 def _check_html_format(self, name): … … 545 530 if name.count('%'): 546 531 name = name.replace('%', '%') 547 532 548 533 return name 549 534 550 535 def set_saved_state(self, name, value): 551 536 """ 552 Set the state list 553 537 Set the state list 538 554 539 : param name: name of the state component 555 540 : param value: value of the state component 556 541 """ 557 rb_list = [['power_law_low','guinier'], 558 ['fit_enable_low','fix_enable_low'], 559 ['fit_enable_high','fix_enable_high']] 560 561 try: 562 if value == None or value.lstrip().rstrip() == '': 563 exec "self.%s = '%s'" % (name, value) 564 exec "self.saved_state['%s'] = '%s'" % (name, value) 565 else: 566 exec 'self.%s = %s' % (name, value) 567 exec "self.saved_state['%s'] = %s" % (name, value) 568 # set the count part of radio button clicked 569 # False for the saved_state 570 for title, content in rb_list: 571 if name == title: 572 name = content 573 value = False 574 elif name == content: 575 name = title 576 value = False 577 exec "self.saved_state['%s'] = '%s'" % (name, value) 578 self.state_num = self.saved_state['state_num'] 579 except: 580 pass 542 rb_list = [['power_law_low', 'guinier'], 543 ['fit_enable_low', 'fix_enable_low'], 544 ['fit_enable_high', 'fix_enable_high']] 545 546 self.name = value 547 self.saved_state[name] = value 548 # set the count part of radio button clicked 549 # False for the saved_state 550 for title, content in rb_list: 551 if name == title: 552 name = content 553 value = False 554 elif name == content: 555 name = title 556 value = False 557 self.saved_state[name] = value 558 self.state_num = self.saved_state['state_num'] 581 559 582 560 def set_plot_state(self, extra_high=False, extra_low=False): … … 584 562 Build image state that wx.html understand 585 563 by plotting, putting it into wx.FileSystem image object 586 564 587 565 : extrap_high,extra_low: low/high extrapolations 588 566 are possible extra-plots … … 593 571 from matplotlib.backends.backend_agg import FigureCanvasAgg 594 572 595 # we use simple plot, not plotpanel596 # make matlab figure573 # we use simple plot, not plotpanel 574 # make matlab figure 597 575 fig = plt.figure() 598 576 fig.set_facecolor('w') 599 577 graph = fig.add_subplot(111) 600 578 601 # data plot579 # data plot 602 580 graph.errorbar(self.data.x, self.data.y, yerr=self.data.dy, fmt='o') 603 # low Q extrapolation fit plot581 # low Q extrapolation fit plot 604 582 if not extra_low == 'False': 605 graph.plot(self.theory_lowQ.x, self.theory_lowQ.y)606 # high Q extrapolation fit plot583 graph.plot(self.theory_lowQ.x, self.theory_lowQ.y) 584 # high Q extrapolation fit plot 607 585 if not extra_high == 'False': 608 graph.plot(self.theory_highQ.x, self.theory_highQ.y)586 graph.plot(self.theory_highQ.x, self.theory_highQ.y) 609 587 graph.set_xscale("log", nonposx='clip') 610 588 graph.set_yscale("log", nonposy='clip') 611 graph.set_xlabel('$\\rm{Q}(\\AA^{-1})$', fontsize =12)612 graph.set_ylabel('$\\rm{Intensity}(cm^{-1})$', fontsize =12)589 graph.set_xlabel('$\\rm{Q}(\\AA^{-1})$', fontsize=12) 590 graph.set_ylabel('$\\rm{Intensity}(cm^{-1})$', fontsize=12) 613 591 canvas = FigureCanvasAgg(fig) 614 # actually make image592 # actually make image 615 593 canvas.draw() 616 617 # make python.Image object618 # size594 595 # make python.Image object 596 # size 619 597 w, h = canvas.get_width_height() 620 # convert to wx.Image621 wximg = wx.EmptyImage(w, h)622 # wxim.SetData(img.convert('RGB').tostring() )623 wximg.SetData(canvas.tostring_rgb()) 624 # get the dynamic image for the htmlwindow598 # convert to wx.Image 599 wximg = wx.EmptyImage(w, h) 600 # wxim.SetData(img.convert('RGB').tostring() ) 601 wximg.SetData(canvas.tostring_rgb()) 602 # get the dynamic image for the htmlwindow 625 603 wximgbmp = wx.BitmapFromImage(wximg) 626 # store the image in wx.FileSystem Object604 # store the image in wx.FileSystem Object 627 605 wx.FileSystem.AddHandler(wx.MemoryFSHandler()) 628 606 # use wx.MemoryFSHandler 629 607 self.imgRAM = wx.MemoryFSHandler() 630 # AddFile, image can be retrieved with 'memory:filename'608 # AddFile, image can be retrieved with 'memory:filename' 631 609 self.imgRAM.AddFile('img_inv.png', wximgbmp, wx.BITMAP_TYPE_PNG) 632 610 633 611 self.wximgbmp = 'memory:img_inv.png' 634 612 self.image = fig … … 638 616 Class to load a .inv invariant file 639 617 """ 640 # # File type618 # # File type 641 619 type_name = "Invariant" 642 643 # # Wildcards620 621 # # Wildcards 644 622 type = ["Invariant file (*.inv)|*.inv", 645 623 "SASView file (*.svs)|*.svs"] 646 # # List of allowed extensions647 ext = ['.inv', '.INV', '.svs', 'SVS'] 648 624 # # List of allowed extensions 625 ext = ['.inv', '.INV', '.svs', 'SVS'] 626 649 627 def __init__(self, call_back, cansas=True): 650 628 """ 651 629 Initialize the call-back method to be called 652 630 after we load a file 653 631 654 632 : param call_back: call-back method 655 633 : param cansas: True = files will be written/read in CanSAS format 656 False = write CanSAS format 657 """ 658 # # Call back method to be executed after a file is read634 False = write CanSAS format 635 """ 636 # # Call back method to be executed after a file is read 659 637 self.call_back = call_back 660 # # CanSAS format flag638 # # CanSAS format flag 661 639 self.cansas = cansas 662 640 self.state = None 663 641 664 642 def read(self, path): 665 """ 643 """ 666 644 Load a new invariant state from file 667 645 668 646 : param path: file path 669 647 : return: None … … 673 651 else: 674 652 return self._read_standalone(path) 675 653 676 654 def _read_standalone(self, path): 677 """ 655 """ 678 656 Load a new invariant state from file. 679 657 The invariant node is assumed to be the top element. 680 658 681 659 : param path: file path 682 660 : return: None … … 686 664 687 665 state.fromXML(file=path) 688 666 689 667 # Call back to post the new state 690 668 self.call_back(state) 691 669 return None 692 670 693 671 def _parse_state(self, entry): 694 672 """ 695 673 Read an invariant result from an XML node 696 697 : param entry: XML node to read from 674 675 : param entry: XML node to read from 698 676 : return: InvariantState object 699 677 """ … … 710 688 msg = "XML document does not contain invariant" 711 689 msg += " information.\n %s" % sys.exc_value 712 logging.info(msg) 690 logging.info(msg) 713 691 return state 714 692 715 693 def _read_cansas(self, path): 716 """ 694 """ 717 695 Load data and invariant information from a CanSAS XML file. 718 696 719 697 : param path: file path 720 : return: Data1D object if a single SASentry was found, 698 : return: Data1D object if a single SASentry was found, 721 699 or a list of Data1D objects if multiple entries were found, 722 700 or None of nothing was found … … 726 704 output = [] 727 705 if os.path.isfile(path): 728 basename 706 basename = os.path.basename(path) 729 707 root, extension = os.path.splitext(basename) 730 708 731 709 if extension.lower() in self.ext or \ 732 710 extension.lower() == '.xml': 733 711 tree = etree.parse(path, parser=etree.ETCompatXMLParser()) 734 712 735 713 # Check the format version number 736 # Specifying the namespace will take care of 737 # the file format version 714 # Specifying the namespace will take care of 715 # the file format version 738 716 root = tree.getroot() 739 717 740 718 entry_list = root.xpath('/ns:SASroot/ns:SASentry', 741 719 namespaces={'ns': CANSAS_NS}) 742 720 743 721 for entry in entry_list: 744 722 745 723 sas_entry, _ = self._parse_entry(entry) 746 724 invstate = self._parse_state(entry) 747 748 # invstate could be None when .svs file is loaded749 # in this case, skip appending to output725 726 # invstate could be None when .svs file is loaded 727 # in this case, skip appending to output 750 728 if invstate != None: 751 729 sas_entry.meta_data['invstate'] = invstate … … 762 740 self.state = output[0].meta_data['invstate'] 763 741 self.call_back(state=output[0].meta_data['invstate'], 764 datainfo =output[0])742 datainfo=output[0]) 765 743 return output[0] 766 744 else: 767 return output 768 745 return output 746 769 747 def get_state(self): 770 748 return self.state 771 749 772 750 def write(self, filename, datainfo=None, invstate=None): 773 751 """ 774 752 Write the content of a Data1D as a CanSAS XML file 775 753 776 754 : param filename: name of the file to write 777 755 : param datainfo: Data1D object … … 780 758 # Sanity check 781 759 if self.cansas == True: 782 doc = self.write_toXML(datainfo, invstate)760 doc = self.write_toXML(datainfo, invstate) 783 761 # Write the XML document 784 762 fd = open(filename, 'w') … … 787 765 else: 788 766 invstate.toXML(file=filename) 789 767 790 768 def write_toXML(self, datainfo=None, state=None): 791 769 """ 792 770 Write toXML, a helper for write() 793 771 794 772 : return: xml doc 795 773 """ 796 774 if datainfo is None: 797 datainfo = sas.dataloader.data_info.Data1D(x=[], y=[]) 775 datainfo = sas.dataloader.data_info.Data1D(x=[], y=[]) 798 776 elif not issubclass(datainfo.__class__, sas.dataloader.data_info.Data1D): 799 777 msg = "The cansas writer expects a Data1D" 800 778 msg += " instance: %s" % str(datainfo.__class__.__name__) 801 779 raise RuntimeError, msg 802 # make sure title and data run is filled up.780 # make sure title and data run is filled up. 803 781 if datainfo.title == None or datainfo.title == '': 804 782 datainfo.title = datainfo.name 805 if datainfo.run_name == None or datainfo.run_name == {}: 783 if datainfo.run_name == None or datainfo.run_name == {}: 806 784 datainfo.run = [str(datainfo.name)] 807 785 datainfo.run_name[0] = datainfo.name … … 810 788 # Add the invariant information to the XML document 811 789 if state is not None: 812 doc = state.toXML(datainfo.name, doc=doc, entry_node=sasentry)790 doc = state.toXML(datainfo.name, doc=doc, entry_node=sasentry) 813 791 return doc 814 792
Note: See TracChangeset
for help on using the changeset viewer.