示例#1
0
    def update_page_name(self):
        """ Handles the trait defining a particular page's name being changed.
        """
        changed = False
        for i, value in enumerate(self._uis):
            dock_control, user_object, view_object, monitoring = value
            if dock_control.control is not None:
                name = None
                handler = getattr(self.ui.handler, '%s_%s_page_name' %
                                  (self.object_name, self.name), None)
                if handler is not None:
                    name = handler(self.ui.info, user_object)

                if name is None:
                    name = unicode(
                        xgetattr(
                            view_object,
                            self.factory.page_name[
                                1:],
                            u'???'))

                changed |= (dock_control.name != name)
                dock_control.name = name

        if changed:
            self.update_layout()
示例#2
0
 def get_raw_value(self, object):
     """ Gets the unformatted value of the column for a specified object.
     """
     try:
         return xgetattr(self.get_object(object), self.name)
     except:
         return None
示例#3
0
文件: gensim.py 项目: hugadams/PAME
    def check_sim_ready(self):
        """Method to update various storage mechanisms for holding trait values for simulations.  
        Takes user data in table editor and stores it in necessary dictionaries so that 
        traits can be set and things automatically.  Decided to use this over a system
        properties because the properties were conflicting with delegation and other stuff.
        """
        sim_traits = {}
        originals = {}
        missing = []
        status_message = ''
        
        # Retain a mapping between shortnames (layer1.material) and attr path
        # from base_app (layereditor.layer1) etc...
        _trait_name_map = dict((s.trait_name, s.trait_name_full) 
                                           for s in self.sim_variables)       
                
        for obj in self.sim_variables:
            obj.inc=self.inc  #Ensures proper increments whether adding new objects to the table or just changing global inc

        for obj in self.sim_variables:
            sim_traits[str(obj.trait_name)]=obj.trait_array        #Simulation traits
                       #^^^ Remove unicode

        for key in sim_traits.keys():
            _true_trait_val = _trait_name_map[key]
            try:
                originals[key]=xgetattr(self.base_app, _true_trait_val)  #If trait found, store its original values
            except (AttributeError, StackError):
                missing.append(key)  #If not, put it in missing

        ready = True

        # Are traits missing?
        if len(missing) > 0:
            status_message='<font color="red"> Could not find required input: </font>'
            status_message += ', '.join(missing)
            ready = False

        # Did user select duplicates of trait names
        trait_names = [obj.trait_name for obj in self.sim_variables]
        duplicates = set([name for name in trait_names if trait_names.count(name) > 1])
        if duplicates:
            status_message='<font color="red"> Duplicate simulation input(s) found: </font>'
            for trait in duplicates:
                status_message += trait + ',  '
            ready = False                        


        if ready:
            status_message='<font color="green"> Simulation ready: all input found</font>'
            ready = True

        self.ready = ready
        self.status_message = status_message.rstrip(',') #<-- trialling commas for list of one element string
        self.simulation_traits = sim_traits# Remove unicode
        self.missing_traits = missing
        self.original_values = originals
        
        self._trait_namemap = _trait_name_map
示例#4
0
 def get_raw_value(self, object):
     """ Gets the unformatted value of the column for a specified object.
     """
     try:
         return xgetattr(self.get_object(object), self.name)
     except Exception as e:
         from traitsui.api import raise_to_debug
         raise_to_debug()
         return None
示例#5
0
    def target_name(self, object):
        """ Returns the target object and name for the column.
        """
        object = self.get_object(object)
        name = self.name
        col = name.rfind(".")
        if col < 0:
            return (object, name)

        return (xgetattr(object, name[:col]), name[col + 1 :])
示例#6
0
    def target_name(self, object):
        """ Returns the target object and name for the column.
        """
        object = self.get_object(object)
        name = self.name
        col = name.rfind('.')
        if col < 0:
            return (object, name)

        return (xgetattr(object, name[:col]), name[col + 1:])
示例#7
0
    def get_raw_value(self, object):
        """ Gets the unformatted value of the column for a specified object.
        """
        try:
            return xgetattr(self.get_object(object), self.name)
        except Exception as e:
            from traitsui.api import raise_to_debug

            raise_to_debug()
            return None
示例#8
0
 def _selected_changed(self, selected):
     """Handles the **selected** trait being changed."""
     for page, ui, _, _ in self._uis:
         if ui.info and selected is ui.info.object:
             self.control.setCurrentWidget(page)
             break
         deletable = self.factory.deletable
         deletable_trait = self.factory.deletable_trait
         if deletable and deletable_trait:
             enabled = xgetattr(selected, deletable_trait, True)
             self.close_button.setEnabled(enabled)
