Changeset 2296316 in sasview for sansview/perspectives/fitting
- Timestamp:
- Mar 29, 2011 12:40:33 PM (14 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:
- e0e2c44f
- Parents:
- 29ef718
- Location:
- sansview/perspectives/fitting
- Files:
-
- 2 added
- 9 edited
Legend:
- Unmodified
- Added
- Removed
-
sansview/perspectives/fitting/basepage.py
r9466f2d6 r2296316 158 158 #self.onSave(event=None) 159 159 self.Bind(wx.EVT_CONTEXT_MENU, self.onContextMenu) 160 161 # bind key event 162 self.Bind(wx.EVT_LEFT_DOWN, self.on_left_down) 160 163 161 164 ## create the basic structure of the panel with empty sizer … … 427 430 style=wx.RB_GROUP) 428 431 self.enable_disp = wx.RadioButton(self, -1, 'On', (10, 30)) 429 432 433 self.disp_help_bt = wx.Button(self,wx.NewId(),'?', size=(20,15)) 434 self.disp_help_bt.Bind(wx.EVT_BUTTON, 435 self.on_pd_help_clicked,id= self.disp_help_bt.GetId()) 436 self.disp_help_bt.SetToolTipString("Helps for Polydispersion.") 430 437 431 438 self.Bind(wx.EVT_RADIOBUTTON, self._set_dipers_Param, … … 442 449 sizer_dispersion.Add((20,20)) 443 450 sizer_dispersion.Add(self.disable_disp ) 444 sizer_dispersion.Add((10,10)) 445 446 ## fill a sizer with the combobox to select dispersion type 447 sizer_select_dispers = wx.BoxSizer(wx.HORIZONTAL) 448 self.model_disp = wx.StaticText(self, -1, 'Distribution Function ') 449 450 import sans.models.dispersion_models 451 self.polydisp= sans.models.dispersion_models.models 452 self.disp_box = wx.ComboBox(self, -1) 453 454 for key, value in self.polydisp.iteritems(): 455 name = str(key) 456 self.disp_box.Append(name,value) 457 self.disp_box.SetStringSelection("gaussian") 458 wx.EVT_COMBOBOX(self.disp_box,-1, self._on_select_Disp) 459 460 sizer_select_dispers.Add((10,10)) 461 sizer_select_dispers.Add(self.model_disp) 462 sizer_select_dispers.Add(self.disp_box,0, 463 wx.TOP|wx.BOTTOM|wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE,border=5) 464 465 self.model_disp.Hide() 466 self.disp_box.Hide() 467 451 sizer_dispersion.Add((25,20)) 452 sizer_dispersion.Add(self.disp_help_bt) 453 454 ## fill a sizer for dispersion 468 455 boxsizer1.Add( sizer_dispersion,0, 469 456 wx.TOP|wx.BOTTOM|wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE,border=5) 470 457 #boxsizer1.Add( (10,10) ) 471 boxsizer1.Add( sizer_select_dispers ) 472 self.sizer4_4 = wx.GridBagSizer(5,5) 458 #boxsizer1.Add( sizer_select_dispers ) 459 self.sizer4_4 = wx.GridBagSizer(6,5) 460 473 461 boxsizer1.Add( self.sizer4_4 ) 474 462 #----------------------------------------------------- … … 484 472 self.SetupScrolling() 485 473 486 def select_disp_angle(self, event):487 """488 Event for when a user select a parameter to average over.489 490 :param event: radiobutton event491 492 """493 self.values=[]494 self.weights=[]495 if event.GetEventObject()==self.noDisper_rbox:496 if self.noDisper_rbox.GetValue():497 #No array dispersity apply yet498 self._reset_dispersity()499 ## Redraw the model ???500 self._draw_model()501 # Go through the list of dispersion check boxes to identify502 # which one has changed503 for p in self.disp_cb_dict:504 self.state.disp_cb_dict[p]= self.disp_cb_dict[p].GetValue()505 # Catch which one of the box was just checked or unchecked.506 if event.GetEventObject() == self.disp_cb_dict[p]:507 if self.disp_cb_dict[p].GetValue() == True:508 509 ##Temp. FIX for V1.0 regarding changing checkbox510 #to radiobutton.511 ##This (self._reset_dispersity) should be removed512 #when the array dispersion is fixed.513 self._reset_dispersity()514 515 # The user wants this parameter to be averaged.516 # Pop up the file selection dialog.517 path = self._selectDlg()518 519 # If nothing was selected, just return520 if path is None:521 self.disp_cb_dict[p].SetValue(False)522 self.noDisper_rbox.SetValue(True)523 return524 try:525 self._default_save_location = os.path.dirname(path)526 except:527 pass528 try:529 self.values,self.weights = self.read_file(path)530 except:531 msg="Could not read input file"532 wx.PostEvent(self.parent.parent,533 StatusEvent(status=msg))534 return535 536 # If any of the two arrays is empty, notify the user that we won't537 # proceed538 if self.values is None or self.weights is None or \539 self.values ==[] or self.weights ==[]:540 msg = "The loaded %s distrubtion is"541 msg + " corrupted or empty" % p542 wx.PostEvent(self.parent.parent,543 StatusEvent(status=msg))544 return545 546 # Tell the user that we are about to apply the distribution547 msg = "Applying loaded %s distribution: %s" % (p, path)548 wx.PostEvent(self.parent.parent, StatusEvent(status=msg))549 550 # Create the dispersion objects551 from sans.models.dispersion_models import ArrayDispersion552 disp_model = ArrayDispersion()553 disp_model.set_weights(self.values, self.weights)554 555 # Store the object to make it persist outside the556 # scope of this method557 #TODO: refactor model to clean this up?558 self._disp_obj_dict[p] = disp_model559 self.state._disp_obj_dict [p]= disp_model560 self.state.values = []561 self.state.weights = []562 self.state.values = copy.deepcopy(self.values)563 self.state.weights = copy.deepcopy(self.weights)564 # Set the new model as the dispersion object for the565 #selected parameter566 self.model.set_dispersion(p, disp_model)567 # Store a reference to the weights in the model object568 #so that569 # it's not lost when we use the model within another thread.570 #TODO: total hack - fix this571 self.state.model= self.model.clone()572 573 self.model._persistency_dict = {}574 self.model._persistency_dict[p] = \575 [self.values, self.weights]576 self.state.model._persistency_dict[p] = \577 [self.values,self.weights]578 else:579 self._reset_dispersity()580 581 ## Redraw the model582 self._draw_model()583 584 ## post state to fit panel585 event = PageInfoEvent(page = self)586 wx.PostEvent(self.parent, event)587 588 474 589 475 def onResetModel(self, event): … … 603 489 previous_state = self.saved_states[name] 604 490 ## reset state of checkbox,textcrtl and regular parameters value 605 self.reset_page(previous_state) 491 self.reset_page(previous_state) 492 493 def on_report_state(self, event): 494 """ 495 Report the current fit results 496 """ 497 event.Skip() 498 # Get plot image from plotpanel 499 images, canvases = self.get_images() 500 # get the report dialog 501 self.state.report(images, canvases) 502 606 503 607 504 def on_save(self, event): … … 785 682 self.state.qmax_x = self.qmax_x 786 683 self.state.qmin_x = self.qmin_x 787 try:788 n = self.disp_box.GetCurrentSelection()789 dispersity= self.disp_box.GetClientData(n)790 name= dispersity.__name__791 self.disp_name = name792 if name == "GaussianDispersion" :793 if hasattr(self,"cb1"):794 self.state.cb1= self.cb1.GetValue()795 except:796 pass797 684 798 685 if hasattr(self,"enable_disp"): … … 811 698 self.state.slit_smearer = copy.deepcopy(self.slit_smearer.GetValue()) 812 699 813 if hasattr(self,"disp_box"): 814 self.state.disp_box = self.disp_box.GetSelection() 815 816 if len(self.disp_cb_dict)>0: 817 for k , v in self.disp_cb_dict.iteritems(): 818 819 if v ==None : 820 self.state.disp_cb_dict[k]= v 821 else: 822 try: 823 self.state.disp_cb_dict[k]=v.GetValue() 824 except: 825 self.state.disp_cb_dict[k]= None 826 827 if len(self._disp_obj_dict)>0: 828 for k , v in self._disp_obj_dict.iteritems(): 829 830 self.state._disp_obj_dict[k]= v 700 if len(self._disp_obj_dict)>0: 701 for k , v in self._disp_obj_dict.iteritems(): 702 self.state._disp_obj_dict[k]= v 831 703 832 704 … … 836 708 self._save_plotting_range() 837 709 838 self.state.orientation_params =[] 839 self.state.orientation_params_disp =[] 840 self.state.parameters =[] 841 self.state.fittable_param =[] 842 self.state.fixed_param =[] 710 self.state.orientation_params = [] 711 self.state.orientation_params_disp = [] 712 self.state.parameters = [] 713 self.state.fittable_param = [] 714 self.state.fixed_param = [] 715 self.state.str_parameters = [] 843 716 844 717 845 718 ## save checkbutton state and txtcrtl values 719 self._copy_parameters_state(self.str_parameters, 720 self.state.str_parameters) 846 721 self._copy_parameters_state(self.orientation_params, 847 722 self.state.orientation_params) … … 873 748 ## save data 874 749 self.state.data= copy.deepcopy(self.data) 875 try:876 n = self.disp_box.GetCurrentSelection()877 dispersity= self.disp_box.GetClientData(n)878 name= dispersity.__name__879 self.disp_name = name880 if name == "GaussianDispersion" :881 if hasattr(self,"cb1"):882 self.state.cb1= self.cb1.GetValue()883 884 except:885 pass886 750 887 751 if hasattr(self,"enable_disp"): … … 1065 929 #self._undo.Enable(False) 1066 930 return 1067 931 # set data, etc. from the state 1068 932 self.set_data(state.data) 1069 933 self.enable2D= state.enable2D … … 1108 972 self.enable_disp.SetValue(state.enable_disp) 1109 973 self.disable_disp.SetValue(state.disable_disp) 1110 1111 if hasattr(self, "disp_box"): 1112 1113 self.disp_box.SetSelection(state.disp_box) 1114 n= self.disp_box.GetCurrentSelection() 1115 dispersity= self.disp_box.GetClientData(n) 1116 name = dispersity.__name__ 1117 974 # If the polydispersion is ON 975 if state.enable_disp: 976 # reset dispersion according the state 1118 977 self._set_dipers_Param(event=None) 1119 1120 if name == "ArrayDispersion": 1121 1122 for item in self.disp_cb_dict.keys(): 1123 1124 if hasattr(self.disp_cb_dict[item], "SetValue") : 1125 self.disp_cb_dict[item].SetValue(\ 1126 state.disp_cb_dict[item]) 1127 # Create the dispersion objects 1128 from sans.models.dispersion_models import ArrayDispersion 1129 disp_model = ArrayDispersion() 1130 if hasattr(state,"values")and\ 1131 self.disp_cb_dict[item].GetValue() == True: 1132 if len(state.values)>0: 1133 self.values=state.values 1134 self.weights=state.weights 1135 disp_model.set_weights(self.values, 1136 state.weights) 1137 else: 1138 self._reset_dispersity() 1139 1140 self._disp_obj_dict[item] = disp_model 1141 # Set the new model as the dispersion object 1142 #for the selected parameter 1143 self.model.set_dispersion(item, disp_model) 1144 1145 self.model._persistency_dict[item] = \ 1146 [state.values, state.weights] 1147 1148 else: 1149 keys = self.model.getParamList() 1150 for item in keys: 1151 if item in self.disp_list and \ 1152 not self.model.details.has_key(item): 1153 self.model.details[item] = ["", None, None] 1154 for k,v in self.state.disp_cb_dict.iteritems(): 1155 self.disp_cb_dict = copy.deepcopy(state.disp_cb_dict) 1156 self.state.disp_cb_dict = copy.deepcopy(state.disp_cb_dict) 1157 978 self._reset_page_disp_helper(state) 1158 979 ##plotting range restore 1159 980 self._reset_plotting_range(state) … … 1185 1006 self.state = state.clone() 1186 1007 1187 1188 def old_reset_page_helper(self, state): 1189 """ 1190 Use page_state and change the state of existing page 1191 1192 :precondition: the page is already drawn or created 1193 1194 :postcondition: the state of the underlying data change as well as the 1195 state of the graphic interface 1196 """ 1197 if state ==None: 1198 #self._undo.Enable(False) 1199 return 1200 1201 self.model= state.model 1202 self.data = state.data 1203 if self.data !=None: 1204 from DataLoader.qsmearing import smear_selection 1205 self.smearer= smear_selection(self.data, self.model) 1206 self.enable2D= state.enable2D 1207 self.engine_type = state.engine_type 1208 1209 self.disp_cb_dict = state.disp_cb_dict 1210 self.disp_list = state.disp_list 1211 1212 ## set the state of the radio box 1213 self.shape_rbutton.SetValue(state.shape_rbutton ) 1214 self.shape_indep_rbutton.SetValue(state.shape_indep_rbutton) 1215 self.struct_rbutton.SetValue(state.struct_rbutton ) 1216 self.plugin_rbutton.SetValue(state.plugin_rbutton) 1217 ##draw sizer containing model parameters value for the current model 1218 self._set_model_sizer_selection( self.model ) 1219 self.set_model_param_sizer(self.model) 1220 1221 ## reset value of combox box 1222 self.structurebox.SetSelection(state.structurecombobox ) 1223 self.formfactorbox.SetSelection(state.formfactorcombobox) 1224 1225 1226 ## enable the view 2d button if this is a modelpage type 1227 if hasattr(self,"model_view"): 1228 if self.enable2D: 1229 self.model_view.Disable() 1008 def _reset_page_disp_helper(self, state): 1009 """ 1010 Help to rest page for dispersions 1011 """ 1012 keys = self.model.getParamList() 1013 for item in keys: 1014 if item in self.disp_list and \ 1015 not self.model.details.has_key(item): 1016 self.model.details[item] = ["", None, None] 1017 #for k,v in self.state.disp_cb_dict.iteritems(): 1018 self.disp_cb_dict = copy.deepcopy(state.disp_cb_dict) 1019 self.state.disp_cb_dict = copy.deepcopy(state.disp_cb_dict) 1020 self.values = copy.deepcopy(state.values) 1021 self.weights = copy.deepcopy(state.weights) 1022 1023 for key, disp in state._disp_obj_dict.iteritems(): 1024 # From saved file, disp_model can not be sent in model obj. 1025 # it will be sent as a string here, then converted to model object. 1026 if disp.__class__.__name__ == 'str': 1027 com_str = "from sans.models.dispersion_models " 1028 com_str += "import %s as disp_func" 1029 exec com_str % disp 1030 disp_model = disp_func() 1230 1031 else: 1231 self.model_view.Enable() 1232 ## set the select all check box to the a given state 1233 if hasattr(self, "cb1"): 1234 self.cb1.SetValue(state.cb1) 1235 1236 ## reset state of checkbox,textcrtl and regular parameters value 1237 1238 self._reset_parameters_state(self.orientation_params_disp, 1239 state.orientation_params_disp) 1240 self._reset_parameters_state(self.orientation_params, 1241 state.orientation_params) 1242 self._reset_parameters_state(self.parameters,state.parameters) 1243 ## display dispersion info layer 1244 self.enable_disp.SetValue(state.enable_disp) 1245 self.disable_disp.SetValue(state.disable_disp) 1246 1247 if hasattr(self, "disp_box"): 1248 1249 self.disp_box.SetSelection(state.disp_box) 1250 n= self.disp_box.GetCurrentSelection() 1251 dispersity= self.disp_box.GetClientData(n) 1252 name= dispersity.__name__ 1253 1254 self._set_dipers_Param(event=None) 1255 1256 if name=="ArrayDispersion": 1257 1258 for item in self.disp_cb_dict.keys(): 1259 1260 if hasattr(self.disp_cb_dict[item],"SetValue") : 1261 self.disp_cb_dict[item].SetValue(state.disp_cb_dict[item]) 1262 # Create the dispersion objects 1263 from sans.models.dispersion_models import ArrayDispersion 1264 disp_model = ArrayDispersion() 1265 if hasattr(state,"values") and\ 1266 self.disp_cb_dict[item].GetValue()==True: 1267 if len(state.values) > 0: 1268 self.values = state.values 1269 self.weights = state.weights 1270 disp_model.set_weights(self.values, 1271 state.weights) 1272 else: 1273 self._reset_dispersity() 1274 1275 self._disp_obj_dict[item] = disp_model 1276 # Set the new model as the dispersion 1277 #object for the selected parameter 1278 self.model.set_dispersion(item, disp_model) 1279 1280 self.model._persistency_dict[item] = [state.values, 1281 state.weights] 1282 1283 else: 1284 keys = self.model.getParamList() 1285 for item in keys: 1286 if item in self.disp_list and \ 1287 not self.model.details.has_key(item): 1288 self.model.details[item]=["",None,None] 1289 for k,v in self.state.disp_cb_dict.iteritems(): 1290 self.disp_cb_dict = copy.deepcopy(state.disp_cb_dict) 1291 self.state.disp_cb_dict = copy.deepcopy(state.disp_cb_dict) 1292 1293 ##plotting range restore 1294 self._reset_plotting_range(state) 1295 1296 ## smearing info restore 1297 if hasattr(self,"enable_smearer"): 1298 ## set smearing value whether or not the data 1299 #contain the smearing info 1300 self.enable_smearer.SetValue(state.enable_smearer) 1301 self.disable_smearer.SetValue(state.disable_smearer) 1302 self.onSmear(event=None) 1303 self.pinhole_smearer.SetValue(state.pinhole_smearer) 1304 self.slit_smearer.SetValue(state.slit_smearer) 1305 ## we have two more options for smearing 1306 if self.pinhole_smearer.GetValue(): self.onPinholeSmear(event=None) 1307 elif self.slit_smearer.GetValue(): self.onSlitSmear(event=None) 1308 1309 ## reset state of checkbox,textcrtl and dispersity parameters value 1310 self._reset_parameters_state(self.fittable_param,state.fittable_param) 1311 self._reset_parameters_state(self.fixed_param,state.fixed_param) 1312 1313 ## draw the model with previous parameters value 1314 self._onparamEnter_helper() 1315 1316 ## reset context menu items 1317 self._reset_context_menu() 1318 1319 ## set the value of the current state to the state given as parameter 1320 self.state = state.clone() 1321 self._draw_model() 1322 1032 disp_model = disp 1033 1034 self._disp_obj_dict[key] = disp_model 1035 param_name = key.split('.')[0] 1036 # Try to set dispersion only when available 1037 # for eg., pass the orient. angles for 1D Cal 1038 try: 1039 self.model.set_dispersion(param_name, disp_model) 1040 self.model._persistency_dict[key] = \ 1041 [state.values, state.weights] 1042 except: 1043 pass 1044 selection = self._find_polyfunc_selection(disp_model) 1045 for list in self.fittable_param: 1046 if list[1] == key and list[7] != None: 1047 list[7].SetSelection(selection) 1048 # For the array disp_model, set the values and weights 1049 if selection == 1: 1050 disp_model.set_weights(self.values[key], 1051 self.weights[key]) 1052 try: 1053 # Diables all fittable params for array 1054 list[0].SetValue(False) 1055 list[0].Disable() 1056 list[2].Disable() 1057 list[5].Disable() 1058 list[6].Disable() 1059 except: 1060 pass 1061 # For array, disable all fixed params 1062 if selection == 1: 1063 for item in self.fixed_param: 1064 if item[1].split(".")[0] == key.split(".")[0]: 1065 # try it and pass it for the orientation for 1D 1066 try: 1067 item[2].Disable() 1068 except: 1069 pass 1070 1071 # Make sure the check box updated when all checked 1072 if self.cb1.GetValue(): 1073 self.select_all_param(None) 1074 1323 1075 def _selectDlg(self): 1324 1076 """ … … 1545 1297 if item_page[2]!=None: 1546 1298 item_page[2].SetValue(item_page_info[2]) 1299 if item_page[2].__class__.__name__ == "ComboBox": 1300 if self.model.fun_list.has_key(item_page_info[2]): 1301 fun_val = self.model.fun_list[item_page_info[2]] 1302 self.model.setParam(item_page_info[1],fun_val) 1547 1303 if item_page[3]!=None: 1548 1304 ## show or hide text +/- … … 1560 1316 if item_page[5]!=None: 1561 1317 ## show of hide the text crtl for fitting error 1562 if item_page_info[5][0]: 1563 item_page[5].Show(True) 1564 item_page[5].SetValue(item_page_info[5][1]) 1565 else: 1566 item_page[5].Hide() 1567 1318 item_page[5].Show(item_page_info[5][0]) 1319 item_page[5].SetValue(item_page_info[5][1]) 1320 1568 1321 if item_page[6]!=None: 1569 1322 ## show of hide the text crtl for fitting error 1570 if item_page_info[6][0]: 1571 item_page[6].Show(True) 1572 item_page[6].SetValue(item_page_info[6][1]) 1573 else: 1574 item_page[6].Hide() 1323 item_page[6].Show(item_page_info[6][0]) 1324 item_page[6].SetValue(item_page_info[6][1]) 1325 1326 1327 def _reset_strparam_state(self, listtorestore, statelist): 1328 """ 1329 Reset the string parameters at the given state 1330 """ 1331 if len(statelist) == 0: 1332 return 1333 1334 listtorestore = copy.deepcopy(statelist) 1335 1336 for j in range(len(listtorestore)): 1337 item_page = listtorestore[j] 1338 item_page_info = statelist[j] 1339 ##change the state of the check box for simple parameters 1340 1341 if item_page[0] != None: 1342 item_page[0].SetValue(format_number(item_page_info[0], True)) 1343 1344 if item_page[2] != None: 1345 param_name = item_page_info[1] 1346 value = item_page_info[2] 1347 selection = value 1348 if self.model.fun_list.has_key(value): 1349 selection = self.model.fun_list[value] 1350 item_page[2].SetValue(selection) 1351 self.model.setParam(param_name, selection) 1575 1352 1576 1353 def _copy_parameters_state(self, listtocopy, statelist): … … 1739 1516 break 1740 1517 1741 def _draw_model(self ):1518 def _draw_model(self, update_chisqr=True): 1742 1519 """ 1743 1520 Method to draw or refresh a plotted model. 1744 1521 The method will use the data member from the model page 1745 1522 to build a call to the fitting perspective manager. 1523 1524 :param chisqr: update chisqr value [bool] 1746 1525 """ 1747 1526 #if self.check_invalid_panel(): … … 1762 1541 toggle_mode_on=toggle_mode_on, 1763 1542 state = self.state, 1764 enable2D=self.enable2D) 1543 enable2D=self.enable2D, 1544 update_chisqr=update_chisqr) 1765 1545 1766 1546 … … 2171 1951 name = str(item[1]) 2172 1952 2173 if string.find(name,".npts") ==-1 and string.find(name,".nsigmas")==-1: 1953 if string.find(name,".npts") ==-1 and \ 1954 string.find(name,".nsigmas")==-1: 2174 1955 ## check model parameters range 2175 1956 param_min= None … … 2191 1972 except: 2192 1973 msg = "Wrong Fit parameter range entered " 2193 wx.PostEvent(self.parent.parent, StatusEvent(status = msg)) 1974 wx.PostEvent(self.parent.parent, 1975 StatusEvent(status = msg)) 2194 1976 raise ValueError, msg 2195 1977 is_modified = True … … 2207 1989 except: 2208 1990 msg = "Wrong Fit parameter range entered " 2209 wx.PostEvent(self.parent.parent, StatusEvent(status = msg)) 1991 wx.PostEvent(self.parent.parent, 1992 StatusEvent(status = msg)) 2210 1993 raise ValueError, msg 2211 1994 is_modified = True … … 2216 1999 msg= "Wrong Fit range entered for parameter " 2217 2000 msg+= "name %s of model %s "%(name, self.model.name) 2218 wx.PostEvent(self.parent.parent, StatusEvent(status = msg)) 2001 wx.PostEvent(self.parent.parent, 2002 StatusEvent(status = msg)) 2219 2003 2220 2004 if name in self.model.details.keys(): 2221 self.model.details[name][1:3] = param_min,param_max2005 self.model.details[name][1:3] = param_min, param_max 2222 2006 is_modified = True 2223 2007 2224 2008 else: 2225 self.model.details [name] = ["", param_min,param_max]2009 self.model.details [name] = ["", param_min, param_max] 2226 2010 is_modified = True 2227 try: 2228 value= float(item[2].GetValue()) 2229 item[2].SetBackgroundColour("white") 2230 # If the value of the parameter has changed, 2231 # +update the model and set the is_modified flag 2232 if value != self.model.getParam(name) and numpy.isfinite(value): 2233 self.model.setParam(name,value) 2234 is_modified = True 2011 try: 2012 # Check if the textctr is enabled 2013 if item[2].IsEnabled(): 2014 value= float(item[2].GetValue()) 2015 item[2].SetBackgroundColour("white") 2016 # If the value of the parameter has changed, 2017 # +update the model and set the is_modified flag 2018 if value != self.model.getParam(name) and \ 2019 numpy.isfinite(value): 2020 self.model.setParam(name, value) 2021 2235 2022 except: 2236 2023 item[2].SetBackgroundColour("pink") … … 2264 2051 if self.model ==None: 2265 2052 self.model_disp.Hide() 2266 self.disp_box.Hide()2267 2053 self.sizer4_4.Clear(True) 2268 2054 return 2269 2055 2270 2056 if self.enable_disp.GetValue(): 2271 self.model_disp.Show(True)2272 self.disp_box.Show(True)2273 2057 ## layout for model containing no dispersity parameters 2274 2058 … … 2281 2065 self._on_select_Disp(event=None) 2282 2066 else: 2283 self.model_disp.Hide()2284 self.disp_box.Hide()2285 self.disp_box.SetSelection(0)2286 2067 self.sizer4_4.Clear(True) 2287 2068 … … 2310 2091 self.orientation_params_disp=[] 2311 2092 2312 self.model_disp.Hide()2313 self.disp_box.Hide()2314 2093 self.sizer4_4.Clear(True) 2315 2094 text = "No polydispersity available for this model" 2095 text = "No polydispersity available for this model" 2316 2096 model_disp = wx.StaticText(self, -1, text) 2317 self.sizer4_4.Add(model_disp,( iy, ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 2097 self.sizer4_4.Add(model_disp,( iy, ix),(1,1), 2098 wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 10) 2318 2099 self.sizer4_4.Layout() 2319 2100 self.sizer4.Layout() … … 2335 2116 self.fixed_param=[] 2336 2117 self.orientation_params_disp=[] 2337 self.values= []2338 self.weights= []2118 self.values={} 2119 self.weights={} 2339 2120 2340 2121 from sans.models.dispersion_models import GaussianDispersion, ArrayDispersion … … 2368 2149 self.disp_list should change type later .now only gaussian 2369 2150 """ 2370 n = self.disp_box.GetCurrentSelection() 2371 name = self.disp_box.GetValue() 2372 dispersity= self.disp_box.GetClientData(n) 2373 self.disp_name = name 2374 2375 if name.lower() == "array": 2376 self._set_sizer_arraydispersion() 2377 else: 2378 self._set_sizer_dispersion(dispersity= dispersity) 2379 2380 self.state.disp_box= n 2151 self._set_sizer_dispersion() 2152 2381 2153 ## Redraw the model 2382 2154 self._draw_model() … … 2389 2161 self.SetupScrolling() 2390 2162 2391 def _set_sizer_arraydispersion(self): 2392 """ 2393 draw sizer with array dispersity parameters 2394 """ 2395 2163 def _on_disp_func(self, event=None): 2164 """ 2165 Select a distribution function for the polydispersion 2166 2167 :Param event: ComboBox event 2168 """ 2169 # get ready for new event 2170 if event != None: 2171 event.Skip() 2172 # Get event object 2173 disp_box = event.GetEventObject() 2174 2175 # Try to select a Distr. function 2176 try: 2177 disp_box.SetBackgroundColour("white") 2178 selection = disp_box.GetCurrentSelection() 2179 param_name = disp_box.Name.split('.')[0] 2180 disp_name = disp_box.GetValue() 2181 dispersity= disp_box.GetClientData(selection) 2182 2183 #disp_model = GaussianDispersion() 2184 disp_model = dispersity() 2185 # Get param names to reset the values of the param 2186 name1 = param_name + ".width" 2187 name2 = param_name + ".npts" 2188 name3 = param_name + ".nsigmas" 2189 # Check Disp. function whether or not it is 'array' 2190 if disp_name.lower() == "array": 2191 value2= "" 2192 value3= "" 2193 value1 = self._set_array_disp(name=name1, disp=disp_model) 2194 else: 2195 self._del_array_values(name1) 2196 #self._reset_array_disp(param_name) 2197 self._disp_obj_dict[name1] = disp_model 2198 self.model.set_dispersion(param_name, disp_model) 2199 self.state._disp_obj_dict[name1]= disp_model 2200 2201 value1= str(format_number(self.model.getParam(name1), True)) 2202 value2= str(format_number(self.model.getParam(name2))) 2203 value3= str(format_number(self.model.getParam(name3))) 2204 # Reset fittable polydispersin parameter value 2205 for item in self.fittable_param: 2206 if item[1] == name1: 2207 item[2].SetValue(value1) 2208 item[5].SetValue("") 2209 item[6].SetValue("") 2210 # Disable for array 2211 if disp_name.lower() == "array": 2212 item[0].SetValue(False) 2213 item[0].Disable() 2214 item[2].Disable() 2215 item[5].Disable() 2216 item[6].Disable() 2217 else: 2218 item[0].Enable() 2219 item[2].Enable() 2220 item[5].Enable() 2221 item[6].Enable() 2222 break 2223 # Reset fixed polydispersion params 2224 for item in self.fixed_param: 2225 if item[1] == name2: 2226 item[2].SetValue(value2) 2227 # Disable Npts for array 2228 if disp_name.lower() == "array": 2229 item[2].Disable() 2230 else: 2231 item[2].Enable() 2232 if item[1] == name3: 2233 item[2].SetValue(value3) 2234 # Disable Nsigs for array 2235 if disp_name.lower() == "array": 2236 item[2].Disable() 2237 else: 2238 item[2].Enable() 2239 2240 # Make sure the check box updated when all checked 2241 if self.cb1.GetValue(): 2242 self.select_all_param(None) 2243 2244 # update params 2245 self._update_paramv_on_fit() 2246 # draw 2247 self._draw_model() 2248 self.Refresh() 2249 except: 2250 # Error msg 2251 msg = "Error occurred:" 2252 msg += " Could not select the distribution function..." 2253 msg += " Please select another distribution function." 2254 disp_box.SetBackgroundColour("pink") 2255 # Focus on Fit button so that users can see the pinky box 2256 self.btFit.SetFocus() 2257 wx.PostEvent(self.parent.parent, 2258 StatusEvent(status=msg, info="error")) 2259 2260 2261 def _set_array_disp(self, name=None, disp=None): 2262 """ 2263 Set array dispersion 2264 2265 :param name: name of the parameter for the dispersion to be set 2266 :param disp: the polydisperion object 2267 """ 2268 # The user wants this parameter to be averaged. 2269 # Pop up the file selection dialog. 2270 path = self._selectDlg() 2271 # Array data 2272 values = [] 2273 weights = [] 2274 # If nothing was selected, just return 2275 if path is None: 2276 self.disp_cb_dict[name].SetValue(False) 2277 #self.noDisper_rbox.SetValue(True) 2278 return 2279 self._default_save_location = os.path.dirname(path) 2280 2281 basename = os.path.basename(path) 2282 values,weights = self.read_file(path) 2283 2284 # If any of the two arrays is empty, notify the user that we won't 2285 # proceed 2396 2286 if len(self.param_toFit)>0: 2397 for item in self.fittable_param: 2398 if item in self.param_toFit: 2399 self.param_toFit.remove(item) 2400 for item in self.orientation_params_disp: 2401 if item in self.param_toFit: 2402 self.param_toFit.remove(item) 2403 for item in self.model.details.keys(): 2404 if item in self.model.fixed: 2405 del self.model.details [item] 2406 2407 self.fittable_param=[] 2408 self.fixed_param=[] 2409 self.orientation_params_disp=[] 2410 self.sizer4_4.Clear(True) 2411 self._reset_dispersity() 2412 ix=0 2413 iy=1 2414 disp1 = wx.StaticText(self, -1, 'Array Dispersion') 2415 self.sizer4_4.Add(disp1,( iy, ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 2416 2417 # Look for model parameters to which we can apply an ArrayDispersion model 2418 # Add a check box for each parameter. 2419 self.disp_cb_dict = {} 2420 ix+=1 2421 self.noDisper_rbox = wx.RadioButton(self, -1,"None", (10, 10),style= wx.RB_GROUP) 2422 self.Bind(wx.EVT_RADIOBUTTON,self.select_disp_angle , id=self.noDisper_rbox.GetId()) 2423 #MAC needs SetValue 2424 self.noDisper_rbox.SetValue(True) 2425 self.sizer4_4.Add(self.noDisper_rbox, (iy, ix), 2426 (1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0) 2427 2428 for p in self.model.dispersion.keys(): 2429 if not p in self.model.orientation_params: 2430 ix+=1 2431 self.disp_cb_dict[p] = wx.RadioButton(self, -1, p, (10, 10)) 2432 self.state.disp_cb_dict[p]= self.disp_cb_dict[p].GetValue() 2433 self.Bind(wx.EVT_RADIOBUTTON, self.select_disp_angle, id=self.disp_cb_dict[p].GetId()) 2434 self.sizer4_4.Add(self.disp_cb_dict[p], (iy, ix), (1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0) 2435 2436 for p in self.model.dispersion.keys(): 2437 if p in self.model.orientation_params: 2438 ix+=1 2439 self.disp_cb_dict[p] = wx.RadioButton(self, -1, p, (10, 10)) 2440 self.state.disp_cb_dict[p]= self.disp_cb_dict[p].GetValue() 2441 if not (self.enable2D or self.data.__class__.__name__ =="Data2D"): 2442 self.disp_cb_dict[p].Hide() 2443 else: 2444 self.disp_cb_dict[p].Show(True) 2445 self.Bind(wx.EVT_RADIOBUTTON, self.select_disp_angle, id=self.disp_cb_dict[p].GetId()) 2446 self.sizer4_4.Add(self.disp_cb_dict[p], (iy, ix), (1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0) 2447 2448 2449 ix =0 2450 iy +=1 2451 self.sizer4_4.Add((20,20),(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 2452 self.Layout() 2453 2454 self.state.orientation_params =[] 2455 self.state.orientation_params_disp =[] 2456 self.state.parameters =[] 2457 self.state.fittable_param =[] 2458 self.state.fixed_param =[] 2459 2460 ## save checkbutton state and txtcrtl values 2461 2462 self._copy_parameters_state(self.orientation_params, 2463 self.state.orientation_params) 2464 2465 self._copy_parameters_state(self.orientation_params_disp, 2466 self.state.orientation_params_disp) 2467 2468 self._copy_parameters_state(self.parameters, self.state.parameters) 2469 self._copy_parameters_state(self.fittable_param, self.state.fittable_param) 2470 self._copy_parameters_state(self.fixed_param, self.state.fixed_param) 2471 2472 2473 ## post state to fit panel 2474 event = PageInfoEvent(page = self) 2475 wx.PostEvent(self.parent, event) 2476 2287 if name in self.param_toFit: 2288 self.param_toFit.remove(name) 2289 2290 # Tell the user that we are about to apply the distribution 2291 msg = "Applying loaded %s distribution: %s" % (name, path) 2292 wx.PostEvent(self.parent.parent, StatusEvent(status=msg)) 2293 2294 disp.set_weights(values, weights) 2295 self._disp_obj_dict[name] = disp 2296 self.model.set_dispersion(name.split('.')[0], disp) 2297 self.state._disp_obj_dict[name]= disp 2298 self.values[name] = values 2299 self.weights[name] = weights 2300 # Store the object to make it persist outside the 2301 # scope of this method 2302 #TODO: refactor model to clean this up? 2303 self.state.values = {} 2304 self.state.weights = {} 2305 self.state.values = copy.deepcopy(self.values) 2306 self.state.weights = copy.deepcopy(self.weights) 2307 2308 # Set the new model as the dispersion object for the 2309 #selected parameter 2310 #self.model.set_dispersion(p, disp_model) 2311 # Store a reference to the weights in the model object 2312 #so that 2313 # it's not lost when we use the model within another thread. 2314 #TODO: total hack - fix this 2315 self.state.model= self.model.clone() 2316 self.model._persistency_dict[name.split('.')[0]] = \ 2317 [values, weights] 2318 self.state.model._persistency_dict[name.split('.')[0]] = \ 2319 [values,weights] 2320 return basename 2321 2322 def _del_array_values(self, name=None): 2323 """ 2324 Reset array dispersion 2325 2326 :param name: name of the parameter for the dispersion to be set 2327 """ 2328 # Try to delete values and weight of the names array dic if exists 2329 try: 2330 del self.values[name] 2331 del self.weights[name] 2332 # delete all other dic 2333 del self.state.values[name] 2334 del self.state.weights[name] 2335 del self.model._persistency_dict[name.split('.')[0]] 2336 del self.state.model._persistency_dict[name.split('.')[0]] 2337 except: 2338 pass 2339 2477 2340 def _lay_out(self): 2478 2341 """ … … 2494 2357 time.sleep(1) 2495 2358 2359 def _find_polyfunc_selection(self, disp_func = None): 2360 """ 2361 FInd Comboox selection from disp_func 2362 2363 :param disp_function: dispersion distr. function 2364 """ 2365 # List of the poly_model name in the combobox 2366 list = ["RectangleDispersion", "ArrayDispersion", 2367 "LogNormalDispersion", "GaussianDispersion", 2368 "SchulzDispersion"] 2369 2370 # Find the selection 2371 try: 2372 selection = list.index(disp_func.__class__.__name__) 2373 return selection 2374 except: 2375 return 3 2376 2496 2377 def on_reset_clicked(self,event): 2497 2378 """ … … 2556 2437 #Re draw plot 2557 2438 self._draw_model() 2439 2440 def get_images(self): 2441 """ 2442 Get the images of the plots corresponding this panel for report 2443 2444 : return graphs: list of figures 2445 : TODO: Move to guiframe 2446 """ 2447 # set list of graphs 2448 graphs = [] 2449 canvases = [] 2450 # call gui_manager 2451 gui_manager = self.parent.parent 2452 # loops through the panels [dic] 2453 for item1, item2 in gui_manager.panels.iteritems(): 2454 data_title = self.data.group_id 2455 data_name = self.data.name 2456 # try to get all plots belonging to this control panel 2457 try: 2458 # check titles (main plot) 2459 # and data_names (model plot[2D], and residuals) 2460 if item2.group_id == data_title or \ 2461 item2.window_name.count(data_name): 2462 #panel = gui_manager._mgr.GetPane(item2.window_name) 2463 # append to the list 2464 graphs.append(item2.figure) 2465 canvases.append(item2.canvas) 2466 except: 2467 # Not for control panels 2468 pass 2469 # return the list of graphs 2470 return graphs, canvases 2558 2471 2559 2472 def on_model_help_clicked(self,event): … … 2562 2475 """ 2563 2476 from help_panel import HelpWindow 2564 2477 import sans.models as models 2478 2479 # Get models help model_function path 2480 path = models.get_data_path(media='media') 2481 model_path = os.path.join(path,"model_functions.html") 2565 2482 if self.model == None: 2566 2483 name = 'FuncHelp' … … 2568 2485 name = self.model.origin_name 2569 2486 2570 frame = HelpWindow(None, -1, pageToOpen= "media/model_functions.html")2487 frame = HelpWindow(None, -1, pageToOpen=model_path) 2571 2488 frame.Show(True) 2572 2489 if frame.rhelp.HasAnchor(name): … … 2575 2492 msg= "Model does not contains an available description " 2576 2493 msg +="Please try searching in the Help window" 2577 wx.PostEvent(self.parent.parent, StatusEvent(status = msg )) 2494 wx.PostEvent(self.parent.parent, StatusEvent(status = msg )) 2495 2496 def on_pd_help_clicked(self, event): 2497 """ 2498 Button event for PD help 2499 """ 2500 from help_panel import HelpWindow 2501 import sans.models as models 2502 2503 # Get models help model_function path 2504 path = models.get_data_path(media='media') 2505 pd_path = os.path.join(path,"pd_help.html") 2506 2507 frame = HelpWindow(None, -1, pageToOpen=pd_path) 2508 frame.Show(True) 2509 2510 def on_left_down(self, event): 2511 """ 2512 Get key stroke event 2513 """ 2514 # Figuring out key combo: Cmd for copy, Alt for paste 2515 if event.CmdDown() and event.ShiftDown(): 2516 flag = self.get_paste() 2517 elif event.CmdDown(): 2518 flag = self.get_copy() 2519 else: 2520 event.Skip() 2521 return 2522 # make event free 2523 event.Skip() 2524 # messages depending on the flag 2525 if flag == None: 2526 msg = " Parameter values are copied to the clipboard..." 2527 infor = 'warning' 2528 elif flag: 2529 msg = " Parameter values are pasted from the clipboad..." 2530 infor = "warning" 2531 else: 2532 msg = "Error was occured during pasting the parameter values " 2533 msg += "from the clipboard..." 2534 infor = "error" 2535 # inform msg to wx 2536 wx.PostEvent( self.parent.parent, 2537 StatusEvent(status= msg, info=infor)) 2538 2539 2540 def get_copy(self): 2541 """ 2542 Get the string copies of the param names and values in the tap 2543 """ 2544 content = 'sansview_parameter_values:' 2545 # Do it if params exist 2546 if self.parameters !=[]: 2547 2548 # go through the parameters 2549 string = self._get_copy_helper(self.parameters, 2550 self.orientation_params) 2551 content += string 2552 2553 # go through the fittables 2554 string = self._get_copy_helper(self.fittable_param, 2555 self.orientation_params_disp) 2556 content += string 2557 2558 # go through the fixed params 2559 string = self._get_copy_helper(self.fixed_param, 2560 self.orientation_params_disp) 2561 content += string 2578 2562 2563 # go through the str params 2564 string = self._get_copy_helper(self.str_parameters, 2565 self.orientation_params) 2566 content += string 2567 2568 if wx.TheClipboard.Open(): 2569 wx.TheClipboard.SetData(wx.TextDataObject(str(content))) 2570 data = wx.TextDataObject() 2571 success = wx.TheClipboard.GetData(data) 2572 text = data.GetText() 2573 wx.TheClipboard.Close() 2574 2575 return None 2576 2577 def _get_copy_helper(self, param, orient_param): 2578 """ 2579 Helping get value and name of the params 2580 2581 : param param: parameters 2582 : param orient_param = oritational params 2583 : return content: strings [list] [name,value:....] 2584 """ 2585 content = '' 2586 # go through the str params 2587 for item in param: 2588 # 2D 2589 if self.data.__class__.__name__== "Data2D": 2590 name = item[1] 2591 value = item[2].GetValue() 2592 # 1D 2593 else: 2594 ## for 1D all parameters except orientation 2595 if not item[1] in orient_param: 2596 name = item[1] 2597 value = item[2].GetValue() 2598 # add to the content 2599 content += name + ',' + value + ':' 2600 2601 return content 2602 2603 def get_paste(self): 2604 """ 2605 Get the string copies of the param names and values in the tap 2606 """ 2607 context = {} 2608 text = "" 2609 2610 # Get text from the clip board 2611 if wx.TheClipboard.Open(): 2612 if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)): 2613 data = wx.TextDataObject() 2614 # get wx dataobject 2615 success = wx.TheClipboard.GetData(data) 2616 # get text 2617 text = data.GetText() 2618 # close clipboard 2619 wx.TheClipboard.Close() 2620 2621 # put the text into dictionary 2622 lines = text.split(':') 2623 if lines[0] != 'sansview_parameter_values': 2624 return False 2625 for line in lines[1:-1]: 2626 if len(line) != 0: 2627 item =line.split(',') 2628 name = item[0] 2629 value = item[1] 2630 # Transfer the text to content[dictionary] 2631 context[name] = value 2632 2633 # Do it if params exist 2634 if self.parameters != []: 2635 # go through the parameters 2636 self._get_paste_helper(self.parameters, 2637 self.orientation_params, context) 2638 2639 # go through the fittables 2640 self._get_paste_helper(self.fittable_param, 2641 self.orientation_params_disp, context) 2642 2643 # go through the fixed params 2644 self._get_paste_helper(self.fixed_param, 2645 self.orientation_params_disp, context) 2646 2647 # go through the str params 2648 self._get_paste_helper(self.str_parameters, 2649 self.orientation_params, context) 2650 2651 return True 2652 2653 def _get_paste_helper(self, param, orient_param, content): 2654 """ 2655 Helping set values of the params 2656 2657 : param param: parameters 2658 : param orient_param: oritational params 2659 : param content: dictionary [ name, value: name1.value1,...] 2660 """ 2661 # go through the str params 2662 for item in param: 2663 # 2D 2664 if self.data.__class__.__name__== "Data2D": 2665 name = item[1] 2666 if name in content.keys(): 2667 item[2].SetValue(content[name]) 2668 # 1D 2669 else: 2670 ## for 1D all parameters except orientation 2671 if not item[1] in orient_param: 2672 name = item[1] 2673 if name in content.keys(): 2674 # Avoid changing combox content which needs special care 2675 if item[2].__class__.__name__ != "ComboBox": 2676 item[2].SetValue(content[name]) 2677 2678 -
sansview/perspectives/fitting/console.py
r66ff250 r2296316 116 116 """ 117 117 """ 118 #self.elapsed_time = time.time() - self.elapsed_time 119 #msg = " Updating fit ...\n result:\n %s \n"%self.result.__str__() 120 #wx.PostEvent(self.parent, StatusEvent(status=msg, info="info", 121 # type="progress")) 122 #if self.manager is not None: 123 # self.manager.update_fit(msg=msg, result=self.result) 124 #time.sleep(0.01) 118 self.elapsed_time = time.time() - self.elapsed_time 119 msg = " Updating fit ...\n result:\n %s \n"%self.result.__str__() 120 wx.PostEvent(self.parent, StatusEvent(status=msg, info="info", 121 type="progress")) 122 time.sleep(0.01) 125 123 126 124 def starting_fit(self): -
sansview/perspectives/fitting/fit_thread.py
r58e0c83 r2296316 15 15 updatefn = None, 16 16 yieldtime = 0.01, 17 worktime = 0.01 18 ):17 worktime = 0.01, 18 ftol = None): 19 19 CalcThread.__init__(self,completefn, 20 20 updatefn, … … 27 27 self.starttime = 0 28 28 self.updatefn = updatefn 29 #Relative error desired in the sum of squares. 30 self.ftol = ftol 29 31 30 32 def isquit(self): -
sansview/perspectives/fitting/fitpage.py
r9466f2d6 r2296316 41 41 ## draw sizer 42 42 self._fill_datainfo_sizer() 43 self.is_2D = None 43 44 # get smear info from data 44 45 self._get_smear_info() … … 48 49 self._set_smear(self.data) 49 50 self.Bind(EVT_CHI2_UPDATE, self.on_complete_chisqr) 51 # bind key event 52 self.Bind(wx.EVT_RIGHT_DOWN, self.on_right_down) 50 53 self._set_bookmark_flag(False) 51 54 self._set_save_flag(False) … … 82 85 self.Layout() 83 86 return 84 for item in self.parameters:85 if self.engine_type =="scipy" :86 item[5].SetValue("")87 item[5].Hide()88 item[6].SetValue("")89 item[6].Hide()90 self.text2_min.Hide()91 self.text2_max.Hide()92 93 else:94 item[5].Show(True)95 item[6].Show(True)96 self.text2_min.Show(True)97 self.text2_max.Show(True)98 for item in self.fittable_param:99 if item[5]!=None and item[6]!=None and not \100 item in self.orientation_params_disp:101 if self.engine_type =="scipy" and \102 not item in self.orientation_params:103 item[5].SetValue("")104 item[5].Hide()105 item[6].SetValue("")106 item[6].Hide()107 self.text2_min.Hide()108 self.text2_max.Hide()109 self.text_disp_min.Hide()110 self.text_disp_max.Hide()111 else:112 item[5].Show(True)113 item[6].Show(True)114 self.text2_min.Show(True)115 self.text2_max.Show(True)116 self.text_disp_min.Show(True)117 self.text_disp_max.Show(True)118 119 for item in self.orientation_params:120 if item[5]!=None and item[6]!=None:121 if self.engine_type =="scipy" or \122 self.data.__class__.__name__ !="Data2D":123 item[5].SetValue("")124 item[5].Hide()125 item[6].SetValue("")126 item[6].Hide()127 else:128 item[5].Show(True)129 item[6].Show(True)130 131 for item in self.orientation_params_disp:132 if item[5]!=None and item[6]!=None:133 if self.engine_type =="scipy" or \134 self.data.__class__.__name__ !="Data2D":135 item[5].SetValue("")136 item[5].Hide()137 item[6].SetValue("")138 item[6].Hide()139 else:140 item[5].Show(True)141 item[6].Show(True)142 87 self.Layout() 143 88 self.Refresh() … … 163 108 smear_message_new_ssmear = "Please enter only the value of interest to customize smearing..." 164 109 smear_message_new_psmear = "Please enter both; the dQ will be generated by interpolation..." 165 smear_message_2d_x_title = "<dQ x>[1/A]:"166 smear_message_2d_y_title = "<dQ y>[1/A]:"110 smear_message_2d_x_title = "<dQp>[1/A]:" 111 smear_message_2d_y_title = "<dQs>[1/A]:" 167 112 smear_message_pinhole_min_title = "dQ_low[1/A]:" 168 113 smear_message_pinhole_max_title = "dQ_high[1/A]:" … … 253 198 self.Npts_total = BGTextCtrl(self, -1, "-", size=(75,20), style=0) 254 199 self.Npts_total.SetToolTipString(" Total Npts : total number of data points") 200 # Update and Draw button 201 self.draw_button = wx.Button(self,wx.NewId(),'Compute', size=(88,24)) 202 self.draw_button.Bind(wx.EVT_BUTTON, self._onDraw,id= self.draw_button.GetId()) 203 self.draw_button.SetToolTipString("Compute and Draw.") 204 255 205 box_description_1= wx.StaticText(self, -1,' Chi2/Npts') 256 206 box_description_2= wx.StaticText(self, -1,'Fitted Npts') 257 207 box_description_3= wx.StaticText(self, -1,'Data Npts') 258 box_description_4= wx.StaticText(self, -1,' ')208 #box_description_4= wx.StaticText(self, -1,' ') 259 209 260 210 … … 262 212 sizer_fit.Add(box_description_2,0,0) 263 213 sizer_fit.Add(box_description_3,0,0) 264 sizer_fit.Add( box_description_4,0,0)214 sizer_fit.Add(self.draw_button,0,0) 265 215 sizer_fit.Add(self.tcChi,0,0) 266 216 sizer_fit.Add(self.Npts_fit ,0,0) … … 281 231 self.smear_message_new_p = wx.StaticText(self, -1, smear_message_new_psmear , style=wx.ALIGN_LEFT) 282 232 self.smear_description_2d_x = wx.StaticText(self, -1, smear_message_2d_x_title , style=wx.ALIGN_LEFT) 233 self.smear_description_2d_x.SetToolTipString(" dQp(parallel) in q_r direction.") 283 234 self.smear_description_2d_y = wx.StaticText(self, -1, smear_message_2d_y_title , style=wx.ALIGN_LEFT) 235 self.smear_description_2d_y.SetToolTipString(" dQs(perpendicular) in q_phi direction.") 284 236 self.smear_description_pin_min = wx.StaticText(self, -1, smear_message_pinhole_min_title , style=wx.ALIGN_LEFT) 285 237 self.smear_description_pin_max = wx.StaticText(self, -1, smear_message_pinhole_max_title , style=wx.ALIGN_LEFT) … … 570 522 sizer.Layout() 571 523 572 def _set_sizer_dispersion(self , dispersity):524 def _set_sizer_dispersion(self): 573 525 """ 574 526 draw sizer with gaussian dispersity parameters … … 588 540 self._reset_dispersity() 589 541 590 # Create the dispersion objects 591 for item in self.model.dispersion.keys(): 592 #disp_model = GaussianDispersion() 593 disp_model = dispersity() 594 self._disp_obj_dict[item] = disp_model 595 self.model.set_dispersion(item, disp_model) 596 self.state._disp_obj_dict[item]= disp_model 597 598 599 ix=0 600 iy=1 542 ## fill a sizer with the combobox to select dispersion type 543 #sizer_select_dispers = wx.BoxSizer(wx.HORIZONTAL) 544 model_disp = wx.StaticText(self, -1, 'Function') 545 546 import sans.models.dispersion_models 547 self.polydisp= sans.models.dispersion_models.models 548 549 ix = 0 550 iy = 0 601 551 disp = wx.StaticText(self, -1, ' ') 602 552 self.sizer4_4.Add(disp,( iy, ix),(1,1), 603 553 wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 604 554 ix += 1 605 values = wx.StaticText(self, -1, 'PD[ratio] 555 values = wx.StaticText(self, -1, 'PD[ratio]') 606 556 polytext = "Polydispersity (= STD/mean); " 607 557 polytext += "the standard deviation over the mean value." … … 614 564 self.sizer4_4.Add( self.text_disp_1,(iy, ix),(1,1),\ 615 565 wx.EXPAND|wx.ADJUST_MINSIZE, 0) 616 self.text_disp_1.Hide()617 566 618 567 … … 621 570 self.sizer4_4.Add(self.text_disp_min,(iy, ix),(1,1),\ 622 571 wx.EXPAND|wx.ADJUST_MINSIZE, 0) 623 self.text_disp_min.Hide() 572 624 573 ix +=1 625 574 self.text_disp_max = wx.StaticText(self, -1, 'Max') … … 635 584 self.sizer4_4.Add(npts,( iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0) 636 585 ix += 1 637 nsigmas = wx.StaticText(self, -1, 'Nsig mas')586 nsigmas = wx.StaticText(self, -1, 'Nsigs') 638 587 nsigmas.SetToolTipString(" Number of sigmas between which the range\n\ 639 588 of the distribution function will be used for weighting. \n\ … … 642 591 self.sizer4_4.Add(nsigmas,( iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 643 592 0) 593 ix +=1 594 self.sizer4_4.Add(model_disp,(iy, ix),(1,1),\ 595 wx.EXPAND|wx.ADJUST_MINSIZE, 0) 644 596 645 597 if self.engine_type=="park": … … 664 616 ix = 0 665 617 cb = wx.CheckBox(self, -1, name0, (10, 10)) 666 cb.SetToolTipString("Check for fitting")618 cb.SetToolTipString("Check mark to fit") 667 619 wx.EVT_CHECKBOX(self, cb.GetId(), self.select_param) 668 620 self.sizer4_4.Add( cb,( iy, ix),(1,1), 669 621 wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 670 15)622 5) 671 623 ix = 1 672 624 value= self.model.getParam(name1) 673 ctl1 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH ,20)625 ctl1 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH/1.3,20) 674 626 ,style=wx.TE_PROCESS_ENTER) 675 627 ctl1.SetLabel('PD[ratio]') … … 678 630 poly_text += " from the mean value." 679 631 ctl1.SetToolTipString(poly_text) 680 ctl1.SetValue(str (format_number(value )))632 ctl1.SetValue(str (format_number(value, True))) 681 633 self.sizer4_4.Add(ctl1, (iy,ix),(1,1),wx.EXPAND) 682 634 ## text to show error sign … … 688 640 689 641 ix = 3 690 ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH ,20),642 ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH/1.3,20), 691 643 style=0) 692 644 … … 703 655 self.sizer4_4.Add(ctl3, (iy,ix),(1,1), 704 656 wx.EXPAND|wx.ADJUST_MINSIZE, 0) 705 ctl3.Hide()657 706 658 707 659 ix = 5 … … 713 665 wx.EXPAND|wx.ADJUST_MINSIZE, 0) 714 666 715 ctl4.Hide()716 667 717 668 if self.engine_type=="park": 718 669 ctl3.Show(True) 719 670 ctl4.Show(True) 720 721 self.fittable_param.append([cb,name1,ctl1,text2, 722 ctl2, ctl3, ctl4,None]) 723 671 724 672 elif p=="npts": 725 673 ix = 6 726 674 value= self.model.getParam(name2) 727 675 Tctl = self.ModelTextCtrl(self, -1, 728 size=(_BOX_WIDTH/2,20),676 size=(_BOX_WIDTH/2.2,20), 729 677 style=wx.TE_PROCESS_ENTER) 730 678 … … 738 686 value= self.model.getParam(name3) 739 687 Tct2 = self.ModelTextCtrl(self, -1, 740 size=(_BOX_WIDTH/2 ,20),688 size=(_BOX_WIDTH/2.2,20), 741 689 style=wx.TE_PROCESS_ENTER) 742 690 … … 744 692 self.sizer4_4.Add(Tct2, (iy,ix),(1,1), 745 693 wx.EXPAND|wx.ADJUST_MINSIZE, 0) 746 ix +=1747 self.sizer4_4.Add((20,20), (iy,ix),(1,1),748 wx.EXPAND|wx.ADJUST_MINSIZE, 0)694 #ix +=1 695 #self.sizer4_4.Add((20,20), (iy,ix),(1,1), 696 # wx.EXPAND|wx.ADJUST_MINSIZE, 0) 749 697 750 self.fixed_param.append([None,name3, Tct2 751 ,None,None,None, 752 None,None]) 753 698 self.fixed_param.append([None, name3, Tct2, 699 None, None, None, 700 None, None]) 701 702 703 ix = 8 704 disp_box = wx.ComboBox(self, -1,size=(65,-1), 705 style=wx.CB_READONLY, name = '%s'% name1) 706 for key, value in self.polydisp.iteritems(): 707 name_disp = str(key) 708 disp_box.Append(name_disp,value) 709 disp_box.SetStringSelection("gaussian") 710 wx.EVT_COMBOBOX(disp_box,-1, self._on_disp_func) 711 self.sizer4_4.Add(disp_box,(iy,ix),(1,1), wx.EXPAND) 712 self.fittable_param.append([cb,name1,ctl1,text2, 713 ctl2, ctl3, ctl4, disp_box]) 714 754 715 ix =0 755 716 iy +=1 … … 776 737 ix = 0 777 738 cb = wx.CheckBox(self, -1, name0, (10, 10)) 778 cb.SetToolTipString("Check for fitting")739 cb.SetToolTipString("Check mark to fit") 779 740 wx.EVT_CHECKBOX(self, cb.GetId(), self.select_param) 780 741 self.sizer4_4.Add( cb,( iy, ix),(1,1), 781 742 wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 782 15)743 5) 783 744 if self.data.__class__.__name__ =="Data2D": 784 745 cb.Show(True) … … 787 748 ix = 1 788 749 value= self.model.getParam(name1) 789 ctl1 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH ,750 ctl1 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH/1.3, 790 751 20),style=wx.TE_PROCESS_ENTER) 791 752 poly_tip = "Absolute Sigma for %s." % item 792 753 ctl1.SetToolTipString(poly_tip) 793 ctl1.SetValue(str (format_number(value )))754 ctl1.SetValue(str (format_number(value, True))) 794 755 if self.data.__class__.__name__ =="Data2D": 795 756 if first_orient: … … 817 778 818 779 ix = 3 819 ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH ,20),780 ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH/1.3,20), 820 781 style=0) 821 782 … … 842 803 wx.EXPAND|wx.ADJUST_MINSIZE, 0) 843 804 ctl4.Hide() 844 #if self.data.__class__.__name__ =="Data2D":845 #ctl4.Enable(True)846 #elif ctl4.Shown():847 #ctl4.Hide()848 805 849 if self.engine_type=="park" and \ 850 self.data.__class__.__name__ =="Data2D": 806 if self.data.__class__.__name__ =="Data2D": 851 807 ctl3.Show(True) 852 808 ctl4.Show(True) 853 854 855 856 857 self.fittable_param.append([cb,name1,ctl1,text2, 858 ctl2, ctl3, ctl4,None]) 859 self.orientation_params_disp.append([cb,name1,ctl1, 860 text2, ctl2, ctl3, ctl4,None]) 809 861 810 elif p=="npts": 862 811 ix = 6 863 812 value= self.model.getParam(name2) 864 813 Tctl = self.ModelTextCtrl(self, -1, 865 size=(_BOX_WIDTH/2,20),814 size=(_BOX_WIDTH/2.2, 20), 866 815 style=wx.TE_PROCESS_ENTER) 867 816 … … 882 831 value= self.model.getParam(name3) 883 832 Tct2 = self.ModelTextCtrl(self, -1, 884 size=(_BOX_WIDTH/2 ,20),833 size=(_BOX_WIDTH/2.2,20), 885 834 style=wx.TE_PROCESS_ENTER) 886 835 … … 892 841 self.sizer4_4.Add(Tct2, (iy,ix),(1,1), 893 842 wx.EXPAND|wx.ADJUST_MINSIZE, 0) 894 ix +=1 843 895 844 896 845 self.fixed_param.append([None,name3, Tct2 … … 900 849 Tct2 ,None,None, None, None,None]) 901 850 851 852 ix = 8 853 disp_box = wx.ComboBox(self, -1,size=(65,-1), 854 style=wx.CB_READONLY, name = '%s'% name1) 855 for key, value in self.polydisp.iteritems(): 856 name_disp = str(key) 857 disp_box.Append(name_disp,value) 858 disp_box.SetStringSelection("gaussian") 859 wx.EVT_COMBOBOX(disp_box,-1, self._on_disp_func) 860 self.sizer4_4.Add(disp_box,(iy,ix),(1,1), wx.EXPAND) 861 self.fittable_param.append([cb,name1,ctl1,text2, 862 ctl2, ctl3, ctl4, disp_box]) 863 self.orientation_params_disp.append([cb,name1,ctl1, 864 text2, ctl2, ctl3, ctl4, disp_box]) 865 866 if self.data.__class__.__name__ =="Data2D": 867 disp_box.Show(True) 868 else: 869 disp_box.Hide() 870 871 902 872 self.state.disp_cb_dict = copy.deepcopy(self.disp_cb_dict) 903 873 … … 920 890 self.Layout() 921 891 892 893 def _onDraw(self, event): 894 """ 895 Update and Draw the model 896 """ 897 if self.model ==None: 898 msg="Please select a Model first..." 899 wx.MessageBox(msg, 'Info') 900 wx.PostEvent(self.manager.parent, StatusEvent(status=\ 901 "Draw model: %s"%msg)) 902 return 903 flag = self._update_paramv_on_fit() 904 self._onparamEnter_helper() 905 if not flag: 906 msg= "The parameters are invalid" 907 wx.PostEvent(self.parent.parent, StatusEvent(status= msg )) 908 return 909 910 922 911 def _onFit(self, event): 923 912 """ … … 934 923 wx.MessageBox(msg, 'Info') 935 924 wx.PostEvent(self._manager.parent, StatusEvent(status=\ 936 "Fit: %s" % msg))925 "Fit: %s"%msg, type="stop")) 937 926 return 938 927 … … 941 930 if not flag: 942 931 msg= "Fitting range or parameters are invalid" 943 wx.PostEvent(self.parent.parent, StatusEvent(status= msg )) 932 wx.PostEvent(self.parent.parent, StatusEvent(status= msg, 933 type="stop")) 944 934 return 945 935 946 936 if len(self.param_toFit) <= 0: 947 937 msg= "Select at least one parameter to fit" 948 wx.PostEvent(self.parent.parent, StatusEvent(status= msg )) 938 wx.PostEvent(self.parent.parent, StatusEvent(status= msg, 939 type="stop" )) 949 940 return 950 941 … … 1227 1218 self.set_npts2fit() 1228 1219 else: 1229 if self.data is not None: 1230 1231 index_data = ((self.qmin_x <= self.data.x)& \ 1232 (self.data.x <= self.qmax_x)) 1233 self.Npts_fit.SetValue(str(len(self.data.x[index_data]))) 1234 1220 index_data = ((self.qmin_x <= self.data.x)& \ 1221 (self.data.x <= self.qmax_x)) 1222 self.Npts_fit.SetValue(str(len(self.data.x[index_data]))) 1235 1223 1236 1224 else: … … 1698 1686 raise ValueError,"missing parameter to fit" 1699 1687 1700 def onsetValues(self, chisqr,p_name, out,cov):1688 def onsetValues(self, chisqr, p_name, out, cov): 1701 1689 """ 1702 1690 Build the panel from the fit result … … 1718 1706 1719 1707 #Check if chi2 is finite 1720 if chisqr != None ornumpy.isfinite(chisqr):1708 if chisqr != None and numpy.isfinite(chisqr): 1721 1709 #format chi2 1722 1710 if self.engine_type == "park": … … 1724 1712 if npt_fit > 0: 1725 1713 chisqr =chisqr/npt_fit 1726 chi2 = format_number(chisqr )1714 chi2 = format_number(chisqr, True) 1727 1715 self.tcChi.SetValue(chi2) 1728 1716 self.tcChi.Refresh() … … 1735 1723 1736 1724 try: 1737 n = self.disp_box.GetCurrentSelection() 1738 dispersity= self.disp_box.GetClientData(n) 1739 if dispersity !=None and self.enable_disp.GetValue(): 1740 name= dispersity.__name__ 1741 if name == "GaussianDispersion": 1742 if hasattr(self,"text_disp_1" ): 1743 if self.text_disp_1 !=None: 1744 self.text_disp_1.Hide() 1725 if self.enable_disp.GetValue(): 1726 if hasattr(self,"text_disp_1" ): 1727 if self.text_disp_1 != None: 1728 self.text_disp_1.Hide() 1745 1729 except: 1746 1730 dispersty = None … … 1748 1732 #set the panel when fit result are float not list 1749 1733 if out.__class__== numpy.float64: 1750 self.param_toFit[0][2].SetValue(format_number(out ))1734 self.param_toFit[0][2].SetValue(format_number(out, True)) 1751 1735 1752 1736 if self.param_toFit[0][4].IsShown: … … 1755 1739 self.text2_3.Show(True) 1756 1740 try: 1757 if dispersity !=None: 1758 name= dispersity.__name__ 1759 if name == "GaussianDispersion" and \ 1760 self.enable_disp.GetValue(): 1761 if hasattr(self,"text_disp_1" ): 1762 if self.text_disp_1 !=None: 1763 self.text_disp_1.Show(True) 1741 if self.enable_disp.GetValue(): 1742 if hasattr(self,"text_disp_1" ): 1743 if self.text_disp_1 !=None: 1744 self.text_disp_1.Show(True) 1764 1745 except: 1765 1746 pass … … 1771 1752 self.param_toFit[0][3].Show(True) 1772 1753 self.param_toFit[0][4].Show(True) 1773 self.param_toFit[0][4].SetValue(format_number(cov[0] ))1754 self.param_toFit[0][4].SetValue(format_number(cov[0], True)) 1774 1755 has_error = True 1775 1756 else: … … 1788 1769 break 1789 1770 if len(out)<=len(self.param_toFit) and out[ind] !=None: 1790 val_out = format_number(out[ind] )1771 val_out = format_number(out[ind], True) 1791 1772 item[2].SetValue(val_out) 1792 1773 … … 1795 1776 try: 1796 1777 if dispersity !=None: 1797 name= dispersity.__name__ 1798 if name == "GaussianDispersion" and \ 1799 self.enable_disp.GetValue(): 1778 if self.enable_disp.GetValue(): 1800 1779 if hasattr(self,"text_disp_1" ): 1801 1780 if self.text_disp_1!=None: … … 1807 1786 if cov[ind]!=None : 1808 1787 if numpy.isfinite(float(cov[ind])): 1809 val_err = format_number(cov[ind] )1788 val_err = format_number(cov[ind], True) 1810 1789 item[3].Show(True) 1811 1790 item[4].Show(True) … … 1821 1800 ## save current state 1822 1801 self.save_current_state() 1823 #plot model 1824 self._draw_model() 1825 self._lay_out() 1802 #plot model ( when drawing, do not update chisqr value again) 1803 self._draw_model(update_chisqr=False) 1804 self._lay_out() 1805 self.Refresh() 1826 1806 #PostStatusEvent 1827 1807 msg = "Fit completed! " … … 2267 2247 else: 2268 2248 output = event.output 2269 self.tcChi.SetValue(str(format_number(output )))2249 self.tcChi.SetValue(str(format_number(output, True))) 2270 2250 2271 2251 self.state.tcChi = self.tcChi.GetValue() … … 2296 2276 item[0].SetValue(True) 2297 2277 self.param_toFit.append(item ) 2278 try: 2279 if len(self.values[item[1]]) > 0: 2280 item[0].SetValue(False) 2281 except: 2282 pass 2283 2298 2284 else: 2299 2285 ## for 1D all parameters except orientation … … 2301 2287 item[0].SetValue(True) 2302 2288 self.param_toFit.append(item ) 2289 try: 2290 if len(self.values[item[1]]) > 0: 2291 item[0].SetValue(False) 2292 except: 2293 pass 2294 2303 2295 else: 2304 2296 for item in self.parameters: … … 2476 2468 sizer.Add(self.text2_min,(iy, ix),(1,1),\ 2477 2469 wx.EXPAND|wx.ADJUST_MINSIZE, 0) 2478 self.text2_min.Hide()2470 #self.text2_min.Hide() 2479 2471 ix +=1 2480 2472 self.text2_max = wx.StaticText(self, -1, 'Max') 2481 2473 sizer.Add(self.text2_max,(iy, ix),(1,1),\ 2482 2474 wx.EXPAND|wx.ADJUST_MINSIZE, 0) 2483 self.text2_max.Hide()2475 #self.text2_max.Hide() 2484 2476 ix += 1 2485 2477 self.text2_4 = wx.StaticText(self, -1, '[Units]') … … 2487 2479 wx.EXPAND|wx.ADJUST_MINSIZE, 0) 2488 2480 self.text2_4.Hide() 2489 if self.engine_type=="park":2490 self.text2_max.Show(True)2491 self.text2_min.Show(True)2492 2481 2493 2482 for item in keys: … … 2524 2513 style=wx.TE_PROCESS_ENTER, name ='%s'% item) 2525 2514 fun_box.SetToolTipString("Hit 'Enter' after typing.") 2526 fun_box.SetValue(format_number(value ))2515 fun_box.SetValue(format_number(value, True)) 2527 2516 sizer.Add(fun_box, (iy,ix),(1,1), wx.EXPAND) 2528 2517 self.str_parameters.append([None,item, fun_box, 2529 None,None,None,None,None]) 2518 None, None, None, 2519 None, None]) 2530 2520 2531 2521 … … 2533 2523 ## add parameters name with checkbox for selecting to fit 2534 2524 cb = wx.CheckBox(self, -1, item ) 2535 cb.SetToolTipString(" Check for fitting.")2525 cb.SetToolTipString(" Check mark to fit.") 2536 2526 #cb.SetValue(True) 2537 2527 wx.EVT_CHECKBOX(self, cb.GetId(), self.select_param) … … 2546 2536 style=wx.TE_PROCESS_ENTER) 2547 2537 ctl1.SetToolTipString("Hit 'Enter' after typing.") 2548 ctl1.SetValue(format_number(value ))2538 ctl1.SetValue(format_number(value, True)) 2549 2539 sizer.Add(ctl1, (iy,ix),(1,1), wx.EXPAND) 2550 2540 ## text to show error sign … … 2555 2545 text2.Hide() 2556 2546 ix += 1 2557 ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH ,20), style=0)2547 ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH/1.2,20), style=0) 2558 2548 sizer.Add(ctl2, (iy,ix),(1,1), 2559 2549 wx.EXPAND|wx.ADJUST_MINSIZE, 0) … … 2561 2551 2562 2552 ix += 1 2563 ctl3 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH/ 2,20),2553 ctl3 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH/1.9,20), 2564 2554 style=wx.TE_PROCESS_ENTER, 2565 2555 text_enter_callback = self._onparamRangeEnter) … … 2567 2557 sizer.Add(ctl3, (iy,ix),(1,1), 2568 2558 wx.EXPAND|wx.ADJUST_MINSIZE, 0) 2569 ctl3.Hide()2570 2559 2571 2560 ix += 1 2572 ctl4 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH/ 2,20),2561 ctl4 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH/1.9,20), 2573 2562 style=wx.TE_PROCESS_ENTER, 2574 2563 text_enter_callback = self._onparamRangeEnter) 2575 2564 sizer.Add(ctl4, (iy,ix),(1,1), 2576 wx.EXPAND|wx.ADJUST_MINSIZE, 0) 2577 2578 ctl4.Hide() 2565 wx.EXPAND|wx.FIXED_MINSIZE, 0) 2579 2566 2580 if self.engine_type=="park":2581 ctl3.Show(True)2582 ctl4.Show(True)2583 2567 ix +=1 2584 2568 # Units … … 2632 2616 cb = wx.CheckBox(self, -1, item ) 2633 2617 cb.SetValue(False) 2634 cb.SetToolTipString("Check for fitting")2618 cb.SetToolTipString("Check mark to fit") 2635 2619 wx.EVT_CHECKBOX(self, cb.GetId(), self.select_param) 2636 2620 if self.data.__class__.__name__ =="Data2D": … … 2647 2631 style=wx.TE_PROCESS_ENTER) 2648 2632 ctl1.SetToolTipString("Hit 'Enter' after typing.") 2649 ctl1.SetValue(format_number(value ))2633 ctl1.SetValue(format_number(value, True)) 2650 2634 if self.data.__class__.__name__ =="Data2D": 2651 2635 ctl1.Show(True) … … 2660 2644 text2.Hide() 2661 2645 ix += 1 2662 ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH ,20), style=0)2646 ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH/1.2,20), style=0) 2663 2647 sizer.Add(ctl2, (iy,ix),(1,1), 2664 2648 wx.EXPAND|wx.ADJUST_MINSIZE, 0) … … 2667 2651 2668 2652 ix += 1 2669 ctl3 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH/ 2,20),2653 ctl3 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH/1.8,20), 2670 2654 style=wx.TE_PROCESS_ENTER, 2671 2655 text_enter_callback = self._onparamRangeEnter) … … 2676 2660 2677 2661 ix += 1 2678 ctl4 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH/ 2,20),2662 ctl4 = self.ModelTextCtrl(self, -1, size=(_BOX_WIDTH/1.8,20), 2679 2663 style=wx.TE_PROCESS_ENTER, 2680 2664 text_enter_callback = self._onparamRangeEnter) … … 2684 2668 ctl4.Hide() 2685 2669 2686 if self.engine_type =="park" and \ 2687 self.data.__class__.__name__ =="Data2D": 2670 if self.data.__class__.__name__ =="Data2D": 2688 2671 ctl3.Show(True) 2689 2672 ctl4.Show(True) … … 2727 2710 self.Layout() 2728 2711 self.Refresh() 2729 2712 2713 def on_right_down(self, event): 2714 """ 2715 Get key stroke event 2716 """ 2717 if self.data == None: 2718 return 2719 # Figuring out key combo: Cmd for copy, Alt for paste 2720 if event.AltDown() and event.ShiftDown(): 2721 self._show_ftol_dialog() 2722 flag = True 2723 else: 2724 flag = False 2725 # make event free 2726 event.Skip() 2727 # messages depending on the flag 2728 if not flag: 2729 msg = " Could not open ftol dialog;" 2730 msg += " Check if the Scipy fit engine is selected in the menubar." 2731 infor = 'warning' 2732 # inform msg to wx 2733 wx.PostEvent( self.parent.parent, 2734 StatusEvent(status= msg, info=infor)) 2735 2736 2737 def _show_ftol_dialog(self): 2738 """ 2739 Dialog to select ftol for Scipy 2740 """ 2741 from ftol_dialog import ChangeFtol 2742 panel = ChangeFtol(self) 2743 panel.ShowModal() 2744 2730 2745 def _onModel2D(self, event): 2731 2746 """ -
sansview/perspectives/fitting/fitpanel.py
r9466f2d6 r2296316 61 61 #add default pages 62 62 self.add_default_pages() 63 63 64 64 65 def _on_engine_change(self, name='scipy'): … … 140 141 Add default pages such as a hint page and an empty fit page 141 142 """ 143 pass 142 144 #add default page 143 from hint_fitpage import HintFitPage144 self.hint_page = HintFitPage(self)145 self.AddPage(self.hint_page,"Hint")146 self.hint_page.set_manager(self._manager)145 #from hint_fitpage import HintFitPage 146 #self.hint_page = HintFitPage(self) 147 #self.AddPage(self.hint_page,"Hint") 148 #self.hint_page.set_manager(self._manager) 147 149 148 150 def close_all(self): -
sansview/perspectives/fitting/fitting.py
r9466f2d6 r2296316 69 69 self.calc_1D = None 70 70 self.fit_thread_list = {} 71 self.residuals = None 71 72 self.fit_panel = None 72 73 # Start with a good default … … 74 75 # the type of optimizer selected, park or scipy 75 76 self.fitter = None 77 self.fit_panel = None 76 78 #let fit ready 77 79 self.fitproblem_count = None … … 82 84 ## Fit engine 83 85 self._fit_engine = 'scipy' 86 ## Relative error desired in the sum of squares (float); scipy only 87 self.ftol=1.49012e-08 84 88 #List of selected data 85 89 self.selected_data_list = [] … … 132 136 id1 = wx.NewId() 133 137 simul_help = "Simultaneous Fit" 134 self.menu1.Append(id1, '&Simultaneous Page',simul_help)138 self.menu1.Append(id1, '&Simultaneous Fit',simul_help) 135 139 wx.EVT_MENU(owner, id1, self.on_add_sim_page) 136 140 … … 143 147 144 148 #create menubar items 145 return [(self.menu1, "Fit ting")]149 return [(self.menu1, "FitEngine")] 146 150 147 151 def on_add_sim_page(self, event): … … 445 449 param_name=param_names[1] 446 450 return model_name,param_name 447 451 452 def set_ftol(self, ftol=None): 453 """ 454 Set ftol: Relative error desired in the sum of chi squares. 455 """ 456 # check if it is flaot 457 try: 458 f_tol = float(ftol) 459 except: 460 # default 461 f_tol = 1.49012e-08 462 463 self.ftol = f_tol 464 448 465 def stop_fit(self, uid): 449 466 """ … … 492 509 state=None, 493 510 toggle_mode_on=False, 494 qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, qstep=DEFAULT_NPTS): 511 qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, 512 qstep=DEFAULT_NPTS, 513 update_chisqr=True): 495 514 """ 496 515 Draw model. … … 505 524 :param qmax: Range's maximum value to draw model 506 525 :param qstep: number of step to divide the x and y-axis 526 :param update_chisqr: update chisqr [bool] 507 527 508 528 """ … … 519 539 toggle_mode_on=toggle_mode_on, 520 540 state=state, 521 qstep=qstep) 541 qstep=qstep, 542 update_chisqr=update_chisqr) 522 543 else: 523 544 ## draw model 2D with no initial data … … 531 552 state=state, 532 553 toggle_mode_on=toggle_mode_on, 533 qstep=qstep) 554 qstep=qstep, 555 update_chisqr=update_chisqr) 534 556 535 557 def onFit(self): … … 598 620 calc_fit = FitThread(handler = handler, 599 621 fn=fitter, 600 pars=pars, 601 page_id=list_page_id, 602 completefn=self._single_fit_completed) 622 pars=pars, 623 page_id=list_page_id, 624 completefn=self._single_fit_completed, 625 ftol=self.ftol) 603 626 else: 604 627 current_page_id = self.sim_page.uid … … 607 630 fn=fitter, 608 631 page_id=list_page_id, 609 completefn= self._simul_fit_completed) 632 updatefn=handler.update_fit, 633 ftol=self.ftol) 610 634 self.fit_thread_list[current_page_id] = calc_fit 611 635 calc_fit.queue() … … 851 875 try: 852 876 if result == None: 853 msg= "Simple Fitting Stop !!!" 854 wx.PostEvent(self.parent, StatusEvent(status=msg,info="warning", 855 type="stop")) 877 msg= "Single Fitting did not converge!!!" 878 wx.PostEvent(self.parent, 879 StatusEvent(status=msg, 880 info="warning", 881 type="stop")) 856 882 return 857 883 if not numpy.isfinite(result.fitness) or \ … … 860 886 msg = "Single Fitting did not converge!!!" 861 887 wx.PostEvent(self.parent, 862 StatusEvent(status=msg, type="stop")) 888 StatusEvent(status=msg, 889 info="warning", 890 type="stop")) 863 891 return 864 892 for uid in page_id: … … 875 903 param_name, result.pvec,result.stderr) 876 904 cpage._on_fit_complete() 877 905 906 except ValueError: 907 msg = "Single Fitting did not converge!!!" 908 wx.PostEvent(self.parent, StatusEvent(status=msg, info="error", 909 type="stop")) 910 return 878 911 except: 879 912 raise … … 899 932 msg = "" 900 933 if result == None: 901 msg = "Complex Fitting Stop!!!"934 msg= "Complex Fitting did not converge!!!" 902 935 wx.PostEvent(self.parent, StatusEvent(status=msg, 903 936 type="stop")) … … 933 966 small_out,small_cov) 934 967 cpage._on_fit_complete() 968 969 except Exception: 970 msg = "Complex Fitting did not converge!!!" 971 wx.PostEvent(self.parent, StatusEvent(status=msg, info="error", 972 type="stop")) 973 return 974 935 975 except: 936 976 msg = "Simultaneous Fit completed" … … 1144 1184 1145 1185 def _complete1D(self, x,y, page_id, elapsed,index,model, 1146 toggle_mode_on=False,state=None, data=None): 1186 toggle_mode_on=False,state=None, 1187 data=None, update_chisqr=True): 1147 1188 """ 1148 1189 Complete plotting 1D data … … 1202 1243 wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot, 1203 1244 title= str(title))) 1204 1205 wx.PostEvent(current_pg,1206 Chi2UpdateEvent(output=self._cal_chisqr(data=data,1245 if update_chisqr: 1246 wx.PostEvent(current_pg, 1247 Chi2UpdateEvent(output=self._cal_chisqr(data=data, 1207 1248 page_id=page_id, 1208 1249 index=index))) 1250 else: 1251 self._plot_residuals(page_id, data, index) 1252 1209 1253 msg = "Plot 1D complete !" 1210 1254 wx.PostEvent( self.parent, StatusEvent(status=msg, type="stop" )) 1255 #self.current_pg.state.theory_data = deepcopy(self.theory_data) 1211 1256 except: 1212 1257 raise … … 1224 1269 1225 1270 def _complete2D(self, image, data, model, page_id, elapsed, index, qmin, 1226 qmax, toggle_mode_on=False,state=None,qstep=DEFAULT_NPTS): 1271 qmax, toggle_mode_on=False,state=None,qstep=DEFAULT_NPTS, 1272 update_chisqr=True): 1227 1273 """ 1228 1274 Complete get the result of modelthread and create model 2D … … 1284 1330 title=title)) 1285 1331 # Chisqr in fitpage 1286 wx.PostEvent(current_pg, 1287 Chi2UpdateEvent(output=self._cal_chisqr(data=data, 1332 if update_chisqr: 1333 wx.PostEvent(current_pg, 1334 Chi2UpdateEvent(output=\ 1335 self._cal_chisqr(data=data, 1288 1336 page_id=page_id, 1289 1337 index=index))) 1338 else: 1339 self._plot_residuals(page_id, data, index) 1290 1340 msg = "Plot 2D complete !" 1291 1341 wx.PostEvent(self.parent, StatusEvent(status=msg, type="stop")) … … 1296 1346 toggle_mode_on=False, 1297 1347 qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, 1298 qstep=DEFAULT_NPTS): 1348 qstep=DEFAULT_NPTS, 1349 update_chisqr=True): 1299 1350 """ 1300 1351 draw model in 2D … … 1346 1397 toggle_mode_on=toggle_mode_on, 1347 1398 state=state, 1348 completefn=self._complete2D)#, 1349 #updatefn=self._update2D) 1399 completefn=self._complete2D, 1400 #updatefn= self._update2D, 1401 update_chisqr=update_chisqr) 1402 1350 1403 self.calc_2D.queue() 1351 1404 … … 1360 1413 state=None, 1361 1414 toggle_mode_on=False, 1362 qstep=DEFAULT_NPTS, enable1D=True): 1415 qstep=DEFAULT_NPTS, update_chisqr=True, 1416 enable1D=True): 1363 1417 """ 1364 1418 Draw model 1D from loaded data1D … … 1378 1432 return 1379 1433 x = data.x 1380 if qmin == DEFAULT_QMIN : 1381 qmin = min(data.x) 1382 if qmax == DEFAULT_QMAX: 1383 qmax = max(data.x) 1434 if qmin == None : 1435 qmin == DEFAULT_QMIN 1436 1437 if qmax == None: 1438 qmax == DEFAULT_QMAX 1384 1439 if not enable1D: 1385 1440 return … … 1398 1453 state=state, 1399 1454 toggle_mode_on=toggle_mode_on, 1400 completefn=self._complete1D)#, 1401 #updatefn=self._update1D) 1455 completefn=self._complete1D, 1456 #updatefn = self._update1D, 1457 update_chisqr=update_chisqr) 1458 1402 1459 self.calc_1D.queue() 1403 1460 … … 1419 1476 1420 1477 # Get data: data I, theory I, and data dI in order 1421 if data.__class__.__name__ == "Data2D":1478 if data.__class__.__name__ == "Data2D": 1422 1479 if index == None: 1423 1480 index = numpy.ones(len(data.data),ntype=bool) 1424 1481 # get rid of zero error points 1425 index = index & (data.err_data != 0) 1482 index = index & (data.err_data != 0 ) 1483 index = index & (numpy.isfinite(data.data)) 1426 1484 fn = data.data[index] 1427 1485 theory_data = self.page_finder[page_id].get_theory_data() … … 1430 1488 else: 1431 1489 # 1 d theory from model_thread is only in the range of index 1432 if index == None: 1490 if index == None: 1433 1491 index = numpy.ones(len(data.y), ntype=bool) 1434 1492 if data.dy == None or data.dy == []: … … 1437 1495 ## Set consitently w/AbstractFitengine: 1438 1496 # But this should be corrected later. 1439 dy = d ata.dy1497 dy = deepcopy(data.dy) 1440 1498 dy[dy==0] = 1 1441 1499 fn = data.y[index] … … 1444 1502 en = dy[index] 1445 1503 # residual 1446 res = (fn - gn)/en 1504 res = (fn - gn) / en 1505 residuals = res[numpy.isfinite(res)] 1447 1506 # get chisqr only w/finite 1448 val = res[numpy.isfinite(res)]*res[numpy.isfinite(res)] 1449 chisqr = numpy.average(val) 1507 chisqr = numpy.average(residuals * residuals) 1508 1509 self._plot_residuals(page_id, data, index) 1450 1510 return chisqr 1451 1511 1452 1512 1513 1514 def _plot_residuals(self, page_id, data=None, index=None): 1515 """ 1516 Plot the residuals 1517 1518 :param data: data 1519 :param index: index array (bool) 1520 : Note: this is different from the residuals in cal_chisqr() 1521 """ 1522 if data == None: 1523 return 1524 1525 # Get data: data I, theory I, and data dI in order 1526 if data.__class__.__name__ == "Data2D": 1527 # build residuals 1528 #print data 1529 residuals = Data2D() 1530 #residuals.copy_from_datainfo(data) 1531 # Not for trunk the line below, instead use the line above 1532 data.clone_without_data(len(data.data), residuals) 1533 residuals.data = None 1534 fn = data.data#[index] 1535 theory_data = self.page_finder[page_id].get_theory_data() 1536 gn = theory_data.data#[index] 1537 en = data.err_data#[index] 1538 residuals.data = (fn - gn) / en 1539 residuals.qx_data = data.qx_data#[index] 1540 residuals.qy_data = data.qy_data #[index] 1541 residuals.q_data = data.q_data#[index] 1542 residuals.err_data = numpy.ones(len(residuals.data))#[index] 1543 residuals.xmin = min(residuals.qx_data) 1544 residuals.xmax = max(residuals.qx_data) 1545 residuals.ymin = min(residuals.qy_data) 1546 residuals.ymax = max(residuals.qy_data) 1547 residuals.q_data = data.q_data#[index] 1548 residuals.mask = data.mask 1549 residuals.scale = 'linear' 1550 #print "print data",residuals 1551 # check the lengths 1552 if len(residuals.data) != len(residuals.q_data): 1553 return 1554 1555 else: 1556 # 1 d theory from model_thread is only in the range of index 1557 if data.dy == None or data.dy == []: 1558 dy = numpy.ones(len(data.y)) 1559 else: 1560 ## Set consitently w/AbstractFitengine: 1561 ## But this should be corrected later. 1562 dy = deepcopy(data.dy) 1563 dy[dy==0] = 1 1564 fn = data.y[index] 1565 theory_data = self.page_finder[page_id].get_theory_data() 1566 gn = theory_data.y 1567 en = dy[index] 1568 # build residuals 1569 residuals = Data1D() 1570 residuals.y = (fn - gn) / en 1571 residuals.x = data.x[index] 1572 residuals.dy = numpy.ones(len(residuals.y)) 1573 residuals.dx = None 1574 residuals.dxl = None 1575 residuals.dxw = None 1576 residuals.ytransform = 'y' 1577 # For latter scale changes 1578 residuals.xaxis('\\rm{Q} ', 'A^{-1}') 1579 residuals.yaxis('\\rm{Residuals} ', 'normalized') 1580 1581 new_plot = residuals 1582 if data.id == None: 1583 data.id = data.name 1584 name = data.id 1585 new_plot.name = "Residuals for " + str(data.name) 1586 ## allow to highlight data when plotted 1587 new_plot.interactive = True 1588 ## when 2 data have the same id override the 1 st plotted 1589 new_plot.id = new_plot.name#name + " residuals" 1590 ##group_id specify on which panel to plot this data 1591 new_plot.group_id = new_plot.id 1592 #new_plot.is_data = True 1593 ##post data to plot 1594 title = new_plot.name 1595 1596 # plot data 1597 wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot, title=title)) 1598 1453 1599 #def profile(fn, *args, **kw): 1454 1600 # import cProfile, pstats, os -
sansview/perspectives/fitting/model_thread.py
re4957fb r2296316 20 20 completefn = None, 21 21 updatefn = None, 22 update_chisqr=True, 22 23 yieldtime = 0.01, 23 24 worktime = 0.01 … … 40 41 self.smearer = smearer#(data=self.data,model=self.model) 41 42 self.starttime = 0 43 self.update_chisqr = update_chisqr 42 44 43 45 def compute(self): … … 130 132 qmin=self.qmin, 131 133 qmax=self.qmax, 132 qstep=self.qstep) 134 qstep=self.qstep, 135 update_chisqr = self.update_chisqr ) 133 136 134 137 … … 146 149 state=None, 147 150 completefn = None, 151 update_chisqr=True, 148 152 updatefn = None, 149 153 yieldtime = 0.01, … … 166 170 self.smearer = smearer 167 171 self.starttime = 0 172 self.update_chisqr = update_chisqr 168 173 169 174 def compute(self): … … 190 195 toggle_mode_on=self.toggle_mode_on, 191 196 elapsed=elapsed,index=index, model=self.model, 192 data=self.data) 197 data=self.data, 198 update_chisqr = self.update_chisqr ) 193 199 194 200 def results(self): -
sansview/perspectives/fitting/pagestate.py
rdce84c0 r2296316 47 47 ["formfactorcombobox", "formfactorcombobox", "float"], 48 48 ["structurecombobox", "structurecombobox", "float"], 49 ["disp_box", "disp_box", "float"],50 49 ["enable_smearer","enable_smearer","bool"], 51 50 ["disable_smearer","disable_smearer","bool"], … … 65 64 list_of_model_attributes = [["values", "values"], 66 65 ["weights", "weights"]] 66 67 list_of_obj_dic = [["disp_obj_dict", "_disp_obj_dict", "string"]] 67 68 68 69 list_of_state_parameters = [["parameters", "parameters"] , … … 139 140 #Data used for fitting 140 141 self.data = data 142 # model data 143 self.theory_data = None 144 #Is 2D 145 self.is_2D = False 146 self.images = None 147 141 148 #save additional information on data that dataloader.reader does not read 142 149 self.is_data = None … … 196 203 if self.model is not None: 197 204 self.disp_list = self.model.getDispParamList() 198 self._disp_obj_dict = {} 205 199 206 self.disp_cb_dict = {} 200 self.values = [] 201 self.weights = [] 207 self.values = {} 208 self.weights = {} 209 202 210 203 211 #contains link between a model and selected parameters to fit … … 289 297 for k , v in self.disp_cb_dict.iteritems(): 290 298 obj.disp_cb_dict[k]= v 291 292 obj.values = copy.deepcopy(self.values) 293 obj.weights = copy.deepcopy(self.weights) 299 if len(self.values)>0: 300 for k , v in self.values.iteritems(): 301 obj.values[k] = v 302 if len(self.weights)>0: 303 for k , v in self.weights.iteritems(): 304 obj.weights[k] = v 294 305 obj.enable_smearer = copy.deepcopy(self.enable_smearer) 295 306 obj.disable_smearer = copy.deepcopy(self.disable_smearer) … … 337 348 rep = "\nState name: %s\n"%self.file 338 349 t = time.localtime(self.timestamp) 339 time_str = time.strftime("%b %d %H :%M", t)350 time_str = time.strftime("%b %d %H;%M of %Y", t) 340 351 rep += "State created on : %s\n"%time_str 341 352 rep += "State form factor combobox selection: %s\n"%self.formfactorcombobox … … 368 379 369 380 rep += "model : %s\n\n"% str(self.model) 370 rep += "number parameters(self.parameters): %s\n"%len(self.parameters) 371 rep = self._repr_helper( list=self.parameters, rep=rep) 372 rep += "number str_parameters(self.str_parameters): %s\n"%len(self.str_parameters) 373 rep = self._repr_helper( list=self.str_parameters, rep=rep) 374 rep += "number orientation parameters" 375 rep += "(self.orientation_params): %s\n"%len(self.orientation_params) 376 rep = self._repr_helper( list=self.orientation_params, rep=rep) 377 rep += "number dispersity parameters" 378 rep += "(self.orientation_params_disp): %s\n"%len(self.orientation_params_disp) 379 rep = self._repr_helper( list=self.orientation_params_disp, rep=rep) 381 temp_parameters = [] 382 temp_fittable_param = [] 383 if self.data.__class__.__name__ == "Data2D": 384 self.is_2D = True 385 else: 386 self.is_2D = False 387 if self.data is not None: 388 if not self.is_2D: 389 for item in self.parameters: 390 if not item in self.orientation_params: 391 temp_parameters.append(item) 392 for item in self.fittable_param: 393 if not item in self.orientation_params_disp: 394 temp_fittable_param.append(item) 395 else: 396 temp_parameters = self.parameters 397 temp_fittable_param = self.fittable_param 398 399 rep += "number parameters(self.parameters): %s\n"%len(temp_parameters) 400 rep = self._repr_helper( list=temp_parameters, rep=rep) 401 rep += "number str_parameters(self.str_parameters): %s\n"%len(self.str_parameters) 402 rep = self._repr_helper( list=self.str_parameters, rep=rep) 403 rep += "number fittable_param(self.fittable_param): %s\n"%len(temp_fittable_param) 404 rep = self._repr_helper( list=temp_fittable_param, rep=rep) 405 """ 406 if is_2D: 407 rep += "number orientation parameters" 408 rep += "(self.orientation_params): %s\n"%len(self.orientation_params) 409 rep = self._repr_helper( list=self.orientation_params, rep=rep) 410 rep += "number dispersity parameters" 411 rep += "(self.orientation_params_disp): %s\n"%len(self.orientation_params_disp) 412 rep = self._repr_helper( list=self.orientation_params_disp, rep=rep) 413 """ 380 414 381 415 return rep 382 416 417 418 def set_report_string(self): 419 """ 420 Get the values (strings) from __str__ for report 421 """ 422 # Dictionary of teh report strings 423 repo_time = "" 424 model_name = "" 425 title = "" 426 title_name = "" 427 file_name = "" 428 param_string = "" 429 paramval_string = "" 430 chi2_string = "" 431 q_range = "" 432 strings = self.__repr__() 433 lines = strings.split('\n') 434 435 # get all string values from __str__() 436 for line in lines: 437 value = "" 438 content = line.split(":") 439 name = content[0] 440 try: 441 value = content[1] 442 except: 443 pass 444 if name.count("State created on"): 445 repo_time = "Created on " + value 446 if name.count("parameter name"): 447 val_name = value.split(".") 448 if len(val_name) > 1: 449 if val_name[1].count("width"): 450 param_string += value + ',' 451 else: 452 continue 453 else: 454 param_string += value + ',' 455 if name == "value": 456 param_string += value + ',' 457 if name == "error value": 458 param_string += value + ',' 459 if name == "parameter unit": 460 param_string += value + ':' 461 if name == "Value of Chisqr ": 462 chi2 = ("Chi2/Npts = " + value) 463 chi2_string = CENTRE % chi2 464 if name == "Title": 465 if len(value.strip()) == 0: 466 continue 467 title = value + " [" + repo_time + "]" 468 title_name = HEADER % title 469 if name == "data ": 470 try: 471 file = ("File name:" + content[2]) 472 file_name = CENTRE % file 473 if len(title) == 0: 474 title = content[2] + " [" + repo_time + "]" 475 title_name = HEADER % title 476 except: 477 pass 478 if name == "Plotting Range": 479 try: 480 q_range = content[1] + " = " + content[2] \ 481 + " = " + content[3].split(",")[0] 482 q_name = ("Q Range: " + q_range) 483 q_range = CENTRE % q_name 484 except: 485 pass 486 paramval = "" 487 for lines in param_string.split(":"): 488 line = lines.split(",") 489 if len(lines) > 0: 490 param = line[0] 491 param += " = " + line[1] 492 if len(line[2].split()) > 0 and not line[2].count("None"): 493 param += " +- " + line[2] 494 if len(line[3].split()) > 0 and not line[3].count("None"): 495 param += " " + line[3] 496 if not paramval.count(param): 497 paramval += param + "\n" 498 paramval_string += CENTRE % param + "\n" 499 500 html_string = title_name + "\n" + file_name + \ 501 "\n" + q_range + \ 502 "\n" + chi2_string + \ 503 "\n" + ELINE + \ 504 "\n" + paramval_string + \ 505 "\n" + ELINE + \ 506 "\n" + FEET_1 % title + \ 507 "\n" + FEET_2 508 509 text_string = "\n\n\n" + title + "\n\n" + file + \ 510 "\n" + q_name + \ 511 "\n" + chi2 + \ 512 "\n\n" + paramval 513 514 return html_string, text_string, title 515 516 def report(self, figs=None, canvases=None): 517 """ 518 Invoke report dialog panel 519 520 : param figs: list of pylab figures [list] 521 """ 522 from report_dialog import ReportDialog 523 # get the strings for report 524 html_str, text_str, title = self.set_report_string() 525 # Allow 2 figures to append 526 if len(figs) == 1: 527 add_str = FEET_3 528 elif len(figs) == 2: 529 add_str = ELINE 530 add_str += FEET_2 % ("%s") 531 add_str += ELINE 532 add_str += FEET_3 533 elif len(figs) > 2: 534 add_str = ELINE 535 add_str += FEET_2 % ("%s") 536 add_str += ELINE 537 add_str += FEET_2 % ("%s") 538 add_str += ELINE 539 add_str += FEET_3 540 else: 541 add_str = "" 542 # final report html strings 543 report_str = html_str % ("%s") + add_str 544 545 # make plot image 546 images = self.set_plot_state(figs, canvases) 547 report_list = [report_str, text_str, images ] 548 dialog = ReportDialog(report_list, None, -1, "") 549 dialog.ShowModal() 550 383 551 def _toXML_helper(self, list, element, newdoc): 384 552 """ … … 463 631 for item in list_of_data_attributes: 464 632 element = newdoc.createElement(item[0]) 465 exec "element.setAttribute(item[0], str(self.%s))" %(item[1])633 exec "element.setAttribute(item[0], str(self.%s))" % (item[1]) 466 634 inputs.appendChild(element) 467 635 468 636 for item in list_of_state_attributes: 469 637 element = newdoc.createElement(item[0]) 470 exec "element.setAttribute(item[0], str(self.%s))" %(item[1])638 exec "element.setAttribute(item[0], str(self.%s))" % (item[1]) 471 639 inputs.appendChild(element) 472 640 641 # For self.values ={ disp_param_name: [vals,...],...} 642 # and for self.weights ={ disp_param_name: [weights,...],...} 473 643 for item in list_of_model_attributes: 474 644 element = newdoc.createElement(item[0]) 475 exec "list = self.%s"%item[1] 476 for value in list: 477 exec "element.appendChild(newdoc.createTextNode(str(%s)))"%value 645 exec "list = self.%s" % item[1] 646 for key, value in list.iteritems(): 647 sub_element = newdoc.createElement(key) 648 sub_element.setAttribute('name', str(key)) 649 for val in value: 650 com = "sub_element.appendChild" 651 com += "(newdoc.createTextNode(str(%s)))" 652 exec com % val 653 654 element.appendChild(sub_element) 478 655 inputs.appendChild(element) 479 656 657 # Create doc for the dictionary of self._disp_obj_dic 658 for item in list_of_obj_dic: 659 element = newdoc.createElement(item[0]) 660 exec "list = self.%s" % item[1] 661 for key, val in list.iteritems(): 662 value = repr(val) 663 sub_element = newdoc.createElement(key) 664 sub_element.setAttribute('name', str(key)) 665 sub_element.setAttribute('value', str(value)) 666 element.appendChild(sub_element) 667 inputs.appendChild(element) 668 480 669 for item in list_of_state_parameters: 481 670 element = newdoc.createElement(item[0]) 482 exec "self._toXML_helper(list=self.%s, element=element, newdoc=newdoc)"%item[1] 671 com = "self._toXML_helper(list=self.%s," 672 com += " element=element, newdoc=newdoc)" 673 exec com % item[1] 483 674 inputs.appendChild(element) 484 675 485 676 # Save the file 486 677 if doc is None: … … 537 728 except: 538 729 unit = None 539 list.append([selected_to_fit, name, value, "+/-",[error_displayed, error_value], 540 [minimum_displayed,minimum_value],[maximum_displayed,maximum_value], unit]) 730 list.append([selected_to_fit, name, value, "+/-", 731 [error_displayed, error_value], 732 [minimum_displayed,minimum_value], 733 [maximum_displayed,maximum_value], unit]) 541 734 542 735 def fromXML(self, file=None, node=None): … … 575 768 node = get_content('ns:%s'%item[0], entry) 576 769 try: 577 exec "self.%s = parse_entry_helper(node, item)" %item[0]770 exec "self.%s = parse_entry_helper(node, item)" % item[0] 578 771 579 772 except: 580 773 raise 581 774 582 775 if entry is not None: 583 776 584 777 for item in list_of_state_attributes: 585 node = get_content('ns:%s' %item[0], entry)778 node = get_content('ns:%s' % item[0], entry) 586 779 try: 587 exec "self.%s = parse_entry_helper(node, item)"%str(item[0]) 780 exec "self.%s = parse_entry_helper(node, item)" % \ 781 str(item[0]) 588 782 except: 589 783 raise 590 784 785 for item in list_of_state_parameters: 786 node = get_content("ns:%s" % item[0], entry) 787 exec "self._fromXML_helper(node=node, list=self.%s)" % \ 788 item[1] 789 790 # Recover _disp_obj_dict from xml file 791 self._disp_obj_dict = {} 792 for item in list_of_obj_dic: 793 # Get node 794 node = get_content("ns:%s" % item[0], entry) 795 for attr in node: 796 name = attr.get('name') 797 val = attr.get('value') 798 value = val.split(" instance")[0] 799 disp_name = value.split("<")[1] 800 try: 801 # Try to recover disp_model object from strings 802 com = "from sans.models.dispersion_models " 803 com += "import %s as disp" 804 com_name = disp_name.split(".")[3] 805 exec com % com_name 806 disp_model = disp() 807 exec "self.%s['%s'] = com_name" % (item[1], name) 808 except: 809 pass 810 811 # get self.values and self.weights dic. if exists 591 812 for item in list_of_model_attributes: 592 node = get_content("ns:%s"%item[0], entry) 813 node = get_content("ns:%s" % item[0], entry) 814 dic = {} 593 815 list = [] 594 for value in node: 595 try: 596 list.append(float(value)) 597 except: 598 list.append(None) 599 exec "self.%s = list"%item[1] 600 601 for item in list_of_state_parameters: 602 node = get_content("ns:%s"%item[0], entry) 603 exec "self._fromXML_helper(node=node, list=self.%s)"%item[1] 604 816 for par in node: 817 name = par.get('name') 818 values = par.text.split('\n') 819 # Get lines only with numbers 820 for line in values: 821 try: 822 val= float(line) 823 list.append(val) 824 except: 825 # pass if line is empty (it happens) 826 pass 827 dic[name] = numpy.array(list) 828 exec "self.%s = dic" % item[1] 829 830 def set_plot_state(self, figs, canvases): 831 """ 832 Build image state that wx.html understand 833 by plotting, putting it into wx.FileSystem image object 834 835 """ 836 images = [] 837 # some imports 838 import wx 839 840 # Reset memory 841 self.imgRAM = None 842 wx.MemoryFSHandler() 843 844 # For no figures in the list, prepare empty plot 845 if figs == None or len(figs) == 0: 846 figs = [None] 847 848 # Loop over the list of figures 849 # use wx.MemoryFSHandler 850 self.imgRAM = wx.MemoryFSHandler() 851 for fig in figs: 852 if figs != None: 853 #fig.set_facecolor('w') 854 ind = figs.index(fig) 855 canvas = canvases[ind] 856 857 #bmp = wx.BitmapDataObject() 858 #bmp.SetBitmap(canvas.bitmap) 859 #store the image in wx.FileSystem Object 860 wx.FileSystem.AddHandler(wx.MemoryFSHandler()) 861 862 # index of the fig 863 ind = figs.index(fig) 864 865 #AddFile, image can be retrieved with 'memory:filename' 866 self.imgRAM.AddFile('img_fit%s.png' % ind , 867 canvas.bitmap, wx.BITMAP_TYPE_PNG) 868 869 #append figs 870 images.append(fig) 871 872 return images 605 873 606 874 class Reader(CansasReader): … … 1233 1501 1234 1502 return doc 1235 1503 1504 1505 # Simple html report templet 1506 HEADER = "<html>\n" 1507 HEADER += "<head>\n" 1508 HEADER += "<meta http-equiv=Content-Type content='text/html; " 1509 HEADER += "charset=windows-1252'> \n" 1510 HEADER += "<meta name=Generator >\n" 1511 HEADER += "</head>\n" 1512 HEADER += "<body lang=EN-US>\n" 1513 HEADER += "<div class=WordSection1>\n" 1514 HEADER += "<p class=MsoNormal><b><span ><center>" 1515 HEADER += "%s</center></span></center></b></p>" 1516 HEADER += "<p class=MsoNormal> </p>" 1517 PARA = "<p class=MsoNormal> %s \n" 1518 PARA += "</p>" 1519 CENTRE = "<p class=MsoNormal><center> %s \n" 1520 CENTRE += "</center></p>" 1521 FEET_1 = \ 1522 """ 1523 <p class=MsoNormal> </p> 1524 <p class=MsoNormal><b><span ><center> Graph</span></center></b></p> 1525 <p class=MsoNormal> </p> 1526 <center> 1527 <br>Model Computation<br> 1528 <br>Data: "%s"<br> 1529 """ 1530 FEET_2 = \ 1531 """ 1532 <img src="%s" > 1533 </img> 1534 """ 1535 FEET_3 = \ 1536 """ 1537 </center> 1538 </div> 1539 </body> 1540 </html> 1541 """ 1542 ELINE = "<p class=MsoNormal> </p>" 1543 1544 1236 1545 if __name__ == "__main__": 1237 1546 state = PageState(parent=None) -
sansview/perspectives/fitting/simfitpage.py
r66ff250 r2296316 234 234 #------------------------------------------------------ 235 235 if len(self.page_finder)==0: 236 sizer_title.Add(wx.StaticText(self,-1," No fit combinations are found!")) 236 msg = " No fit combinations are found! \n\n" 237 msg += " Please load data and set up at least two fit panels first..." 238 sizer_title.Add(wx.StaticText(self, -1, msg)) 237 239 else: 238 240 ## store model
Note: See TracChangeset
for help on using the changeset viewer.