1 | import re |
---|
2 | import sys, wx, logging |
---|
3 | import string, numpy, math |
---|
4 | |
---|
5 | from copy import deepcopy |
---|
6 | from danse.common.plottools.plottables import Data1D, Theory1D,Data2D |
---|
7 | from danse.common.plottools.PlotPanel import PlotPanel |
---|
8 | from sans.guicomm.events import NewPlotEvent, StatusEvent |
---|
9 | from sans.guicomm.events import EVT_SLICER_PANEL,ERR_DATA |
---|
10 | |
---|
11 | from sans.fit.AbstractFitEngine import Model,FitData1D,FitData2D#,Data, |
---|
12 | from fitproblem import FitProblem |
---|
13 | from fitpanel import FitPanel |
---|
14 | from fit_thread import FitThread |
---|
15 | import models |
---|
16 | import fitpage |
---|
17 | |
---|
18 | DEFAULT_BEAM = 0.005 |
---|
19 | DEFAULT_QMIN = 0.0 |
---|
20 | DEFAULT_QMAX = 0.1 |
---|
21 | DEFAULT_NPTS = 50 |
---|
22 | import time |
---|
23 | import thread |
---|
24 | class PlotInfo: |
---|
25 | """ |
---|
26 | store some plotting field |
---|
27 | """ |
---|
28 | _xunit = 'A^{-1}' |
---|
29 | _xaxis= "\\rm{Q}" |
---|
30 | _yunit = "cm^{-1}" |
---|
31 | _yaxis= "\\rm{Intensity} " |
---|
32 | id = "Model" |
---|
33 | group_id = "Model" |
---|
34 | title= None |
---|
35 | info= None |
---|
36 | |
---|
37 | |
---|
38 | class Plugin: |
---|
39 | """ |
---|
40 | Fitting plugin is used to perform fit |
---|
41 | """ |
---|
42 | def __init__(self): |
---|
43 | ## Plug-in name |
---|
44 | self.sub_menu = "Fitting" |
---|
45 | |
---|
46 | ## Reference to the parent window |
---|
47 | self.parent = None |
---|
48 | #Provide list of models existing in the application |
---|
49 | self.menu_mng = models.ModelManager() |
---|
50 | ## List of panels for the simulation perspective (names) |
---|
51 | self.perspective = [] |
---|
52 | #list of panel to send to guiframe |
---|
53 | self.mypanels=[] |
---|
54 | # reference to the current running thread |
---|
55 | self.calc_2D= None |
---|
56 | self.calc_1D= None |
---|
57 | self.calc_fit= None |
---|
58 | |
---|
59 | # Start with a good default |
---|
60 | self.elapsed = 0.022 |
---|
61 | # the type of optimizer selected, park or scipy |
---|
62 | self.fitter = None |
---|
63 | #Flag to let the plug-in know that it is running stand alone |
---|
64 | self.standalone=True |
---|
65 | ## Fit engine |
---|
66 | self._fit_engine = 'scipy' |
---|
67 | #List of selected data |
---|
68 | self.selected_data_list=[] |
---|
69 | # Log startup |
---|
70 | logging.info("Fitting plug-in started") |
---|
71 | # model 2D view |
---|
72 | self.model2D_id=None |
---|
73 | #keep reference of the simultaneous fit page |
---|
74 | self.sim_page=None |
---|
75 | #dictionary containing data name and error on dy of that data |
---|
76 | self.err_dy={} |
---|
77 | |
---|
78 | |
---|
79 | |
---|
80 | def populate_menu(self, id, owner): |
---|
81 | """ |
---|
82 | Create a menu for the Fitting plug-in |
---|
83 | @param id: id to create a menu |
---|
84 | @param owner: owner of menu |
---|
85 | @ return : list of information to populate the main menu |
---|
86 | """ |
---|
87 | #Menu for fitting |
---|
88 | self.menu1 = wx.Menu() |
---|
89 | id1 = wx.NewId() |
---|
90 | self.menu1.Append(id1, '&Simultaneous') |
---|
91 | wx.EVT_MENU(owner, id1, self.on_add_sim_page) |
---|
92 | self.menu1.AppendSeparator() |
---|
93 | #Set park engine |
---|
94 | id3 = wx.NewId() |
---|
95 | scipy_help= "Scipy Engine: Perform Simple fit. More in Help window...." |
---|
96 | self.menu1.Append(id3, "Scipy",scipy_help) |
---|
97 | wx.EVT_MENU(owner, id3, self._onset_engine_scipy) |
---|
98 | self.menu1.AppendSeparator() |
---|
99 | id3 = wx.NewId() |
---|
100 | park_help = "Park Engine: Perform Complex fit. More in Help window...." |
---|
101 | self.menu1.Append(id3, "park",park_help) |
---|
102 | wx.EVT_MENU(owner, id3, self._onset_engine_park) |
---|
103 | |
---|
104 | #menu for model |
---|
105 | menu2 = wx.Menu() |
---|
106 | |
---|
107 | self.menu_mng.populate_menu(menu2, owner) |
---|
108 | id2 = wx.NewId() |
---|
109 | owner.Bind(models.EVT_MODEL,self._on_model_menu) |
---|
110 | |
---|
111 | self.fit_panel.set_owner(owner) |
---|
112 | self.fit_panel.set_model_list(self.menu_mng.get_model_list()) |
---|
113 | owner.Bind(fitpage.EVT_MODEL_BOX,self._on_model_panel) |
---|
114 | |
---|
115 | #create menubar items |
---|
116 | return [(id, self.menu1, "Fitting"),(id2, menu2, "Model")] |
---|
117 | |
---|
118 | def on_add_sim_page(self, event): |
---|
119 | """ |
---|
120 | Create a page to access simultaneous fit option |
---|
121 | """ |
---|
122 | if self.sim_page !=None: |
---|
123 | msg= "Simultaneous Fit page already opened" |
---|
124 | wx.PostEvent(self.parent, StatusEvent(status= msg)) |
---|
125 | return |
---|
126 | |
---|
127 | self.sim_page= self.fit_panel.add_sim_page() |
---|
128 | |
---|
129 | |
---|
130 | |
---|
131 | def help(self, evt): |
---|
132 | """ |
---|
133 | Show a general help dialog. |
---|
134 | TODO: replace the text with a nice image |
---|
135 | """ |
---|
136 | from helpPanel import HelpWindow |
---|
137 | frame = HelpWindow(None, -1, 'HelpWindow') |
---|
138 | frame.Show(True) |
---|
139 | |
---|
140 | |
---|
141 | def get_context_menu(self, graph=None): |
---|
142 | """ |
---|
143 | Get the context menu items available for P(r) |
---|
144 | @param graph: the Graph object to which we attach the context menu |
---|
145 | @return: a list of menu items with call-back function |
---|
146 | """ |
---|
147 | self.graph=graph |
---|
148 | for item in graph.plottables: |
---|
149 | if item.__class__.__name__ is "Data2D": |
---|
150 | return [["Select data for Fitting",\ |
---|
151 | "Dialog with fitting parameters ", self._onSelect]] |
---|
152 | else: |
---|
153 | |
---|
154 | if item.name==graph.selected_plottable : |
---|
155 | if not hasattr(item, "group_id"): |
---|
156 | return [] |
---|
157 | return [["Select data for Fitting", \ |
---|
158 | "Dialog with fitting parameters ", self._onSelect]] |
---|
159 | return [] |
---|
160 | |
---|
161 | |
---|
162 | def get_panels(self, parent): |
---|
163 | """ |
---|
164 | Create and return a list of panel objects |
---|
165 | """ |
---|
166 | self.parent = parent |
---|
167 | # Creation of the fit panel |
---|
168 | self.fit_panel = FitPanel(self.parent, -1) |
---|
169 | #Set the manager for the main panel |
---|
170 | self.fit_panel.set_manager(self) |
---|
171 | # List of windows used for the perspective |
---|
172 | self.perspective = [] |
---|
173 | self.perspective.append(self.fit_panel.window_name) |
---|
174 | # take care of saving data, model and page associated with each other |
---|
175 | self.page_finder = {} |
---|
176 | #index number to create random model name |
---|
177 | self.index_model = 0 |
---|
178 | self.index_theory= 0 |
---|
179 | self.parent.Bind(EVT_SLICER_PANEL, self._on_slicer_event) |
---|
180 | self.parent.Bind( ERR_DATA, self._on_data_error) |
---|
181 | |
---|
182 | #Send the fitting panel to guiframe |
---|
183 | self.mypanels.append(self.fit_panel) |
---|
184 | return self.mypanels |
---|
185 | |
---|
186 | |
---|
187 | |
---|
188 | def get_perspective(self): |
---|
189 | """ |
---|
190 | Get the list of panel names for this perspective |
---|
191 | """ |
---|
192 | return self.perspective |
---|
193 | |
---|
194 | |
---|
195 | def on_perspective(self, event): |
---|
196 | """ |
---|
197 | Call back function for the perspective menu item. |
---|
198 | We notify the parent window that the perspective |
---|
199 | has changed. |
---|
200 | """ |
---|
201 | self.parent.set_perspective(self.perspective) |
---|
202 | |
---|
203 | |
---|
204 | def post_init(self): |
---|
205 | """ |
---|
206 | Post initialization call back to close the loose ends |
---|
207 | [Somehow openGL needs this call] |
---|
208 | """ |
---|
209 | self.parent.set_perspective(self.perspective) |
---|
210 | |
---|
211 | |
---|
212 | def copy_data(self, item, dy): |
---|
213 | """ |
---|
214 | receive a data 1D and the list of errors on dy |
---|
215 | and create a new data1D data |
---|
216 | @param return |
---|
217 | """ |
---|
218 | detector=None |
---|
219 | source=None |
---|
220 | dxl=None |
---|
221 | dxw=None |
---|
222 | if hasattr(item, "dxl"): |
---|
223 | dxl = item.dxl |
---|
224 | if hasattr(item, "dxw"): |
---|
225 | dxw = item.dxw |
---|
226 | if hasattr(item, "detector"): |
---|
227 | detector =item.detector |
---|
228 | if hasattr(item, "source"): |
---|
229 | source =item.source |
---|
230 | from sans.guiframe import dataFitting |
---|
231 | data= dataFitting.Data1D(x=item.x, y=item.y, dy=dy, dxl=dxl, dxw=dxw) |
---|
232 | data.name=item.name |
---|
233 | data.detector=detector |
---|
234 | data.source= source |
---|
235 | return data |
---|
236 | |
---|
237 | def set_fit_range(self, page, qmin, qmax): |
---|
238 | """ |
---|
239 | Set the fitting range of a given page |
---|
240 | """ |
---|
241 | if page in self.page_finder.iterkeys(): |
---|
242 | fitproblem= self.page_finder[page] |
---|
243 | fitproblem.set_range(qmin= qmin, qmax= qmax) |
---|
244 | |
---|
245 | def schedule_for_fit(self,value=0,page=None,fitproblem =None): |
---|
246 | """ |
---|
247 | Set the fit problem field to 0 or 1 to schedule that problem to fit. |
---|
248 | Schedule the specified fitproblem or get the fit problem related to |
---|
249 | the current page and set value. |
---|
250 | @param value : integer 0 or 1 |
---|
251 | @param fitproblem: fitproblem to schedule or not to fit |
---|
252 | """ |
---|
253 | if fitproblem !=None: |
---|
254 | fitproblem.schedule_tofit(value) |
---|
255 | else: |
---|
256 | if page in self.page_finder.iterkeys(): |
---|
257 | fitproblem= self.page_finder[page] |
---|
258 | fitproblem.schedule_tofit(value) |
---|
259 | |
---|
260 | |
---|
261 | |
---|
262 | def get_page_finder(self): |
---|
263 | """ @return self.page_finder used also by simfitpage.py""" |
---|
264 | return self.page_finder |
---|
265 | |
---|
266 | |
---|
267 | def set_page_finder(self,modelname,names,values): |
---|
268 | """ |
---|
269 | Used by simfitpage.py to reset a parameter given the string constrainst. |
---|
270 | @param modelname: the name ot the model for with the parameter has to reset |
---|
271 | @param value: can be a string in this case. |
---|
272 | @param names: the paramter name |
---|
273 | @note: expecting park used for fit. |
---|
274 | """ |
---|
275 | sim_page= self.sim_page |
---|
276 | for page, value in self.page_finder.iteritems(): |
---|
277 | if page != sim_page: |
---|
278 | list=value.get_model() |
---|
279 | model = list[0] |
---|
280 | if model.name== modelname: |
---|
281 | value.set_model_param(names,values) |
---|
282 | break |
---|
283 | |
---|
284 | |
---|
285 | |
---|
286 | def split_string(self,item): |
---|
287 | """ |
---|
288 | receive a word containing dot and split it. used to split parameterset |
---|
289 | name into model name and parameter name example: |
---|
290 | paramaterset (item) = M1.A |
---|
291 | @return model_name =M1 , parameter name =A |
---|
292 | """ |
---|
293 | if string.find(item,".")!=-1: |
---|
294 | param_names= re.split("\.",item) |
---|
295 | model_name=param_names[0] |
---|
296 | param_name=param_names[1] |
---|
297 | return model_name,param_name |
---|
298 | |
---|
299 | |
---|
300 | def stop_fit(self): |
---|
301 | """ |
---|
302 | Stop the fit engine |
---|
303 | """ |
---|
304 | if self.calc_fit!= None and self.calc_thread.isrunning(): |
---|
305 | self.calc_thread.stop() |
---|
306 | wx.PostEvent(self.parent, StatusEvent(status="Fitting \ |
---|
307 | is cancelled" , type="stop")) |
---|
308 | |
---|
309 | |
---|
310 | |
---|
311 | def set_smearer(self,smearer, qmin=None, qmax=None): |
---|
312 | """ |
---|
313 | Get a smear object and store it to a fit problem |
---|
314 | @param smearer: smear object to allow smearing data |
---|
315 | """ |
---|
316 | current_pg=self.fit_panel.get_current_page() |
---|
317 | self.page_finder[current_pg].set_smearer(smearer) |
---|
318 | ## draw model 1D with smeared data |
---|
319 | data = self.page_finder[current_pg].get_plotted_data() |
---|
320 | model = self.page_finder[current_pg].get_model() |
---|
321 | ## if user has already selected a model to plot |
---|
322 | ## redraw the model with data smeared |
---|
323 | |
---|
324 | smearer =self.page_finder[current_pg].get_smearer() |
---|
325 | if smearer != None: |
---|
326 | self.draw_model( model=model, data= data, smearer= smearer, |
---|
327 | qmin= qmin, qmax= qmax) |
---|
328 | |
---|
329 | |
---|
330 | |
---|
331 | def draw_model(self, model, data= None,smearer= None, |
---|
332 | enable1D= True, enable2D= False, |
---|
333 | qmin= DEFAULT_QMIN, qmax= DEFAULT_QMAX, qstep= DEFAULT_NPTS): |
---|
334 | """ |
---|
335 | Draw model. |
---|
336 | @param model: the model to draw |
---|
337 | @param name: the name of the model to draw |
---|
338 | @param data: the data on which the model is based to be drawn |
---|
339 | @param description: model's description |
---|
340 | @param enable1D: if true enable drawing model 1D |
---|
341 | @param enable2D: if true enable drawing model 2D |
---|
342 | @param qmin: Range's minimum value to draw model |
---|
343 | @param qmax: Range's maximum value to draw model |
---|
344 | @param qstep: number of step to divide the x and y-axis |
---|
345 | |
---|
346 | """ |
---|
347 | ## draw model 1D with no loaded data |
---|
348 | self._draw_model1D( model= model, data= data,enable1D=enable1D, smearer= smearer, |
---|
349 | qmin= qmin, qmax= qmax, qstep= qstep ) |
---|
350 | ## draw model 2D with no initial data |
---|
351 | self._draw_model2D(model=model, |
---|
352 | data = data, |
---|
353 | enable2D= enable2D, |
---|
354 | qmin=qmin, |
---|
355 | qmax=qmax, |
---|
356 | qstep=qstep) |
---|
357 | |
---|
358 | def onFit(self): |
---|
359 | """ |
---|
360 | perform fit |
---|
361 | """ |
---|
362 | ## count the number of fitproblem schedule to fit |
---|
363 | fitproblem_count= 0 |
---|
364 | for value in self.page_finder.itervalues(): |
---|
365 | if value.get_scheduled()==1: |
---|
366 | fitproblem_count += 1 |
---|
367 | |
---|
368 | ## if simultaneous fit change automatically the engine to park |
---|
369 | if fitproblem_count >1: |
---|
370 | self._on_change_engine(engine='park') |
---|
371 | from sans.fit.Fitting import Fit |
---|
372 | self.fitter= Fit(self._fit_engine) |
---|
373 | |
---|
374 | if self._fit_engine=="park": |
---|
375 | engineType="Simutaneous Fit" |
---|
376 | else: |
---|
377 | engineType="Single Fit" |
---|
378 | |
---|
379 | fproblemId = 0 |
---|
380 | current_pg=None |
---|
381 | for page, value in self.page_finder.iteritems(): |
---|
382 | try: |
---|
383 | if value.get_scheduled()==1: |
---|
384 | #Get list of parameters name to fit |
---|
385 | pars = [] |
---|
386 | templist = [] |
---|
387 | templist = page.get_param_list() |
---|
388 | for element in templist: |
---|
389 | name = str(element[0].GetLabelText()) |
---|
390 | pars.append(name) |
---|
391 | #Set Engine (model , data) related to the page on |
---|
392 | self._fit_helper( current_pg=page, value=value,pars=pars, |
---|
393 | id=fproblemId, title= engineType ) |
---|
394 | fproblemId += 1 |
---|
395 | current_pg= page |
---|
396 | except: |
---|
397 | msg= "%s error: %s" % (engineType,sys.exc_value) |
---|
398 | wx.PostEvent(self.parent, StatusEvent(status= msg )) |
---|
399 | return |
---|
400 | #Do the simultaneous fit |
---|
401 | try: |
---|
402 | ## If a thread is already started, stop it |
---|
403 | if self.calc_fit!= None and self.calc_fit.isrunning(): |
---|
404 | self.calc_fit.stop() |
---|
405 | ## perform single fit |
---|
406 | if self._fit_engine=="scipy": |
---|
407 | qmin, qmax= current_pg.get_range() |
---|
408 | self.calc_fit=FitThread(parent =self.parent, |
---|
409 | fn= self.fitter, |
---|
410 | cpage=current_pg, |
---|
411 | pars= pars, |
---|
412 | completefn= self._single_fit_completed, |
---|
413 | updatefn=None) |
---|
414 | |
---|
415 | else: |
---|
416 | ## Perform more than 1 fit at the time |
---|
417 | self.calc_fit=FitThread(parent =self.parent, |
---|
418 | fn= self.fitter, |
---|
419 | completefn= self._simul_fit_completed, |
---|
420 | updatefn=None) |
---|
421 | self.calc_fit.queue() |
---|
422 | self.calc_fit.ready(2.5) |
---|
423 | |
---|
424 | except: |
---|
425 | msg= "%s error: %s" % (engineType,sys.exc_value) |
---|
426 | wx.PostEvent(self.parent, StatusEvent(status= msg )) |
---|
427 | return |
---|
428 | |
---|
429 | |
---|
430 | |
---|
431 | |
---|
432 | |
---|
433 | |
---|
434 | def _fit_helper(self,current_pg,pars,value, id, title="Single Fit " ): |
---|
435 | """ |
---|
436 | helper for fitting |
---|
437 | """ |
---|
438 | metadata = value.get_fit_data() |
---|
439 | model = value.get_model() |
---|
440 | smearer = value.get_smearer() |
---|
441 | qmin , qmax = value.get_range() |
---|
442 | self.fit_id =id |
---|
443 | #Create list of parameters for fitting used |
---|
444 | templist=[] |
---|
445 | pars=pars |
---|
446 | try: |
---|
447 | ## create a park model and reset parameter value if constraint |
---|
448 | ## is given |
---|
449 | new_model = Model(model) |
---|
450 | param = value.get_model_param() |
---|
451 | if len(param)>0: |
---|
452 | for item in param: |
---|
453 | param_value = item[1] |
---|
454 | param_name = item[0] |
---|
455 | ## check if constraint |
---|
456 | if param_value !=None and param_name != None: |
---|
457 | new_model.parameterset[ param_name].set( param_value ) |
---|
458 | |
---|
459 | |
---|
460 | #Do the single fit |
---|
461 | self.fitter.set_model(new_model, self.fit_id, pars) |
---|
462 | dy=[] |
---|
463 | x=[] |
---|
464 | y=[] |
---|
465 | ## checking the validity of error |
---|
466 | if metadata.__class__ in ["Data1D","Theory1D"]: |
---|
467 | for i in range(len(metadata.dy)): |
---|
468 | if metadata.dy[i] !=0: |
---|
469 | dy.append(metadata.dy[i]) |
---|
470 | x.append(metadata.x[i]) |
---|
471 | y.append(metadata.y[i]) |
---|
472 | if len(dy)>0: |
---|
473 | metadata.dy=numpy.zeros(len(dy)) |
---|
474 | metadata.dy=dy |
---|
475 | metadata.y=numpy.zeros(len(y)) |
---|
476 | metadata.y=y |
---|
477 | metadata.x=numpy.zeros(len(x)) |
---|
478 | metadata.x=x |
---|
479 | |
---|
480 | self.fitter.set_data(data=metadata,Uid=self.fit_id, |
---|
481 | smearer=smearer,qmin= qmin,qmax=qmax ) |
---|
482 | |
---|
483 | self.fitter.select_problem_for_fit(Uid= self.fit_id, |
---|
484 | value= value.get_scheduled()) |
---|
485 | |
---|
486 | except: |
---|
487 | msg= title +" error: %s" % sys.exc_value |
---|
488 | wx.PostEvent(self.parent, StatusEvent(status= msg )) |
---|
489 | return |
---|
490 | |
---|
491 | def _onSelect(self,event): |
---|
492 | """ |
---|
493 | when Select data to fit a new page is created .Its reference is |
---|
494 | added to self.page_finder |
---|
495 | """ |
---|
496 | self.panel = event.GetEventObject() |
---|
497 | for item in self.panel.graph.plottables: |
---|
498 | if item.name == self.panel.graph.selected_plottable: |
---|
499 | ## put the errors values back to the model if the errors were hiden |
---|
500 | ## before sending them to the fit engine |
---|
501 | if len(self.err_dy)>0: |
---|
502 | if item.name in self.err_dy.iterkeys(): |
---|
503 | dy= self.err_dy[item.name] |
---|
504 | data= self.copy_data(item, dy) |
---|
505 | else: |
---|
506 | data= item |
---|
507 | else: |
---|
508 | if item.dy==None: |
---|
509 | dy= numpy.zeros(len(item.y)) |
---|
510 | dy[dy==0]=1 |
---|
511 | data= self.copy_data(item, dy) |
---|
512 | else: |
---|
513 | data= item |
---|
514 | else: |
---|
515 | data= item |
---|
516 | ## create anew page |
---|
517 | if item.name == self.panel.graph.selected_plottable or\ |
---|
518 | item.__class__.__name__ is "Data2D": |
---|
519 | try: |
---|
520 | page = self.fit_panel.add_fit_page(data) |
---|
521 | # add data associated to the page created |
---|
522 | if page !=None: |
---|
523 | #create a fitproblem storing all link to data,model,page creation |
---|
524 | self.page_finder[page]= FitProblem() |
---|
525 | ## item is almost the same as data but contains |
---|
526 | ## axis info for plotting |
---|
527 | self.page_finder[page].add_plotted_data(item) |
---|
528 | self.page_finder[page].add_fit_data(data) |
---|
529 | |
---|
530 | wx.PostEvent(self.parent, StatusEvent(status="Page Created")) |
---|
531 | else: |
---|
532 | wx.PostEvent(self.parent, StatusEvent(status="Page was already Created")) |
---|
533 | except: |
---|
534 | wx.PostEvent(self.parent, StatusEvent(status="Creating Fit page: %s"\ |
---|
535 | %sys.exc_value)) |
---|
536 | return |
---|
537 | |
---|
538 | def _single_fit_completed(self,result,pars,cpage, elapsed=None): |
---|
539 | """ |
---|
540 | Display fit result on one page of the notebook. |
---|
541 | @param result: result of fit |
---|
542 | @param pars: list of names of parameters fitted |
---|
543 | @param current_pg: the page where information will be displayed |
---|
544 | @param qmin: the minimum value of x to replot the model |
---|
545 | @param qmax: the maximum value of x to replot model |
---|
546 | |
---|
547 | """ |
---|
548 | #wx.PostEvent(self.parent, StatusEvent(status="Single fit \ |
---|
549 | #complete! " , type="stop")) |
---|
550 | try: |
---|
551 | for page, value in self.page_finder.iteritems(): |
---|
552 | if page==cpage : |
---|
553 | model= value.get_model() |
---|
554 | break |
---|
555 | i = 0 |
---|
556 | for name in pars: |
---|
557 | if result.pvec.__class__==numpy.float64: |
---|
558 | model.setParam(name,result.pvec) |
---|
559 | else: |
---|
560 | model.setParam(name,result.pvec[i]) |
---|
561 | i += 1 |
---|
562 | ## Reset values of the current page to fit result |
---|
563 | cpage.onsetValues(result.fitness, result.pvec,result.stderr) |
---|
564 | ## plot the current model with new param |
---|
565 | metadata = self.page_finder[cpage].get_fit_data() |
---|
566 | model = self.page_finder[cpage].get_model() |
---|
567 | qmin, qmax= self.page_finder[cpage].get_range() |
---|
568 | #Replot models |
---|
569 | msg= "Single Fit completed. plotting... %s:"%model.name |
---|
570 | wx.PostEvent(self.parent, StatusEvent(status="%s " % msg)) |
---|
571 | self.draw_model( model=model, data= metadata,qmin= qmin, qmax= qmax) |
---|
572 | |
---|
573 | except: |
---|
574 | msg= "Single Fit completed but Following error occurred:" |
---|
575 | wx.PostEvent(self.parent, StatusEvent(status="%s %s" % (msg, sys.exc_value))) |
---|
576 | return |
---|
577 | |
---|
578 | |
---|
579 | def _simul_fit_completed(self,result,pars=None,cpage=None, elapsed=None): |
---|
580 | """ |
---|
581 | Parameter estimation completed, |
---|
582 | display the results to the user |
---|
583 | @param alpha: estimated best alpha |
---|
584 | @param elapsed: computation time |
---|
585 | """ |
---|
586 | wx.PostEvent(self.parent, StatusEvent(status="Simultaneous fit \ |
---|
587 | complete ", type="stop")) |
---|
588 | |
---|
589 | ## fit more than 1 model at the same time |
---|
590 | try: |
---|
591 | for page, value in self.page_finder.iteritems(): |
---|
592 | if value.get_scheduled()==1: |
---|
593 | model = value.get_model() |
---|
594 | metadata = value.get_plotted_data() |
---|
595 | small_out = [] |
---|
596 | small_cov = [] |
---|
597 | i = 0 |
---|
598 | #Separate result in to data corresponding to each page |
---|
599 | for p in result.parameters: |
---|
600 | model_name,param_name = self.split_string(p.name) |
---|
601 | if model.name == model_name: |
---|
602 | p_name= model.name+"."+param_name |
---|
603 | if p.name == p_name: |
---|
604 | small_out.append(p.value ) |
---|
605 | model.setParam(param_name,p.value) |
---|
606 | if p.stderr==None: |
---|
607 | p.stderr=numpy.nan |
---|
608 | small_cov.append(p.stderr) |
---|
609 | |
---|
610 | else: |
---|
611 | small_cov.append(p.stderr) |
---|
612 | else: |
---|
613 | value= model.getParam(param_name) |
---|
614 | small_out.append(value ) |
---|
615 | small_cov.append(numpy.nan) |
---|
616 | # Display result on each page |
---|
617 | page.onsetValues(result.fitness, small_out,small_cov) |
---|
618 | #Replot models |
---|
619 | msg= "Simultaneous Fit completed. plotting... %s:"%model.name |
---|
620 | wx.PostEvent(self.parent, StatusEvent(status="%s " % msg)) |
---|
621 | qmin, qmax= page.get_range() |
---|
622 | self.draw_model( model=model, data= metadata,qmin= qmin, qmax= qmax) |
---|
623 | |
---|
624 | except: |
---|
625 | msg= "Simultaneous Fit completed but Following error occurred: " |
---|
626 | wx.PostEvent(self.parent, StatusEvent(status="%s%s" %(msg,sys.exc_value))) |
---|
627 | return |
---|
628 | |
---|
629 | |
---|
630 | |
---|
631 | def _on_show_panel(self, event): |
---|
632 | print "_on_show_panel: fitting" |
---|
633 | |
---|
634 | |
---|
635 | def _onset_engine_park(self,event): |
---|
636 | """ |
---|
637 | set engine to park |
---|
638 | """ |
---|
639 | self._on_change_engine('park') |
---|
640 | |
---|
641 | |
---|
642 | def _onset_engine_scipy(self,event): |
---|
643 | """ |
---|
644 | set engine to scipy |
---|
645 | """ |
---|
646 | self._on_change_engine('scipy') |
---|
647 | |
---|
648 | def _on_slicer_event(self, event): |
---|
649 | """ |
---|
650 | Receive a panel as event and send it to guiframe |
---|
651 | @param event: event containing a panel |
---|
652 | """ |
---|
653 | if event.panel!=None: |
---|
654 | new_panel = event.panel |
---|
655 | # Set group ID if available |
---|
656 | event_id = self.parent.popup_panel(new_panel) |
---|
657 | self.menu1.Append(event_id, new_panel.window_caption, |
---|
658 | "Show %s plot panel" % new_panel.window_caption) |
---|
659 | # Set UID to allow us to reference the panel later |
---|
660 | new_panel.uid = event_id |
---|
661 | new_panel |
---|
662 | self.mypanels.append(new_panel) |
---|
663 | return |
---|
664 | |
---|
665 | def _on_change_engine(self, engine='park'): |
---|
666 | """ |
---|
667 | Allow to select the type of engine to perform fit |
---|
668 | @param engine: the key work of the engine |
---|
669 | """ |
---|
670 | self._fit_engine = engine |
---|
671 | wx.PostEvent(self.parent, StatusEvent(status="Engine set to: %s" % self._fit_engine)) |
---|
672 | |
---|
673 | |
---|
674 | def _on_model_panel(self, evt): |
---|
675 | """ |
---|
676 | react to model selection on any combo box or model menu.plot the model |
---|
677 | @param evt: wx.combobox event |
---|
678 | """ |
---|
679 | model = evt.model |
---|
680 | if model ==None: |
---|
681 | return |
---|
682 | |
---|
683 | sim_page=self.sim_page |
---|
684 | current_pg = self.fit_panel.get_current_page() |
---|
685 | ## make sure nothing is done on self.sim_page |
---|
686 | ## example trying to call set_panel on self.sim_page |
---|
687 | if current_pg != sim_page: |
---|
688 | |
---|
689 | if self.page_finder[current_pg].get_model()== None : |
---|
690 | |
---|
691 | model.name="M"+str(self.index_model) |
---|
692 | self.index_model += 1 |
---|
693 | else: |
---|
694 | |
---|
695 | model.name= self.page_finder[current_pg].get_model().name |
---|
696 | |
---|
697 | |
---|
698 | metadata = self.page_finder[current_pg].get_plotted_data() |
---|
699 | |
---|
700 | # save the name containing the data name with the appropriate model |
---|
701 | self.page_finder[current_pg].set_model(model) |
---|
702 | # save model name |
---|
703 | self.draw_model( model=model, data= metadata) |
---|
704 | |
---|
705 | if self.sim_page!=None: |
---|
706 | self.sim_page.draw_page() |
---|
707 | |
---|
708 | |
---|
709 | |
---|
710 | def _on_model_menu(self, evt): |
---|
711 | """ |
---|
712 | Plot a theory from a model selected from the menu |
---|
713 | @param evt: wx.menu event |
---|
714 | """ |
---|
715 | name = evt.model.__class__.__name__ |
---|
716 | if hasattr(evt.model, "name"): |
---|
717 | name = evt.model.name |
---|
718 | model=evt.model |
---|
719 | description=model.description |
---|
720 | |
---|
721 | # Create a model page. If a new page is created, the model |
---|
722 | # will be plotted automatically. If a page already exists, |
---|
723 | # the content will be updated and the plot refreshed |
---|
724 | self.fit_panel.add_model_page(model,description,name,topmenu=True) |
---|
725 | |
---|
726 | |
---|
727 | |
---|
728 | |
---|
729 | def _update1D(self,x, output): |
---|
730 | """ |
---|
731 | Update the output of plotting model 1D |
---|
732 | """ |
---|
733 | self.calc_thread.ready(1) |
---|
734 | |
---|
735 | def _fill_default_model2D(self, theory, qmax,qstep, qmin=None): |
---|
736 | """ |
---|
737 | fill Data2D with default value |
---|
738 | @param theory: Data2D to fill |
---|
739 | """ |
---|
740 | from DataLoader.data_info import Detector, Source |
---|
741 | |
---|
742 | detector = Detector() |
---|
743 | theory.detector.append(detector) |
---|
744 | |
---|
745 | theory.detector[0].distance=1e+32 |
---|
746 | theory.source= Source() |
---|
747 | theory.source.wavelength=2*math.pi/1e+32 |
---|
748 | |
---|
749 | ## Create detector for Model 2D |
---|
750 | xmax=2*theory.detector[0].distance*math.atan(\ |
---|
751 | qmax/(4*math.pi/theory.source.wavelength)) |
---|
752 | |
---|
753 | theory.detector[0].pixel_size.x= xmax/(qstep/2-0.5) |
---|
754 | theory.detector[0].pixel_size.y= xmax/(qstep/2-0.5) |
---|
755 | theory.detector[0].beam_center.x= qmax |
---|
756 | theory.detector[0].beam_center.y= qmax |
---|
757 | ## create x_bins and y_bins of the model 2D |
---|
758 | distance = theory.detector[0].distance |
---|
759 | pixel = qstep/2-1 |
---|
760 | theta = pixel / distance / qstep#100.0 |
---|
761 | wavelength = theory.source.wavelength |
---|
762 | pixel_width_x = theory.detector[0].pixel_size.x |
---|
763 | pixel_width_y = theory.detector[0].pixel_size.y |
---|
764 | center_x = theory.detector[0].beam_center.x/pixel_width_x |
---|
765 | center_y = theory.detector[0].beam_center.y/pixel_width_y |
---|
766 | |
---|
767 | |
---|
768 | size_x, size_y= numpy.shape(theory.data) |
---|
769 | for i_x in range(size_x): |
---|
770 | theta = (i_x-center_x)*pixel_width_x / distance |
---|
771 | qx = 4.0*math.pi/wavelength * math.tan(theta/2.0) |
---|
772 | theory.x_bins.append(qx) |
---|
773 | for i_y in range(size_y): |
---|
774 | theta = (i_y-center_y)*pixel_width_y / distance |
---|
775 | qy =4.0*math.pi/wavelength * math.tan(theta/2.0) |
---|
776 | theory.y_bins.append(qy) |
---|
777 | |
---|
778 | theory.group_id ="Model" |
---|
779 | theory.id ="Model" |
---|
780 | ## determine plot boundaries |
---|
781 | theory.xmin= -qmax |
---|
782 | theory.xmax= qmax |
---|
783 | theory.ymin= -qmax |
---|
784 | theory.ymax= qmax |
---|
785 | |
---|
786 | |
---|
787 | def _get_plotting_info(self, data=None): |
---|
788 | """ |
---|
789 | get plotting info from data if data !=None |
---|
790 | else use some default |
---|
791 | """ |
---|
792 | my_info = PlotInfo() |
---|
793 | if data !=None: |
---|
794 | if hasattr(data,"info"): |
---|
795 | x_name, x_units = data.get_xaxis() |
---|
796 | y_name, y_units = data.get_yaxis() |
---|
797 | |
---|
798 | my_info._xunit = x_units |
---|
799 | my_info._xaxis = x_name |
---|
800 | my_info._yunit = y_units |
---|
801 | my_info._yaxis = y_name |
---|
802 | |
---|
803 | my_info.title= data.name |
---|
804 | if hasattr(data, "info"): |
---|
805 | my_info.info= data.info |
---|
806 | if hasattr(data, "group_id"): |
---|
807 | my_info.group_id= data.group_id |
---|
808 | |
---|
809 | return my_info |
---|
810 | |
---|
811 | def _complete1D(self, x,y, elapsed,model,data=None): |
---|
812 | """ |
---|
813 | Complete plotting 1D data |
---|
814 | """ |
---|
815 | try: |
---|
816 | new_plot = Theory1D(x=x, y=y) |
---|
817 | my_info = self._get_plotting_info( data) |
---|
818 | new_plot.name = model.name |
---|
819 | new_plot.id = my_info.id |
---|
820 | new_plot.group_id = my_info.group_id |
---|
821 | |
---|
822 | new_plot.xaxis( my_info._xaxis, my_info._xunit) |
---|
823 | new_plot.yaxis( my_info._yaxis, my_info._yunit) |
---|
824 | |
---|
825 | # Pass the reset flag to let the plotting event handler |
---|
826 | # know that we are replacing the whole plot |
---|
827 | title= my_info.title |
---|
828 | if title== None: |
---|
829 | title="Analytical model 1D " |
---|
830 | wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot, |
---|
831 | title= str(title), reset=True )) |
---|
832 | else: |
---|
833 | wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot, |
---|
834 | title= str(title))) |
---|
835 | |
---|
836 | except: |
---|
837 | msg= " Error occurred when drawing %s Model 1D: "%new_plot.name |
---|
838 | msg+= " %s"%sys.exc_value |
---|
839 | wx.PostEvent( self.parent, StatusEvent(status= msg )) |
---|
840 | return |
---|
841 | |
---|
842 | |
---|
843 | |
---|
844 | |
---|
845 | def _update2D(self, output,time=None): |
---|
846 | """ |
---|
847 | Update the output of plotting model |
---|
848 | """ |
---|
849 | wx.PostEvent(self.parent, StatusEvent(status="Plot \ |
---|
850 | #updating ... ",type="update")) |
---|
851 | self.calc_thread.ready(0.01) |
---|
852 | |
---|
853 | |
---|
854 | def _complete2D(self, image,data, model, elapsed,qmin, qmax,qstep=DEFAULT_NPTS): |
---|
855 | """ |
---|
856 | Complete get the result of modelthread and create model 2D |
---|
857 | that can be plot. |
---|
858 | """ |
---|
859 | msg = "Calc complete !" |
---|
860 | wx.PostEvent( self.parent, StatusEvent( status= msg , type="stop" )) |
---|
861 | |
---|
862 | err_image = numpy.zeros(numpy.shape(image)) |
---|
863 | err_image[err_image==0]= 1 |
---|
864 | theory= Data2D(image= image , err_image= err_image) |
---|
865 | theory.name= model.name |
---|
866 | |
---|
867 | if data ==None: |
---|
868 | self._fill_default_model2D(theory= theory, qmax=qmax,qstep=qstep, qmin= qmin) |
---|
869 | |
---|
870 | else: |
---|
871 | theory.id= "Model" |
---|
872 | theory.group_id= "Model"+data.name |
---|
873 | theory.x_bins= data.x_bins |
---|
874 | theory.y_bins= data.y_bins |
---|
875 | theory.detector= data.detector |
---|
876 | theory.source= data.source |
---|
877 | |
---|
878 | ## plot boundaries |
---|
879 | theory.ymin= data.ymin |
---|
880 | theory.ymax= data.ymax |
---|
881 | theory.xmin= data.xmin |
---|
882 | theory.xmax= data.xmax |
---|
883 | |
---|
884 | ## plot |
---|
885 | wx.PostEvent(self.parent, NewPlotEvent(plot=theory, |
---|
886 | title="Analytical model 2D ", reset=True )) |
---|
887 | |
---|
888 | def _on_data_error(self, event): |
---|
889 | """ |
---|
890 | receives and event from plotting plu-gins to store the data name and |
---|
891 | their errors of y coordinates for 1Data hide and show error |
---|
892 | """ |
---|
893 | self.err_dy= event.err_dy |
---|
894 | |
---|
895 | def _draw_model2D(self,model,data=None,description=None, enable2D=False, |
---|
896 | qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, qstep=DEFAULT_NPTS): |
---|
897 | """ |
---|
898 | draw model in 2D |
---|
899 | @param model: instance of the model to draw |
---|
900 | @param description: the description of the model |
---|
901 | @param enable2D: when True allows to draw model 2D |
---|
902 | @param qmin: the minimum value to draw model 2D |
---|
903 | @param qmax: the maximum value to draw model 2D |
---|
904 | @param qstep: the number of division of Qx and Qy of the model to draw |
---|
905 | |
---|
906 | """ |
---|
907 | |
---|
908 | x= numpy.linspace(start= -1*qmax, |
---|
909 | stop= qmax, |
---|
910 | num= qstep, |
---|
911 | endpoint=True ) |
---|
912 | y = numpy.linspace(start= -1*qmax, |
---|
913 | stop= qmax, |
---|
914 | num= qstep, |
---|
915 | endpoint=True ) |
---|
916 | ## use data info instead |
---|
917 | if data !=None: |
---|
918 | ## check if data2D to plot |
---|
919 | if hasattr(data, "x_bins"): |
---|
920 | enable2D = True |
---|
921 | x= data.x_bins |
---|
922 | y= data.y_bins |
---|
923 | |
---|
924 | if not enable2D: |
---|
925 | return |
---|
926 | try: |
---|
927 | from model_thread import Calc2D |
---|
928 | ## If a thread is already started, stop it |
---|
929 | if self.calc_2D != None and self.calc_2D.isrunning(): |
---|
930 | self.calc_2D.stop() |
---|
931 | self.calc_2D = Calc2D( x= x, |
---|
932 | y= y, |
---|
933 | model= model, |
---|
934 | data = data, |
---|
935 | qmin= qmin, |
---|
936 | qmax= qmax, |
---|
937 | qstep= qstep, |
---|
938 | completefn= self._complete2D, |
---|
939 | updatefn= self._update2D ) |
---|
940 | self.calc_2D.queue() |
---|
941 | |
---|
942 | except: |
---|
943 | msg= " Error occurred when drawing %s Model 2D: "%model.name |
---|
944 | msg+= " %s"%sys.exc_value |
---|
945 | wx.PostEvent( self.parent, StatusEvent(status= msg )) |
---|
946 | return |
---|
947 | |
---|
948 | def _draw_model1D(self, model, data=None, smearer= None, |
---|
949 | qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, qstep= DEFAULT_NPTS,enable1D= True): |
---|
950 | """ |
---|
951 | Draw model 1D from loaded data1D |
---|
952 | @param data: loaded data |
---|
953 | @param model: the model to plot |
---|
954 | """ |
---|
955 | |
---|
956 | x= numpy.linspace(start= qmin, |
---|
957 | stop= qmax, |
---|
958 | num= qstep, |
---|
959 | endpoint=True |
---|
960 | ) |
---|
961 | if data!=None: |
---|
962 | ## check for data2D |
---|
963 | if hasattr(data,"x_bins"): |
---|
964 | return |
---|
965 | x = data.x |
---|
966 | if qmin == DEFAULT_QMIN : |
---|
967 | qmin = min(data.x) |
---|
968 | if qmax == DEFAULT_QMAX: |
---|
969 | qmax = max(data.x) |
---|
970 | |
---|
971 | if not enable1D: |
---|
972 | return |
---|
973 | |
---|
974 | try: |
---|
975 | from model_thread import Calc1D |
---|
976 | ## If a thread is already started, stop it |
---|
977 | if self.calc_1D!= None and self.calc_1D.isrunning(): |
---|
978 | self.calc_1D.stop() |
---|
979 | self.calc_1D= Calc1D( x= x, |
---|
980 | data = data, |
---|
981 | model= model, |
---|
982 | qmin = qmin, |
---|
983 | qmax = qmax, |
---|
984 | smearer = smearer, |
---|
985 | completefn = self._complete1D, |
---|
986 | updatefn = self._update1D ) |
---|
987 | self.calc_1D.queue() |
---|
988 | |
---|
989 | except: |
---|
990 | msg= " Error occurred when drawing %s Model 1D: "%model.name |
---|
991 | msg+= " %s"%sys.exc_value |
---|
992 | wx.PostEvent( self.parent, StatusEvent(status= msg )) |
---|
993 | return |
---|
994 | |
---|
995 | |
---|
996 | |
---|
997 | |
---|
998 | |
---|
999 | if __name__ == "__main__": |
---|
1000 | i = Plugin() |
---|
1001 | |
---|
1002 | |
---|
1003 | |
---|
1004 | |
---|