示例#9
0
   def get_raw_value ( self, object ):
        """ Gets the unformatted value of the column for a specified object.
        Overridden here to return the trait name (which is the object's name trait) rather than the
        column's name trait.

        """
        try:
            target, name = self.target_name( object )
            return xgetattr( target, name )
        except:
            return None
示例#10
0
    def get_raw_value(self, object):
        """ Gets the unformatted value of the column for a specified object.
        Overridden here to return the trait name (which is the object's name trait) rather than the
        column's name trait.

        """
        try:
            target, name = self.target_name(object)
            return xgetattr(target, name)
        except:
            return None
示例#11
0
 def _selected_changed(self, selected):
     """ Handles the **selected** trait being changed.
     """
     for page, ui, _, _ in self._uis:
         if ui.info and selected is ui.info.object:
             self.control.setCurrentWidget(page)
             break
         deletable = self.factory.deletable
         deletable_trait = self.factory.deletable_trait
         if deletable and deletable_trait:
             enabled = xgetattr(selected, deletable_trait, True)
             self.close_button.setEnabled(enabled)
示例#12
0
   def target_name ( self, object ):
        """ Returns the target object and name for the column.
        Overridden here to return the trait name (which is the object's name trait) rather than the
        column's name trait.

        """
        name   = object.name
        object = self.get_object( object )
        col    = name.rfind( '.' )
        if col < 0:
            return ( object, name )

        return ( xgetattr( object, name[ :col ] ), name[ col + 1: ] )
示例#13
0
    def target_name(self, object):
        """ Returns the target object and name for the column.
        Overridden here to return the trait name (which is the object's name trait) rather than the
        column's name trait.

        """
        name = object.name
        object = self.get_object(object)
        col = name.rfind('.')
        if col < 0:
            return (object, name)

        return (xgetattr(object, name[:col]), name[col + 1:])
示例#14
0
    def get_value(self, obj):
        """ Return the attribute value for the provided object.

        Parameters
        ----------
        obj : any
            The object that contains the data.

        Returns
        -------
        value : any
            The data value contained in the object's attribute.
        """
        return xgetattr(obj, self.attr)
示例#15
0
    def update_page_name ( self, object, name, old, new ):
        """ Handles the trait defining a particular page's name being changed.
        """
        for i, value in enumerate(self._uis):
            page, ui, _, _ = value
            if object is ui.info.object:
                name = None
                handler = getattr(self.ui.handler,
                        '%s_%s_page_name' % (self.object_name, self.name),
                        None)

                if handler is not None:
                    name = handler(self.ui.info, object)

                if name is None:
                    name = str(xgetattr(object, self.factory.page_name[1:], '???'))
                self.control.setTabText(self.control.indexOf(page), name)
                break
示例#16
0
    def update_page_name ( self, object, name, old, new ):
        """ Handles the trait defining a particular page's name being changed.
        """
        for i, value in enumerate(self._uis):
            page, ui, _, _ = value
            if object is ui.info.object:
                name = None
                handler = getattr(self.ui.handler,
                        '%s_%s_page_name' % (self.object_name, self.name),
                        None)

                if handler is not None:
                    name = handler(self.ui.info, object)

                if name is None:
                    name = str(xgetattr(object, self.factory.page_name[1:], '???'))
                self.control.setTabText(self.control.indexOf(page), name)
                break
示例#17
0
    def bind(self, binder, context):
        the_binder, binder_trait = self._normalize_binder_trait(
            binder, self.left, context)
        rhs = self.right.strip()
        ext_traits = find_ext_attrs(rhs)
        if ext_traits == [rhs]:
            # Simple case of one attribute.
            context_name, xattr = rhs.split('.', 1)
            context_obj = context[context_name]

            handler = _TraitModified(the_binder, binder_trait).handler
            # FIXME: Only check as far down as are HasTraits objects available.
            # We would like to be able to include references to methods on
            # attributes of HasTraits classes.
            # Unfortunately, a valid use case is where a leading object in
            # a true trait chain is None.
            context_obj.on_trait_change(handler, xattr)
            self.pull_handler_data = [(context_obj, handler, xattr)]
            # FIXME: do a better check for an event trait
            try:
                xsetattr(the_binder, binder_trait,
                         xgetattr(context_obj, xattr))
            except AttributeError as e:
                if 'event' not in str(e):
                    raise
        elif ext_traits == []:
            msg = "No traits found in expression: {0!r}".format(rhs)
            raise ValueError(msg)
        else:
            # Expression.
            self.pull_handler_data = []
            handler = _EvaluateExpression(the_binder, binder_trait,
                                          context, rhs).handler
            for ext_trait in ext_traits:
                context_name, xattr = ext_trait.split('.', 1)
                if context_name not in context:
                    # Assume it's a builtin.
                    continue
                context_obj = context[context_name]
                context_obj.on_trait_change(handler, xattr)
                self.pull_handler_data.append((context_obj, handler, xattr))
            # Call the handler once to evaluate and set the value initially.
            handler()
