Ejemplo n.º 1
0
 def handler(self, new):
     if not self._in_handler:
         self._in_handler = True
         try:
             xsetattr(self.obj, self.xattr, new)
         finally:
             self._in_handler = False
Ejemplo n.º 2
0
 def handler(self, new):
     if not self._in_handler:
         self._in_handler = True
         try:
             xsetattr(self.obj, self.xattr, new)
         finally:
             self._in_handler = False
Ejemplo n.º 3
0
 def restore_original_values(self):
     """ Restore all traits to original values """
     for trait in self.simulation_traits:
         xsetattr(
             self.base_app,
             self._trait_namemap[trait],  #<--- Use actual variable name
             self.original_values[trait])
Ejemplo n.º 4
0
 def handler(self):
     if not self._in_handler:
         self._in_handler = True
         try:
             value = eval(self.expression, self.context)
             xsetattr(self.obj, self.xattr, value)
         finally:
             self._in_handler = False
Ejemplo n.º 5
0
 def handler(self):
     if not self._in_handler:
         self._in_handler = True
         try:
             value = eval(self.expression, self.context)
             xsetattr(self.obj, self.xattr, value)
         finally:
             self._in_handler = False
Ejemplo n.º 6
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()
Ejemplo n.º 7
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()
Ejemplo n.º 8
0
 def bind(self, binder, context):
     expression = self.right
     the_binder, binder_trait = self._normalize_binder_trait(
         binder, self.left, context)
     value = eval(expression, context)
     xsetattr(the_binder, binder_trait, value)
Ejemplo n.º 9
0
 def bind(self, binder, context):
     the_binder, binder_trait = self._normalize_binder_trait(
         binder, self.left, context)
     value = self.right()
     xsetattr(the_binder, binder_trait, value)
Ejemplo n.º 10
0
 def editor_trait_modified(new):
     if key not in self._no_trait_update:
         with self.no_trait_update(key), self.raise_to_debug():
             xsetattr(user_object, xuser_name, new)
Ejemplo n.º 11
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)
Ejemplo n.º 12
0
    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)
Ejemplo n.º 13
0
 def bind(self, binder, context):
     expression = self.right
     the_binder, binder_trait = self._normalize_binder_trait(
         binder, self.left, context)
     value = eval(expression, context)
     xsetattr(the_binder, binder_trait, value)
Ejemplo n.º 14
0
 def bind(self, binder, context):
     the_binder, binder_trait = self._normalize_binder_trait(
         binder, self.left, context)
     value = self.right()
     xsetattr(the_binder, binder_trait, value)
Ejemplo n.º 15
0
    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)
Ejemplo n.º 16
0
 def set_value(self, obj, value):
     if not self.can_set_value(obj):
         raise DataViewSetError(
             "Attribute is not specified for {!r}".format(self))
     xsetattr(obj, self.attr, value)
Ejemplo n.º 17
0
 def set_value(self, obj, value):
     if not self.value:
         return
     xsetattr(obj, self.value, value)
Ejemplo n.º 18
0
 def restore_original_values(self): 
     """ Restore all traits to original values """
     for trait in self.simulation_traits:
         xsetattr(self.base_app, 
                  self._trait_namemap[trait], #<--- Use actual variable name
                  self.original_values[trait])