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