示例#18
0
    def bind(self, binder, context):
        the_binder, binder_trait = self._normalize_binder_trait(
            binder, self.left, context)
        rhs = self.right.strip()
        ext_traits = find_ext_attrs(rhs)
        if ext_traits == [rhs]:
            # Simple case of one attribute.
            context_name, xattr = rhs.split('.', 1)
            context_obj = context[context_name]

            handler = _TraitModified(the_binder, binder_trait).handler
            # FIXME: Only check as far down as are HasTraits objects available.
            # We would like to be able to include references to methods on
            # attributes of HasTraits classes.
            # Unfortunately, a valid use case is where a leading object in
            # a true trait chain is None.
            context_obj.on_trait_change(handler, xattr)
            self.pull_handler_data = [(context_obj, handler, xattr)]
            # FIXME: do a better check for an event trait
            try:
                xsetattr(the_binder, binder_trait,
                         xgetattr(context_obj, xattr))
            except AttributeError as e:
                if 'event' not in str(e):
                    raise
        elif ext_traits == []:
            msg = "No traits found in expression: {0!r}".format(rhs)
            raise ValueError(msg)
        else:
            # Expression.
            self.pull_handler_data = []
            handler = _EvaluateExpression(the_binder, binder_trait, context,
                                          rhs).handler
            for ext_trait in ext_traits:
                context_name, xattr = ext_trait.split('.', 1)
                if context_name not in context:
                    # Assume it's a builtin.
                    continue
                context_obj = context[context_name]
                context_obj.on_trait_change(handler, xattr)
                self.pull_handler_data.append((context_obj, handler, xattr))
            # Call the handler once to evaluate and set the value initially.
            handler()
示例#19
0
    def update_page_name ( self ):
        """ Handles the trait defining a particular page's name being changed.
        """
        changed = False
        for i, value in enumerate( self._uis ):
            dock_control, user_object, view_object, monitoring = value
            if dock_control.control is not None:
                name    = None
                handler = getattr( self.ui.handler, '%s_%s_page_name' %
                                   ( self.object_name, self.name ), None )
                if handler is not None:
                    name = handler( self.ui.info, user_object )

                if name is None:
                    name = unicode( xgetattr( view_object,
                                          self.factory.page_name[1:], u'???' ) )

                changed |= (dock_control.name != name)
                dock_control.name = name

        if changed:
            self.update_layout()
示例#20
0
    def _create_page(self, object):
        # Create the view for the object:
        view_object = object
        factory = self.factory
        if factory.factory is not None:
            view_object = factory.factory(object)
        ui = view_object.edit_traits(parent=self.control,
                                     view=factory.view,
                                     kind=factory.ui_kind).set(parent=self.ui)

        # Get the name of the page being added to the notebook:
        name = ''
        monitoring = False
        prefix = '%s_%s_page_' % (self.object_name, self.name)
        page_name = factory.page_name
        if page_name[0:1] == '.':
            name = xgetattr(view_object, page_name[1:], None)
            monitoring = (name is not None)
            if monitoring:
                handler_name = None
                method = getattr(self.ui.handler, prefix + 'name', None)
                if method is not None:
                    handler_name = method(self.ui.info, object)
                if handler_name is not None:
                    name = handler_name
                else:
                    name = str(name) or '???'
                view_object.on_trait_change(self.update_page_name,
                                            page_name[1:],
                                            dispatch='ui')
            else:
                name = ''
        elif page_name != '':
            name = page_name

        if name == '':
            name = user_name_for(view_object.__class__.__name__)

        # Make sure the name is not a duplicate:
        if not monitoring:
            self._pages[name] = count = self._pages.get(name, 0) + 1
            if count > 1:
                name += (' %d' % count)

        # Return the control for the ui, and whether or not its name is being
        # monitored:
        image = None
        method = getattr(self.ui.handler, prefix + 'image', None)
        if method is not None:
            image = method(self.ui.info, object)

        if image is None:
            self.control.addTab(ui.control, name)
        else:
            self.control.addTab(ui.control, image, name)

        if self.factory.show_notebook_menu:
            newaction = self._context_menu.addAction(name)
            newaction.setText(name)
            newaction.setCheckable(True)
            newaction.setChecked(True)
            newaction.triggered.connect(
                lambda e, name=name: self._menu_action(e, name=name))
            self._action_dict[name] = newaction
            self._pagewidgets[name] = ui.control

        return (ui, view_object, monitoring)
