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