def _register_control_signal_type(self, context=None): from psyneulink.core.globals.registry import register_category from psyneulink.core.components.ports.port import Port_Base # Create registry for GatingSignals (to manage names) register_category(entry=GatingSignal, base_class=Port_Base, registry=self._portRegistry, context=context)
def __deepcopy__(self, memo): new = super().__deepcopy__(memo) # ensure copy does not have identical name register_category(new, Function_Base, new.name, FunctionRegistry) try: # HACK: Make sure any copies are re-seeded to avoid dependent RNG. new.random_state.seed([get_global_seed()]) except: pass return new
def __init__(self, default_variable, params, function=None, owner=None, name=None, prefs=None, context=None): """Assign category-level preferences, register category, and call super.__init__ Initialization arguments: - default_variable (anything): establishes type for the variable, used for validation - params_default (dict): assigned as paramInstanceDefaults Note: if parameter_validation is off, validation is suppressed (for efficiency) (Function class default = on) :param default_variable: (anything but a dict) - value to assign as self.defaults.variable :param params: (dict) - params to be assigned to paramInstanceDefaults :param log: (ComponentLog enum) - log entry types set in self.componentLog :param name: (string) - optional, overrides assignment of default (componentName of subclass) :return: """ if context != ContextFlags.CONSTRUCTOR: raise FunctionError( "Direct call to abstract class Function() is not allowed; use a Function subclass" ) if self.context.initialization_status == ContextFlags.DEFERRED_INIT: self._assign_deferred_init_name(name, context) self.init_args[NAME] = name return self._output_type = None self.enable_output_type_conversion = False register_category(entry=self, base_class=Function_Base, registry=FunctionRegistry, name=name, context=context) self.owner = owner super().__init__(default_variable=default_variable, function=function, param_defaults=params, name=name, prefs=prefs)
def __init__(self, pathway: list, name=None, **kwargs): context = kwargs.pop(CONTEXT, None) # Get composition arg (if specified) self.composition = None self.composition = kwargs.pop('composition', None) # composition arg not allowed from command line if self.composition and context.source == ContextFlags.COMMAND_LINE: raise CompositionError( f"'composition' can not be specified as an arg in the constructor for a " f"{self.__class__.__name__}; it is assigned when the {self.__class__.__name__} " f"is added to a {Composition.__name__}.") # composition arg must be a Composition if self.composition: assert isinstance(self.composition, Composition), \ f"'composition' arg of constructor for {self.__class__.__name__} must be a {Composition.__name__}." # There should be no other arguments in constructor if kwargs: raise CompositionError( f"Illegal argument(s) used in constructor for {self.__class__.__name__}: " f"{', '.join(list(kwargs.keys()))}.") # Register and get name # - if called from command line, being used as a template, so don't register if context.source == ContextFlags.COMMAND_LINE: # But do pass through name so that it can be used to construct the instance that will be used self.name = name else: # register and set name register_category(entry=self, base_class=Pathway, registry=PathwayRegistry, name=name) # Initialize attributes self.pathway = pathway if self.composition: self.learning_components = {} self.roles = set() else: self.learning_components = None self.roles = None
def __init__( self, default_variable, params, owner=None, name=None, prefs=None, context=None, **kwargs ): """Assign category-level preferences, register category, and call super.__init__ Initialization arguments: - default_variable (anything): establishes type for the variable, used for validation Note: if parameter_validation is off, validation is suppressed (for efficiency) (Function class default = on) :param default_variable: (anything but a dict) - value to assign as self.defaults.variable :param params: (dict) - params to be assigned as instance defaults :param log: (ComponentLog enum) - log entry types set in self.componentLog :param name: (string) - optional, overrides assignment of default (componentName of subclass) :return: """ if self.initialization_status == ContextFlags.DEFERRED_INIT: self._assign_deferred_init_name(name) self._init_args[NAME] = name return register_category(entry=self, base_class=Function_Base, registry=FunctionRegistry, name=name, ) self.owner = owner super().__init__( default_variable=default_variable, param_defaults=params, name=name, prefs=prefs, **kwargs )
self.error_value = error_value def __str__(self): return repr(self.error_value) #region ***************************************** MECHANISM SUBCLASSES ************************************************* from psyneulink.core.components.mechanisms.mechanism import MechanismRegistry from psyneulink.core.components.mechanisms.mechanism import Mechanism_Base from psyneulink.core.components.mechanisms.processing.defaultprocessingmechanism \ import DefaultProcessingMechanism_Base from psyneulink.core.components.mechanisms.modulatory.control.controlmechanism \ import ControlMechanism register_category(entry=ControlMechanism, base_class=Mechanism_Base, registry=MechanismRegistry, context=kwInitPy) from psyneulink.core.components.mechanisms.modulatory.control.defaultcontrolmechanism \ import DefaultControlMechanism register_category(entry=DefaultControlMechanism, base_class=Mechanism_Base, registry=MechanismRegistry, context=kwInitPy) # DDM (used as DefaultMechanism) from psyneulink.library.components.mechanisms.processing.integrator.ddm import DDM register_category(entry=DDM, base_class=Mechanism_Base, registry=MechanismRegistry,
def __init__(self, owner, level=PreferenceLevel.COMPOSITION, prefs=None, name=None, context=None): """Instantiate PreferenceSet from subclass for object and/or class -------------------------- CONDITIONS AND ACTIONS:---------------------------------------------------- Condition Type classPref's exist prefs arg Action 1 class YES NO assign self to classPreferences 2 class YES dict override classPreferences with any prefs 3 class NO NO instantiate ClassPreferences from <subclass>.defaultPrefs 4 class NO dict instantiate ClassPrefs from defaultPrefs, override w/ prefs 5 object YES NO use classPreferences 6 object YES dict use classPreferences as base; override with any prefs 6.5 object YES (dict) NO instantiate ClassPrefs from defaultPrefs, override w/ dict 7 object NO NO |_| raise exception: these should never occur as instantiation 8 object NO dict | | of object should force instantiation of classPreferences # 7 object NO NO instantiate and use classPreferences from defaultPrefs # 8 object NO dict inst. & use classPrefs from defaultPrefs, override w/ prefs ------------------------------------------------------------------------------------------------------- :param owner: :param level: :param prefs: :param name: :param context: """ # VALIDATE ATTRIBUTES AND ARGS # Make sure subclass implements a baseClass class attribute and that owner is a subclass or instance of it try: base_class_NOT_A_CLASS = not inspect.isclass(self.baseClass) except: raise PreferenceSetError( "{0} must implement baseClass as a class attribute".format( self.__class__.__name__)) else: if base_class_NOT_A_CLASS: raise PreferenceSetError( "{0}.baseClass ({0}) must be a class".format( self.__class__.__name__, self.baseClass)) else: # owner of PreferenceSet must be a subclass or instance of a subclass in baseClass if not (inspect.isclass(owner) or isinstance(owner, self.baseClass)) or owner is None: raise PreferenceSetError( "owner argument must be included in call to {1}() " "and must be an object in the {2} class hierarchy". format(owner, self.__class__.__name__, self.baseClass.__name__)) self.owner = owner # Make sure subclass implements a defaultPreferencesDict class attribute try: default_prefs_dict = self.defaultPreferencesDict except AttributeError: raise PreferenceSetError( "{0} must implement defaultPreferencesDict dict as a class attribute" .format(self.__class__.__name__)) # prefs must be a specification dict or None # FIX: replace with typecheck if not (isinstance(prefs, dict) or prefs is None): raise PreferenceSetError( "Preferences ({0}) specified for {1} must a PreferenceSet or" " specification dict of preferences".format(prefs, owner.name)) # ASSIGN NAME # ****** FIX: 9/10/16: MOVE TO REGISTRY ********** # FIX: MAKE SURE DEFAULT NAMING SCHEME WORKS WITH CLASSES - 5/30/16 # FIX: INTEGRATE WITH NAME FROM PREFERENCE_SET_NAME ENTRY IN DICT BELOW - 5/30/16 if not name: # Assign name of preference set class as base of name name = self.__class__.__name__ # If it belongs to a class, append name of owner's class to name if inspect.isclass(owner): name = name + 'DefaultsFor' + owner.__name__ # Otherwise, it belongs to an object, so append name of the owner object's class to name else: name = name + 'Defaultsfor' + owner.__class__.__name__ # REGISTER # FIX: MAKE SURE THIS MAKES SENSE from psyneulink.core.globals.registry import register_category register_category(entry=self, base_class=PreferenceSet, name=name, registry=PreferenceSetRegistry, context=context) # ASSIGN PREFS condition = 0 # Get class preferences (if any) from owner's class try: class_prefs = owner.classPreferences except AttributeError: class_prefs = None else: # Class preferences must be a PreferenceSet or a dict if not (isinstance(class_prefs, (PreferenceSet, dict))): raise PreferenceSetError( "Class preferences for {0} ({1}) must be a PreferenceSet " "or specification dict for one".format( owner.__name__, class_prefs)) # Owner is a class if inspect.isclass(owner): # Class PreferenceSet already exists if isinstance(class_prefs, PreferenceSet): self = class_prefs if prefs is None: # Condition 1 # No prefs arg, so just assign self to class_prefs condition = 1 else: # Condition 2 # Get pref from prefs arg or, if not there, from class_prefs #FIX: SHOULD TEST FOR *prefsList* ABOVE AND GENERATE IF IT IS NOT THERE, THEN REMOVE TWO SETS OF CODE BELOW THAT DO IT try: self.prefsList except AttributeError: # Generate prefsList for PreferenceSet (since it was not generated when it was created self.prefsList = [ i for i in list(class_prefs.__dict__.keys()) if '_pref' in i ] for pref_key in self.prefsList: class_pref_entry = getattr(class_prefs, pref_key) try: # Get pref from prefs arg; use class_prefs as validation/default self.set_preference(candidate_info=prefs[pref_key], default_entry=class_pref_entry, pref_ivar_name=pref_key) except (KeyError): # No need for default_entry here, as class prefs exist and were validated when instantiated self.set_preference( candidate_info=class_pref_entry, default_entry=default_prefs_dict[ pref_key], # IMPLEMENTATION: FILLER pref_ivar_name=pref_key) condition = 2 # Class preferences either don't exist, or are coming from a specification dict in the class declaration, # so use <subclass>.defaultPreferencesDict to instantiate full set, and create PrefsList else: self.prefsList = [] if isinstance(class_prefs, dict): # class_prefs are a specification dict from the class declaration # - if prefs are present and are the default set (e.g., in instantiation call from __init__.py), # replace with class_prefs dict since default_prefs_dict will be used below as base set anyhow) # - if prefs are not the default set, merge with class_prefs dict, giving precedence to prefs # since they were in a script from the user if prefs is default_prefs_dict: prefs = class_prefs else: prefs.update(class_prefs) for pref_key in default_prefs_dict: if pref_key == PREFERENCE_SET_NAME: continue try: # Get pref from prefs arg; # Condition 4 # use default_prefs_dict for validation and backup self.set_preference( candidate_info=prefs[pref_key], default_entry=default_prefs_dict[pref_key], pref_ivar_name=pref_key) condition = 4 except (KeyError, TypeError) as error: if isinstance(error, KeyError): # Pref not in prefs arg, so get pref from <subclass>.defaultPreferences condition = 4 if isinstance(error, TypeError): # No prefs, so get pref from <subclass>.defaultPreferences # Condition 3 condition = 3 # No need for default_entry here, as if the default_prefs_dict is no good there is no hope self.set_preference( candidate_info=default_prefs_dict[pref_key], default_entry=default_prefs_dict[ pref_key], # IMPLEMENTATION: FILLER pref_ivar_name=pref_key, ) condition = 3 # Poplulate prefsList self.prefsList.append(pref_key) owner.classPreferences = self # Owner is an object else: if class_prefs: # # MODIFIED 6/28/16 ADDED: # # FIX: class_prefs IS A DICT, SO GETTING AN ERROR BELOW TREATING AS PreferenceSet AND TESTING FOR class_prefs.prefsList # # (SEE EXPLANATION ABOVE CONDITION), ??SO ADD THIS: # # IMPLEMENT Condition 6.5 (see Table above) # if isinstance(class_prefs, dict): # # class_prefs are a specification dict from the class declaration # # - if prefs are present and are the default set (e.g., in instantiation call from __init__.py), # # replace with class_prefs dict since default_prefs_dict will be used below as base set anyhow) # # - if prefs are not the default set, merge with class_prefs dict, giving precedence to prefs # # since they were in a script from the user # if prefs is default_prefs_dict: # prefs = class_prefs # else: # prefs.update(class_prefs) # # MODIFIED 6/28/16 END ADDITION try: class_prefs.prefsList except AttributeError: # Generate class_prefs.prefsList (since it was not generated when class_prefs was created class_prefs.prefsList = [ i for i in list(class_prefs.__dict__.keys()) if '_pref' in i ] for pref_key in class_prefs.prefsList: try: # Get pref from prefs arg # Condition 6 self.set_preference(candidate_info=prefs[pref_key], default_entry=getattr( class_prefs, pref_key), pref_ivar_name=pref_key) condition = 6 except (KeyError, TypeError) as error: if isinstance(error, KeyError): # Pref not in prefs arg, so get pref from class prefs condition = 6 if isinstance(error, TypeError): # No prefs, so get pref from class_prefs # Condition 5 condition = 5 self.set_preference( candidate_info=getattr(class_prefs, pref_key), default_entry=default_prefs_dict[ pref_key], # IMPLEMENTATION: FILLER pref_ivar_name=pref_key) owner.prefs = self else: # Conditions 7 and 8 raise PreferenceSetError( "Program Error: attempt to create a PreferenceSet for object ({0}) " "in a class ({1}) for which classPreferences have not been instantiated" .format(owner.name, owner.__class__.__name__)) if PreferenceSetVerbosity: print("Preference assignment condition {0}".format(condition))