示例#21
0
 def get_value(self, obj):
     return xgetattr(obj, self.value, None)
示例#22
0
 def set_value(self, obj, value):
     data = xgetattr(obj, self.value, None)
     data[self.key] = value
示例#23
0
 def get_value(self, obj):
     data = xgetattr(obj, self.value, None)
     return data.get(self.key, None)
示例#24
0
文件: gensim.py 项目: Python3pkg/PAME
    def runsim(self):
        """ Increments, updates all results.  Thre primary storage objects:

        staticdict --> Traits that are no altered in simulation.  
           Includes simulation inputs, spectral parameters and fiber/strata
           parameters.  In future version, could relax these if needed
           to simulation over a fiber parameter like core size.

        primarydict --> Results that are to be promoted to top level.  
            Simparaser will try to show these as a panel.

        resultsdict ---> Deep, nested results of layer and optical stack.  For 
            example, could access full optical stack on third increment via:
                 resultsdict['step3']['optics']['opticalstack'] 
            or a selected material:
                 resultsdict['step5']['selectedlayer']['material1']['fullmie']
            etc...
            Simparser should have methods to make these data more accessible.

        """

        print('running sim with traits', list(self.simulation_traits.keys()))

        # for name brevity
        sconfig = self.configure_storage
        b_app = self.base_app

        # Storage
        primarydict = OrderedDict(
        )  #<-- Keyed by increment, becomes primary panel!
        resultsdict = OrderedDict(
        )  #<-- Keyed by increment, stores deep results, stays as dict

        # Traits not involved in simulation.  For this sim, includes spectral parameters, fiber/strata params
        # at simulation inputs.  Later sims may want to simulate over fiber traits (ie fiber diameter changes)
        # so would migrate these into resultsdict instead
        staticdict = OrderedDict()
        staticdict['Layers in Slab'] = len(b_app.stack)
        staticdict[
            globalparms.
            spectralparameters] = b_app.specparms.simulation_requested()
        staticdict[
            globalparms.strataname] = b_app.fiberparms.simulation_requested()

        # Begin iterations
        sorted_keys = []
        for i in range(self.inc):
            for trait in list(self.simulation_traits.keys()):
                _true_trait = self._trait_namemap[
                    trait]  #<--- Trait stored in memory (ie b_app.layereditor.layer1...)
                xsetattr(b_app, _true_trait, self.simulation_traits[trait]
                         [i])  #Object, traitname, traitvalue

            stepname = 'step_%s' % i

            primary_increment = OrderedDict(
            )  #<--- Toplevel/Summary of just this increment (becomes dataframe)
            results_increment = OrderedDict(
            )  #<--- Deep results of just thsi increment (ie selected_material/layer etc..)

            key = '%s_%s' % (str(i), self.key_title)
            sorted_keys.append(key)

            # Update Optical Stack
            b_app.opticstate.update_optical_stack()

            # Flatten sim attributes.  For example, if attrs selected for Sim are R, A, kz
            # kz actually has value in each layer so R, A, kz_1, kz_2, kz_3 is what needs
            # to be iterated over.
            flat_attributes = []

            # How many layers in optical stack
            layer_indicies = list(range(len(
                b_app.opticstate.ns)))  #0,1,2,3,4 for 5 layers etc...

            for attr in sconfig.choose_optics:
                if attr in b_app.opticstate.optical_stack.minor_axis:
                    flat_attributes.append(attr)
                else:
                    # http://stackoverflow.com/questions/28031354/match-the-pattern-at-the-end-of-a-string
                    delim = '_%s' % globalparms._flat_suffix

                    # ['kz', 'vn', 'ang_prop']
                    setkeys = set(
                        name.split(delim)[0]
                        for name in b_app.opticstate.optical_stack.minor_axis
                        if delim in name)
                    if attr in setkeys:
                        for idx in layer_indicies:
                            flat_attributes.append(attr + delim +
                                                   str(idx))  #kz_L1 etc...)
                    else:
                        raise SimError(
                            'Cannot simulate over optical stack attr "%s" '
                            ' not found in optical stack.' % attr)

            # --- PRIMARY RESULTS
            # Take parameters from optical stack, put in toplevel via sconfig.choose_optics
            if sconfig.averaging in ['Average', 'Both']:
                for optical_attr in flat_attributes:
                    primary_increment['%s_%s' % (optical_attr, 'avg')] = \
                        b_app.opticstate.compute_average(optical_attr) #<-- IS NUMPY ARRAY, object type

            if sconfig.averaging in ['Not Averaged', 'Both']:
                for optical_attr in flat_attributes:
                    # ITERATE OVER ANGLES! SAVE EACH ANGLE
                    for angle in b_app.opticstate.angles:
                        primary_increment['%s_%.2f' % (optical_attr, angle)] = \
                            b_app.opticstate.optical_stack[angle][optical_attr]  #<-- Save as what, numpy/pandas?

            # User-set dielectric slab quantites to be in primary
            for trait in sconfig.additional_list:
                traitval = xgetattr(b_app.layereditor, trait)
                primary_increment['%s' % trait] = traitval

            # --- DEEP RESULTS
            # Store full Optical Stack
            if sconfig.store_optical_stack:
                results_increment[
                    globalparms.optresponse] = b_app.opticstate.optical_stack

            # Save layer/material traits.  If None selected, it just skips
            if sconfig.choose_layers == 'Selected Layer':
                key = 'Layer%s' % (b_app.layereditor.selected_index
                                   )  #<-- index of selected layer
                results_increment[
                    key] = self.selected_layer.simulation_requested()

            elif sconfig.choose_layers == 'All Layers':
                materials_only = False
                if sconfig.mater_only == 'Material Data':
                    materials_only = True

                results_increment[
                    'dielectric_layers'] = b_app.layereditor.simulation_requested(
                        materials_only)

            # resultsdict >>  {step1 : {results_of_increment}, ...}
            resultsdict[stepname] = results_increment
            primarydict[stepname] = primary_increment

            print("Iteration\t", i + 1, "\t of \t", self.inc, "\t completed")

        # SET STORAGE TRAITS
        self.primary = primarydict
        self.results = resultsdict
        self.static = staticdict

        # Prompt user to save?
        popup = BasicDialog(
            message='Simulation complete.  Would you like to save now?')
        ui = popup.edit_traits(kind='modal')
        if ui.result == True:
            self.save(confirmwindow=True)
