Changeset 78a205a in sasview


Ignore:
Timestamp:
Mar 5, 2015 8:29:42 AM (9 years ago)
Author:
Mathieu Doucet <doucetm@…>
Branches:
master, ESS_GUI, ESS_GUI_Docs, ESS_GUI_batch_fitting, ESS_GUI_bumps_abstraction, ESS_GUI_iss1116, ESS_GUI_iss879, ESS_GUI_iss959, ESS_GUI_opencl, ESS_GUI_ordering, ESS_GUI_sync_sascalc, costrafo411, magnetic_scatt, release-4.1.1, release-4.1.2, release-4.2.2, release_4.0.1, ticket-1009, ticket-1094-headless, ticket-1242-2d-resolution, ticket-1243, ticket-1249, ticket885, unittest-saveload
Children:
dca6188
Parents:
74f419d
Message:

pylint fixes

Location:
src/sas/perspectives/invariant
Files:
6 edited

Legend:

Unmodified
Added
Removed
  • src/sas/perspectives/invariant/help_panel.py

    rb9a5f0e r78a205a  
    1 #!/usr/bin/python 
     1""" 
     2    Help panel for Invariant perspective 
     3""" 
    24import wx 
    35import wx.html as html 
     
    57import os 
    68 
    7      
     9 
    810class HelpDialog(wx.Dialog): 
    911    """ 
     12        Dialog box showing invariant panel help 
    1013    """ 
    1114    def __init__(self, parent, id): 
     
    1316        """ 
    1417        wx.Dialog.__init__(self, parent, id, size=(400, 420)) 
    15         self.SetTitle("Invariant help")  
    16          
     18        self.SetTitle("Invariant help") 
     19 
    1720        vbox = wx.BoxSizer(wx.VERTICAL) 
    1821 
    1922        explanation = help() 
    20             
     23 
    2124        label_explain = wx.StaticText(self, -1, explanation, size=(350, 320)) 
    22              
    23         vbox.Add(label_explain, 0, wx.ALL|wx.EXPAND, 15) 
     25 
     26        vbox.Add(label_explain, 0, wx.ALL | wx.EXPAND, 15) 
    2427 
    2528 
    2629        static_line = wx.StaticLine(self, -1) 
    2730        vbox.Add(static_line, 0, wx.EXPAND, 0) 
    28          
     31 
    2932        button_OK = wx.Button(self, wx.ID_OK, "OK") 
    3033 
    3134        sizer_button = wx.BoxSizer(wx.HORIZONTAL) 
    32         sizer_button.Add((20, 20), 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
    33         sizer_button.Add(button_OK, 0, wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10)        
    34         vbox.Add(sizer_button, 0, wx.EXPAND|wx.BOTTOM|wx.TOP, 10) 
     35        sizer_button.Add((20, 20), 1, wx.EXPAND | wx.ADJUST_MINSIZE, 0) 
     36        sizer_button.Add(button_OK, 0, wx.LEFT | wx.RIGHT | wx.ADJUST_MINSIZE, 10) 
     37        vbox.Add(sizer_button, 0, wx.EXPAND | wx.BOTTOM | wx.TOP, 10) 
    3538 
    3639        self.SetSizer(vbox) 
    3740        self.SetAutoLayout(True) 
    38          
     41 
    3942        self.Layout() 
    4043        self.Centre() 
     
    4245class HelpWindow(wx.Frame): 
    4346    """ 
     47        Help window for invariant perspective 
    4448    """ 
    45     def __init__(self, parent, id, title= 'HelpWindow', pageToOpen=None): 
     49    def __init__(self, parent, id, title='HelpWindow', pageToOpen=None): 
    4650        wx.Frame.__init__(self, parent, id, title, size=(820, 450)) 
    4751        """ 
    4852        contains help info 
    4953        """ 
    50         self.SetTitle("Invariant Help")  
     54        self.SetTitle("Invariant Help") 
    5155        splitter = MultiSplitterWindow(self, style=wx.SP_LIVE_UPDATE) 
    5256        rpanel = wx.Panel(splitter, -1) 
    5357        lpanel = wx.Panel(splitter, -1, style=wx.BORDER_SUNKEN) 
    54          
     58 
    5559        vbox = wx.BoxSizer(wx.VERTICAL) 
    5660        header = wx.Panel(rpanel, -1) 
     
    6569        header.SetSizer(hbox) 
    6670        vbox.Add(header, 0, wx.EXPAND) 
    67         
     71 
    6872        vboxl = wx.BoxSizer(wx.VERTICAL) 
    6973        headerl = wx.Panel(lpanel, -1, size=(-1, 20)) 
    70         
     74 
    7175        headerl.SetBackgroundColour('#6666FF') 
    7276        headerl.SetForegroundColour('WHITE') 
     
    8084        vboxl.Add(headerl, 0, wx.EXPAND) 
    8185        self.lhelp = html.HtmlWindow(lpanel, -1, style=wx.NO_BORDER) 
    82         self.rhelp = html.HtmlWindow(rpanel, -1, style=wx.NO_BORDER,  
     86        self.rhelp = html.HtmlWindow(rpanel, -1, style=wx.NO_BORDER, 
    8387                                     size=(500, -1)) 
    8488        import sas.perspectives.invariant as invariant 
    8589        path = invariant.get_data_path(media='media') 
    86         self.path = os.path.join(path,"invariant_help.html") 
    87       
     90        self.path = os.path.join(path, "invariant_help.html") 
     91 
    8892        self.rhelp.LoadPage(self.path) 
    8993        page = """<html> 
     
    9498            </body> 
    9599            </html>""" % self.path 
    96          
     100 
    97101        self.lhelp.SetPage(page) 
    98102        self.lhelp.Bind(wx.html.EVT_HTML_LINK_CLICKED, self.OnLinkClicked) 
    99          
     103 
    100104        vbox.Add(self.rhelp, 1, wx.EXPAND) 
    101105        vboxl.Add(self.lhelp, 1, wx.EXPAND) 
     
    103107        lpanel.SetSizer(vboxl) 
    104108        lpanel.SetFocus() 
    105          
     109 
    106110        vbox1 = wx.BoxSizer(wx.HORIZONTAL) 
    107111        vbox1.Add(splitter, 1, wx.EXPAND) 
     
    109113        splitter.AppendWindow(rpanel) 
    110114        self.SetSizer(vbox1) 
    111         
     115 
    112116        self.Centre() 
    113117        self.Show(True) 
    114          
    115          
     118 
     119 
    116120    def OnLinkClicked(self, event): 
    117121        """ 
     
    122126class ViewApp(wx.App): 
    123127    """ 
     128        Test application 
    124129    """ 
    125130    def OnInit(self): 
    126131        """ 
     132            Initialization for test application 
    127133        """ 
    128         frame = HelpWindow(None, -1, 'HelpWindow')     
     134        frame = HelpWindow(None, -1, 'HelpWindow') 
    129135        frame.Show(True) 
    130136        self.SetTopWindow(frame) 
    131          
     137 
    132138        return True 
    133          
    134139 
    135 if __name__ == "__main__":  
     140 
     141if __name__ == "__main__": 
    136142    app = ViewApp(0) 
    137     app.MainLoop()      
     143    app.MainLoop() 
  • src/sas/perspectives/invariant/invariant.py

    rb9a5f0e r78a205a  
    33 
    44################################################################################ 
    5 #This software was developed by the University of Tennessee as part of the 
    6 #Distributed Data Analysis of Neutron Scattering Experiments (DANSE) 
    7 #project funded by the US National Science Foundation.  
     5# This software was developed by the University of Tennessee as part of the 
     6# Distributed Data Analysis of Neutron Scattering Experiments (DANSE) 
     7# project funded by the US National Science Foundation. 
    88# 
    9 #See the license text in license.txt 
     9# See the license text in license.txt 
    1010# 
    11 #copyright 2009, University of Tennessee 
     11# copyright 2009, University of Tennessee 
    1212################################################################################ 
    1313 
     
    3030    """ 
    3131    This class defines the interface for invariant Plugin class 
    32     that can be used by the gui_manager.        
     32    that can be used by the gui_manager. 
    3333    """ 
    34      
     34 
    3535    def __init__(self, standalone=False): 
    3636        PluginBase.__init__(self, name="Invariant", standalone=standalone) 
    37          
    38         #dictionary containing data name and error on dy of that data  
     37 
     38        # dictionary containing data name and error on dy of that data 
    3939        self.err_dy = {} 
    40         
    41         #default state objects 
    42         self.state_reader = None  
     40 
     41        # default state objects 
     42        self.state_reader = None 
    4343        self._extensions = '.inv' 
    44         self.temp_state = None  
    45         self.__data = None  
    46         
     44        self.temp_state = None 
     45        self.__data = None 
     46 
    4747        # Log startup 
    4848        logging.info("Invariant plug-in started") 
    49         
     49 
    5050    def help(self, evt): 
    5151        """ 
    52         Show a general help dialog.  
     52        Show a general help dialog. 
    5353        """ 
    5454        from help_panel import  HelpWindow 
    55         frame = HelpWindow(None, -1)  
     55        frame = HelpWindow(None, -1) 
    5656        if hasattr(frame, "IsIconized"): 
    5757            if not frame.IsIconized(): 
     
    6060                    frame.SetIcon(icon) 
    6161                except: 
    62                     pass   
     62                    logging.error(sys.exc_value) 
    6363        frame.Show(True) 
    64          
     64 
    6565    def get_data(self): 
    6666        """ 
    6767        """ 
    6868        return self.__data 
    69      
     69 
    7070    def get_panels(self, parent): 
    7171        """ 
    7272        Create and return the list of wx.Panels for your plug-in. 
    7373        Define the plug-in perspective. 
    74          
     74 
    7575        Panels should inherit from DefaultPanel defined below, 
    7676        or should present the same interface. They must define 
    7777        "window_caption" and "window_name". 
    78          
     78 
    7979        :param parent: parent window 
    80          
     80 
    8181        :return: list of panels 
    8282        """ 
    83         ## Save a reference to the parent 
     83        # # Save a reference to the parent 
    8484        self.parent = parent 
    85         self.frame = MDIFrame(self.parent, None, 'None', (100, 200))      
    86         self.invariant_panel = InvariantPanel(parent=self.frame)         
     85        self.frame = MDIFrame(self.parent, None, 'None', (100, 200)) 
     86        self.invariant_panel = InvariantPanel(parent=self.frame) 
    8787        self.frame.set_panel(self.invariant_panel) 
    8888        self._frame_set_helper() 
    8989        self.invariant_panel.set_manager(manager=self) 
    90         self.perspective.append(self.invariant_panel.window_name)   
    91         #Create reader when fitting panel are created 
    92         self.state_reader = reader(self.set_state)    
    93         #append that reader to list of available reader  
     90        self.perspective.append(self.invariant_panel.window_name) 
     91        # Create reader when fitting panel are created 
     92        self.state_reader = reader(self.set_state) 
     93        # append that reader to list of available reader 
    9494        loader = Loader() 
    9595        loader.associate_file_reader(".inv", self.state_reader) 
    96         #loader.associate_file_reader(".svs", self.state_reader) 
     96        # loader.associate_file_reader(".svs", self.state_reader) 
    9797        # Return the list of panels 
    9898        return [self.invariant_panel] 
    99    
     99 
    100100    def get_context_menu(self, plotpanel=None): 
    101101        """ 
    102102        This method is optional. 
    103      
    104         When the context menu of a plot is rendered, the  
    105         get_context_menu method will be called to give you a  
     103 
     104        When the context menu of a plot is rendered, the 
     105        get_context_menu method will be called to give you a 
    106106        chance to add a menu item to the context menu. 
    107          
     107 
    108108        A ref to a Graph object is passed so that you can 
    109109        investigate the plot content and decide whether you 
    110         need to add items to the context menu.   
    111          
     110        need to add items to the context menu. 
     111 
    112112        This method returns a list of menu items. 
    113         Each item is itself a list defining the text to  
     113        Each item is itself a list defining the text to 
    114114        appear in the menu, a tool-tip help text, and a 
    115115        call-back method. 
    116          
     116 
    117117        :param graph: the Graph object to which we attach the context menu 
    118          
     118 
    119119        :return: a list of menu items with call-back function 
    120120        """ 
     
    123123        invariant_hint = "Will displays the invariant panel for" 
    124124        invariant_hint += " further computation" 
    125          
     125 
    126126        if graph.selected_plottable not in plotpanel.plots: 
    127127            return [] 
    128128        data = plotpanel.plots[graph.selected_plottable] 
    129          
     129 
    130130        if issubclass(data.__class__, Data1D): 
    131            if data.name != "$I_{obs}(q)$" and  data.name != " $P_{fit}(r)$": 
    132                return [[invariant_option, invariant_hint,  
    133                                         self._compute_invariant]] 
     131            if data.name != "$I_{obs}(q)$" and  data.name != " $P_{fit}(r)$": 
     132                return [[invariant_option, invariant_hint, self._compute_invariant]] 
    134133        return [] 
    135134 
    136     def _compute_invariant(self, event):     
     135    def _compute_invariant(self, event): 
    137136        """ 
    138137        Open the invariant panel to invariant computation 
     
    147146            name = data.__class__.__name__ 
    148147            msg = "Invariant use only Data1D got: [%s] " % str(name) 
    149             raise ValueError, msg  
     148            raise ValueError, msg 
    150149        self.compute_helper(data=data) 
    151                  
     150 
    152151    def set_data(self, data_list=None): 
    153152        """ 
     
    172171                        else: 
    173172                            error_msg += " %s  type %s \n" % (str(data.name), 
    174                                              str(data.__class__.__name__)) 
     173                                                              str(data.__class__.__name__)) 
    175174                            data_2d_list.append(data) 
    176175                if len(data_2d_list) > 0: 
     
    178177                    msg += error_msg 
    179178                if len(data_1d_list) == 0: 
    180                     wx.PostEvent(self.parent,  
    181                     StatusEvent(status=msg, info='error')) 
     179                    wx.PostEvent(self.parent, StatusEvent(status=msg, info='error')) 
    182180                    return 
    183181                msg += "Invariant panel does not allow multiple data!\n" 
     
    194192            if data is None: 
    195193                msg += "invariant receives no data. \n" 
    196                 wx.PostEvent(self.parent,  
    197                      StatusEvent(status=msg, info='error')) 
     194                wx.PostEvent(self.parent, StatusEvent(status=msg, info='error')) 
    198195                return 
    199196            if not issubclass(data.__class__, Data1D): 
    200                  msg += "invariant cannot be computed for data of " 
    201                  msg += "type %s\n" % (data.__class__.__name__) 
    202                  wx.PostEvent(self.parent,  
    203                      StatusEvent(status=msg, info='error')) 
    204                  return 
     197                msg += "invariant cannot be computed for data of " 
     198                msg += "type %s\n" % (data.__class__.__name__) 
     199                wx.PostEvent(self.parent, StatusEvent(status=msg, info='error')) 
     200                return 
    205201            else: 
    206                 wx.PostEvent(self.parent, NewPlotEvent(plot=data, 
    207                                            title=data.title)) 
     202                wx.PostEvent(self.parent, NewPlotEvent(plot=data, title=data.title)) 
    208203                try: 
    209204                    self.compute_helper(data) 
    210205                except: 
    211206                    msg = "Invariant Set_data: " + str(sys.exc_value) 
    212                     wx.PostEvent(self.parent, StatusEvent(status=msg, 
    213                                                                 info="error")) 
    214         else:     
     207                    wx.PostEvent(self.parent, StatusEvent(status=msg, info="error")) 
     208        else: 
    215209            msg = "invariant cannot be computed for data of " 
    216210            msg += "type %s" % (data.__class__.__name__) 
    217             wx.PostEvent(self.parent,  
    218                      StatusEvent(status=msg, info='error')) 
     211            wx.PostEvent(self.parent, StatusEvent(status=msg, info='error')) 
     212 
    219213    def delete_data(self, data_id): 
    220214        """ 
     
    225219            if id == self.__data.id: 
    226220                self.clear_panel() 
    227                  
     221 
    228222    def clear_panel(self): 
    229223        """ 
    230224        """ 
    231225        self.invariant_panel.clear_panel() 
    232          
     226 
    233227    def compute_helper(self, data): 
    234228        """ 
    235229        """ 
    236230        if data is None: 
    237             return  
     231            return 
    238232        # set current data if not it's a state data 
    239233        if not self.invariant_panel.is_state_data: 
     
    242236            # Set the data set to be user for invariant calculation 
    243237            self.invariant_panel.set_data(data=data) 
    244             
     238 
    245239    def save_file(self, filepath, state=None): 
    246240        """ 
    247241        Save data in provided state object. 
    248                  
     242 
    249243        :param filepath: path of file to write to 
    250         :param state: invariant state  
    251         """      
     244        :param state: invariant state 
     245        """ 
    252246        # Write the state to file 
    253247        # First, check that the data is of the right type 
     
    258252        else: 
    259253            msg = "invariant.save_file: the data being saved is" 
    260             msg += " not a sas.dataloader.data_info.Data1D object"  
     254            msg += " not a sas.dataloader.data_info.Data1D object" 
    261255            raise RuntimeError, msg 
    262256 
    263     def set_state(self, state=None, datainfo=None):     
     257    def set_state(self, state=None, datainfo=None): 
    264258        """ 
    265259        Call-back method for the state reader. 
    266260        This method is called when a .inv/.svs file is loaded. 
    267          
     261 
    268262        :param state: State object 
    269263        """ 
     
    279273                raise RuntimeError, msg 
    280274            # Make sure the user sees the invariant panel after loading 
    281             #self.parent.set_perspective(self.perspective) 
     275            # self.parent.set_perspective(self.perspective) 
    282276            self.on_perspective(event=None) 
    283277            name = data.meta_data['invstate'].file 
     
    286280            data.filename = name 
    287281 
    288             data = self.parent.create_gui_data(data,None) 
     282            data = self.parent.create_gui_data(data, None) 
    289283            self.__data = data 
    290284            wx.PostEvent(self.parent, NewPlotEvent(plot=self.__data, 
    291                                         reset=True, title=self.__data.title)) 
     285                                                   reset=True, title=self.__data.title)) 
    292286            data_dict = {self.__data.id:self.__data} 
    293287            self.parent.add_data(data_list=data_dict) 
    294288            # set state 
    295289            self.invariant_panel.is_state_data = True 
    296              
     290 
    297291            # Load the invariant states 
    298292            self.temp_state = state 
     
    300294            self.on_set_state_helper(None) 
    301295 
    302         except:  
     296        except: 
    303297            logging.error("invariant.set_state: %s" % sys.exc_value) 
    304              
     298 
    305299    def on_set_state_helper(self, event=None): 
    306300        """ 
    307301        Set the state when called by EVT_STATE_UPDATE event from guiframe 
    308         after a .inv/.svs file is loaded  
     302        after a .inv/.svs file is loaded 
    309303        """ 
    310304        self.invariant_panel.set_state(state=self.temp_state, 
    311305                                       data=self.__data) 
    312306        self.temp_state = None 
    313          
    314          
     307 
     308 
    315309    def plot_theory(self, data=None, name=None): 
    316310        """ 
    317311        Receive a data set and post a NewPlotEvent to parent. 
    318          
     312 
    319313        :param data: extrapolated data to be plotted 
    320314        :param name: Data's name to use for the legend 
    321315        """ 
    322         #import copy 
     316        # import copy 
    323317        if data is None: 
    324318            id = str(self.__data.id) + name 
    325319            group_id = self.__data.group_id 
    326             wx.PostEvent(self.parent, NewPlotEvent(id=id, 
    327                                                group_id=group_id, 
    328                                                action='Remove')) 
    329             return 
    330      
     320            wx.PostEvent(self.parent, NewPlotEvent(id=id, group_id=group_id, action='Remove')) 
     321            return 
     322 
    331323        new_plot = Data1D(x=[], y=[], dy=None) 
    332324        new_plot.symbol = GUIFRAME_ID.CURVE_SYMBOL_NUM 
    333325        scale = self.invariant_panel.get_scale() 
    334326        background = self.invariant_panel.get_background() 
    335          
     327 
    336328        if scale != 0: 
    337329            # Put back the sacle and bkg for plotting 
    338             data.y = (data.y + background)/scale 
     330            data.y = (data.y + background) / scale 
    339331            new_plot = Data1D(x=data.x, y=data.y, dy=None) 
    340332            new_plot.symbol = GUIFRAME_ID.CURVE_SYMBOL_NUM 
     
    342334            msg = "Scale can not be zero." 
    343335            raise ValueError, msg 
    344         if len(new_plot.x)== 0 : 
    345             return 
    346          
     336        if len(new_plot.x) == 0: 
     337            return 
     338 
    347339        new_plot.name = name 
    348340        new_plot.xaxis(self.__data._xaxis, self.__data._xunit) 
     
    357349                self.invariant_panel.state.theory_lowQ = copy.deepcopy(new_plot) 
    358350            elif name_head[0] == 'High': 
    359                 self.invariant_panel.state.theory_highQ =copy.deepcopy(new_plot) 
    360              
     351                self.invariant_panel.state.theory_highQ = copy.deepcopy(new_plot) 
     352 
    361353        self.parent.update_theory(data_id=self.__data.id, theory=new_plot) 
    362354        wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot, 
    363355                                               title=self.__data.title)) 
    364          
     356 
    365357    def plot_data(self, scale, background): 
    366358        """ 
     
    370362        new_plot.name = self.__data.name 
    371363        new_plot.group_id = self.__data.group_id 
    372         new_plot.id = self.__data.id  
     364        new_plot.id = self.__data.id 
    373365        new_plot.title = self.__data.title 
    374         
    375         # Save data in a state: but seems to never happen  
     366 
     367        # Save data in a state: but seems to never happen 
    376368        if new_plot != None: 
    377369            self.invariant_panel.state.data = copy.deepcopy(new_plot) 
    378370        wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot, 
    379371                                               title=new_plot.title)) 
    380          
     372 
  • src/sas/perspectives/invariant/invariant_details.py

    r79492222 r78a205a  
    88from invariant_widgets import OutputTextCtrl 
    99# Dimensions related to chart 
    10 RECTANGLE_WIDTH  = 400.0   
     10RECTANGLE_WIDTH = 400.0 
    1111RECTANGLE_HEIGHT = 20 
    12 #Invariant panel size  
     12# Invariant panel size 
    1313_BOX_WIDTH = 76 
    1414 
    15 #scale to use for a bar of value zero 
    16 RECTANGLE_SCALE  = 0.0001 
    17 DEFAULT_QSTAR = 1.0   
    18    
     15# scale to use for a bar of value zero 
     16RECTANGLE_SCALE = 0.0001 
     17DEFAULT_QSTAR = 1.0 
     18 
    1919if sys.platform.count("win32") > 0: 
    2020    _STATICBOX_WIDTH = 450 
     
    2727    PANEL_HEIGHT = 430 
    2828    FONT_VARIANT = 1 
    29      
    30 ERROR_COLOR = wx.Colour(255,  0, 0, 128) 
    31 EXTRAPOLATION_COLOR = wx.Colour(169,  169, 168, 128) 
    32 INVARIANT_COLOR =  wx.Colour(67,  208,  128, 128)     
    33    
    34    
     29 
     30ERROR_COLOR = wx.Colour(255, 0, 0, 128) 
     31EXTRAPOLATION_COLOR = wx.Colour(169, 169, 168, 128) 
     32INVARIANT_COLOR = wx.Colour(67, 208, 128, 128) 
     33 
     34 
    3535class InvariantContainer(wx.Object): 
    3636    """ 
    3737    This class stores some values resulting resulting from invariant 
    38     calculations. Given the value of total invariant, this class can also  
     38    calculations. Given the value of total invariant, this class can also 
    3939    determine the percentage of invariants resulting from extrapolation. 
    4040    """ 
    4141    def __init__(self): 
    42         #invariant at low range 
     42        # invariant at low range 
    4343        self.qstar_low = None 
    44         #invariant at low range error 
     44        # invariant at low range error 
    4545        self.qstar_low_err = None 
    46         #invariant  
     46        # invariant 
    4747        self.qstar = None 
    48         #invariant error 
     48        # invariant error 
    4949        self.qstar_err = None 
    50         #invariant at high range 
     50        # invariant at high range 
    5151        self.qstar_high = None 
    52         #invariant at high range error 
     52        # invariant at high range error 
    5353        self.qstar_high_err = None 
    54         #invariant total 
     54        # invariant total 
    5555        self.qstar_total = None 
    56         #invariant error 
     56        # invariant error 
    5757        self.qstar_total_err = None 
    58         #scale 
     58        # scale 
    5959        self.qstar_low_percent = None 
    6060        self.qstar_high_percent = None 
     
    6363        self.existing_warning = False 
    6464        self.warning_msg = "No Details on calculations available...\n" 
    65          
     65 
    6666    def compute_percentage(self): 
    6767        """ 
     
    7373            self.qstar_high = None 
    7474            self.check_values() 
    75             return  
    76          
    77         #compute invariant percentage 
     75            return 
     76 
     77        # compute invariant percentage 
    7878        if self.qstar is None: 
    7979            self.qstar_percent = None 
    8080        else: 
    8181            try: 
    82                 self.qstar_percent = float(self.qstar)/float(self.qstar_total) 
     82                self.qstar_percent = float(self.qstar) / float(self.qstar_total) 
    8383            except: 
    8484                self.qstar_percent = 'error' 
    85         #compute low q invariant percentage 
     85        # compute low q invariant percentage 
    8686        if self.qstar_low is None: 
    8787            self.qstar_low_percent = None 
     
    8989            try: 
    9090                self.qstar_low_percent = float(self.qstar_low)\ 
    91                                             /float(self.qstar_total) 
     91                                            / float(self.qstar_total) 
    9292            except: 
    9393                self.qstar_low_percent = 'error' 
    94         #compute high q invariant percentage 
     94        # compute high q invariant percentage 
    9595        if self.qstar_high is None: 
    9696            self.qstar_high_percent = None 
     
    9898            try: 
    9999                self.qstar_high_percent = float(self.qstar_high)\ 
    100                                                 /float(self.qstar_total) 
     100                                                / float(self.qstar_total) 
    101101            except: 
    102102                self.qstar_high_percent = 'error' 
    103103        wx.CallAfter(self.check_values) 
    104     
     104 
    105105    def check_values(self): 
    106106        """ 
     
    109109        if self.qstar_total is None and self.qstar is None: 
    110110            self.warning_msg = "Invariant not calculated.\n" 
    111             return  
     111            return 
    112112        if self.qstar_total == 0: 
    113113            self.existing_warning = True 
     
    115115            self.warning_msg += "The calculations are likely " 
    116116            self.warning_msg += "to be unreliable!\n" 
    117             return  
    118         #warning to the user when the extrapolated invariant is greater than %5 
     117            return 
     118        # warning to the user when the extrapolated invariant is greater than %5 
    119119        msg = '' 
    120120        if self.qstar_percent == 'error': 
     
    135135                msg += "Error occurred when computing extrapolated invariant" 
    136136                msg += " at low-Q region.\n" 
    137         elif self.qstar_low_percent is not None : 
     137        elif self.qstar_low_percent is not None: 
    138138            if self.qstar_low_percent >= 0.05: 
    139139                self.existing_warning = True 
     
    172172            msg += "The sum of all extrapolated contributions is higher " 
    173173            msg += "than 5% of the invariant.\n" 
    174              
     174 
    175175        if self.existing_warning: 
    176176            self.warning_msg = '' 
    177             self.warning_msg += msg  
     177            self.warning_msg += msg 
    178178            self.warning_msg += "The calculations are likely to be" 
    179179            self.warning_msg += " unreliable!\n" 
    180180        else: 
    181181            self.warning_msg = "No Details on calculations available...\n" 
    182              
     182 
    183183class InvariantDetailsPanel(wx.Dialog): 
    184184    """ 
    185     This panel describes proportion of invariants  
     185    This panel describes proportion of invariants 
    186186    """ 
    187     def __init__(self, parent=None, id=-1, qstar_container=None,  
    188                                     title="Invariant Details", 
    189                                     size=(PANEL_WIDTH, PANEL_HEIGHT)): 
     187    def __init__(self, parent=None, id=-1, qstar_container=None, 
     188                 title="Invariant Details", 
     189                 size=(PANEL_WIDTH, PANEL_HEIGHT)): 
    190190        wx.Dialog.__init__(self, parent=parent, id=id, title=title, size=size) 
    191          
    192         #Font size  
     191 
     192        # Font size 
    193193        self.SetWindowVariant(variant=FONT_VARIANT) 
    194194        self.parent = parent 
    195         #self.qstar_container 
     195        # self.qstar_container 
    196196        self.qstar_container = qstar_container 
    197         #warning message 
     197        # warning message 
    198198        self.warning_msg = self.qstar_container.warning_msg 
    199     
    200         #Define scale of each bar 
     199 
     200        # Define scale of each bar 
    201201        self.low_inv_percent = self.qstar_container.qstar_low_percent 
    202202        self.low_scale = self.get_scale(percentage=self.low_inv_percent, 
    203                                          scale_name="Extrapolated at Low Q") 
     203                                        scale_name="Extrapolated at Low Q") 
    204204        self.inv_percent = self.qstar_container.qstar_percent 
    205         self.inv_scale = self.get_scale(percentage=self.inv_percent,  
    206                                             scale_name="Inv in Q range") 
     205        self.inv_scale = self.get_scale(percentage=self.inv_percent, 
     206                                        scale_name="Inv in Q range") 
    207207        self.high_inv_percent = self.qstar_container.qstar_high_percent 
    208208        self.high_scale = self.get_scale(percentage=self.high_inv_percent, 
    209209                                         scale_name="Extrapolated at High Q") 
    210         
    211         #Default color the extrapolation bar is grey 
     210 
     211        # Default color the extrapolation bar is grey 
    212212        self.extrapolation_color_low = EXTRAPOLATION_COLOR 
    213213        self.extrapolation_color_high = EXTRAPOLATION_COLOR 
    214214        self.invariant_color = INVARIANT_COLOR 
    215         #change color of high and low bar when necessary 
     215        # change color of high and low bar when necessary 
    216216        self.set_color_bar() 
    217         #draw the panel itself 
     217        # draw the panel itself 
    218218        self._do_layout() 
    219219        self.set_values() 
    220    
     220 
    221221    def _define_structure(self): 
    222222        """ 
    223223        Define main sizers needed for this panel 
    224224        """ 
    225         #Box sizers must be defined first before defining buttons/textctrls 
     225        # Box sizers must be defined first before defining buttons/textctrls 
    226226        # (MAC). 
    227227        self.main_sizer = wx.BoxSizer(wx.VERTICAL) 
    228         #Sizer related to chart 
     228        # Sizer related to chart 
    229229        chart_box = wx.StaticBox(self, -1, "Invariant Chart") 
    230230        self.chart_sizer = wx.StaticBoxSizer(chart_box, wx.VERTICAL) 
    231231        self.chart_sizer.SetMinSize((PANEL_WIDTH - 50, 110)) 
    232         #Sizer related to invariant values 
    233         self.invariant_sizer =  wx.GridBagSizer(4, 4) 
     232        # Sizer related to invariant values 
     233        self.invariant_sizer = wx.GridBagSizer(4, 4) 
    234234        invariant_box = wx.StaticBox(self, -1, "Numerical Values") 
    235         self.invariant_box_sizer = wx.StaticBoxSizer(invariant_box, 
    236                                                       wx.HORIZONTAL) 
     235        self.invariant_box_sizer = wx.StaticBoxSizer(invariant_box, wx.HORIZONTAL) 
    237236 
    238237        self.invariant_box_sizer.SetMinSize((PANEL_WIDTH - 50, -1)) 
    239         #Sizer related to warning message 
     238        # Sizer related to warning message 
    240239        warning_box = wx.StaticBox(self, -1, "Warning") 
    241240        self.warning_sizer = wx.StaticBoxSizer(warning_box, wx.VERTICAL) 
    242         self.warning_sizer.SetMinSize((PANEL_WIDTH-50, -1)) 
    243         #Sizer related to button 
     241        self.warning_sizer.SetMinSize((PANEL_WIDTH - 50, -1)) 
     242        # Sizer related to button 
    244243        self.button_sizer = wx.BoxSizer(wx.HORIZONTAL) 
    245        
     244 
    246245    def _layout_shart(self): 
    247246        """ 
     
    250249        self.panel_chart = wx.Panel(self) 
    251250        self.panel_chart.Bind(wx.EVT_PAINT, self.on_paint) 
    252         self.chart_sizer.Add(self.panel_chart, 1, wx.EXPAND|wx.ALL, 0) 
    253          
     251        self.chart_sizer.Add(self.panel_chart, 1, wx.EXPAND | wx.ALL, 0) 
     252 
    254253    def _layout_invariant(self): 
    255254        """ 
    256255        Draw widgets related to invariant 
    257256        """ 
    258         uncertainty = "+/-"  
     257        uncertainty = "+/-" 
    259258        unit_invariant = '[1/(cm * A^3)]' 
    260       
     259 
    261260        invariant_txt = wx.StaticText(self, -1, 'Q* from Data ') 
    262261        invariant_txt.SetToolTipString("Invariant in the data set's Q range.") 
     
    270269        hint_msg = "Unit of the invariant from data's Q range" 
    271270        invariant_units_txt.SetToolTipString(hint_msg) 
    272         
     271 
    273272        invariant_low_txt = wx.StaticText(self, -1, 'Q* from Low-Q') 
    274273        hint_msg = "Extrapolated invariant from low-Q range." 
     
    284283        hint_msg = "Unit of the extrapolated invariant from  low-Q range" 
    285284        invariant_low_units_txt.SetToolTipString(hint_msg) 
    286          
     285 
    287286        invariant_high_txt = wx.StaticText(self, -1, 'Q* from High-Q') 
    288287        hint_msg = "Extrapolated invariant from  high-Q range" 
     
    299298        hint_msg = "Unit of the extrapolated invariant from  high-Q range" 
    300299        invariant_high_units_txt.SetToolTipString(hint_msg) 
    301     
    302         #Invariant low 
     300 
     301        # Invariant low 
    303302        iy = 0 
    304         ix = 0  
     303        ix = 0 
    305304        self.invariant_sizer.Add(invariant_low_txt, (iy, ix), (1, 1), 
    306                              wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 
     305                                 wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15) 
    307306        ix += 1 
    308307        self.invariant_sizer.Add(self.invariant_low_tcl, (iy, ix), (1, 1), 
    309                             wx.EXPAND|wx.ADJUST_MINSIZE, 0)  
    310         ix += 1 
    311         self.invariant_sizer.Add( wx.StaticText(self, -1, uncertainty), 
    312                          (iy, ix), (1, 1),wx.EXPAND|wx.ADJUST_MINSIZE, 0)  
     308                                 wx.EXPAND | wx.ADJUST_MINSIZE, 0) 
     309        ix += 1 
     310        self.invariant_sizer.Add(wx.StaticText(self, -1, uncertainty), 
     311                                 (iy, ix), (1, 1), wx.EXPAND | wx.ADJUST_MINSIZE, 0) 
    313312        ix += 1 
    314313        self.invariant_sizer.Add(self.invariant_low_err_tcl, (iy, ix), (1, 1), 
    315                             wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
    316         ix += 1 
    317         self.invariant_sizer.Add(invariant_low_units_txt 
    318                          ,(iy, ix), (1, 1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)   
    319         #Invariant  
     314                                 wx.EXPAND | wx.ADJUST_MINSIZE, 0) 
     315        ix += 1 
     316        self.invariant_sizer.Add(invariant_low_units_txt, 
     317                                 (iy, ix), (1, 1), wx.EXPAND | wx.ADJUST_MINSIZE, 0) 
     318        # Invariant 
    320319        iy += 1 
    321         ix = 0  
     320        ix = 0 
    322321        self.invariant_sizer.Add(invariant_txt, (iy, ix), (1, 1), 
    323                              wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 
     322                                 wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15) 
    324323        ix += 1 
    325324        self.invariant_sizer.Add(self.invariant_tcl, (iy, ix), (1, 1), 
    326                             wx.EXPAND|wx.ADJUST_MINSIZE, 0)  
     325                                 wx.EXPAND | wx.ADJUST_MINSIZE, 0) 
    327326        ix += 1 
    328327        self.invariant_sizer.Add(wx.StaticText(self, -1, uncertainty), 
    329                          (iy, ix), (1, 1),wx.EXPAND|wx.ADJUST_MINSIZE, 0)  
     328                                 (iy, ix), (1, 1), wx.EXPAND | wx.ADJUST_MINSIZE, 0) 
    330329        ix += 1 
    331330        self.invariant_sizer.Add(self.invariant_err_tcl, (iy, ix), (1, 1), 
    332                             wx.EXPAND|wx.ADJUST_MINSIZE, 0)  
    333         ix +=1 
    334         self.invariant_sizer.Add(invariant_units_txt 
    335                          ,(iy, ix), (1, 1),wx.EXPAND|wx.ADJUST_MINSIZE, 0)   
    336         #Invariant high 
     331                                 wx.EXPAND | wx.ADJUST_MINSIZE, 0) 
     332        ix += 1 
     333        self.invariant_sizer.Add(invariant_units_txt, 
     334                                 (iy, ix), (1, 1), wx.EXPAND | wx.ADJUST_MINSIZE, 0) 
     335        # Invariant high 
    337336        iy += 1 
    338         ix = 0  
     337        ix = 0 
    339338        self.invariant_sizer.Add(invariant_high_txt, (iy, ix), (1, 1), 
    340                              wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 
     339                                 wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15) 
    341340        ix += 1 
    342341        self.invariant_sizer.Add(self.invariant_high_tcl, (iy, ix), (1, 1), 
    343                             wx.EXPAND|wx.ADJUST_MINSIZE, 0)  
     342                                 wx.EXPAND | wx.ADJUST_MINSIZE, 0) 
    344343        ix += 1 
    345344        self.invariant_sizer.Add(wx.StaticText(self, -1, uncertainty), 
    346                          (iy, ix), (1, 1),wx.EXPAND|wx.ADJUST_MINSIZE, 0)  
     345                                 (iy, ix), (1, 1), wx.EXPAND | wx.ADJUST_MINSIZE, 0) 
    347346        ix += 1 
    348347        self.invariant_sizer.Add(self.invariant_high_err_tcl, (iy, ix), (1, 1), 
    349                             wx.EXPAND|wx.ADJUST_MINSIZE, 0)  
    350         ix += 1 
    351         self.invariant_sizer.Add(invariant_high_units_txt 
    352                          ,(iy, ix), (1, 1),wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
    353         self.invariant_box_sizer.Add(self.invariant_sizer, 0, 
    354                                      wx.TOP|wx.BOTTOM, 10)   
    355         
     348                                 wx.EXPAND | wx.ADJUST_MINSIZE, 0) 
     349        ix += 1 
     350        self.invariant_sizer.Add(invariant_high_units_txt, 
     351                                 (iy, ix), (1, 1), wx.EXPAND | wx.ADJUST_MINSIZE, 0) 
     352        self.invariant_box_sizer.Add(self.invariant_sizer, 0, wx.TOP | wx.BOTTOM, 10) 
     353 
    356354    def _layout_warning(self): 
    357355        """ 
    358356        Draw widgets related to warning 
    359357        """ 
    360         #Warning [string] 
    361         self.warning_msg_txt = wx.StaticText(self, -1, self.warning_msg)   
     358        # Warning [string] 
     359        self.warning_msg_txt = wx.StaticText(self, -1, self.warning_msg) 
    362360        if self.qstar_container.existing_warning: 
    363             self.warning_msg_txt.SetForegroundColour('red')  
     361            self.warning_msg_txt.SetForegroundColour('red') 
    364362        self.warning_sizer.AddMany([(self.warning_msg_txt, 0, 
    365                                      wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 10)]) 
    366          
     363                                     wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 10)]) 
     364 
    367365    def _layout_button(self): 
    368366        """ 
    369367        Draw widgets related to button 
    370368        """ 
    371         #Close button 
     369        # Close button 
    372370        id = wx.NewId() 
    373371        button_ok = wx.Button(self, id, "Ok") 
    374372        button_ok.SetToolTipString("Give Details on Computation") 
    375373        self.Bind(wx.EVT_BUTTON, self.on_close, id=id) 
    376         self.button_sizer.AddMany([((20, 20), 0 , wx.LEFT, 350), 
    377                                    (button_ok, 0 , wx.RIGHT, 10)]) 
     374        self.button_sizer.AddMany([((20, 20), 0, wx.LEFT, 350), 
     375                                   (button_ok, 0, wx.RIGHT, 10)]) 
    378376    def _do_layout(self): 
    379377        """ 
     
    386384        self._layout_button() 
    387385        self.main_sizer.AddMany([(self.chart_sizer, 0, wx.ALL, 10), 
    388                                  ( self.invariant_box_sizer, 0, wx.ALL, 10), 
    389                                   (self.warning_sizer, 0, wx.ALL, 10), 
    390                                   (self.button_sizer, 0, wx.ALL, 10)]) 
     386                                 (self.invariant_box_sizer, 0, wx.ALL, 10), 
     387                                 (self.warning_sizer, 0, wx.ALL, 10), 
     388                                 (self.button_sizer, 0, wx.ALL, 10)]) 
    391389        self.SetSizer(self.main_sizer) 
    392         
    393          
     390 
     391 
    394392    def set_values(self): 
    395393        """ 
     
    399397        self.invariant_tcl.SetValue(value) 
    400398        value = format_number(self.qstar_container.qstar_err) 
    401         self.invariant_err_tcl.SetValue(value)  
     399        self.invariant_err_tcl.SetValue(value) 
    402400        value = format_number(self.qstar_container.qstar_low) 
    403401        self.invariant_low_tcl.SetValue(value) 
    404402        value = format_number(self.qstar_container.qstar_low_err) 
    405         self.invariant_low_err_tcl.SetValue(value)  
     403        self.invariant_low_err_tcl.SetValue(value) 
    406404        value = format_number(self.qstar_container.qstar_high) 
    407405        self.invariant_high_tcl.SetValue(value) 
    408406        value = format_number(self.qstar_container.qstar_high_err) 
    409         self.invariant_high_err_tcl.SetValue(value)  
     407        self.invariant_high_err_tcl.SetValue(value) 
    410408 
    411409    def get_scale(self, percentage, scale_name='scale'): 
    412410        """ 
    413         Check scale receive in this panel.  
     411        Check scale receive in this panel. 
    414412        """ 
    415413        scale = RECTANGLE_SCALE 
    416         try:  
     414        try: 
    417415            if percentage in [None, 0.0, "error"]: 
    418                  scale = RECTANGLE_SCALE 
    419                  return scale 
     416                scale = RECTANGLE_SCALE 
     417                return scale 
    420418            elif percentage < 0: 
    421419                scale = RECTANGLE_SCALE 
     
    427425            self.warning_msg += "check this value : %s\n" % str(percentage) 
    428426        return  scale 
    429      
     427 
    430428    def set_color_bar(self): 
    431429        """ 
     
    435433        self.extrapolation_color_high = EXTRAPOLATION_COLOR 
    436434        self.invariant_color = INVARIANT_COLOR 
    437         #warning to the user when the extrapolated invariant is greater than %5 
     435        # warning to the user when the extrapolated invariant is greater than %5 
    438436        if self.low_scale >= 0.05 or self.low_scale > 1 or self.low_scale < 0: 
    439             self.extrapolation_color_low = ERROR_COLOR  
     437            self.extrapolation_color_low = ERROR_COLOR 
    440438        if self.high_scale >= 0.05 or self.high_scale > 1 or self.high_scale < 0: 
    441             self.extrapolation_color_high = ERROR_COLOR  
     439            self.extrapolation_color_high = ERROR_COLOR 
    442440        if self.inv_scale > 1 or self.inv_scale < 0: 
    443             self.invariant_color = ERROR_COLOR   
    444      
     441            self.invariant_color = ERROR_COLOR 
     442 
    445443    def on_close(self, event): 
    446444        """ 
     
    448446        """ 
    449447        self.Close() 
    450       
     448 
    451449    def on_paint(self, event): 
    452450        """ 
     
    461459            dc.DrawText(msg, 25, 25) 
    462460            return 
    463         #Start the drawing 
     461        # Start the drawing 
    464462        font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) 
    465463        font.SetWeight(wx.BOLD) 
     
    467465        # Draw a rectangle 
    468466        path = gc.CreatePath() 
    469         path.AddRectangle(-RECTANGLE_WIDTH/2,-RECTANGLE_HEIGHT/2, 
    470                           RECTANGLE_WIDTH/2,RECTANGLE_HEIGHT/2) 
     467        path.AddRectangle(-RECTANGLE_WIDTH / 2, -RECTANGLE_HEIGHT / 2, 
     468                          RECTANGLE_WIDTH / 2, RECTANGLE_HEIGHT / 2) 
    471469        x_origine = 20 
    472470        y_origine = 15 
    473         #Draw low rectangle 
    474         gc.PushState()         
     471        # Draw low rectangle 
     472        gc.PushState() 
    475473        label = "Q* from Low-Q " 
    476474        PathFunc = gc.DrawPath 
    477475        w, h = gc.GetTextExtent(label) 
    478476        gc.DrawText(label, x_origine, y_origine) 
    479         #Translate the rectangle 
    480         x_center = x_origine + RECTANGLE_WIDTH * self.low_scale/2 + w +10 
     477        # Translate the rectangle 
     478        x_center = x_origine + RECTANGLE_WIDTH * self.low_scale / 2 + w + 10 
    481479        y_center = y_origine + h 
    482         gc.Translate(x_center, y_center)     
     480        gc.Translate(x_center, y_center) 
    483481        gc.SetPen(wx.Pen("black", 1)) 
    484482        gc.SetBrush(wx.Brush(self.extrapolation_color_low)) 
     
    488486            low_percent = 'Error' 
    489487        else: 
    490             low_percent = format_number(self.low_inv_percent*100)+ '%' 
     488            low_percent = format_number(self.low_inv_percent * 100) + '%' 
    491489        x_center = 20 
    492490        y_center = -h 
    493491        gc.DrawText(low_percent, x_center, y_center) 
    494492        # Increase width by self.low_scale 
    495         gc.Scale(self.low_scale, 1.0)  
     493        gc.Scale(self.low_scale, 1.0) 
    496494        PathFunc(path) 
    497         gc.PopState()   
    498         #Draw rectangle for invariant    
    499         gc.PushState()    # save it again 
    500         y_origine += 20          
     495        gc.PopState() 
     496        # Draw rectangle for invariant 
     497        gc.PushState()  # save it again 
     498        y_origine += 20 
    501499        gc.DrawText("Q* from Data ", x_origine, y_origine) 
    502500        # offset to the lower part of the window 
    503         x_center = x_origine + RECTANGLE_WIDTH * self.inv_scale/2 + w + 10 
     501        x_center = x_origine + RECTANGLE_WIDTH * self.inv_scale / 2 + w + 10 
    504502        y_center = y_origine + h 
    505503        gc.Translate(x_center, y_center) 
    506504        # 128 == half transparent 
    507         gc.SetBrush(wx.Brush(self.invariant_color))  
     505        gc.SetBrush(wx.Brush(self.invariant_color)) 
    508506        # Increase width by self.inv_scale 
    509507        if self.inv_percent is None: 
     
    512510            inv_percent = 'Error' 
    513511        else: 
    514             inv_percent = format_number(self.inv_percent*100)+ '%' 
    515         x_center = 20  
     512            inv_percent = format_number(self.inv_percent * 100) + '%' 
     513        x_center = 20 
    516514        y_center = -h 
    517515        gc.DrawText(inv_percent, x_center, y_center) 
    518         gc.Scale(self.inv_scale, 1.0)     
     516        gc.Scale(self.inv_scale, 1.0) 
    519517        gc.DrawPath(path) 
    520518        gc.PopState() 
    521519        # restore saved state 
    522         #Draw rectangle for high invariant 
    523         gc.PushState()  
    524         y_origine += 20  
    525         gc.DrawText("Q* from High-Q ", x_origine, y_origine)  
    526         #define the position of the new rectangle 
    527         x_center = x_origine + RECTANGLE_WIDTH * self.high_scale/2 + w + 10 
     520        # Draw rectangle for high invariant 
     521        gc.PushState() 
     522        y_origine += 20 
     523        gc.DrawText("Q* from High-Q ", x_origine, y_origine) 
     524        # define the position of the new rectangle 
     525        x_center = x_origine + RECTANGLE_WIDTH * self.high_scale / 2 + w + 10 
    528526        y_center = y_origine + h 
    529527        gc.Translate(x_center, y_center) 
    530         gc.SetBrush(wx.Brush(self.extrapolation_color_high))  
     528        gc.SetBrush(wx.Brush(self.extrapolation_color_high)) 
    531529        # increase scale by self.high_scale 
    532530        if self.high_inv_percent is None: 
     
    535533            high_percent = 'Error' 
    536534        else: 
    537             high_percent = format_number(self.high_inv_percent*100)+ '%' 
     535            high_percent = format_number(self.high_inv_percent * 100) + '%' 
    538536        x_center = 20 
    539537        y_center = -h 
    540538        gc.DrawText(high_percent, x_center, y_center) 
    541         
    542         gc.Scale(self.high_scale, 1.0)   
     539 
     540        gc.Scale(self.high_scale, 1.0) 
    543541        gc.DrawPath(path) 
    544542        gc.PopState() 
  • src/sas/perspectives/invariant/invariant_state.py

    rb9a5f0e r78a205a  
    11""" 
     2    State class for the invariant UI 
    23""" 
    34 
    4 #import time 
     5# import time 
    56import os 
    67import sys 
     
    89import copy 
    910import sas.dataloader 
    10 #from xml.dom.minidom import parse 
     11# from xml.dom.minidom import parse 
    1112from lxml import etree 
    1213from sas.dataloader.readers.cansas_reader import Reader as CansasReader 
     
    2021 
    2122# default state 
    22 list = {'file': 'None', 
    23         'compute_num':0, 
    24         'state_num':0, 
    25         'is_time_machine':False, 
    26         'background_tcl':0.0, 
    27         'scale_tcl':1.0, 
    28         'contrast_tcl':1.0, 
    29         'porod_constant_tcl':'', 
    30         'npts_low_tcl':10, 
    31         'npts_high_tcl':10, 
    32         'power_high_tcl':4.0, 
    33         'power_low_tcl': 4.0, 
    34         'enable_high_cbox':False, 
    35         'enable_low_cbox':False, 
    36         'guinier': True, 
    37         'power_law_high': False, 
    38         'power_law_low': False, 
    39         'fit_enable_high': False, 
    40         'fit_enable_low': False, 
    41         'fix_enable_high':True, 
    42         'fix_enable_low':True, 
    43         'volume_tcl':'', 
    44         'volume_err_tcl':'', 
    45         'surface_tcl':'', 
    46         'surface_err_tcl':''} 
    47 # list of states: This list will be filled as panel  
     23DEFAULT_STATE = {'file': 'None', 
     24                 'compute_num':0, 
     25                 'state_num':0, 
     26                 'is_time_machine':False, 
     27                 'background_tcl':0.0, 
     28                 'scale_tcl':1.0, 
     29                 'contrast_tcl':1.0, 
     30                 'porod_constant_tcl':'', 
     31                 'npts_low_tcl':10, 
     32                 'npts_high_tcl':10, 
     33                 'power_high_tcl':4.0, 
     34                 'power_low_tcl': 4.0, 
     35                 'enable_high_cbox':False, 
     36                 'enable_low_cbox':False, 
     37                 'guinier': True, 
     38                 'power_law_high': False, 
     39                 'power_law_low': False, 
     40                 'fit_enable_high': False, 
     41                 'fit_enable_low': False, 
     42                 'fix_enable_high':True, 
     43                 'fix_enable_low':True, 
     44                 'volume_tcl':'', 
     45                 'volume_err_tcl':'', 
     46                 'surface_tcl':'', 
     47                 'surface_err_tcl':''} 
     48# list of states: This list will be filled as panel 
    4849# init and the number of states increases 
    4950state_list = {} 
    5051bookmark_list = {} 
    51 # list of input parameters (will be filled up on panel init) used by __str__  
     52# list of input parameters (will be filled up on panel init) used by __str__ 
    5253input_list = {'background_tcl':0, 
    53         'scale_tcl':0, 
    54         'contrast_tcl':0, 
    55         'porod_constant_tcl':'', 
    56         'npts_low_tcl':0, 
    57         'npts_high_tcl':0, 
    58         'power_high_tcl':0, 
    59         'power_low_tcl': 0}   
    60 # list of output parameters (order sensitive) used by __str__     
    61 output_list = [["qstar_low",      "Q* from low Q extrapolation [1/(cm*A)]"], 
    62                ["qstar_low_err",             "dQ* from low Q extrapolation"], 
    63                ["qstar_low_percent",  "Q* percent from low Q extrapolation"], 
    64                ["qstar",              "Q* from data [1/(cm*A)]"], 
    65                ["qstar_err",                                "dQ* from data"], 
    66                ["qstar_percent",                     "Q* percent from data"], 
    67                ["qstar_high",    "Q* from high Q extrapolation [1/(cm*A)]"], 
    68                ["qstar_high_err",           "dQ* from high Q extrapolation"], 
     54              'scale_tcl':0, 
     55              'contrast_tcl':0, 
     56              'porod_constant_tcl':'', 
     57              'npts_low_tcl':0, 
     58              'npts_high_tcl':0, 
     59              'power_high_tcl':0, 
     60              'power_low_tcl': 0} 
     61# list of output parameters (order sensitive) used by __str__ 
     62output_list = [["qstar_low", "Q* from low Q extrapolation [1/(cm*A)]"], 
     63               ["qstar_low_err", "dQ* from low Q extrapolation"], 
     64               ["qstar_low_percent", "Q* percent from low Q extrapolation"], 
     65               ["qstar", "Q* from data [1/(cm*A)]"], 
     66               ["qstar_err", "dQ* from data"], 
     67               ["qstar_percent", "Q* percent from data"], 
     68               ["qstar_high", "Q* from high Q extrapolation [1/(cm*A)]"], 
     69               ["qstar_high_err", "dQ* from high Q extrapolation"], 
    6970               ["qstar_high_percent", "Q* percent from low Q extrapolation"], 
    70                ["qstar_total",         "total Q* [1/(cm*A)]"], 
    71                ["qstar_total_err",                              "total dQ*"], 
    72                ["volume",                                 "volume fraction"], 
    73                ["volume_err",                       "volume fraction error"], 
    74                ["surface",                               "specific surface"], 
    75                ["surface_err",                     "specific surface error"]] 
    76  
    77     
     71               ["qstar_total", "total Q* [1/(cm*A)]"], 
     72               ["qstar_total_err", "total dQ*"], 
     73               ["volume", "volume fraction"], 
     74               ["volume_err", "volume fraction error"], 
     75               ["surface", "specific surface"], 
     76               ["surface_err", "specific surface error"]] 
     77 
     78 
    7879 
    7980class InvariantState(object): 
     
    8586        Default values 
    8687        """ 
    87         # Input  
    88         self.file  = None 
     88        # Input 
     89        self.file = None 
    8990        self.data = Data1D(x=[], y=[], dx=None, dy=None) 
    90         self.theory_lowQ =  Data1D(x=[], y=[], dy=None) 
     91        self.theory_lowQ = Data1D(x=[], y=[], dy=None) 
    9192        self.theory_lowQ.symbol = GUIFRAME_ID.CURVE_SYMBOL_NUM 
    9293        self.theory_highQ = Data1D(x=[], y=[], dy=None) 
    9394        self.theory_highQ.symbol = GUIFRAME_ID.CURVE_SYMBOL_NUM 
    94         #self.is_time_machine = False 
    95         self.saved_state = list 
     95        # self.is_time_machine = False 
     96        self.saved_state = DEFAULT_STATE 
    9697        self.state_list = state_list 
    9798        self.bookmark_list = bookmark_list 
    9899        self.input_list = input_list 
    99100        self.output_list = output_list 
    100          
     101 
    101102        self.compute_num = 0 
    102103        self.state_num = 0 
    103104        self.timestamp = ('00:00:00', '00/00/0000') 
    104105        self.container = None 
    105         #plot image 
     106        # plot image 
    106107        self.wximbmp = None 
    107108        # report_html strings 
    108109        import sas.perspectives.invariant as invariant 
    109110        path = invariant.get_data_path(media='media') 
    110         path_report_html = os.path.join(path,"report_template.html") 
    111         html_template = open(path_report_html,"r") 
     111        path_report_html = os.path.join(path, "report_template.html") 
     112        html_template = open(path_report_html, "r") 
    112113        self.template_str = html_template.read() 
    113114        self.report_str = self.template_str 
    114         #self.report_str_save = None 
     115        # self.report_str_save = None 
    115116        html_template.close() 
    116          
     117 
    117118    def __str__(self): 
    118119        """ 
    119120        Pretty print 
    120              
     121 
    121122        : return: string representing the state 
    122123        """ 
     
    132133        state += "State No.: %d \n" % state_num 
    133134        state += "\n=== Inputs ===\n" 
    134          
     135 
    135136        # text ctl general inputs ( excluding extrapolation text ctl) 
    136         for key, value in self.input_list.iteritems():  
     137        for key, value in self.input_list.iteritems(): 
    137138            if value == '': 
    138139                continue 
    139             key_split = key.split('_')  
    140             max_ind = len(key_split)-1 
    141             if key_split[max_ind] == 'tcl':  
     140            key_split = key.split('_') 
     141            max_ind = len(key_split) - 1 
     142            if key_split[max_ind] == 'tcl': 
    142143                name = "" 
    143144                if key_split[1] == 'low' or key_split[1] == 'high': 
     
    146147                    name += " %s" % key_split[ind] 
    147148                state += "%s:   %s\n" % (name.lstrip(" "), value) 
    148                  
    149         # other input parameters        
     149 
     150        # other input parameters 
    150151        extra_lo = compute_state['enable_low_cbox'] 
    151152        if compute_state['enable_low_cbox']: 
     
    157158        if compute_state['enable_high_cbox']: 
    158159            extra_hi = 'Power law' 
    159         state += "\nExtrapolation:  High=%s; Low=%s\n" %(extra_hi, extra_lo)    
     160        state += "\nExtrapolation:  High=%s; Low=%s\n" % (extra_hi, extra_lo) 
    160161        low_off = False 
    161162        high_off = False 
    162         for key, value in self.input_list.iteritems():  
    163             key_split = key.split('_')  
    164             max_ind = len(key_split) - 1    
    165             if key_split[max_ind] == 'tcl':  
    166                 name = ""  
     163        for key, value in self.input_list.iteritems(): 
     164            key_split = key.split('_') 
     165            max_ind = len(key_split) - 1 
     166            if key_split[max_ind] == 'tcl': 
     167                name = "" 
    167168                # check each buttons whether or not ON or OFF 
    168169                if key_split[1] == 'low' or key_split[1] == 'high': 
    169170                    if not compute_state['enable_low_cbox'] and \ 
    170                         key_split[max_ind-1] == 'low': 
     171                        key_split[max_ind - 1] == 'low': 
    171172                        low_off = True 
    172                         continue               
     173                        continue 
    173174                    elif not compute_state['enable_high_cbox'] and \ 
    174                         key_split[max_ind-1] == 'high': 
     175                        key_split[max_ind - 1] == 'high': 
    175176                        high_off = True 
    176177                        continue 
    177178                    elif extra_lo == 'Guinier' and key_split[0] == 'power' and \ 
    178                         key_split[max_ind-1] == 'low': 
     179                        key_split[max_ind - 1] == 'low': 
    179180                        continue 
    180181                    for ind in range(0, max_ind): 
    181182                        name += " %s" % key_split[ind] 
    182183                    name = name.lstrip(" ") 
    183                     if name == "power low" : 
     184                    if name == "power low": 
    184185                        if compute_state['fix_enable_low']: 
    185186                            name += ' (Fixed)' 
    186187                        else: 
    187188                            name += ' (Fitted)' 
    188                     if name == "power high" : 
     189                    if name == "power high": 
    189190                        if compute_state['fix_enable_high']: 
    190191                            name += ' (Fixed)' 
     
    195196        state += "\n=== Outputs ===" 
    196197        for item in output_list: 
    197             item_split = item[0].split('_')  
     198            item_split = item[0].split('_') 
    198199            # Exclude the extrapolation that turned off 
    199200            if len(item_split) > 1: 
     
    204205            max_ind = len(item_split) - 1 
    205206            value = None 
    206             try: 
     207            if hasattr(self.container, item[0]): 
    207208                # Q* outputs 
    208                 exec "value = self.container.%s\n" % item[0] 
    209             except: 
     209                value = getattr(self.container, item[0]) 
     210            else: 
    210211                # other outputs than Q* 
    211212                name = item[0] + "_tcl" 
    212213                if name in self.saved_state.keys(): 
    213                     exec "value = self.saved_state['%s']" % name 
    214                  
    215             # Exclude the outputs w/''     
     214                    value = self.saved_state[name] 
     215 
     216            # Exclude the outputs w/'' 
    216217            if value == '': 
    217                 continue     
     218                continue 
    218219            # Error outputs 
    219220            if item_split[max_ind] == 'err': 
     
    221222            # Percentage outputs 
    222223            elif item_split[max_ind] == 'percent': 
    223                 try: 
    224                     value = float(value) * 100 
    225                 except: 
    226                     pass 
     224                value = float(value) * 100 
    227225                state += "(%s %s)" % (format_number(value), '%') 
    228226            # Outputs 
    229227            else: 
    230                 state += "\n%s:   %s " % (item[1],  
    231                                         format_number(value, high=True)) 
     228                state += "\n%s:   %s " % (item[1], 
     229                                          format_number(value, high=True)) 
    232230        # Include warning msg 
    233231        if self.container is not None: 
     
    244242        """ 
    245243        Writes the state of the InversionControl panel to file, as XML. 
    246          
     244 
    247245        Compatible with standalone writing, or appending to an 
    248246        already existing XML document. In that case, the XML document 
    249         is required. An optional entry node in the XML document  
     247        is required. An optional entry node in the XML document 
    250248        may also be given. 
    251          
     249 
    252250        : param file: file to write to 
    253251        : param doc: XML document object [optional] 
    254         : param entry_node: XML node within the XML document at which we will append the data [optional] 
     252        : param entry_node: XML node within the document at which we will append the data [optional] 
    255253        """ 
    256254        # TODO: Get this to work 
     
    261259        if doc is None: 
    262260            impl = getDOMImplementation() 
    263          
    264             doc_type = impl.createDocumentType(INVNODE_NAME, "1.0", "1.0")      
    265          
     261 
     262            doc_type = impl.createDocumentType(INVNODE_NAME, "1.0", "1.0") 
     263 
    266264            newdoc = impl.createDocument(None, INVNODE_NAME, doc_type) 
    267265            top_element = newdoc.documentElement 
     
    274272            else: 
    275273                entry_node.appendChild(top_element) 
    276                  
     274 
    277275        attr = newdoc.createAttribute("version") 
    278276        attr.nodeValue = '1.0' 
    279277        top_element.setAttributeNode(attr) 
    280          
     278 
    281279        # File name 
    282280        element = newdoc.createElement("filename") 
     
    286284            element.appendChild(newdoc.createTextNode(str(file))) 
    287285        top_element.appendChild(element) 
    288          
     286 
    289287        element = newdoc.createElement("timestamp") 
    290288        element.appendChild(newdoc.createTextNode(time.ctime(timestamp))) 
     
    293291        element.setAttributeNode(attr) 
    294292        top_element.appendChild(element) 
    295          
     293 
    296294        # Current state 
    297295        state = newdoc.createElement("state") 
    298296        top_element.appendChild(state) 
    299          
    300         for name,value in self.saved_state.iteritems(): 
     297 
     298        for name, value in self.saved_state.iteritems(): 
    301299            element = newdoc.createElement(str(name)) 
    302300            element.appendChild(newdoc.createTextNode(str(value))) 
    303301            state.appendChild(element) 
    304                
     302 
    305303        # State history list 
    306304        history = newdoc.createElement("history") 
    307305        top_element.appendChild(history) 
    308          
     306 
    309307        for name, value in self.state_list.iteritems(): 
    310308            history_element = newdoc.createElement('state_' + str(name)) 
    311             for state_name,state_value in value.iteritems(): 
     309            for state_name, state_value in value.iteritems(): 
    312310                state_element = newdoc.createElement(str(state_name)) 
    313311                child = newdoc.createTextNode(str(state_value)) 
    314312                state_element.appendChild(child) 
    315313                history_element.appendChild(state_element) 
    316             #history_element.appendChild(state_list_element) 
     314            # history_element.appendChild(state_list_element) 
    317315            history.appendChild(history_element) 
    318316 
    319317        # Bookmarks  bookmark_list[self.bookmark_num] = [\ 
    320         #my_time,date,state,comp_state] 
     318        # my_time,date,state,comp_state] 
    321319        bookmark = newdoc.createElement("bookmark") 
    322320        top_element.appendChild(bookmark) 
    323         item_list = ['time','date','state','comp_state'] 
     321        item_list = ['time', 'date', 'state', 'comp_state'] 
    324322        for name, value_list in self.bookmark_list.iteritems(): 
    325             element = newdoc.createElement('mark_'+ str(name)) 
    326             _,date,state,comp_state = value_list 
     323            element = newdoc.createElement('mark_' + str(name)) 
     324            _, date, state, comp_state = value_list 
    327325            time_element = newdoc.createElement('time') 
    328326            time_element.appendChild(newdoc.createTextNode(str(value_list[0]))) 
     
    354352        else: 
    355353            return newdoc 
    356          
     354 
    357355    def fromXML(self, file=None, node=None): 
    358356        """ 
    359357        Load invariant states from a file 
    360              
     358 
    361359        : param file: .inv file 
    362         : param node: node of a XML document to read from        
     360        : param node: node of a XML document to read from 
    363361        """ 
    364362        if file is not None: 
     
    366364            msg += " format for invariant files" 
    367365            raise RuntimeError, msg 
    368          
     366 
    369367        if node.get('version')\ 
    370368            and node.get('version') == '1.0': 
     
    384382                    msg += " timestamp\n %s" % sys.exc_value 
    385383                    logging.error(msg) 
    386              
     384 
    387385            # Parse bookmarks 
    388386            entry_bookmark = get_content('ns:bookmark', node) 
     
    391389                temp_state = {} 
    392390                temp_bookmark = {} 
    393                 entry = get_content('ns:mark_%s' % ind, entry_bookmark)  
    394                                  
     391                entry = get_content('ns:mark_%s' % ind, entry_bookmark) 
     392 
    395393                if entry is not None: 
    396394                    my_time = get_content('ns:time', entry) 
     
    399397                    val_date = str(date.text.strip()) 
    400398                    state_entry = get_content('ns:state', entry) 
    401                     for item in list: 
    402  
     399                    for item in DEFAULT_STATE: 
    403400                        input_field = get_content('ns:%s' % item, state_entry) 
    404401                        val = str(input_field.text.strip()) 
    405402                        if input_field is not None: 
    406                             try: 
    407                                 exec "temp_state['%s'] = %s" % (item, val)       
    408                             except: 
    409                                 exec "temp_state['%s'] = '%s'" % (item, val) 
     403                            temp_state[item] = val 
    410404                    comp_entry = get_content('ns:comp_state', entry) 
    411                      
    412                     for item in list: 
     405 
     406                    for item in DEFAULT_STATE: 
    413407                        input_field = get_content('ns:%s' % item, comp_entry) 
    414408                        val = str(input_field.text.strip()) 
    415409                        if input_field is not None: 
    416                             try: 
    417                                 exec "temp_bookmark['%s'] = %s" % (item, val)       
    418                             except: 
    419                                 exec "temp_bookmark['%s'] = '%s'" % (item, val) 
     410                            temp_bookmark[item] = val 
    420411                    try: 
    421                         cmd = "self.bookmark_list[%s] = [val_time," 
    422                         cmd += "val_date,temp_state,temp_bookmark]" 
    423                         exec cmd % ind 
     412                        self.bookmark_list[ind] = [val_time, val_date, temp_state, temp_bookmark] 
    424413                    except: 
    425414                        raise "missing components of bookmarks..." 
     
    429418            for ind in range(0, len(entry_history)): 
    430419                temp_state = {} 
    431                 entry = get_content('ns:state_%s' % ind, entry_history)  
     420                entry = get_content('ns:state_%s' % ind, entry_history) 
    432421 
    433422                if entry is not None: 
    434                     for item in list: 
    435                         input_field = get_content('ns:%s' % item, entry ) 
     423                    for item in DEFAULT_STATE: 
     424                        input_field = get_content('ns:%s' % item, entry) 
    436425                        val = str(input_field.text.strip()) 
    437  
    438426                        if input_field is not None: 
    439                             try: 
    440                                 exec "temp_state['%s'] = %s" % (item, val)          
    441                             except: 
    442                                 exec "temp_state['%s'] = '%s'" % (item, val) 
    443                             finally: 
    444                                 exec "self.state_list['%s'] = temp_state" % ind  
     427                            temp_state[item] = val 
     428                            self.state_list[ind] = temp_state 
     429 
    445430            # Parse current state (ie, saved_state) 
    446             entry = get_content('ns:state', node)            
     431            entry = get_content('ns:state', node) 
    447432            if entry is not None: 
    448                 for item in list: 
     433                for item in DEFAULT_STATE: 
    449434                    input_field = get_content('ns:%s' % item, entry) 
    450435                    val = str(input_field.text.strip()) 
     
    452437                        self.set_saved_state(name=item, value=val) 
    453438            self.file = file_name 
    454              
     439 
    455440    def set_report_string(self): 
    456441        """ 
    457         Get the values (strings) from __str__ for report  
     442        Get the values (strings) from __str__ for report 
    458443        """ 
    459444        strings = self.__str__() 
    460      
     445 
    461446        # default string values 
    462         for num in range (1, 19): 
     447        for num in range(1, 19): 
    463448            exec "s_%s = 'NA'" % str(num) 
    464449        lines = strings.split('\n') 
     
    491476                    s_10 = item[1] 
    492477                elif item[0] == "volume fraction": 
    493                     val=item[1].split("+-")[0].strip() 
     478                    val = item[1].split("+-")[0].strip() 
    494479                    error = item[1].split("+-")[1].strip() 
    495480                    s_17 = val + " &plusmn; " + error 
     
    499484                    s_18 = val + " &plusmn; " + error 
    500485                elif item[0].split("(")[0].strip() == "power low": 
    501                     s_11 = item[0]+" ="+item[1] 
     486                    s_11 = item[0] + " =" + item[1] 
    502487                elif item[0].split("(")[0].strip() == "power high": 
    503                     s_12 = item[0]+" ="+item[1] 
     488                    s_12 = item[0] + " =" + item[1] 
    504489                elif item[0].split("[")[0].strip() == "Q* from low Q extrapolation": 
    505                     #looks messy but this way the symbols +_ and % work on html 
     490                    # looks messy but this way the symbols +_ and % work on html 
    506491                    val = item[1].split("+-")[0].strip() 
    507492                    error = item[1].split("+-")[1].strip() 
     
    532517 
    533518        # make plot image 
    534         self.set_plot_state(extra_high=bool_0[1],extra_low=bool_1[1]) 
     519        self.set_plot_state(extra_high=bool_0[1], extra_low=bool_1[1]) 
    535520        # get ready for report with setting all the html strings 
    536521        self.report_str = str(self.template_str) % (s_1, s_2, 
    537                                         s_3, s_4, s_5, s_6, s_7, s_8, 
    538                                     s_9, s_10, s_11, s_12, s_13, s_14, s_15, 
    539                                         s_16, s_17, s_18, file_name, "%s") 
     522                                                    s_3, s_4, s_5, s_6, s_7, s_8, 
     523                                                    s_9, s_10, s_11, s_12, s_13, s_14, s_15, 
     524                                                    s_16, s_17, s_18, file_name, "%s") 
    540525 
    541526    def _check_html_format(self, name): 
     
    545530        if name.count('%'): 
    546531            name = name.replace('%', '&#37') 
    547          
     532 
    548533        return name 
    549          
     534 
    550535    def set_saved_state(self, name, value): 
    551536        """ 
    552         Set the state list  
    553                      
     537        Set the state list 
     538 
    554539        : param name: name of the state component 
    555540        : param value: value of the state component 
    556541        """ 
    557         rb_list = [['power_law_low','guinier'], 
    558                    ['fit_enable_low','fix_enable_low'], 
    559                    ['fit_enable_high','fix_enable_high']] 
    560  
    561         try: 
    562             if value == None or value.lstrip().rstrip() == '': 
    563                 exec "self.%s = '%s'" % (name, value) 
    564                 exec "self.saved_state['%s'] = '%s'" % (name, value) 
    565             else: 
    566                 exec 'self.%s = %s' % (name, value) 
    567                 exec "self.saved_state['%s'] = %s" % (name, value) 
    568             # set the count part of radio button clicked  
    569             # False for the saved_state 
    570             for title, content in rb_list: 
    571                 if name ==  title: 
    572                     name = content  
    573                     value = False      
    574                 elif name == content: 
    575                     name = title 
    576                     value = False  
    577             exec "self.saved_state['%s'] = '%s'" % (name, value)      
    578             self.state_num = self.saved_state['state_num'] 
    579         except:            
    580             pass 
     542        rb_list = [['power_law_low', 'guinier'], 
     543                   ['fit_enable_low', 'fix_enable_low'], 
     544                   ['fit_enable_high', 'fix_enable_high']] 
     545 
     546        self.name = value 
     547        self.saved_state[name] = value 
     548        # set the count part of radio button clicked 
     549        # False for the saved_state 
     550        for title, content in rb_list: 
     551            if name == title: 
     552                name = content 
     553                value = False 
     554            elif name == content: 
     555                name = title 
     556                value = False 
     557        self.saved_state[name] = value 
     558        self.state_num = self.saved_state['state_num'] 
    581559 
    582560    def set_plot_state(self, extra_high=False, extra_low=False): 
     
    584562        Build image state that wx.html understand 
    585563        by plotting, putting it into wx.FileSystem image object 
    586          
     564 
    587565        : extrap_high,extra_low: low/high extrapolations 
    588566        are possible extra-plots 
     
    593571        from matplotlib.backends.backend_agg import FigureCanvasAgg 
    594572 
    595         #we use simple plot, not plotpanel 
    596         #make matlab figure 
     573        # we use simple plot, not plotpanel 
     574        # make matlab figure 
    597575        fig = plt.figure() 
    598576        fig.set_facecolor('w') 
    599577        graph = fig.add_subplot(111) 
    600578 
    601         #data plot 
     579        # data plot 
    602580        graph.errorbar(self.data.x, self.data.y, yerr=self.data.dy, fmt='o') 
    603         #low Q extrapolation fit plot 
     581        # low Q extrapolation fit plot 
    604582        if not extra_low == 'False': 
    605             graph.plot(self.theory_lowQ.x,self.theory_lowQ.y) 
    606         #high Q extrapolation fit plot 
     583            graph.plot(self.theory_lowQ.x, self.theory_lowQ.y) 
     584        # high Q extrapolation fit plot 
    607585        if not extra_high == 'False': 
    608             graph.plot(self.theory_highQ.x,self.theory_highQ.y) 
     586            graph.plot(self.theory_highQ.x, self.theory_highQ.y) 
    609587        graph.set_xscale("log", nonposx='clip') 
    610588        graph.set_yscale("log", nonposy='clip') 
    611         graph.set_xlabel('$\\rm{Q}(\\AA^{-1})$', fontsize = 12) 
    612         graph.set_ylabel('$\\rm{Intensity}(cm^{-1})$', fontsize = 12) 
     589        graph.set_xlabel('$\\rm{Q}(\\AA^{-1})$', fontsize=12) 
     590        graph.set_ylabel('$\\rm{Intensity}(cm^{-1})$', fontsize=12) 
    613591        canvas = FigureCanvasAgg(fig) 
    614         #actually make image 
     592        # actually make image 
    615593        canvas.draw() 
    616          
    617         #make python.Image object  
    618         #size 
     594 
     595        # make python.Image object 
     596        # size 
    619597        w, h = canvas.get_width_height() 
    620         #convert to wx.Image 
    621         wximg = wx.EmptyImage(w,h) 
    622         #wxim.SetData(img.convert('RGB').tostring() )  
    623         wximg.SetData(canvas.tostring_rgb())  
    624         #get the dynamic image for the htmlwindow 
     598        # convert to wx.Image 
     599        wximg = wx.EmptyImage(w, h) 
     600        # wxim.SetData(img.convert('RGB').tostring() ) 
     601        wximg.SetData(canvas.tostring_rgb()) 
     602        # get the dynamic image for the htmlwindow 
    625603        wximgbmp = wx.BitmapFromImage(wximg) 
    626         #store the image in wx.FileSystem Object  
     604        # store the image in wx.FileSystem Object 
    627605        wx.FileSystem.AddHandler(wx.MemoryFSHandler()) 
    628606        # use wx.MemoryFSHandler 
    629607        self.imgRAM = wx.MemoryFSHandler() 
    630         #AddFile, image can be retrieved with 'memory:filename' 
     608        # AddFile, image can be retrieved with 'memory:filename' 
    631609        self.imgRAM.AddFile('img_inv.png', wximgbmp, wx.BITMAP_TYPE_PNG) 
    632          
     610 
    633611        self.wximgbmp = 'memory:img_inv.png' 
    634612        self.image = fig 
     
    638616    Class to load a .inv invariant file 
    639617    """ 
    640     ## File type 
     618    # # File type 
    641619    type_name = "Invariant" 
    642      
    643     ## Wildcards 
     620 
     621    # # Wildcards 
    644622    type = ["Invariant file (*.inv)|*.inv", 
    645623            "SASView file (*.svs)|*.svs"] 
    646     ## List of allowed extensions 
    647     ext = ['.inv', '.INV', '.svs', 'SVS']   
    648      
     624    # # List of allowed extensions 
     625    ext = ['.inv', '.INV', '.svs', 'SVS'] 
     626 
    649627    def __init__(self, call_back, cansas=True): 
    650628        """ 
    651629        Initialize the call-back method to be called 
    652630        after we load a file 
    653          
     631 
    654632        : param call_back: call-back method 
    655633        : param cansas:  True = files will be written/read in CanSAS format 
    656                         False = write CanSAS format   
    657         """ 
    658         ## Call back method to be executed after a file is read 
     634                        False = write CanSAS format 
     635        """ 
     636        # # Call back method to be executed after a file is read 
    659637        self.call_back = call_back 
    660         ## CanSAS format flag 
     638        # # CanSAS format flag 
    661639        self.cansas = cansas 
    662640        self.state = None 
    663641 
    664642    def read(self, path): 
    665         """  
     643        """ 
    666644        Load a new invariant state from file 
    667          
     645 
    668646        : param path: file path 
    669647        : return: None 
     
    673651        else: 
    674652            return self._read_standalone(path) 
    675          
     653 
    676654    def _read_standalone(self, path): 
    677         """  
     655        """ 
    678656        Load a new invariant state from file. 
    679657        The invariant node is assumed to be the top element. 
    680          
     658 
    681659        : param path: file path 
    682660        : return: None 
     
    686664 
    687665        state.fromXML(file=path) 
    688          
     666 
    689667        # Call back to post the new state 
    690668        self.call_back(state) 
    691669        return None 
    692      
     670 
    693671    def _parse_state(self, entry): 
    694672        """ 
    695673        Read an invariant result from an XML node 
    696          
    697         : param entry: XML node to read from  
     674 
     675        : param entry: XML node to read from 
    698676        : return: InvariantState object 
    699677        """ 
     
    710688            msg = "XML document does not contain invariant" 
    711689            msg += " information.\n %s" % sys.exc_value 
    712             logging.info(msg)   
     690            logging.info(msg) 
    713691        return state 
    714      
     692 
    715693    def _read_cansas(self, path): 
    716         """  
     694        """ 
    717695        Load data and invariant information from a CanSAS XML file. 
    718          
     696 
    719697        : param path: file path 
    720         : return: Data1D object if a single SASentry was found,  
     698        : return: Data1D object if a single SASentry was found, 
    721699                    or a list of Data1D objects if multiple entries were found, 
    722700                    or None of nothing was found 
     
    726704        output = [] 
    727705        if os.path.isfile(path): 
    728             basename  = os.path.basename(path) 
     706            basename = os.path.basename(path) 
    729707            root, extension = os.path.splitext(basename) 
    730              
     708 
    731709            if  extension.lower() in self.ext or \ 
    732710                extension.lower() == '.xml': 
    733711                tree = etree.parse(path, parser=etree.ETCompatXMLParser()) 
    734         
     712 
    735713                # Check the format version number 
    736                 # Specifying the namespace will take care of  
    737                 # the file format version  
     714                # Specifying the namespace will take care of 
     715                # the file format version 
    738716                root = tree.getroot() 
    739                  
     717 
    740718                entry_list = root.xpath('/ns:SASroot/ns:SASentry', 
    741719                                        namespaces={'ns': CANSAS_NS}) 
    742                  
     720 
    743721                for entry in entry_list: 
    744                      
     722 
    745723                    sas_entry, _ = self._parse_entry(entry) 
    746724                    invstate = self._parse_state(entry) 
    747                      
    748                     #invstate could be None when .svs file is loaded 
    749                     #in this case, skip appending to output 
     725 
     726                    # invstate could be None when .svs file is loaded 
     727                    # in this case, skip appending to output 
    750728                    if invstate != None: 
    751729                        sas_entry.meta_data['invstate'] = invstate 
     
    762740            self.state = output[0].meta_data['invstate'] 
    763741            self.call_back(state=output[0].meta_data['invstate'], 
    764                           datainfo = output[0]) 
     742                           datainfo=output[0]) 
    765743            return output[0] 
    766744        else: 
    767             return output                 
    768      
     745            return output 
     746 
    769747    def get_state(self): 
    770748        return self.state 
    771      
     749 
    772750    def write(self, filename, datainfo=None, invstate=None): 
    773751        """ 
    774752        Write the content of a Data1D as a CanSAS XML file 
    775          
     753 
    776754        : param filename: name of the file to write 
    777755        : param datainfo: Data1D object 
     
    780758        # Sanity check 
    781759        if self.cansas == True: 
    782             doc = self.write_toXML(datainfo,invstate) 
     760            doc = self.write_toXML(datainfo, invstate) 
    783761            # Write the XML document 
    784762            fd = open(filename, 'w') 
     
    787765        else: 
    788766            invstate.toXML(file=filename) 
    789          
     767 
    790768    def write_toXML(self, datainfo=None, state=None): 
    791769        """ 
    792770        Write toXML, a helper for write() 
    793          
     771 
    794772        : return: xml doc 
    795773        """ 
    796774        if datainfo is None: 
    797             datainfo = sas.dataloader.data_info.Data1D(x=[], y=[])     
     775            datainfo = sas.dataloader.data_info.Data1D(x=[], y=[]) 
    798776        elif not issubclass(datainfo.__class__, sas.dataloader.data_info.Data1D): 
    799777            msg = "The cansas writer expects a Data1D" 
    800778            msg += " instance: %s" % str(datainfo.__class__.__name__) 
    801779            raise RuntimeError, msg 
    802         #make sure title and data run is filled up. 
     780        # make sure title and data run is filled up. 
    803781        if datainfo.title == None or datainfo.title == '': 
    804782            datainfo.title = datainfo.name 
    805         if datainfo.run_name == None or datainfo.run_name == {}:  
     783        if datainfo.run_name == None or datainfo.run_name == {}: 
    806784            datainfo.run = [str(datainfo.name)] 
    807785            datainfo.run_name[0] = datainfo.name 
     
    810788        # Add the invariant information to the XML document 
    811789        if state is not None: 
    812             doc = state.toXML(datainfo.name,doc=doc, entry_node=sasentry) 
     790            doc = state.toXML(datainfo.name, doc=doc, entry_node=sasentry) 
    813791        return doc 
    814792 
  • src/sas/perspectives/invariant/invariant_widgets.py

    r79492222 r78a205a  
    1  
    2  
    3  
    41################################################################################ 
    5 #This software was developed by the University of Tennessee as part of the 
    6 #Distributed Data Analysis of Neutron Scattering Experiments (DANSE) 
    7 #project funded by the US National Science Foundation.  
     2# This software was developed by the University of Tennessee as part of the 
     3# Distributed Data Analysis of Neutron Scattering Experiments (DANSE) 
     4# project funded by the US National Science Foundation. 
    85# 
    9 #See the license text in license.txt 
     6# See the license text in license.txt 
    107# 
    11 #copyright 2009, University of Tennessee 
     8# copyright 2009, University of Tennessee 
    129################################################################################ 
    13  
    1410 
    1511import wx 
     
    2319        ScrolledPanel.__init__(self, *args, **kwds) 
    2420        self.SetupScrolling() 
    25          
     21 
    2622class InvTextCtrl(wx.TextCtrl): 
    2723    """ 
     
    3127    def __init__(self, *args, **kwds): 
    3228        wx.TextCtrl.__init__(self, *args, **kwds) 
    33         ## Set to True when the mouse is clicked while  
    34         #the whole string is selected 
     29        # # Set to True when the mouse is clicked while 
     30        # the whole string is selected 
    3531        self.full_selection = False 
    36         ## Call back for EVT_SET_FOCUS events 
     32        # # Call back for EVT_SET_FOCUS events 
    3733        _on_set_focus_callback = None 
    3834 
     
    4036        self.Bind(wx.EVT_LEFT_UP, self._highlight_text) 
    4137        self.Bind(wx.EVT_SET_FOCUS, self._on_set_focus) 
    42          
     38 
    4339    def _on_set_focus(self, event): 
    4440        """ 
    4541        Catch when the text control is set in focus to highlight the whole 
    4642        text if necessary 
    47          
     43 
    4844        :param event: mouse event 
    4945        """ 
    5046        event.Skip() 
    5147        self.full_selection = True 
    52          
     48 
    5349    def _highlight_text(self, event): 
    5450        """ 
    5551        Highlight text of a TextCtrl only of no text has be selected 
    56          
     52 
    5753        :param event: mouse event 
    5854        """ 
    5955        # Make sure the mouse event is available to other listeners 
    6056        event.Skip() 
    61         control  = event.GetEventObject() 
     57        control = event.GetEventObject() 
    6258        if self.full_selection: 
    6359            self.full_selection = False 
    6460            # Check that we have a TextCtrl 
    6561            if issubclass(control.__class__, wx.TextCtrl): 
    66                 # Check whether text has been selected,  
     62                # Check whether text has been selected, 
    6763                # if not, select the whole string 
    6864                (start, end) = control.GetSelection() 
    6965                if start == end: 
    7066                    control.SetSelection(-1, -1) 
    71             
     67 
    7268 
    7369class OutputTextCtrl(wx.TextCtrl): 
    7470    """ 
    7571    Text control used to display outputs. 
    76     No editing allowed. The background is  
     72    No editing allowed. The background is 
    7773    grayed out. User can't select text. 
    7874    """ 
     
    8177        self.SetEditable(False) 
    8278        self.SetBackgroundColour(self.GetParent().GetBackgroundColour()) 
    83          
     79 
    8480        # Bind to mouse event to avoid text highlighting 
    8581        # The event will be skipped once the call-back 
    8682        # is called. 
    87          
     83 
    8884        self.Bind(wx.EVT_MOUSE_EVENTS, self._click) 
    8985 
    90          
     86 
    9187    def _click(self, event): 
    9288        """ 
    9389        Prevent further handling of the mouse event 
    9490        by not calling Skip(). 
    95         """  
     91        """ 
    9692        pass 
    97      
     93 
    9894class DataDialog(wx.Dialog): 
    9995    """ 
     
    110106        self._choice_sizer = wx.GridBagSizer(5, 5) 
    111107        self._panel = DialogPanel(self, style=wx.RAISED_BORDER, 
    112                                size=(WIDTH-20, HEIGHT/3)) 
     108                                  size=(WIDTH - 20, HEIGHT / 3)) 
    113109        self.SetSizer(self._sizer_main) 
    114110        self.__do_layout(data_list, text=text) 
    115111        self.Layout() 
    116          
     112 
    117113    def __do_layout(self, data_list, text=''): 
    118114        """ 
    119115        layout the dialog 
    120116        """ 
    121         #add text 
     117        # add text 
    122118        if text.strip() == "": 
    123119            text = "This Perspective does not allow multiple data !\n" 
    124120            text += "Please select only one Data.\n" 
    125121        text_ctrl = wx.TextCtrl(self, -1, str(text), style=wx.TE_MULTILINE, 
    126                                 size=(-1, HEIGHT/3)) 
     122                                size=(-1, HEIGHT / 3)) 
    127123        text_ctrl.SetEditable(False) 
    128         self._sizer_txt.Add(text_ctrl , 1, wx.EXPAND|wx.ALL, 10) 
     124        self._sizer_txt.Add(text_ctrl, 1, wx.EXPAND | wx.ALL, 10) 
    129125        iy = 0 
    130126        ix = 0 
    131         rbox = wx.RadioButton(self._panel, -1, str(data_list[0].name),  
    132                                   (10, 10), style= wx.RB_GROUP) 
     127        rbox = wx.RadioButton(self._panel, -1, str(data_list[0].name), 
     128                              (10, 10), style=wx.RB_GROUP) 
    133129        rbox.SetValue(True) 
    134130        self.list_of_ctrl.append((rbox, data_list[0])) 
    135131        self._choice_sizer.Add(rbox, (iy, ix), (1, 1), 
    136                          wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 
     132                               wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15) 
    137133        for i in range(1, len(data_list)): 
    138134            iy += 1 
    139             rbox = wx.RadioButton(self._panel, -1,  
     135            rbox = wx.RadioButton(self._panel, -1, 
    140136                                  str(data_list[i].name), (10, 10)) 
    141137            rbox.SetValue(False) 
    142138            self.list_of_ctrl.append((rbox, data_list[i])) 
    143139            self._choice_sizer.Add(rbox, (iy, ix), 
    144                            (1, 1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 
     140                                   (1, 1), wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15) 
    145141        self._panel.SetSizer(self._choice_sizer) 
    146         #add sizer 
    147         self._sizer_button.Add((20, 20), 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
     142        # add sizer 
     143        self._sizer_button.Add((20, 20), 1, wx.EXPAND | wx.ADJUST_MINSIZE, 0) 
    148144        button_cancel = wx.Button(self, wx.ID_CANCEL, "Cancel") 
    149145        self._sizer_button.Add(button_cancel, 0, 
    150                           wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10) 
     146                               wx.LEFT | wx.RIGHT | wx.ADJUST_MINSIZE, 10) 
    151147        button_OK = wx.Button(self, wx.ID_OK, "Ok") 
    152148        button_OK.SetFocus() 
    153149        self._sizer_button.Add(button_OK, 0, 
    154                                 wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10) 
     150                               wx.LEFT | wx.RIGHT | wx.ADJUST_MINSIZE, 10) 
    155151        static_line = wx.StaticLine(self, -1) 
    156          
    157         self._sizer_txt.Add(self._panel, 0, wx.EXPAND|wx.ALL, 5) 
    158         self._sizer_main.Add(self._sizer_txt, 0, wx.EXPAND|wx.ALL, 5) 
     152 
     153        self._sizer_txt.Add(self._panel, 0, wx.EXPAND | wx.ALL, 5) 
     154        self._sizer_main.Add(self._sizer_txt, 0, wx.EXPAND | wx.ALL, 5) 
    159155        self._sizer_main.Add(static_line, 0, wx.EXPAND, 0) 
    160         self._sizer_main.Add(self._sizer_button, 0, wx.EXPAND|wx.ALL, 10) 
    161          
    162          
     156        self._sizer_main.Add(self._sizer_button, 0, wx.EXPAND | wx.ALL, 10) 
     157 
    163158    def get_data(self): 
    164159        """ 
     
    168163            rbox, data = item 
    169164            if rbox.GetValue(): 
    170                 return data  
    171  
    172      
    173  
    174   
     165                return data 
  • src/sas/perspectives/invariant/report_dialog.py

    re8bb5b6 r78a205a  
    11 
    22################################################################################ 
    3 #This software was developed by the University of Tennessee as part of the 
    4 #Distributed Data Analysis of Neutron Scattering Experiments (DANSE) 
    5 #project funded by the US National Science Foundation.  
     3# This software was developed by the University of Tennessee as part of the 
     4# Distributed Data Analysis of Neutron Scattering Experiments (DANSE) 
     5# project funded by the US National Science Foundation. 
    66# 
    7 #See the license text in license.txt 
     7# See the license text in license.txt 
    88# 
    9 #copyright 2009, University of Tennessee 
     9# copyright 2009, University of Tennessee 
    1010################################################################################ 
    1111 
    1212""" 
    13 Dialog report panel to show and summarize the results of  
     13Dialog report panel to show and summarize the results of 
    1414the invariant calculation. 
    1515""" 
    1616import wx 
    1717import os 
    18 import wx.html as html 
    19   
     18import sys 
     19import logging 
     20 
    2021from sas.guiframe.report_dialog import BaseReportDialog 
    2122 
    2223class ReportDialog(BaseReportDialog): 
    2324    """ 
    24     The report dialog box.  
     25    The report dialog box. 
    2526    """ 
    26      
    27     def __init__(self,  report_list, *args, **kwds): 
     27 
     28    def __init__(self, report_list, *args, **kwds): 
    2829        """ 
    2930        Initialization. The parameters added to Dialog are: 
    30          
     31 
    3132        :param report_list: list of html_str, text_str, image 
    3233        from invariant_state 
     
    4647        Save 
    4748        """ 
    48         #todo: complete saving fig file and as a txt file 
     49        # todo: complete saving fig file and as a txt file 
    4950        dlg = wx.FileDialog(self, "Choose a file", 
    5051                            wildcard=self.wild_card, 
    51                             style=wx.SAVE|wx.OVERWRITE_PROMPT|wx.CHANGE_DIR) 
    52         dlg.SetFilterIndex(0) #Set .html files to be default 
     52                            style=wx.SAVE | wx.OVERWRITE_PROMPT | wx.CHANGE_DIR) 
     53        dlg.SetFilterIndex(0)  # Set .html files to be default 
    5354 
    5455        if dlg.ShowModal() != wx.ID_OK: 
     
    5758 
    5859        fName = dlg.GetPath() 
    59         ext_num = dlg.GetFilterIndex()   
    60         #set file extensions   
     60        ext_num = dlg.GetFilterIndex() 
     61        # set file extensions 
    6162        if ext_num == (0 + 2 * self.index_offset): 
    6263            # TODO: Sort this case out 
     
    6667            dlg.Destroy() 
    6768 
    68             #pic (png) file path/name 
     69            # pic (png) file path/name 
    6970            pic_fname = os.path.splitext(fName)[0] + img_ext 
    7071            # save the image for use with pdf writer 
     
    7374            # put the image file path in the html data 
    7475            html = self.report_list[0] % str(pic_fname) 
    75              
     76 
    7677            # make/open file in case of absence 
    7778            f = open(fName, 'w') 
     
    7980            # write pdf as a pdf file 
    8081            pdf = self.HTML2PDF(data=html, filename=fName) 
    81              
    82             #open pdf 
     82 
     83            # open pdf 
    8384            if pdf: 
    8485                try: 
    85                     #Windows 
     86                    # Windows 
    8687                    os.startfile(str(fName)) 
    8788                except: 
    8889                    try: 
    89                         #Mac 
    90                         os.system("open %s"% fName) 
     90                        # Mac 
     91                        os.system("open %s" % fName) 
    9192                    except: 
    92                         #DO not open 
    93                         pass 
    94             #delete image file 
     93                        # DO not open 
     94                        logging.error("Could not open file: %s" % sys.exc_value) 
     95            # delete image file 
    9596            os.remove(pic_fname) 
    9697            return 
     
    100101            report_frame = self.report_list[0] 
    101102        elif ext_num == (2 - self.index_offset): 
    102             ext = '.txt'    
     103            ext = '.txt' 
    103104            # changing the image extension actually changes the image 
    104105            # format on saving 
     
    108109            return 
    109110 
    110         #file name      
     111        # file name 
    111112        fName = os.path.splitext(fName)[0] + ext 
    112113        dlg.Destroy() 
    113         #pic (png) file path/name 
     114        # pic (png) file path/name 
    114115        pic_fname = os.path.splitext(fName)[0] + img_ext 
    115         #put the image path in html string 
     116        # put the image path in html string 
    116117        if ext_num == (1 - self.index_offset): 
    117118            report = report_frame % os.path.basename(pic_fname) 
     
    120121        f.write(report) 
    121122        f.close() 
    122         #save png file using pic_fname 
     123        # save png file using pic_fname 
    123124        self.report_list[2].savefig(pic_fname) 
    124          
Note: See TracChangeset for help on using the changeset viewer.