1 | import os,os.path, 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,EVT_MODEL2D_PANEL |
---|
10 | |
---|
11 | from sans.fit.AbstractFitEngine import Model,Data,FitData1D,FitData2D |
---|
12 | from fitproblem import FitProblem |
---|
13 | from fitpanel import FitPanel |
---|
14 | from fit_thread import FitThread |
---|
15 | import models,modelpage |
---|
16 | import fitpage1D,fitpage2D |
---|
17 | import park |
---|
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 | print "main",thread.get_ident() |
---|
25 | |
---|
26 | class Plugin: |
---|
27 | """ |
---|
28 | Fitting plugin is used to perform fit |
---|
29 | """ |
---|
30 | def __init__(self): |
---|
31 | ## Plug-in name |
---|
32 | self.sub_menu = "Fitting" |
---|
33 | |
---|
34 | ## Reference to the parent window |
---|
35 | self.parent = None |
---|
36 | self.menu_mng = models.ModelManager() |
---|
37 | ## List of panels for the simulation perspective (names) |
---|
38 | self.perspective = [] |
---|
39 | self.mypanels=[] |
---|
40 | self.calc_thread = None |
---|
41 | self.done = False |
---|
42 | # Start with a good default |
---|
43 | self.elapsed = 0.022 |
---|
44 | self.fitter = None |
---|
45 | |
---|
46 | #Flag to let the plug-in know that it is running standalone |
---|
47 | self.standalone=True |
---|
48 | ## Fit engine |
---|
49 | self._fit_engine = 'scipy' |
---|
50 | self.enable_model2D=False |
---|
51 | # Log startup |
---|
52 | logging.info("Fitting plug-in started") |
---|
53 | # model 2D view |
---|
54 | self.model2D_id=None |
---|
55 | |
---|
56 | def populate_menu(self, id, owner): |
---|
57 | """ |
---|
58 | Create a menu for the Fitting plug-in |
---|
59 | @param id: id to create a menu |
---|
60 | @param owner: owner of menu |
---|
61 | @ return : list of information to populate the main menu |
---|
62 | """ |
---|
63 | self.parent.Bind(EVT_MODEL2D_PANEL, self._on_model2D_show) |
---|
64 | #Menu for fitting |
---|
65 | self.menu1 = wx.Menu() |
---|
66 | id1 = wx.NewId() |
---|
67 | self.menu1.Append(id1, '&Show fit panel') |
---|
68 | wx.EVT_MENU(owner, id1, self.on_perspective) |
---|
69 | id3 = wx.NewId() |
---|
70 | self.menu1.AppendCheckItem(id3, "park") |
---|
71 | |
---|
72 | wx.EVT_MENU(owner, id3, self._onset_engine) |
---|
73 | |
---|
74 | #menu for model |
---|
75 | menu2 = wx.Menu() |
---|
76 | |
---|
77 | self.menu_mng.populate_menu(menu2, owner) |
---|
78 | id2 = wx.NewId() |
---|
79 | owner.Bind(models.EVT_MODEL,self._on_model_menu) |
---|
80 | #owner.Bind(modelpage.EVT_MODEL,self._on_model_menu) |
---|
81 | self.fit_panel.set_owner(owner) |
---|
82 | self.fit_panel.set_model_list(self.menu_mng.get_model_list()) |
---|
83 | owner.Bind(fitpage1D.EVT_MODEL_BOX,self._on_model_panel) |
---|
84 | owner.Bind(fitpage2D.EVT_MODEL_BOX,self._on_model_panel) |
---|
85 | #create menubar items |
---|
86 | return [(id, self.menu1, "Fitting"),(id2, menu2, "Model")] |
---|
87 | |
---|
88 | |
---|
89 | def help(self, evt): |
---|
90 | """ |
---|
91 | Show a general help dialog. |
---|
92 | TODO: replace the text with a nice image |
---|
93 | """ |
---|
94 | #from helpDialog import HelpWindow |
---|
95 | #dialog = HelpWindow(None, -1, 'HelpWindow') |
---|
96 | #if dialog.ShowModal() == wx.ID_OK: |
---|
97 | # pass |
---|
98 | #dialog.Destroy() |
---|
99 | from helpPanel import HelpWindow |
---|
100 | frame = HelpWindow(None, -1, 'HelpWindow') |
---|
101 | frame.Show(True) |
---|
102 | |
---|
103 | |
---|
104 | |
---|
105 | |
---|
106 | def get_context_menu(self, graph=None): |
---|
107 | """ |
---|
108 | Get the context menu items available for P(r) |
---|
109 | @param graph: the Graph object to which we attach the context menu |
---|
110 | @return: a list of menu items with call-back function |
---|
111 | """ |
---|
112 | self.graph=graph |
---|
113 | for item in graph.plottables: |
---|
114 | if item.__class__.__name__ is "Data2D": |
---|
115 | return [["Select data for Fitting",\ |
---|
116 | "Dialog with fitting parameters ", self._onSelect]] |
---|
117 | else: |
---|
118 | if item.name==graph.selected_plottable and\ |
---|
119 | item.__class__.__name__ is "Data1D": |
---|
120 | return [["Select data for Fitting", \ |
---|
121 | "Dialog with fitting parameters ", self._onSelect]] |
---|
122 | return [] |
---|
123 | |
---|
124 | |
---|
125 | def get_panels(self, parent): |
---|
126 | """ |
---|
127 | Create and return a list of panel objects |
---|
128 | """ |
---|
129 | self.parent = parent |
---|
130 | # Creation of the fit panel |
---|
131 | self.fit_panel = FitPanel(self.parent, -1) |
---|
132 | #Set the manager forthe main panel |
---|
133 | self.fit_panel.set_manager(self) |
---|
134 | # List of windows used for the perspective |
---|
135 | self.perspective = [] |
---|
136 | self.perspective.append(self.fit_panel.window_name) |
---|
137 | # take care of saving data, model and page associated with each other |
---|
138 | self.page_finder = {} |
---|
139 | #index number to create random model name |
---|
140 | self.index_model = 0 |
---|
141 | self.index_theory= 0 |
---|
142 | self.parent.Bind(EVT_SLICER_PANEL, self._on_slicer_event) |
---|
143 | |
---|
144 | |
---|
145 | #create the fitting panel |
---|
146 | #return [self.fit_panel] |
---|
147 | |
---|
148 | self.mypanels.append(self.fit_panel) |
---|
149 | return self.mypanels |
---|
150 | |
---|
151 | |
---|
152 | def _on_model2D_show(self, event ): |
---|
153 | print "model2D get the id ", event.id |
---|
154 | |
---|
155 | |
---|
156 | def _on_slicer_event(self, event): |
---|
157 | print "fitting:slicer event ", event.panel |
---|
158 | if event.panel!=None: |
---|
159 | new_panel = event.panel |
---|
160 | # Set group ID if available |
---|
161 | event_id = self.parent.popup_panel(new_panel) |
---|
162 | self.menu1.Append(event_id, new_panel.window_caption, |
---|
163 | "Show %s plot panel" % new_panel.window_caption) |
---|
164 | # Set UID to allow us to reference the panel later |
---|
165 | new_panel.uid = event_id |
---|
166 | new_panel |
---|
167 | self.mypanels.append(new_panel) |
---|
168 | return |
---|
169 | def _on_show_panel(self, event): |
---|
170 | print "_on_show_panel: fitting" |
---|
171 | |
---|
172 | def get_perspective(self): |
---|
173 | """ |
---|
174 | Get the list of panel names for this perspective |
---|
175 | """ |
---|
176 | return self.perspective |
---|
177 | |
---|
178 | |
---|
179 | def on_perspective(self, event): |
---|
180 | """ |
---|
181 | Call back function for the perspective menu item. |
---|
182 | We notify the parent window that the perspective |
---|
183 | has changed. |
---|
184 | """ |
---|
185 | self.parent.set_perspective(self.perspective) |
---|
186 | |
---|
187 | |
---|
188 | def post_init(self): |
---|
189 | """ |
---|
190 | Post initialization call back to close the loose ends |
---|
191 | [Somehow openGL needs this call] |
---|
192 | """ |
---|
193 | self.parent.set_perspective(self.perspective) |
---|
194 | |
---|
195 | |
---|
196 | def _onSelect(self,event): |
---|
197 | """ |
---|
198 | when Select data to fit a new page is created .Its reference is |
---|
199 | added to self.page_finder |
---|
200 | """ |
---|
201 | self.panel = event.GetEventObject() |
---|
202 | for item in self.panel.graph.plottables: |
---|
203 | if item.name == self.panel.graph.selected_plottable or\ |
---|
204 | item.__class__.__name__ is "Data2D": |
---|
205 | #find a name for the page created for notebook |
---|
206 | try: |
---|
207 | |
---|
208 | page = self.fit_panel.add_fit_page(item) |
---|
209 | #page, model_name = self.fit_panel.add_fit_page(item) |
---|
210 | # add data associated to the page created |
---|
211 | |
---|
212 | if page !=None: |
---|
213 | #create a fitproblem storing all link to data,model,page creation |
---|
214 | self.page_finder[page]= FitProblem() |
---|
215 | #self.page_finder[page].save_model_name(model_name) |
---|
216 | self.page_finder[page].add_data(item) |
---|
217 | wx.PostEvent(self.parent, StatusEvent(status="Page Created")) |
---|
218 | else: |
---|
219 | wx.PostEvent(self.parent, StatusEvent(status="Page was already Created")) |
---|
220 | except: |
---|
221 | #raise |
---|
222 | wx.PostEvent(self.parent, StatusEvent(status="Creating Fit page: %s"\ |
---|
223 | %sys.exc_value)) |
---|
224 | def schedule_for_fit(self,value=0,fitproblem =None): |
---|
225 | """ |
---|
226 | |
---|
227 | """ |
---|
228 | if fitproblem !=None: |
---|
229 | fitproblem.schedule_tofit(value) |
---|
230 | else: |
---|
231 | current_pg=self.fit_panel.get_current_page() |
---|
232 | for page, val in self.page_finder.iteritems(): |
---|
233 | if page ==current_pg : |
---|
234 | val.schedule_tofit(value) |
---|
235 | break |
---|
236 | |
---|
237 | |
---|
238 | def get_page_finder(self): |
---|
239 | """ @return self.page_finder used also by simfitpage.py""" |
---|
240 | return self.page_finder |
---|
241 | |
---|
242 | |
---|
243 | def set_page_finder(self,modelname,names,values): |
---|
244 | """ |
---|
245 | Used by simfitpage.py to reset a parameter given the string constrainst. |
---|
246 | @param modelname: the name ot the model for with the parameter has to reset |
---|
247 | @param value: can be a string in this case. |
---|
248 | @param names: the paramter name |
---|
249 | @note: expecting park used for fit. |
---|
250 | """ |
---|
251 | sim_page=self.fit_panel.get_page(1) |
---|
252 | for page, value in self.page_finder.iteritems(): |
---|
253 | if page != sim_page: |
---|
254 | list=value.get_model() |
---|
255 | model=list[0] |
---|
256 | #print "fitting",model.name,modelname |
---|
257 | if model.name== modelname: |
---|
258 | value.set_model_param(names,values) |
---|
259 | break |
---|
260 | |
---|
261 | |
---|
262 | |
---|
263 | def split_string(self,item): |
---|
264 | """ |
---|
265 | receive a word containing dot and split it. used to split parameterset |
---|
266 | name into model name and parameter name example: |
---|
267 | paramaterset (item) = M1.A |
---|
268 | @return model_name =M1 , parameter name =A |
---|
269 | """ |
---|
270 | if string.find(item,".")!=-1: |
---|
271 | param_names= re.split("\.",item) |
---|
272 | model_name=param_names[0] |
---|
273 | param_name=param_names[1] |
---|
274 | return model_name,param_name |
---|
275 | |
---|
276 | |
---|
277 | def _single_fit_completed(self,result,pars,cpage,qmin,qmax,elapsed, |
---|
278 | ymin=None, ymax=None, xmin=None, xmax=None): |
---|
279 | """ |
---|
280 | Display fit result on one page of the notebook. |
---|
281 | @param result: result of fit |
---|
282 | @param pars: list of names of parameters fitted |
---|
283 | @param current_pg: the page where information will be displayed |
---|
284 | @param qmin: the minimum value of x to replot the model |
---|
285 | @param qmax: the maximum value of x to replot model |
---|
286 | |
---|
287 | """ |
---|
288 | #print "single fit ", pars,result.pvec,result.stderr,result.fitness |
---|
289 | #self.done = True |
---|
290 | #wx.PostEvent(self.parent, StatusEvent(status="Fitting Completed: %g" % elapsed)) |
---|
291 | try: |
---|
292 | for page, value in self.page_finder.iteritems(): |
---|
293 | if page==cpage : |
---|
294 | #fitdata = value.get_data() |
---|
295 | list = value.get_model() |
---|
296 | model= list[0] |
---|
297 | break |
---|
298 | i = 0 |
---|
299 | #print "fitting: single fit pars ", pars |
---|
300 | for name in pars: |
---|
301 | if result.pvec.__class__==numpy.float64: |
---|
302 | model.setParam(name,result.pvec) |
---|
303 | else: |
---|
304 | model.setParam(name,result.pvec[i]) |
---|
305 | # print "fitting: single fit", name, result.pvec[i] |
---|
306 | i += 1 |
---|
307 | print "fitting result : chisqr",result.fitness |
---|
308 | print "fitting result : pvec",result.pvec |
---|
309 | print "fitting result : stderr",result.stderr |
---|
310 | print "qmin qmax xmin xmax ymin , ymax",qmin, qmax,xmin, xmax ,ymin, ymax |
---|
311 | |
---|
312 | cpage.onsetValues(result.fitness, result.pvec,result.stderr) |
---|
313 | #title="Fitted model 2D " |
---|
314 | self.plot_helper(currpage=cpage,qmin=qmin,qmax=qmax, |
---|
315 | ymin=ymin, ymax=ymax, |
---|
316 | xmin=xmin, xmax=xmax,title=None) |
---|
317 | except: |
---|
318 | #raise |
---|
319 | wx.PostEvent(self.parent, StatusEvent(status="Fitting error: %s" % sys.exc_value)) |
---|
320 | |
---|
321 | |
---|
322 | def _simul_fit_completed(self,result,qmin,qmax, elapsed,pars=None,cpage=None, ymin=None, ymax=None): |
---|
323 | """ |
---|
324 | Parameter estimation completed, |
---|
325 | display the results to the user |
---|
326 | @param alpha: estimated best alpha |
---|
327 | @param elapsed: computation time |
---|
328 | """ |
---|
329 | wx.PostEvent(self.parent, StatusEvent(status="Fitting Completed: %g" % elapsed)) |
---|
330 | try: |
---|
331 | for page, value in self.page_finder.iteritems(): |
---|
332 | if value.get_scheduled()==1: |
---|
333 | #fitdata = value.get_data() |
---|
334 | list = value.get_model() |
---|
335 | model= list[0] |
---|
336 | |
---|
337 | small_out = [] |
---|
338 | small_cov = [] |
---|
339 | i = 0 |
---|
340 | #Separate result in to data corresponding to each page |
---|
341 | for p in result.parameters: |
---|
342 | model_name,param_name = self.split_string(p.name) |
---|
343 | if model.name == model_name: |
---|
344 | small_out.append(p.value ) |
---|
345 | small_cov.append(p.stderr) |
---|
346 | model.setParam(param_name,p.value) |
---|
347 | # Display result on each page |
---|
348 | page.onsetValues(result.fitness, small_out,small_cov) |
---|
349 | #Replot model |
---|
350 | self.plot_helper(currpage= page,qmin= qmin,qmax= qmax,ymin=ymin, ymax=ymax) |
---|
351 | except: |
---|
352 | wx.PostEvent(self.parent, StatusEvent(status="Fitting error: %s" % sys.exc_value)) |
---|
353 | |
---|
354 | |
---|
355 | def _on_single_fit(self,id=None,qmin=None, qmax=None,ymin=None, ymax=None,xmin=None,xmax=None): |
---|
356 | """ |
---|
357 | perform fit for the current page and return chisqr,out and cov |
---|
358 | @param engineName: type of fit to be performed |
---|
359 | @param id: unique id corresponding to a fit problem(model, set of data) |
---|
360 | @param model: model to fit |
---|
361 | |
---|
362 | """ |
---|
363 | #print "in single fitting" |
---|
364 | #set an engine to perform fit |
---|
365 | from sans.fit.Fitting import Fit |
---|
366 | self.fitter= Fit(self._fit_engine) |
---|
367 | #Setting an id to store model and data in fit engine |
---|
368 | if id==None: |
---|
369 | self.id=0 |
---|
370 | else: |
---|
371 | self.id = id |
---|
372 | page_fitted=None |
---|
373 | fit_problem=None |
---|
374 | #Get information (model , data) related to the page on |
---|
375 | #with the fit will be perform |
---|
376 | #current_pg=self.fit_panel.get_current_page() |
---|
377 | #simul_pg=self.fit_panel.get_page(0) |
---|
378 | |
---|
379 | for page, value in self.page_finder.iteritems(): |
---|
380 | if value.get_scheduled() ==1 : |
---|
381 | metadata = value.get_data() |
---|
382 | list=value.get_model() |
---|
383 | model=list[0] |
---|
384 | smearer= value.get_smearer() |
---|
385 | print "single fit", model, smearer |
---|
386 | #Create list of parameters for fitting used |
---|
387 | pars=[] |
---|
388 | templist=[] |
---|
389 | try: |
---|
390 | #templist=current_pg.get_param_list() |
---|
391 | templist=page.get_param_list() |
---|
392 | for element in templist: |
---|
393 | pars.append(str(element[0].GetLabelText())) |
---|
394 | pars.sort() |
---|
395 | #print "single fit start pars:", pars |
---|
396 | #Do the single fit |
---|
397 | self.fitter.set_model(Model(model), self.id, pars) |
---|
398 | #print "args...:",metadata,self.id,smearer,qmin,qmax,ymin,ymax |
---|
399 | |
---|
400 | self.fitter.set_data(data=metadata,Uid=self.id, |
---|
401 | smearer=smearer,qmin= qmin,qmax=qmax, |
---|
402 | ymin=ymin,ymax=ymax) |
---|
403 | |
---|
404 | self.fitter.select_problem_for_fit(Uid=self.id,value=value.get_scheduled()) |
---|
405 | page_fitted=page |
---|
406 | self.id+=1 |
---|
407 | self.schedule_for_fit( 0,value) |
---|
408 | except: |
---|
409 | raise |
---|
410 | #wx.PostEvent(self.parent, StatusEvent(status="Fitting error: %s" % sys.exc_value)) |
---|
411 | return |
---|
412 | # make sure to keep an alphabetic order |
---|
413 | #of parameter names in the list |
---|
414 | try: |
---|
415 | # If a thread is already started, stop it |
---|
416 | if self.calc_thread != None and self.calc_thread.isrunning(): |
---|
417 | self.calc_thread.stop() |
---|
418 | |
---|
419 | self.calc_thread =FitThread(parent =self.parent, |
---|
420 | fn= self.fitter, |
---|
421 | pars= pars, |
---|
422 | cpage= page_fitted, |
---|
423 | qmin=qmin, |
---|
424 | qmax=qmax, |
---|
425 | |
---|
426 | completefn=self._single_fit_completed, |
---|
427 | updatefn=None) |
---|
428 | self.calc_thread.queue() |
---|
429 | self.calc_thread.ready(2.5) |
---|
430 | #while not self.done: |
---|
431 | #print "when here" |
---|
432 | # time.sleep(1) |
---|
433 | |
---|
434 | |
---|
435 | except: |
---|
436 | raise |
---|
437 | wx.PostEvent(self.parent, StatusEvent(status="Single Fit error: %s" % sys.exc_value)) |
---|
438 | return |
---|
439 | |
---|
440 | def _on_simul_fit(self, id=None,qmin=None,qmax=None, ymin=None, ymax=None): |
---|
441 | """ |
---|
442 | perform fit for all the pages selected on simpage and return chisqr,out and cov |
---|
443 | @param engineName: type of fit to be performed |
---|
444 | @param id: unique id corresponding to a fit problem(model, set of data) |
---|
445 | in park_integration |
---|
446 | @param model: model to fit |
---|
447 | |
---|
448 | """ |
---|
449 | #set an engine to perform fit |
---|
450 | from sans.fit.Fitting import Fit |
---|
451 | self.fitter= Fit(self._fit_engine) |
---|
452 | |
---|
453 | #Setting an id to store model and data |
---|
454 | if id==None: |
---|
455 | id = 0 |
---|
456 | self.id = id |
---|
457 | |
---|
458 | for page, value in self.page_finder.iteritems(): |
---|
459 | try: |
---|
460 | if value.get_scheduled()==1: |
---|
461 | metadata = value.get_data() |
---|
462 | list = value.get_model() |
---|
463 | model= list[0] |
---|
464 | #Create dictionary of parameters for fitting used |
---|
465 | pars = [] |
---|
466 | templist = [] |
---|
467 | templist = page.get_param_list() |
---|
468 | for element in templist: |
---|
469 | try: |
---|
470 | name = str(element[0].GetLabelText()) |
---|
471 | pars.append(name) |
---|
472 | except: |
---|
473 | wx.PostEvent(self.parent, StatusEvent(status="Fitting error: %s" % sys.exc_value)) |
---|
474 | return |
---|
475 | # need to check this print "new model " |
---|
476 | new_model=Model(model) |
---|
477 | param=value.get_model_param() |
---|
478 | |
---|
479 | if len(param)>0: |
---|
480 | for item in param: |
---|
481 | param_value = item[1] |
---|
482 | param_name = item[0] |
---|
483 | #print "fitting ", param,param_name, param_value |
---|
484 | |
---|
485 | #new_model.set( model.getParam(param_name[0])= param_value) |
---|
486 | #new_model.set( exec"%s=%s"%(param_name[0], param_value)) |
---|
487 | #new_model.set( exec "%s"%(param_nam) = param_value) |
---|
488 | new_model.parameterset[ param_name].set( param_value ) |
---|
489 | |
---|
490 | self.fitter.set_model(new_model, self.id, pars) |
---|
491 | self.fitter.set_data(metadata,self.id,qmin,qmax,ymin,ymax) |
---|
492 | self.fitter.select_problem_for_fit(Uid=self.id,value=value.get_scheduled()) |
---|
493 | self.id += 1 |
---|
494 | except: |
---|
495 | #raise |
---|
496 | wx.PostEvent(self.parent, StatusEvent(status="Fitting error: %s" % sys.exc_value)) |
---|
497 | return |
---|
498 | #Do the simultaneous fit |
---|
499 | try: |
---|
500 | # If a thread is already started, stop it |
---|
501 | if self.calc_thread != None and self.calc_thread.isrunning(): |
---|
502 | self.calc_thread.stop() |
---|
503 | |
---|
504 | self.calc_thread =FitThread(parent =self.parent, |
---|
505 | fn= self.fitter, |
---|
506 | qmin=qmin, |
---|
507 | qmax=qmax, |
---|
508 | ymin= ymin, |
---|
509 | ymax= ymax, |
---|
510 | completefn= self._simul_fit_completed, |
---|
511 | updatefn=None) |
---|
512 | self.calc_thread.queue() |
---|
513 | self.calc_thread.ready(2.5) |
---|
514 | |
---|
515 | except: |
---|
516 | #raise |
---|
517 | wx.PostEvent(self.parent, StatusEvent(status="Simultaneous Fitting error: %s" % sys.exc_value)) |
---|
518 | return |
---|
519 | |
---|
520 | |
---|
521 | def _onset_engine(self,event): |
---|
522 | """ set engine to scipy""" |
---|
523 | if self._fit_engine== 'park': |
---|
524 | self._on_change_engine('scipy') |
---|
525 | else: |
---|
526 | self._on_change_engine('park') |
---|
527 | wx.PostEvent(self.parent, StatusEvent(status="Engine set to: %s" % self._fit_engine)) |
---|
528 | |
---|
529 | |
---|
530 | def _on_change_engine(self, engine='park'): |
---|
531 | """ |
---|
532 | Allow to select the type of engine to perform fit |
---|
533 | @param engine: the key work of the engine |
---|
534 | """ |
---|
535 | self._fit_engine = engine |
---|
536 | |
---|
537 | |
---|
538 | def _on_model_panel(self, evt): |
---|
539 | """ |
---|
540 | react to model selection on any combo box or model menu.plot the model |
---|
541 | """ |
---|
542 | |
---|
543 | model = evt.model |
---|
544 | name = evt.name |
---|
545 | |
---|
546 | print "name fitting", name |
---|
547 | sim_page=self.fit_panel.GetPage(1) |
---|
548 | current_pg = self.fit_panel.get_current_page() |
---|
549 | if current_pg != sim_page: |
---|
550 | current_pg.set_panel(model) |
---|
551 | #model.name = self.page_finder[current_pg].get_name() |
---|
552 | #print "model name", model.name |
---|
553 | model.name="M"+str(self.index_model) |
---|
554 | try: |
---|
555 | metadata=self.page_finder[current_pg].get_data() |
---|
556 | M_name=model.name+"= "+name+"("+metadata.group_id+")" |
---|
557 | except: |
---|
558 | M_name=model.name+"= "+name |
---|
559 | self.index_model += 1 |
---|
560 | |
---|
561 | |
---|
562 | # save model name |
---|
563 | |
---|
564 | # save the name containing the data name with the appropriate model |
---|
565 | self.page_finder[current_pg].set_model(model,M_name) |
---|
566 | self.plot_helper(currpage= current_pg,qmin= None,qmax= None) |
---|
567 | sim_page.add_model(self.page_finder) |
---|
568 | |
---|
569 | def set_smearer(self,smearer): |
---|
570 | current_pg=self.fit_panel.get_current_page() |
---|
571 | self.page_finder[current_pg].set_smearer(smearer) |
---|
572 | |
---|
573 | def redraw_model(self,qmin= None,qmax= None): |
---|
574 | """ |
---|
575 | Draw a theory according to model changes or data range. |
---|
576 | @param qmin: the minimum value plotted for theory |
---|
577 | @param qmax: the maximum value plotted for theory |
---|
578 | """ |
---|
579 | current_pg=self.fit_panel.get_current_page() |
---|
580 | for page, value in self.page_finder.iteritems(): |
---|
581 | if page ==current_pg : |
---|
582 | break |
---|
583 | self.plot_helper(currpage=page,qmin= qmin,qmax= qmax) |
---|
584 | |
---|
585 | def plot_helper(self,currpage, fitModel=None, qmin=None,qmax=None, |
---|
586 | ymin=None,ymax=None, xmin=None, xmax=None,title=None ): |
---|
587 | """ |
---|
588 | Plot a theory given a model and data |
---|
589 | @param model: the model from where the theory is derived |
---|
590 | @param currpage: page in a dictionary referring to some data |
---|
591 | """ |
---|
592 | if self.fit_panel.GetPageCount() >1: |
---|
593 | for page in self.page_finder.iterkeys(): |
---|
594 | if page==currpage : |
---|
595 | data=self.page_finder[page].get_data() |
---|
596 | list=self.page_finder[page].get_model() |
---|
597 | model=list[0] |
---|
598 | break |
---|
599 | print "model in fitting",model |
---|
600 | if data!=None and data.__class__.__name__ != 'Data2D': |
---|
601 | theory = Theory1D(x=[], y=[]) |
---|
602 | theory.name = model.name |
---|
603 | theory.group_id = data.group_id |
---|
604 | """ |
---|
605 | if hasattr(data, "id"): |
---|
606 | import string |
---|
607 | if string.find("Model",data.id )!=None: |
---|
608 | #allow plotting on the same panel |
---|
609 | theory.id =str(data.id )+" "+str(self.index_theory) |
---|
610 | self.index_theory +=1 |
---|
611 | else: |
---|
612 | """ |
---|
613 | theory.id = "Model" |
---|
614 | |
---|
615 | x_name, x_units = data.get_xaxis() |
---|
616 | y_name, y_units = data.get_yaxis() |
---|
617 | theory.xaxis(x_name, x_units) |
---|
618 | theory.yaxis(y_name, y_units) |
---|
619 | if qmin == None : |
---|
620 | qmin = min(data.x) |
---|
621 | if qmax == None : |
---|
622 | qmax = max(data.x) |
---|
623 | try: |
---|
624 | tempx = qmin |
---|
625 | tempy = model.run(qmin) |
---|
626 | theory.x.append(tempx) |
---|
627 | theory.y.append(tempy) |
---|
628 | except : |
---|
629 | wx.PostEvent(self.parent, StatusEvent(status="fitting \ |
---|
630 | skipping point x %g %s" %(qmin, sys.exc_value))) |
---|
631 | |
---|
632 | for i in range(len(data.x)): |
---|
633 | try: |
---|
634 | if data.x[i]> qmin and data.x[i]< qmax: |
---|
635 | tempx = data.x[i] |
---|
636 | tempy = model.run(tempx) |
---|
637 | theory.x.append(tempx) |
---|
638 | theory.y.append(tempy) |
---|
639 | |
---|
640 | except: |
---|
641 | wx.PostEvent(self.parent, StatusEvent(status="fitting \ |
---|
642 | skipping point x %g %s" %(data.x[i], sys.exc_value))) |
---|
643 | try: |
---|
644 | tempx = qmax |
---|
645 | tempy = model.run(qmax) |
---|
646 | theory.x.append(tempx) |
---|
647 | theory.y.append(tempy) |
---|
648 | except: |
---|
649 | wx.PostEvent(self.parent, StatusEvent(status="fitting \ |
---|
650 | skipping point x %g %s" %(qmin, sys.exc_value)) ) |
---|
651 | wx.PostEvent(self.parent, NewPlotEvent(plot=theory, |
---|
652 | title=str(data.name))) |
---|
653 | else: |
---|
654 | |
---|
655 | theory=Data2D(data.data, data.err_data) |
---|
656 | theory.name= model.name |
---|
657 | if title !=None: |
---|
658 | self.title = title |
---|
659 | theory.id= self.title |
---|
660 | theory.group_id= self.title+data.name |
---|
661 | else: |
---|
662 | self.title= "Analytical model 2D " |
---|
663 | theory.id= "Model" |
---|
664 | theory.group_id= "Model"+data.name |
---|
665 | theory.x_bins= data.x_bins |
---|
666 | theory.y_bins= data.y_bins |
---|
667 | tempy=[] |
---|
668 | #print "max x,y",max(data.xmax,data.xmin),max(data.ymax,data.ymin) |
---|
669 | if qmin==None: |
---|
670 | qmin=0#data.xmin |
---|
671 | if qmax==None: |
---|
672 | qmax=math.sqrt(math.pow(max(math.fabs(data.xmax),math.fabs(data.xmin)),2)/ |
---|
673 | +math.pow(max(math.fabs(data.ymax),math.fabs(data.ymin)),2)) |
---|
674 | if ymin==None: |
---|
675 | ymin=data.ymin |
---|
676 | if ymax==None: |
---|
677 | ymax=data.ymax |
---|
678 | if xmin ==None: |
---|
679 | xmin=data.xmin |
---|
680 | if xmax==None: |
---|
681 | xmax=data.xmax |
---|
682 | #print " q range =", |
---|
683 | theory.data = numpy.zeros((len(data.y_bins),len(data.x_bins))) |
---|
684 | for j in range(len(data.y_bins)): |
---|
685 | for i in range(len(data.x_bins)): |
---|
686 | tempqij=math.sqrt((math.pow(data.y_bins[j],2)+math.pow(data.x_bins[i],2))) |
---|
687 | #if tempqij>= qmin and tempqij<= qmax: |
---|
688 | theory.data[j][i]=model.runXY([data.y_bins[j],data.x_bins[i]]) |
---|
689 | #else: |
---|
690 | #theory.data[j][i]=None |
---|
691 | #print "len(data.x_bins),len(data.y_bins);",len(data.x_bins),len(data.y_bins),i,j |
---|
692 | #print "fitting : plot_helper:", theory.image |
---|
693 | #print "fitting : plot_helper:",theory.image |
---|
694 | theory.detector= data.detector |
---|
695 | theory.source= data.source |
---|
696 | |
---|
697 | theory.qmin= qmin |
---|
698 | theory.qmax= qmax |
---|
699 | theory.ymin= ymin |
---|
700 | theory.ymax= ymax |
---|
701 | theory.xmin= xmin |
---|
702 | theory.xmax= xmax |
---|
703 | |
---|
704 | wx.PostEvent(self.parent, NewPlotEvent(plot=theory, |
---|
705 | title=self.title +str(data.name))) |
---|
706 | |
---|
707 | |
---|
708 | def _on_model_menu(self, evt): |
---|
709 | """ |
---|
710 | Plot a theory from a model selected from the menu |
---|
711 | """ |
---|
712 | name = evt.model.__name__ |
---|
713 | if hasattr(evt.model, "name"): |
---|
714 | name = evt.model.name |
---|
715 | print "on model menu", name |
---|
716 | model=evt.model() |
---|
717 | description=model.description |
---|
718 | |
---|
719 | # Create a model page. If a new page is created, the model |
---|
720 | # will be plotted automatically. If a page already exists, |
---|
721 | # the content will be updated and the plot refreshed |
---|
722 | self.fit_panel.add_model_page(model,description,name,topmenu=True) |
---|
723 | |
---|
724 | def draw_model(self,model,name ,data=None,description=None,enable1D=True, enable2D=False, |
---|
725 | qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, qstep=DEFAULT_NPTS): |
---|
726 | """ |
---|
727 | draw model with default data value |
---|
728 | """ |
---|
729 | if data !=None: |
---|
730 | self.redraw_model(qmin,qmax) |
---|
731 | return |
---|
732 | self._draw_model2D(model=model, |
---|
733 | description=model.description, |
---|
734 | enable2D= enable2D, |
---|
735 | qmin=qmin, |
---|
736 | qmax=qmax, |
---|
737 | qstep=qstep) |
---|
738 | self._draw_model1D(model,name,model.description, enable1D,qmin,qmax, qstep) |
---|
739 | |
---|
740 | def _draw_model1D(self,model,name,description=None, enable1D=True, |
---|
741 | qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, qstep=DEFAULT_NPTS): |
---|
742 | |
---|
743 | if enable1D: |
---|
744 | x= numpy.linspace(start= qmin, |
---|
745 | stop= qmax, |
---|
746 | num= qstep, |
---|
747 | endpoint=True |
---|
748 | ) |
---|
749 | xlen= len(x) |
---|
750 | y = numpy.zeros(xlen) |
---|
751 | if not enable1D: |
---|
752 | for i in range(xlen): |
---|
753 | y[i] = model.run(x[i]) |
---|
754 | |
---|
755 | try: |
---|
756 | new_plot = Theory1D(x, y) |
---|
757 | |
---|
758 | new_plot.name = name |
---|
759 | new_plot.xaxis("\\rm{Q}", 'A^{-1}') |
---|
760 | new_plot.yaxis("\\rm{Intensity} ","cm^{-1}") |
---|
761 | new_plot.id = "Model" |
---|
762 | new_plot.group_id ="Model" |
---|
763 | wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot, title="Analytical model 1D")) |
---|
764 | except: |
---|
765 | wx.PostEvent(self.parent, StatusEvent(status="Draw model 1D error: %s" % sys.exc_value)) |
---|
766 | #raise |
---|
767 | else: |
---|
768 | for i in range(xlen): |
---|
769 | y[i] = model.run(x[i]) |
---|
770 | #print x, y |
---|
771 | try: |
---|
772 | new_plot = Theory1D(x, y) |
---|
773 | print "draw model 1D", name |
---|
774 | new_plot.name = name |
---|
775 | new_plot.xaxis("\\rm{Q}", 'A^{-1}') |
---|
776 | new_plot.yaxis("\\rm{Intensity} ","cm^{-1}") |
---|
777 | new_plot.id ="Model" |
---|
778 | new_plot.group_id ="Model" |
---|
779 | |
---|
780 | # Pass the reset flag to let the plotting event handler |
---|
781 | # know that we are replacing the whole plot |
---|
782 | wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot, |
---|
783 | title="Analytical model 1D ", reset=True )) |
---|
784 | |
---|
785 | except: |
---|
786 | #raise |
---|
787 | wx.PostEvent(self.parent, StatusEvent(status="Draw model 1D error: %s" % sys.exc_value)) |
---|
788 | def update(self, output,time): |
---|
789 | pass |
---|
790 | |
---|
791 | def complete(self, output, elapsed, model, qmin, qmax,qstep=DEFAULT_NPTS): |
---|
792 | |
---|
793 | wx.PostEvent(self.parent, StatusEvent(status="Calc \ |
---|
794 | complete in %g sec" % elapsed)) |
---|
795 | #print "complete",output, model,qmin, qmax |
---|
796 | data = output |
---|
797 | temp= numpy.zeros(numpy.shape(data)) |
---|
798 | temp[temp==0]=1 |
---|
799 | theory= Data2D(image=data, err_image=temp) |
---|
800 | |
---|
801 | from DataLoader.data_info import Detector, Source |
---|
802 | |
---|
803 | detector = Detector() |
---|
804 | theory.detector=[] |
---|
805 | theory.detector.append(detector) |
---|
806 | |
---|
807 | theory.detector[0].distance=1e+32#13705.0 |
---|
808 | theory.source= Source() |
---|
809 | theory.source.wavelength=2*math.pi/1e+32#8.4 |
---|
810 | theory.x_bins =[] |
---|
811 | theory.y_bins =[] |
---|
812 | #Now qmax is xmax. |
---|
813 | xmax=2*theory.detector[0].distance*math.atan(qmax/(4*math.pi/theory.source.wavelength)) |
---|
814 | theory.detector[0].pixel_size.x= xmax/(qstep/2-0.5)#5.0 |
---|
815 | theory.detector[0].pixel_size.y= xmax/(qstep/2-0.5)#5.0 |
---|
816 | theory.detector[0].beam_center.x= qmax |
---|
817 | theory.detector[0].beam_center.y= qmax |
---|
818 | #print "xmax,qmax",xmax,qmax |
---|
819 | # compute x_bins and y_bins |
---|
820 | # Qx and Qy vectors |
---|
821 | |
---|
822 | distance = theory.detector[0].distance |
---|
823 | pixel = qstep/2-1 |
---|
824 | theta = pixel / distance / qstep#100.0 |
---|
825 | wavelength = theory.source.wavelength |
---|
826 | pixel_width_x = theory.detector[0].pixel_size.x |
---|
827 | pixel_width_y = theory.detector[0].pixel_size.y |
---|
828 | center_x = theory.detector[0].beam_center.x/pixel_width_x |
---|
829 | center_y = theory.detector[0].beam_center.y/pixel_width_y |
---|
830 | |
---|
831 | |
---|
832 | size_x, size_y= numpy.shape(theory.data) |
---|
833 | #print "size_x,size_y",size_x, size_y |
---|
834 | #This case, q and x are equivalent to each other. |
---|
835 | for i_x in range(size_x): |
---|
836 | theta = (i_x-center_x)*pixel_width_x / distance #/ size_x#100.0 |
---|
837 | qx = 4.0*math.pi/wavelength * math.tan(theta/2.0) |
---|
838 | theory.x_bins.append(qx) |
---|
839 | for i_y in range(size_y): |
---|
840 | theta = (i_y-center_y)*pixel_width_y / distance #/ size_y#100.0 |
---|
841 | qy =4.0*math.pi/wavelength * math.tan(theta/2.0) |
---|
842 | theory.y_bins.append(qy) |
---|
843 | |
---|
844 | #theory.err_data= numpy. |
---|
845 | theory.name= model.name |
---|
846 | theory.group_id ="Model" |
---|
847 | theory.id ="Model" |
---|
848 | |
---|
849 | |
---|
850 | |
---|
851 | theory.xmin= -qmax/math.sqrt(2) |
---|
852 | theory.xmax= qmax/math.sqrt(2) |
---|
853 | theory.ymin= -qmax/math.sqrt(2) |
---|
854 | theory.ymax= qmax/math.sqrt(2) |
---|
855 | |
---|
856 | print "model draw comptele xmax",theory.xmax,model.name |
---|
857 | wx.PostEvent(self.parent, NewPlotEvent(plot=theory, |
---|
858 | title="Analytical model 2D ", reset=True )) |
---|
859 | |
---|
860 | |
---|
861 | |
---|
862 | def _draw_model2D(self,model,description=None, enable2D=False, |
---|
863 | qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, qstep=DEFAULT_NPTS): |
---|
864 | |
---|
865 | x= numpy.linspace(start= -1*qmax, |
---|
866 | stop= qmax, |
---|
867 | num= qstep, |
---|
868 | endpoint=True ) |
---|
869 | y = numpy.linspace(start= -1*qmax, |
---|
870 | stop= qmax, |
---|
871 | num= qstep, |
---|
872 | endpoint=True ) |
---|
873 | |
---|
874 | lx = len(x) |
---|
875 | #print x |
---|
876 | data=numpy.zeros([len(x),len(y)]) |
---|
877 | self.model= model |
---|
878 | if enable2D: |
---|
879 | from sans.guiframe.model_thread import Calc2D |
---|
880 | self.calc_thread = Calc2D(parent =self.parent,x=x, |
---|
881 | y=y,model= self.model, |
---|
882 | qmin=qmin, |
---|
883 | qmax=qmax, |
---|
884 | qstep=qstep, |
---|
885 | completefn=self.complete, |
---|
886 | updatefn=None) |
---|
887 | self.calc_thread.queue() |
---|
888 | self.calc_thread.ready(2.5) |
---|
889 | |
---|
890 | def show_panel2D(self, id=None ): |
---|
891 | self.parent.show_panel(self.model2D_id) |
---|
892 | |
---|
893 | |
---|
894 | if __name__ == "__main__": |
---|
895 | i = Plugin() |
---|
896 | |
---|
897 | |
---|
898 | |
---|
899 | |
---|