示例#25
0
文件: gensim.py 项目: Python3pkg/PAME
    def check_sim_ready(self):
        """Method to update various storage mechanisms for holding trait values for simulations.  
        Takes user data in table editor and stores it in necessary dictionaries so that 
        traits can be set and things automatically.  Decided to use this over a system
        properties because the properties were conflicting with delegation and other stuff.
        """
        sim_traits = {}
        originals = {}
        missing = []
        status_message = ''

        # Retain a mapping between shortnames (layer1.material) and attr path
        # from base_app (layereditor.layer1) etc...
        _trait_name_map = dict(
            (s.trait_name, s.trait_name_full) for s in self.sim_variables)

        for obj in self.sim_variables:
            obj.inc = self.inc  #Ensures proper increments whether adding new objects to the table or just changing global inc

        for obj in self.sim_variables:
            sim_traits[str(
                obj.trait_name)] = obj.trait_array  #Simulation traits
            #^^^ Remove unicode

        for key in list(sim_traits.keys()):
            _true_trait_val = _trait_name_map[key]
            try:
                originals[key] = xgetattr(
                    self.base_app, _true_trait_val
                )  #If trait found, store its original values
            except (AttributeError, StackError):
                missing.append(key)  #If not, put it in missing

        ready = True

        # Are traits missing?
        if len(missing) > 0:
            status_message = '<font color="red"> Could not find required input: </font>'
            status_message += ', '.join(missing)
            ready = False

        # Did user select duplicates of trait names
        trait_names = [obj.trait_name for obj in self.sim_variables]
        duplicates = set(
            [name for name in trait_names if trait_names.count(name) > 1])
        if duplicates:
            status_message = '<font color="red"> Duplicate simulation input(s) found: </font>'
            for trait in duplicates:
                status_message += trait + ',  '
            ready = False

        if ready:
            status_message = '<font color="green"> Simulation ready: all input found</font>'
            ready = True

        self.ready = ready
        self.status_message = status_message.rstrip(
            ',')  #<-- trialling commas for list of one element string
        self.simulation_traits = sim_traits  # Remove unicode
        self.missing_traits = missing
        self.original_values = originals

        self._trait_namemap = _trait_name_map
