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 | for i in range(len(metadata.dy)): |
---|
472 | if metadata.dy[i] !=0: |
---|
473 | dy.append(metadata.dy[i]) |
---|
474 | x.append(metadata.x[i]) |
---|
475 | y.append(metadata.y[i]) |
---|
476 | if len(dy)>0: |
---|
477 | metadata.dy=numpy.zeros(len(dy)) |
---|
478 | metadata.dy=dy |
---|
479 | metadata.y=numpy.zeros(len(y)) |
---|
480 | metadata.y=y |
---|
481 | metadata.x=numpy.zeros(len(x)) |
---|
482 | metadata.x=x |
---|
483 | self.fitter.set_data(data=metadata,Uid=self.fit_id, |
---|
484 | smearer=smearer,qmin= qmin,qmax=qmax, |
---|
485 | ymin=ymin,ymax=ymax) |
---|
486 | self.fitter.select_problem_for_fit(Uid=self.fit_id,value=value.get_scheduled()) |
---|
487 | page_fitted=current_pg |
---|
488 | #self.fit_id+=1 |
---|
489 | #self.schedule_for_fit( 0,value) |
---|
490 | except: |
---|
491 | wx.PostEvent(self.parent, StatusEvent(status="Single Fit error: %s" % sys.exc_value)) |
---|
492 | return |
---|
493 | # make sure to keep an alphabetic order |
---|
494 | #of parameter names in the list |
---|
495 | try: |
---|
496 | # If a thread is already started, stop it |
---|
497 | if self.calc_thread != None and self.calc_thread.isrunning(): |
---|
498 | self.calc_thread.stop() |
---|
499 | |
---|
500 | self.calc_thread =FitThread(parent =self.parent, |
---|
501 | fn= self.fitter, |
---|
502 | pars= pars, |
---|
503 | cpage= page_fitted, |
---|
504 | qmin=qmin, |
---|
505 | qmax=qmax, |
---|
506 | |
---|
507 | completefn=self._single_fit_completed, |
---|
508 | updatefn=None) |
---|
509 | self.calc_thread.queue() |
---|
510 | self.calc_thread.ready(2.5) |
---|
511 | #while not self.done: |
---|
512 | #print "when here" |
---|
513 | # time.sleep(1) |
---|
514 | |
---|
515 | |
---|
516 | except: |
---|
517 | wx.PostEvent(self.parent, StatusEvent(status="Single Fit error: %s" % sys.exc_value)) |
---|
518 | return |
---|
519 | |
---|
520 | def _on_simul_fit(self, id=None,qmin=None,qmax=None, ymin=None, ymax=None): |
---|
521 | """ |
---|
522 | perform fit for all the pages selected on simpage and return chisqr,out and cov |
---|
523 | @param engineName: type of fit to be performed |
---|
524 | @param id: unique id corresponding to a fit problem(model, set of data) |
---|
525 | in park_integration |
---|
526 | @param model: model to fit |
---|
527 | |
---|
528 | """ |
---|
529 | #set an engine to perform fit |
---|
530 | from sans.fit.Fitting import Fit |
---|
531 | self.fitter= Fit(self._fit_engine) |
---|
532 | self.fit_id= 0 |
---|
533 | #Setting an id to store model and data |
---|
534 | if id!=None: |
---|
535 | self.fit_id= id |
---|
536 | |
---|
537 | |
---|
538 | for page, value in self.page_finder.iteritems(): |
---|
539 | try: |
---|
540 | if value.get_scheduled()==1: |
---|
541 | metadata = value.get_fit_data() |
---|
542 | list = value.get_model() |
---|
543 | model= list[0] |
---|
544 | #Create dictionary of parameters for fitting used |
---|
545 | cpage= page |
---|
546 | print "" |
---|
547 | pars = [] |
---|
548 | templist = [] |
---|
549 | templist = page.get_param_list() |
---|
550 | for element in templist: |
---|
551 | try: |
---|
552 | name = str(element[0].GetLabelText()) |
---|
553 | pars.append(name) |
---|
554 | except: |
---|
555 | wx.PostEvent(self.parent, StatusEvent(status="Simultaneous Fit error: %s" % sys.exc_value)) |
---|
556 | return |
---|
557 | # need to check this print "new model " |
---|
558 | |
---|
559 | new_model=Model(model) |
---|
560 | param=value.get_model_param() |
---|
561 | |
---|
562 | if len(param)>0: |
---|
563 | for item in param: |
---|
564 | param_value = item[1] |
---|
565 | param_name = item[0] |
---|
566 | #print "fitting ", param,param_name, param_value |
---|
567 | |
---|
568 | #new_model.set( model.getParam(param_name[0])= param_value) |
---|
569 | #new_model.set( exec"%s=%s"%(param_name[0], param_value)) |
---|
570 | #new_model.set( exec "%s"%(param_nam) = param_value) |
---|
571 | new_model.parameterset[ param_name].set( param_value ) |
---|
572 | |
---|
573 | self.fitter.set_model(new_model, self.fit_id, pars) |
---|
574 | print "sim-->model",metadata,model,self.fit_id, pars |
---|
575 | #self.fitter.set_model(Model(model), self.fit_id, pars) |
---|
576 | self.fitter.set_data(metadata,self.fit_id,qmin,qmax,ymin,ymax) |
---|
577 | print "sim---->value of problem",value.get_scheduled() |
---|
578 | self.fitter.select_problem_for_fit(Uid=self.fit_id,value=value.get_scheduled()) |
---|
579 | self.fit_id += 1 |
---|
580 | value.clear_model_param() |
---|
581 | #self.schedule_for_fit( 0,value) |
---|
582 | except: |
---|
583 | wx.PostEvent(self.parent, StatusEvent(status="Simultaneous Fit error: %s" % sys.exc_value)) |
---|
584 | return |
---|
585 | #Do the simultaneous fit |
---|
586 | try: |
---|
587 | # If a thread is already started, stop it |
---|
588 | if self.calc_thread != None and self.calc_thread.isrunning(): |
---|
589 | self.calc_thread.stop() |
---|
590 | if self.fit_id==1: |
---|
591 | self.calc_thread =FitThread(parent =self.parent, |
---|
592 | fn= self.fitter, |
---|
593 | qmin=qmin, |
---|
594 | qmax=qmax, |
---|
595 | ymin= ymin, |
---|
596 | ymax= ymax, |
---|
597 | cpage=cpage, |
---|
598 | pars= pars, |
---|
599 | completefn= self._simul_fit_completed, |
---|
600 | updatefn=None) |
---|
601 | |
---|
602 | else: |
---|
603 | self.calc_thread =FitThread(parent =self.parent, |
---|
604 | fn= self.fitter, |
---|
605 | qmin=qmin, |
---|
606 | qmax=qmax, |
---|
607 | ymin= ymin, |
---|
608 | ymax= ymax, |
---|
609 | completefn= self._simul_fit_completed, |
---|
610 | updatefn=None) |
---|
611 | self.calc_thread.queue() |
---|
612 | self.calc_thread.ready(2.5) |
---|
613 | |
---|
614 | except: |
---|
615 | wx.PostEvent(self.parent, StatusEvent(status="Simultaneous Fit error: %s" % sys.exc_value)) |
---|
616 | return |
---|
617 | |
---|
618 | |
---|
619 | def _onset_engine(self,event): |
---|
620 | """ set engine to scipy""" |
---|
621 | if self._fit_engine== 'park': |
---|
622 | self._on_change_engine('scipy') |
---|
623 | else: |
---|
624 | self._on_change_engine('park') |
---|
625 | wx.PostEvent(self.parent, StatusEvent(status="Engine set to: %s" % self._fit_engine)) |
---|
626 | |
---|
627 | |
---|
628 | def _on_change_engine(self, engine='park'): |
---|
629 | """ |
---|
630 | Allow to select the type of engine to perform fit |
---|
631 | @param engine: the key work of the engine |
---|
632 | """ |
---|
633 | self._fit_engine = engine |
---|
634 | |
---|
635 | |
---|
636 | def _on_model_panel(self, evt): |
---|
637 | """ |
---|
638 | react to model selection on any combo box or model menu.plot the model |
---|
639 | """ |
---|
640 | |
---|
641 | model = evt.model |
---|
642 | name = evt.name |
---|
643 | |
---|
644 | print "name fitting", name |
---|
645 | sim_page=self.fit_panel.GetPage(1) |
---|
646 | current_pg = self.fit_panel.get_current_page() |
---|
647 | if current_pg != sim_page: |
---|
648 | current_pg.set_panel(model) |
---|
649 | #model.name = self.page_finder[current_pg].get_name() |
---|
650 | #print "model name", model.name |
---|
651 | model.name="M"+str(self.index_model) |
---|
652 | try: |
---|
653 | metadata=self.page_finder[current_pg].get_data() |
---|
654 | M_name=model.name+"= "+name+"("+metadata.group_id+")" |
---|
655 | except: |
---|
656 | M_name=model.name+"= "+name |
---|
657 | self.index_model += 1 |
---|
658 | |
---|
659 | |
---|
660 | # save model name |
---|
661 | |
---|
662 | # save the name containing the data name with the appropriate model |
---|
663 | self.page_finder[current_pg].set_model(model,M_name) |
---|
664 | self.plot_helper(currpage= current_pg,qmin= None,qmax= None) |
---|
665 | sim_page.add_model(self.page_finder) |
---|
666 | |
---|
667 | def set_smearer(self,smearer): |
---|
668 | current_pg=self.fit_panel.get_current_page() |
---|
669 | self.page_finder[current_pg].set_smearer(smearer) |
---|
670 | |
---|
671 | def redraw_model(self,qmin= None,qmax= None): |
---|
672 | """ |
---|
673 | Draw a theory according to model changes or data range. |
---|
674 | @param qmin: the minimum value plotted for theory |
---|
675 | @param qmax: the maximum value plotted for theory |
---|
676 | """ |
---|
677 | current_pg=self.fit_panel.get_current_page() |
---|
678 | for page, value in self.page_finder.iteritems(): |
---|
679 | if page ==current_pg : |
---|
680 | break |
---|
681 | self.plot_helper(currpage=page,qmin= qmin,qmax= qmax) |
---|
682 | |
---|
683 | def plot_helper(self,currpage, fitModel=None, qmin=None,qmax=None, |
---|
684 | ymin=None,ymax=None, xmin=None, xmax=None,title=None ): |
---|
685 | """ |
---|
686 | Plot a theory given a model and data |
---|
687 | @param model: the model from where the theory is derived |
---|
688 | @param currpage: page in a dictionary referring to some data |
---|
689 | """ |
---|
690 | if self.fit_panel.GetPageCount() >1: |
---|
691 | for page in self.page_finder.iterkeys(): |
---|
692 | if page==currpage : |
---|
693 | data=self.page_finder[page].get_plotted_data() |
---|
694 | list=self.page_finder[page].get_model() |
---|
695 | model=list[0] |
---|
696 | break |
---|
697 | print "model in fitting",model |
---|
698 | if data!=None and data.__class__.__name__ != 'Data2D': |
---|
699 | theory = Theory1D(x=[], y=[]) |
---|
700 | theory.name = model.name |
---|
701 | theory.group_id = data.group_id |
---|
702 | """ |
---|
703 | if hasattr(data, "id"): |
---|
704 | import string |
---|
705 | if string.find("Model",data.id )!=None: |
---|
706 | #allow plotting on the same panel |
---|
707 | theory.id =str(data.id )+" "+str(self.index_theory) |
---|
708 | self.index_theory +=1 |
---|
709 | else: |
---|
710 | """ |
---|
711 | theory.id = "Model" |
---|
712 | |
---|
713 | x_name, x_units = data.get_xaxis() |
---|
714 | y_name, y_units = data.get_yaxis() |
---|
715 | theory.xaxis(x_name, x_units) |
---|
716 | theory.yaxis(y_name, y_units) |
---|
717 | if qmin == None : |
---|
718 | qmin = min(data.x) |
---|
719 | if qmax == None : |
---|
720 | qmax = max(data.x) |
---|
721 | try: |
---|
722 | tempx = qmin |
---|
723 | tempy = model.run(qmin) |
---|
724 | theory.x.append(tempx) |
---|
725 | theory.y.append(tempy) |
---|
726 | except : |
---|
727 | wx.PostEvent(self.parent, StatusEvent(status="fitting \ |
---|
728 | skipping point x %g %s" %(qmin, sys.exc_value))) |
---|
729 | |
---|
730 | for i in range(len(data.x)): |
---|
731 | try: |
---|
732 | if data.x[i]> qmin and data.x[i]< qmax: |
---|
733 | tempx = data.x[i] |
---|
734 | tempy = model.run(tempx) |
---|
735 | theory.x.append(tempx) |
---|
736 | theory.y.append(tempy) |
---|
737 | |
---|
738 | except: |
---|
739 | wx.PostEvent(self.parent, StatusEvent(status="fitting \ |
---|
740 | skipping point x %g %s" %(data.x[i], sys.exc_value))) |
---|
741 | try: |
---|
742 | tempx = qmax |
---|
743 | tempy = model.run(qmax) |
---|
744 | theory.x.append(tempx) |
---|
745 | theory.y.append(tempy) |
---|
746 | except: |
---|
747 | wx.PostEvent(self.parent, StatusEvent(status="fitting \ |
---|
748 | skipping point x %g %s" %(qmin, sys.exc_value)) ) |
---|
749 | wx.PostEvent(self.parent, NewPlotEvent(plot=theory, |
---|
750 | title=str(data.name))) |
---|
751 | else: |
---|
752 | |
---|
753 | theory=Data2D(data.data, data.err_data) |
---|
754 | theory.name= model.name |
---|
755 | if title !=None: |
---|
756 | self.title = title |
---|
757 | theory.id= self.title |
---|
758 | theory.group_id= self.title+data.name |
---|
759 | else: |
---|
760 | self.title= "Analytical model 2D " |
---|
761 | theory.id= "Model" |
---|
762 | theory.group_id= "Model"+data.name |
---|
763 | theory.x_bins= data.x_bins |
---|
764 | theory.y_bins= data.y_bins |
---|
765 | tempy=[] |
---|
766 | #print "max x,y",max(data.xmax,data.xmin),max(data.ymax,data.ymin) |
---|
767 | if qmin==None: |
---|
768 | qmin=0#min(math.fabs(data.xmax),math.fabs(data.ymin)) |
---|
769 | if qmax==None: |
---|
770 | qmax=math.sqrt(math.pow(max(math.fabs(data.xmax),math.fabs(data.xmin)),2)/ |
---|
771 | +math.pow(max(math.fabs(data.ymax),math.fabs(data.ymin)),2)) |
---|
772 | if ymin==None: |
---|
773 | ymin=data.ymin |
---|
774 | if ymax==None: |
---|
775 | ymax=data.ymax |
---|
776 | if xmin ==None: |
---|
777 | xmin=data.xmin |
---|
778 | if xmax==None: |
---|
779 | xmax=data.xmax |
---|
780 | |
---|
781 | theory.data = numpy.zeros((len(data.y_bins),len(data.x_bins))) |
---|
782 | for j in range(len(data.y_bins)): |
---|
783 | for i in range(len(data.x_bins)): |
---|
784 | tempqij=math.sqrt((math.pow(data.y_bins[j],2)+math.pow(data.x_bins[i],2))) |
---|
785 | if tempqij>= qmin and tempqij<= qmax: |
---|
786 | theory.data[j][i]=model.runXY([data.y_bins[j],data.x_bins[i]]) |
---|
787 | else: |
---|
788 | theory.data[j][i]=0 #None # Later, We need to decide which of 0 and None is better. |
---|
789 | #print "len(data.x_bins),len(data.y_bins);",len(data.x_bins),len(data.y_bins),qmax |
---|
790 | #print "fitting : plot_helper:", theory.image |
---|
791 | #print "fitting : plot_helper:",theory.image |
---|
792 | theory.detector= data.detector |
---|
793 | theory.source= data.source |
---|
794 | |
---|
795 | theory.qmin= qmin |
---|
796 | theory.qmax= qmax |
---|
797 | theory.ymin= ymin |
---|
798 | theory.ymax= ymax |
---|
799 | theory.xmin= xmin |
---|
800 | theory.xmax= xmax |
---|
801 | |
---|
802 | wx.PostEvent(self.parent, NewPlotEvent(plot=theory, |
---|
803 | title=self.title +str(data.name))) |
---|
804 | |
---|
805 | |
---|
806 | def _on_model_menu(self, evt): |
---|
807 | """ |
---|
808 | Plot a theory from a model selected from the menu |
---|
809 | """ |
---|
810 | name = evt.model.__name__ |
---|
811 | if hasattr(evt.model, "name"): |
---|
812 | name = evt.model.name |
---|
813 | print "on model menu", name |
---|
814 | model=evt.model() |
---|
815 | description=model.description |
---|
816 | |
---|
817 | # Create a model page. If a new page is created, the model |
---|
818 | # will be plotted automatically. If a page already exists, |
---|
819 | # the content will be updated and the plot refreshed |
---|
820 | self.fit_panel.add_model_page(model,description,name,topmenu=True) |
---|
821 | |
---|
822 | def draw_model(self,model,name ,data=None,description=None,enable1D=True, enable2D=False, |
---|
823 | qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, qstep=DEFAULT_NPTS): |
---|
824 | """ |
---|
825 | draw model with default data value |
---|
826 | """ |
---|
827 | if data !=None: |
---|
828 | self.redraw_model(qmin,qmax) |
---|
829 | return |
---|
830 | self._draw_model1D(model,name,model.description, enable1D,qmin,qmax, qstep) |
---|
831 | self._draw_model2D(model=model, |
---|
832 | description=model.description, |
---|
833 | enable2D= enable2D, |
---|
834 | qmin=qmin, |
---|
835 | qmax=qmax, |
---|
836 | qstep=qstep) |
---|
837 | |
---|
838 | |
---|
839 | def _draw_model1D(self,model,name,description=None, enable1D=True, |
---|
840 | qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, qstep=DEFAULT_NPTS): |
---|
841 | |
---|
842 | if enable1D: |
---|
843 | x= numpy.linspace(start= qmin, |
---|
844 | stop= qmax, |
---|
845 | num= qstep, |
---|
846 | endpoint=True |
---|
847 | ) |
---|
848 | xlen= len(x) |
---|
849 | y = numpy.zeros(xlen) |
---|
850 | if not enable1D: |
---|
851 | for i in range(xlen): |
---|
852 | y[i] = model.run(x[i]) |
---|
853 | |
---|
854 | try: |
---|
855 | new_plot = Theory1D(x, y) |
---|
856 | |
---|
857 | new_plot.name = name |
---|
858 | new_plot.xaxis("\\rm{Q}", 'A^{-1}') |
---|
859 | new_plot.yaxis("\\rm{Intensity} ","cm^{-1}") |
---|
860 | new_plot.id = "Model" |
---|
861 | new_plot.group_id ="Model" |
---|
862 | wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot, title="Analytical model 1D")) |
---|
863 | except: |
---|
864 | wx.PostEvent(self.parent, StatusEvent(status="Draw model 1D error: %s" % sys.exc_value)) |
---|
865 | #raise |
---|
866 | else: |
---|
867 | for i in range(xlen): |
---|
868 | y[i] = model.run(x[i]) |
---|
869 | try: |
---|
870 | new_plot = Theory1D(x, y) |
---|
871 | print "draw model 1D", name |
---|
872 | new_plot.name = name |
---|
873 | new_plot.xaxis("\\rm{Q}", 'A^{-1}') |
---|
874 | new_plot.yaxis("\\rm{Intensity} ","cm^{-1}") |
---|
875 | new_plot.id ="Model" |
---|
876 | new_plot.group_id ="Model" |
---|
877 | |
---|
878 | # Pass the reset flag to let the plotting event handler |
---|
879 | # know that we are replacing the whole plot |
---|
880 | wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot, |
---|
881 | title="Analytical model 1D ", reset=True )) |
---|
882 | |
---|
883 | except: |
---|
884 | #raise |
---|
885 | wx.PostEvent(self.parent, StatusEvent(status="Draw model 1D error: %s" % sys.exc_value)) |
---|
886 | def update(self, output,time): |
---|
887 | pass |
---|
888 | |
---|
889 | def complete(self, output, elapsed, model, qmin, qmax,qstep=DEFAULT_NPTS): |
---|
890 | |
---|
891 | wx.PostEvent(self.parent, StatusEvent(status="Calc \ |
---|
892 | complete !" , type="stop")) |
---|
893 | #print "complete",output, model,qmin, qmax |
---|
894 | data = output |
---|
895 | temp= numpy.zeros(numpy.shape(data)) |
---|
896 | temp[temp==0]=1 |
---|
897 | theory= Data2D(image=data, err_image=temp) |
---|
898 | |
---|
899 | from DataLoader.data_info import Detector, Source |
---|
900 | |
---|
901 | detector = Detector() |
---|
902 | theory.detector=[] |
---|
903 | theory.detector.append(detector) |
---|
904 | |
---|
905 | theory.detector[0].distance=1e+32#13705.0 |
---|
906 | theory.source= Source() |
---|
907 | theory.source.wavelength=2*math.pi/1e+32#8.4 |
---|
908 | theory.x_bins =[] |
---|
909 | theory.y_bins =[] |
---|
910 | #Now qmax is xmax. |
---|
911 | xmax=2*theory.detector[0].distance*math.atan(qmax/(4*math.pi/theory.source.wavelength)) |
---|
912 | theory.detector[0].pixel_size.x= xmax/(qstep/2-0.5)#5.0 |
---|
913 | theory.detector[0].pixel_size.y= xmax/(qstep/2-0.5)#5.0 |
---|
914 | theory.detector[0].beam_center.x= qmax |
---|
915 | theory.detector[0].beam_center.y= qmax |
---|
916 | #print "xmax,qmax",xmax,qmax |
---|
917 | # compute x_bins and y_bins |
---|
918 | # Qx and Qy vectors |
---|
919 | |
---|
920 | distance = theory.detector[0].distance |
---|
921 | pixel = qstep/2-1 |
---|
922 | theta = pixel / distance / qstep#100.0 |
---|
923 | wavelength = theory.source.wavelength |
---|
924 | pixel_width_x = theory.detector[0].pixel_size.x |
---|
925 | pixel_width_y = theory.detector[0].pixel_size.y |
---|
926 | center_x = theory.detector[0].beam_center.x/pixel_width_x |
---|
927 | center_y = theory.detector[0].beam_center.y/pixel_width_y |
---|
928 | |
---|
929 | |
---|
930 | size_x, size_y= numpy.shape(theory.data) |
---|
931 | #print "size_x,size_y",size_x, size_y |
---|
932 | #This case, q and x are equivalent to each other. |
---|
933 | for i_x in range(size_x): |
---|
934 | theta = (i_x-center_x)*pixel_width_x / distance #/ size_x#100.0 |
---|
935 | qx = 4.0*math.pi/wavelength * math.tan(theta/2.0) |
---|
936 | theory.x_bins.append(qx) |
---|
937 | for i_y in range(size_y): |
---|
938 | theta = (i_y-center_y)*pixel_width_y / distance #/ size_y#100.0 |
---|
939 | qy =4.0*math.pi/wavelength * math.tan(theta/2.0) |
---|
940 | theory.y_bins.append(qy) |
---|
941 | |
---|
942 | #theory.err_data= numpy. |
---|
943 | theory.name= model.name |
---|
944 | theory.group_id ="Model" |
---|
945 | theory.id ="Model" |
---|
946 | |
---|
947 | |
---|
948 | |
---|
949 | theory.xmin= -qmax#/math.sqrt(2)#You can not do sqrt(2), that changes axis scale not data itself |
---|
950 | theory.xmax= qmax#/math.sqrt(2) |
---|
951 | theory.ymin= -qmax#/math.sqrt(2) |
---|
952 | theory.ymax= qmax#/math.sqrt(2) |
---|
953 | |
---|
954 | #print "model draw comptele xmax",theory.xmax,model.name |
---|
955 | wx.PostEvent(self.parent, NewPlotEvent(plot=theory, |
---|
956 | title="Analytical model 2D ", reset=True )) |
---|
957 | |
---|
958 | |
---|
959 | |
---|
960 | def _draw_model2D(self,model,description=None, enable2D=False, |
---|
961 | qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, qstep=DEFAULT_NPTS): |
---|
962 | |
---|
963 | x= numpy.linspace(start= -1*qmax, |
---|
964 | stop= qmax, |
---|
965 | num= qstep, |
---|
966 | endpoint=True ) |
---|
967 | y = numpy.linspace(start= -1*qmax, |
---|
968 | stop= qmax, |
---|
969 | num= qstep, |
---|
970 | endpoint=True ) |
---|
971 | |
---|
972 | lx = len(x) |
---|
973 | #print x |
---|
974 | #data=numpy.zeros([len(x),len(y)]) |
---|
975 | self.model= model |
---|
976 | if enable2D: |
---|
977 | try: |
---|
978 | from sans.guiframe.model_thread import Calc2D |
---|
979 | print "in draw model 2d ",self.model |
---|
980 | self.calc_thread = Calc2D(parent =self.parent,x=x, |
---|
981 | y=y,model= self.model, |
---|
982 | qmin=qmin, |
---|
983 | qmax=qmax, |
---|
984 | qstep=qstep, |
---|
985 | completefn=self.complete, |
---|
986 | updatefn=None) |
---|
987 | self.calc_thread.queue() |
---|
988 | self.calc_thread.ready(2.5) |
---|
989 | except: |
---|
990 | raise |
---|
991 | |
---|
992 | def show_panel2D(self, id=None ): |
---|
993 | self.parent.show_panel(self.model2D_id) |
---|
994 | |
---|
995 | |
---|
996 | if __name__ == "__main__": |
---|
997 | i = Plugin() |
---|
998 | |
---|
999 | |
---|
1000 | |
---|
1001 | |
---|