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