示例#26
0
    def _create_page(self, object):
        # Create the view for the object:
        view_object = object
        factory = self.factory
        if factory.factory is not None:
            view_object = factory.factory(object)
        ui = view_object.edit_traits(parent=self.control,
                                     view=factory.view,
                                     kind=factory.ui_kind).trait_set(
            parent=self.ui)

        # Get the name of the page being added to the notebook:
        name = ''
        monitoring = False
        prefix = '%s_%s_page_' % (self.object_name, self.name)
        page_name = factory.page_name
        if page_name[0:1] == '.':
            name = xgetattr(view_object, page_name[1:], None)
            monitoring = (name is not None)
            if monitoring:
                handler_name = None
                method = getattr(self.ui.handler, prefix + 'name', None)
                if method is not None:
                    handler_name = method(self.ui.info, object)
                if handler_name is not None:
                    name = handler_name
                else:
                    name = str(name) or '???'
                view_object.on_trait_change(self.update_page_name,
                                            page_name[1:], dispatch='ui')
            else:
                name = ''
        elif page_name != '':
            name = page_name

        if name == '':
            name = user_name_for(view_object.__class__.__name__)

        # Make sure the name is not a duplicate:
        if not monitoring:
            self._pages[name] = count = self._pages.get(name, 0) + 1
            if count > 1:
                name += (' %d' % count)

        # Return the control for the ui, and whether or not its name is being
        # monitored:
        image = None
        method = getattr(self.ui.handler, prefix + 'image', None)
        if method is not None:
            image = method(self.ui.info, object)

        if image is None:
            self.control.addTab(ui.control, name)
        else:
            self.control.addTab(ui.control, image, name)

        if self.factory.show_notebook_menu:
            newaction = self._context_menu.addAction(name)
            newaction.setText(name)
            newaction.setCheckable(True)
            newaction.setChecked(True)
            newaction.triggered.connect(
                lambda e, name=name: self._menu_action(
                    e, name=name))
            self._action_dict[name] = newaction
            self._pagewidgets[name] = ui.control

        return (ui, view_object, monitoring)
示例#27
0
文件: gensim.py 项目: hugadams/PAME
    def runsim(self): 
        """ Increments, updates all results.  Thre primary storage objects:

        staticdict --> Traits that are no altered in simulation.  
           Includes simulation inputs, spectral parameters and fiber/strata
           parameters.  In future version, could relax these if needed
           to simulation over a fiber parameter like core size.

        primarydict --> Results that are to be promoted to top level.  
            Simparaser will try to show these as a panel.

        resultsdict ---> Deep, nested results of layer and optical stack.  For 
            example, could access full optical stack on third increment via:
                 resultsdict['step3']['optics']['opticalstack'] 
            or a selected material:
                 resultsdict['step5']['selectedlayer']['material1']['fullmie']
            etc...
            Simparser should have methods to make these data more accessible.

        """

        print 'running sim with traits', self.simulation_traits.keys()

        # for name brevity
        sconfig = self.configure_storage 
        b_app = self.base_app

        # Storage
        primarydict = OrderedDict()   #<-- Keyed by increment, becomes primary panel!
        resultsdict = OrderedDict()   #<-- Keyed by increment, stores deep results, stays as dict

        # Traits not involved in simulation.  For this sim, includes spectral parameters, fiber/strata params
        # at simulation inputs.  Later sims may want to simulate over fiber traits (ie fiber diameter changes)
        # so would migrate these into resultsdict instead
        staticdict = OrderedDict()
        staticdict['Layers in Slab'] = len(b_app.stack)
        staticdict[globalparms.spectralparameters] = b_app.specparms.simulation_requested()         
        staticdict[globalparms.strataname] = b_app.fiberparms.simulation_requested()

        # Begin iterations
        sorted_keys = []
        for i in range(self.inc):
            for trait in self.simulation_traits.keys():
                _true_trait = self._trait_namemap[trait]#<--- Trait stored in memory (ie b_app.layereditor.layer1...)
                xsetattr(b_app, _true_trait, self.simulation_traits[trait][i]) #Object, traitname, traitvalue

            stepname = 'step_%s' % i

            primary_increment = OrderedDict()  #<--- Toplevel/Summary of just this increment (becomes dataframe)
            results_increment = OrderedDict()  #<--- Deep results of just thsi increment (ie selected_material/layer etc..)

            key = '%s_%s' % (str(i), self.key_title)
            sorted_keys.append(key)

            # Update Optical Stack
            b_app.opticstate.update_optical_stack() 

            # Flatten sim attributes.  For example, if attrs selected for Sim are R, A, kz
            # kz actually has value in each layer so R, A, kz_1, kz_2, kz_3 is what needs
            # to be iterated over.
            flat_attributes = []

            # How many layers in optical stack
            layer_indicies = range(len(b_app.opticstate.ns)) #0,1,2,3,4 for 5 layers etc...            

            for attr in sconfig.choose_optics:
                if attr in b_app.opticstate.optical_stack.minor_axis:
                    flat_attributes.append(attr)
                else:
                    # http://stackoverflow.com/questions/28031354/match-the-pattern-at-the-end-of-a-string
                    delim = '_%s' % globalparms._flat_suffix

                    # ['kz', 'vn', 'ang_prop']
                    setkeys = set(name.split(delim)[0] for name in 
                                  b_app.opticstate.optical_stack.minor_axis if delim in name)    
                    if attr in setkeys:
                        for idx in layer_indicies:
                            flat_attributes.append(attr + delim + str(idx)) #kz_L1 etc...)                   
                    else:
                        raise SimError('Cannot simulate over optical stack attr "%s" '
                                       ' not found in optical stack.' % attr)

            # --- PRIMARY RESULTS           
            # Take parameters from optical stack, put in toplevel via sconfig.choose_optics
            if sconfig.averaging in ['Average','Both']:
                for optical_attr in flat_attributes:
                    primary_increment['%s_%s' % (optical_attr, 'avg')] = \
                        b_app.opticstate.compute_average(optical_attr) #<-- IS NUMPY ARRAY, object type

            if sconfig.averaging in ['Not Averaged', 'Both']:
                for optical_attr in flat_attributes:
                    # ITERATE OVER ANGLES! SAVE EACH ANGLE
                    for angle in b_app.opticstate.angles:
                        primary_increment['%s_%.2f' % (optical_attr, angle)] = \
                            b_app.opticstate.optical_stack[angle][optical_attr]  #<-- Save as what, numpy/pandas?        

            # User-set dielectric slab quantites to be in primary
            for trait in sconfig.additional_list:
                traitval = xgetattr(b_app.layereditor, trait)
                primary_increment['%s' % trait]  = traitval

            # --- DEEP RESULTS
            # Store full Optical Stack
            if sconfig.store_optical_stack:
                results_increment[globalparms.optresponse] = b_app.opticstate.optical_stack

            # Save layer/material traits.  If None selected, it just skips
            if sconfig.choose_layers == 'Selected Layer':
                key = 'Layer%s' % (b_app.layereditor.selected_index) #<-- index of selected layer
                results_increment[key] = self.selected_layer.simulation_requested()

            elif sconfig.choose_layers == 'All Layers':
                materials_only = False
                if sconfig.mater_only == 'Material Data':
                    materials_only = True
                    
                results_increment['dielectric_layers'] = b_app.layereditor.simulation_requested(materials_only)


            # resultsdict >>  {step1 : {results_of_increment}, ...}
            resultsdict[stepname] = results_increment               
            primarydict[stepname] = primary_increment

            print "Iteration\t", i+1, "\t of \t", self.inc, "\t completed"

        # SET STORAGE TRAITS
        self.primary = primarydict
        self.results = resultsdict
        self.static = staticdict        

        # Prompt user to save?
        popup = BasicDialog(message='Simulation complete.  Would you like to save now?')
        ui = popup.edit_traits(kind='modal')
        if ui.result == True:
            self.save(confirmwindow=True)
示例#28
0
    def sync_value(
        self,
        user_name,
        editor_name,
        mode="both",
        is_list=False,
        is_event=False,
    ):
        """ Synchronize an editor trait and a user object trait.

        Also sets the initial value of the editor trait from the
        user object trait (for modes 'from' and 'both'), and the initial
        value of the user object trait from the editor trait (for mode
        'to'), as long as the relevant traits are not events.

        Parameters
        ----------
        user_name : str
            The name of the trait to be used on the user object. If empty, no
            synchronization will be set up.
        editor_name : str
            The name of the relevant editor trait.
        mode : str, optional; one of 'to', 'from' or 'both'
            The direction of synchronization. 'from' means that trait changes
            in the user object should be propagated to the editor. 'to' means
            that trait changes in the editor should be propagated to the user
            object. 'both' means changes should be propagated in both
            directions. The default is 'both'.
        is_list : bool, optional
            If true, synchronization for item events will be set up in
            addition to the synchronization for the object itself.
            The default is False.
        is_event : bool, optional
            If true, this method won't attempt to initialize the user
            object or editor trait values. The default is False.
        """
        if user_name == "":
            return

        key = "%s:%s" % (user_name, editor_name)

        parts = user_name.split(".")
        if len(parts) == 1:
            user_object = self.context_object
            xuser_name = user_name
        else:
            user_object = self.ui.context[parts[0]]
            xuser_name = ".".join(parts[1:])
            user_name = parts[-1]

        if mode in {"from", "both"}:
            self._bind_from(key, user_object, xuser_name, editor_name, is_list)

            if not is_event:
                # initialize editor value from user value
                with self.raise_to_debug():
                    user_value = xgetattr(user_object, xuser_name)
                    setattr(self, editor_name, user_value)

        if mode in {"to", "both"}:
            self._bind_to(key, user_object, xuser_name, editor_name, is_list)

            if mode == "to" and not is_event:
                # initialize user value from editor value
                with self.raise_to_debug():
                    editor_value = xgetattr(self, editor_name)
                    xsetattr(user_object, xuser_name, editor_value)
示例#29
0
 def editor_list_modified(event):
     if key not in self._no_trait_update:
         with self.no_trait_update(key), self.raise_to_debug():
             n = event.index
             value = xgetattr(user_object, xuser_name)
             value[n:n + len(event.removed)] = event.added
示例#30
0
    def _create_page ( self, object ):
        """ Creates a DockControl for a specified object.
        """
        # Create the view for the object:
        view_object = object
        factory     = self.factory
        if factory.factory is not None:
            view_object = factory.factory( object )

        ui = view_object.edit_traits( parent = self.control,
                                      view   = factory.view,
                                      kind   = factory.ui_kind ).set(
                                      parent = self.ui )

        # Get the name of the page being added to the notebook:
        name       = ''
        monitoring = False
        prefix     = '%s_%s_page_' % ( self.object_name, self.name )
        page_name  = self.factory.page_name
        if page_name[0:1] == '.':
            name       = xgetattr( view_object, page_name[1:], None )
            monitoring = (name is not None)
            if monitoring:
                handler_name = None
                method       = getattr( self.ui.handler, prefix + 'name', None )
                if method is not None:
                    handler_name = method( self.ui.info, object )
                if handler_name is not None:
                    name = handler_name
                else:
                    name = unicode( name ) or u'???'
                view_object.on_trait_change( self.update_page_name,
                                             page_name[1:], dispatch = 'ui' )
            else:
                name = ''
        elif page_name != '':
            name = page_name

        if name == '':
            name = user_name_for( view_object.__class__.__name__ )

        # Make sure the name is not a duplicate:
        if not monitoring:
            self._pages[ name ] = count = self._pages.get( name, 0 ) + 1
            if count > 1:
                name += (' %d' % count)

        # Return a new DockControl for the ui, and whether or not its name is
        # being monitored:
        image   = None
        method  = getattr( self.ui.handler, prefix + 'image', None )
        if method is not None:
            image = method( self.ui.info, object )
        dock_control = DockControl( control   = ui.control,
                                    id        = str( id( ui.control ) ),
                                    name      = name,
                                    style     = factory.dock_style,
                                    image     = image,
                                    export    = factory.export,
                                    closeable = factory.deletable,
                                    dockable  = DockableListElement(
                                                    ui     = ui,
                                                    editor = self ) )
        return ( dock_control, view_object, monitoring )
示例#31
0
    def _create_page(self, object):
        """ Creates a DockControl for a specified object.
        """
        # Create the view for the object:
        view_object = object
        factory = self.factory
        if factory.factory is not None:
            view_object = factory.factory(object)

        ui = view_object.edit_traits(parent=self.control,
                                     view=factory.view,
                                     kind=factory.ui_kind).set(parent=self.ui)

        # Get the name of the page being added to the notebook:
        name = ''
        monitoring = False
        prefix = '%s_%s_page_' % (self.object_name, self.name)
        page_name = self.factory.page_name
        if page_name[0:1] == '.':
            name = xgetattr(view_object, page_name[1:], None)
            monitoring = (name is not None)
            if monitoring:
                handler_name = None
                method = getattr(self.ui.handler, prefix + 'name', None)
                if method is not None:
                    handler_name = method(self.ui.info, object)
                if handler_name is not None:
                    name = handler_name
                else:
                    name = unicode(name) or u'???'
                view_object.on_trait_change(self.update_page_name,
                                            page_name[1:],
                                            dispatch='ui')
            else:
                name = ''
        elif page_name != '':
            name = page_name

        if name == '':
            name = user_name_for(view_object.__class__.__name__)

        # Make sure the name is not a duplicate:
        if not monitoring:
            self._pages[name] = count = self._pages.get(name, 0) + 1
            if count > 1:
                name += (' %d' % count)

        # Return a new DockControl for the ui, and whether or not its name is
        # being monitored:
        image = None
        method = getattr(self.ui.handler, prefix + 'image', None)
        if method is not None:
            image = method(self.ui.info, object)
        dock_control = DockControl(control=ui.control,
                                   id=str(id(ui.control)),
                                   name=name,
                                   style=factory.dock_style,
                                   image=image,
                                   export=factory.export,
                                   closeable=factory.deletable,
                                   dockable=DockableListElement(ui=ui,
                                                                editor=self))
        return (dock_control, view_object, monitoring)