signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def __get__(self,obj,objtype):
<EOL>if obj is None:<EOL><INDENT>result = self.default<EOL><DEDENT>else:<EOL><INDENT>result = obj.__dict__.get(self._internal_name,self.default)<EOL><DEDENT>return result<EOL>
Return the value for this Parameter. If called for a Parameterized class, produce that class's value (i.e. this Parameter object's 'default' attribute). If called for a Parameterized instance, produce that instance's value, if one has been set - otherwise produce the class's value (default).
f1240:c2:m5
@instance_descriptor<EOL><INDENT>def __set__(self,obj,val):<DEDENT>
<EOL>if hasattr(self, '<STR_LIT>'):<EOL><INDENT>val = self.set_hook(obj,val)<EOL><DEDENT>self._validate(val)<EOL>_old = NotImplemented<EOL>if self.constant or self.readonly:<EOL><INDENT>if self.readonly:<EOL><INDENT>raise TypeError("<STR_LIT>"%self.name)<EOL><DEDENT>elif obj is None: <EOL><INDENT>_old = self.default<EOL>self.default = val<EOL><DEDENT>elif not obj.initialized:<EOL><INDENT>_old = obj.__dict__.get(self._internal_name,self.default)<EOL>obj.__dict__[self._internal_name] = val<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>"%self.name)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if obj is None:<EOL><INDENT>_old = self.default<EOL>self.default = val<EOL><DEDENT>else:<EOL><INDENT>_old = obj.__dict__.get(self._internal_name,self.default)<EOL>obj.__dict__[self._internal_name] = val<EOL><DEDENT><DEDENT>self._post_setter(obj, val)<EOL>if obj is None:<EOL><INDENT>watchers = self.watchers.get("<STR_LIT:value>",[])<EOL><DEDENT>else:<EOL><INDENT>watchers = getattr(obj,"<STR_LIT>",{}).get(self.name,{}).get('<STR_LIT:value>',self.watchers.get("<STR_LIT:value>",[]))<EOL><DEDENT>event = Event(what='<STR_LIT:value>',name=self.name,obj=obj,cls=self.owner,old=_old,new=val, type=None)<EOL>obj = self.owner if obj is None else obj<EOL>if obj is None:<EOL><INDENT>return<EOL><DEDENT>for watcher in watchers:<EOL><INDENT>obj.param._call_watcher(watcher, event)<EOL><DEDENT>if not obj.param._BATCH_WATCH:<EOL><INDENT>obj.param._batch_call_watchers()<EOL><DEDENT>
Set the value for this Parameter. If called for a Parameterized class, set that class's value (i.e. set this Parameter object's 'default' attribute). If called for a Parameterized instance, set the value of this Parameter on that instance (i.e. in the instance's __dict__, under the parameter's internal_name). If the Parameter's constant attribute is True, only allows the value to be set for a Parameterized class or on uninitialized Parameterized instances. If the Parameter's readonly attribute is True, only allows the value to be specified in the Parameter declaration inside the Parameterized source code. A read-only parameter also cannot be set on a Parameterized class. Note that until we support some form of read-only object, it is still possible to change the attributes of the object stored in a constant or read-only Parameter (e.g. the left bound of a BoundingBox).
f1240:c2:m6
def _validate(self, val):
Implements validation for the parameter
f1240:c2:m7
def _post_setter(self, obj, val):
Called after the parameter value has been validated and set
f1240:c2:m8
def __getstate__(self):
state = {}<EOL>for slot in get_occupied_slots(self):<EOL><INDENT>state[slot] = getattr(self,slot)<EOL><DEDENT>return state<EOL>
All Parameters have slots, not a dict, so we have to support pickle and deepcopy ourselves.
f1240:c2:m11
def __init__(self_, cls, self=None):
self_.cls = cls<EOL>self_.self = self<EOL>self_._BATCH_WATCH = False <EOL>self_._TRIGGER = False<EOL>self_._events = [] <EOL>self_._watchers = [] <EOL>
cls is the Parameterized class which is always set. self is the instance if set.
f1240:c6:m0
def __getitem__(self_, key):
inst = self_.self<EOL>parameters = self_.objects(False) if inst is None else inst.param.objects(False)<EOL>p = parameters[key]<EOL>if (inst is not None and p.per_instance and<EOL>not getattr(inst, '<STR_LIT>', False)):<EOL><INDENT>if key not in inst._instance__params:<EOL><INDENT>try:<EOL><INDENT>watchers = p.watchers<EOL>p.watchers = {}<EOL>p = copy.copy(p)<EOL><DEDENT>except:<EOL><INDENT>raise<EOL><DEDENT>finally:<EOL><INDENT>p.watchers = watchers<EOL><DEDENT>p.owner = inst<EOL>inst._instance__params[key] = p<EOL><DEDENT>else:<EOL><INDENT>p = inst._instance__params[key]<EOL><DEDENT><DEDENT>return p<EOL>
Returns the class or instance parameter
f1240:c6:m2
def __dir__(self_):
return super(Parameters, self_).__dir__() + list(self_)<EOL>
Adds parameters to dir
f1240:c6:m3
def __iter__(self_):
for p in self_.objects(instance=False):<EOL><INDENT>yield p<EOL><DEDENT>
Iterates over the parameters on this object.
f1240:c6:m4
def __getattr__(self_, attr):
cls = self_.__dict__.get('<STR_LIT>')<EOL>if cls is None: <EOL><INDENT>raise AttributeError<EOL><DEDENT>try:<EOL><INDENT>params = list(getattr(cls, '<STR_LIT>' % cls.__name__))<EOL><DEDENT>except AttributeError:<EOL><INDENT>params = [n for class_ in classlist(cls) for n, v in class_.__dict__.items()<EOL>if isinstance(v, Parameter)]<EOL><DEDENT>if attr in params:<EOL><INDENT>return self_.__getitem__(attr)<EOL><DEDENT>elif self_.self is None:<EOL><INDENT>raise AttributeError("<STR_LIT>" %<EOL>(self_.cls.__name__, attr))<EOL><DEDENT>else:<EOL><INDENT>raise AttributeError("<STR_LIT>" %<EOL>(self_.cls.__name__, attr))<EOL><DEDENT>
Extends attribute access to parameter objects.
f1240:c6:m6
@as_uninitialized<EOL><INDENT>def _setup_params(self_,**params):<DEDENT>
self = self_.param.self<EOL>params_to_instantiate = {}<EOL>for class_ in classlist(type(self)):<EOL><INDENT>if not issubclass(class_, Parameterized):<EOL><INDENT>continue<EOL><DEDENT>for (k,v) in class_.__dict__.items():<EOL><INDENT>if isinstance(v,Parameter) and v.instantiate and k!="<STR_LIT:name>":<EOL><INDENT>params_to_instantiate[k]=v<EOL><DEDENT><DEDENT><DEDENT>for p in params_to_instantiate.values():<EOL><INDENT>self.param._instantiate_param(p)<EOL><DEDENT>for name,val in params.items():<EOL><INDENT>desc = self.__class__.get_param_descriptor(name)[<NUM_LIT:0>] <EOL>if not desc:<EOL><INDENT>self.param.warning("<STR_LIT>",name,val)<EOL><DEDENT>setattr(self,name,val)<EOL><DEDENT>
Initialize default and keyword parameter values. First, ensures that all Parameters with 'instantiate=True' (typically used for mutable Parameters) are copied directly into each object, to ensure that there is an independent copy (to avoid suprising aliasing errors). Then sets each of the keyword arguments, warning when any of them are not defined as parameters. Constant Parameters can be set during calls to this method.
f1240:c6:m9
@classmethod<EOL><INDENT>def deprecate(cls, fn):<DEDENT>
def inner(*args, **kwargs):<EOL><INDENT>if cls._disable_stubs:<EOL><INDENT>raise AssertionError('<STR_LIT>')<EOL><DEDENT>elif cls._disable_stubs is None:<EOL><INDENT>pass<EOL><DEDENT>elif cls._disable_stubs is False:<EOL><INDENT>get_logger(name=args[<NUM_LIT:0>].__class__.__name__).log(<EOL>WARNING, '<STR_LIT>' % fn.__name__)<EOL><DEDENT>return fn(*args, **kwargs)<EOL><DEDENT>inner.__doc__= "<STR_LIT>" % fn.__name__<EOL>return inner<EOL>
Decorator to issue warnings for API moving onto the param namespace and to add a docstring directing people to the appropriate method.
f1240:c6:m10
@classmethod<EOL><INDENT>def _changed(cls, event):<DEDENT>
return not Comparator.is_equal(event.old, event.new)<EOL>
Predicate that determines whether a Event object has actually changed such that old != new.
f1240:c6:m11
def print_param_defaults(self_):
cls = self_.cls<EOL>for key,val in cls.__dict__.items():<EOL><INDENT>if isinstance(val,Parameter):<EOL><INDENT>print(cls.__name__+'<STR_LIT:.>'+key+ '<STR_LIT:=>'+ repr(val.default))<EOL><DEDENT><DEDENT>
Print the default values of all cls's Parameters.
f1240:c6:m13
def set_default(self_,param_name,value):
cls = self_.cls<EOL>setattr(cls,param_name,value)<EOL>
Set the default value of param_name. Equivalent to setting param_name on the class.
f1240:c6:m14
def _add_parameter(self_, param_name,param_obj):
<EOL>cls = self_.cls<EOL>type.__setattr__(cls,param_name,param_obj)<EOL>ParameterizedMetaclass._initialize_parameter(cls,param_name,param_obj)<EOL>try:<EOL><INDENT>delattr(cls,'<STR_LIT>'%cls.__name__)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>
Add a new Parameter object into this object's class. Supposed to result in a Parameter equivalent to one declared in the class's source code.
f1240:c6:m15
def params(self_, parameter_name=None):
if self_.self is not None and self_.self._instance__params:<EOL><INDENT>self_.warning('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>pdict = self_.objects(instance='<STR_LIT>')<EOL>if parameter_name is None:<EOL><INDENT>return pdict<EOL><DEDENT>else:<EOL><INDENT>return pdict[parameter_name]<EOL><DEDENT>
Return the Parameters of this class as the dictionary {name: parameter_object} Includes Parameters from this class and its superclasses.
f1240:c6:m16
def set_param(self_, *args,**kwargs):
BATCH_WATCH = self_.self_or_cls.param._BATCH_WATCH<EOL>self_.self_or_cls.param._BATCH_WATCH = True<EOL>self_or_cls = self_.self_or_cls<EOL>if args:<EOL><INDENT>if len(args) == <NUM_LIT:2> and not args[<NUM_LIT:0>] in kwargs and not kwargs:<EOL><INDENT>kwargs[args[<NUM_LIT:0>]] = args[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>self_.self_or_cls.param._BATCH_WATCH = False<EOL>raise ValueError("<STR_LIT>" %<EOL>(self_or_cls.name))<EOL><DEDENT><DEDENT>for (k, v) in kwargs.items():<EOL><INDENT>if k not in self_or_cls.param:<EOL><INDENT>self_.self_or_cls.param._BATCH_WATCH = False<EOL>raise ValueError("<STR_LIT>" % (k, self_or_cls.name))<EOL><DEDENT>try:<EOL><INDENT>setattr(self_or_cls, k, v)<EOL><DEDENT>except:<EOL><INDENT>self_.self_or_cls.param._BATCH_WATCH = False<EOL>raise<EOL><DEDENT><DEDENT>self_.self_or_cls.param._BATCH_WATCH = BATCH_WATCH<EOL>if not BATCH_WATCH:<EOL><INDENT>self_._batch_call_watchers()<EOL><DEDENT>
For each param=value keyword argument, sets the corresponding parameter of this object or class to the given value. For backwards compatibility, also accepts set_param("param",value) for a single parameter value using positional arguments, but the keyword interface is preferred because it is more compact and can set multiple values.
f1240:c6:m17
def objects(self_, instance=True):
cls = self_.cls<EOL>try:<EOL><INDENT>pdict = getattr(cls, '<STR_LIT>' % cls.__name__)<EOL><DEDENT>except AttributeError:<EOL><INDENT>paramdict = {}<EOL>for class_ in classlist(cls):<EOL><INDENT>for name, val in class_.__dict__.items():<EOL><INDENT>if isinstance(val, Parameter):<EOL><INDENT>paramdict[name] = val<EOL><DEDENT><DEDENT><DEDENT>setattr(cls, '<STR_LIT>' % cls.__name__, paramdict)<EOL>pdict = paramdict<EOL><DEDENT>if instance and self_.self is not None:<EOL><INDENT>if instance == '<STR_LIT>':<EOL><INDENT>if self_.self._instance__params:<EOL><INDENT>return dict(pdict, **self_.self._instance__params)<EOL><DEDENT>return pdict<EOL><DEDENT>else:<EOL><INDENT>return {k: self_.self.param[k] for k in pdict}<EOL><DEDENT><DEDENT>return pdict<EOL>
Returns the Parameters of this instance or class If instance=True and called on a Parameterized instance it will create instance parameters for all Parameters defined on the class. To force class parameters to be returned use instance=False. Since classes avoid creating instance parameters unless necessary you may also request only existing instance parameters to be returned by setting instance='existing'.
f1240:c6:m18
def trigger(self_, *param_names):
events = self_.self_or_cls.param._events<EOL>watchers = self_.self_or_cls.param._watchers<EOL>self_.self_or_cls.param._events = []<EOL>self_.self_or_cls.param._watchers = []<EOL>param_values = dict(self_.get_param_values())<EOL>params = {name: param_values[name] for name in param_names}<EOL>self_.self_or_cls.param._TRIGGER = True<EOL>self_.set_param(**params)<EOL>self_.self_or_cls.param._TRIGGER = False<EOL>self_.self_or_cls.param._events = events<EOL>self_.self_or_cls.param._watchers = watchers<EOL>
Trigger watchers for the given set of parameter names. Watchers will be triggered whether or not the parameter values have actually changed.
f1240:c6:m19
def _update_event_type(self_, watcher, event, triggered):
if triggered:<EOL><INDENT>event_type = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>event_type = '<STR_LIT>' if watcher.onlychanged else '<STR_LIT>'<EOL><DEDENT>return Event(what=event.what, name=event.name, obj=event.obj, cls=event.cls,<EOL>old=event.old, new=event.new, type=event_type)<EOL>
Returns an updated Event object with the type field set appropriately.
f1240:c6:m20
def _call_watcher(self_, watcher, event):
if self_.self_or_cls.param._TRIGGER:<EOL><INDENT>pass<EOL><DEDENT>elif watcher.onlychanged and (not self_._changed(event)):<EOL><INDENT>return<EOL><DEDENT>if self_.self_or_cls.param._BATCH_WATCH:<EOL><INDENT>self_._events.append(event)<EOL>if watcher not in self_._watchers:<EOL><INDENT>self_._watchers.append(watcher)<EOL><DEDENT><DEDENT>elif watcher.mode == '<STR_LIT:args>':<EOL><INDENT>with batch_watch(self_.self_or_cls, run=False):<EOL><INDENT>watcher.fn(self_._update_event_type(watcher, event, self_.self_or_cls.param._TRIGGER))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>with batch_watch(self_.self_or_cls, run=False):<EOL><INDENT>event = self_._update_event_type(watcher, event, self_.self_or_cls.param._TRIGGER)<EOL>watcher.fn(**{event.name: event.new})<EOL><DEDENT><DEDENT>
Invoke the given the watcher appropriately given a Event object.
f1240:c6:m21
def _batch_call_watchers(self_):
while self_.self_or_cls.param._events:<EOL><INDENT>event_dict = OrderedDict([((event.name, event.what), event)<EOL>for event in self_.self_or_cls.param._events])<EOL>watchers = self_.self_or_cls.param._watchers[:]<EOL>self_.self_or_cls.param._events = []<EOL>self_.self_or_cls.param._watchers = []<EOL>for watcher in watchers:<EOL><INDENT>events = [self_._update_event_type(watcher, event_dict[(name, watcher.what)],<EOL>self_.self_or_cls.param._TRIGGER)<EOL>for name in watcher.parameter_names<EOL>if (name, watcher.what) in event_dict]<EOL>with batch_watch(self_.self_or_cls, run=False):<EOL><INDENT>if watcher.mode == '<STR_LIT:args>':<EOL><INDENT>watcher.fn(*events)<EOL><DEDENT>else:<EOL><INDENT>watcher.fn(**{c.name:c.new for c in events})<EOL><DEDENT><DEDENT><DEDENT><DEDENT>
Batch call a set of watchers based on the parameter value settings in kwargs using the queued Event and watcher objects.
f1240:c6:m22
def set_dynamic_time_fn(self_,time_fn,sublistattr=None):
self_or_cls = self_.self_or_cls<EOL>self_or_cls._Dynamic_time_fn = time_fn<EOL>if isinstance(self_or_cls,type):<EOL><INDENT>a = (None,self_or_cls)<EOL><DEDENT>else:<EOL><INDENT>a = (self_or_cls,)<EOL><DEDENT>for n,p in self_or_cls.param.objects('<STR_LIT>').items():<EOL><INDENT>if hasattr(p, '<STR_LIT>'):<EOL><INDENT>if p._value_is_dynamic(*a):<EOL><INDENT>g = self_or_cls.param.get_value_generator(n)<EOL>g._Dynamic_time_fn = time_fn<EOL><DEDENT><DEDENT><DEDENT>if sublistattr:<EOL><INDENT>try:<EOL><INDENT>sublist = getattr(self_or_cls,sublistattr)<EOL><DEDENT>except AttributeError:<EOL><INDENT>sublist = []<EOL><DEDENT>for obj in sublist:<EOL><INDENT>obj.param.set_dynamic_time_fn(time_fn,sublistattr)<EOL><DEDENT><DEDENT>
Set time_fn for all Dynamic Parameters of this class or instance object that are currently being dynamically generated. Additionally, sets _Dynamic_time_fn=time_fn on this class or instance object, so that any future changes to Dynamic Parmeters can inherit time_fn (e.g. if a Number is changed from a float to a number generator, the number generator will inherit time_fn). If specified, sublistattr is the name of an attribute of this class or instance that contains an iterable collection of subobjects on which set_dynamic_time_fn should be called. If the attribute sublistattr is present on any of the subobjects, set_dynamic_time_fn() will be called for those, too.
f1240:c6:m23
def get_param_values(self_,onlychanged=False):
self_or_cls = self_.self_or_cls<EOL>vals = []<EOL>for name,val in self_or_cls.param.objects('<STR_LIT>').items():<EOL><INDENT>value = self_or_cls.param.get_value_generator(name)<EOL>if not onlychanged or not all_equal(value,val.default):<EOL><INDENT>vals.append((name,value))<EOL><DEDENT><DEDENT>vals.sort(key=itemgetter(<NUM_LIT:0>))<EOL>return vals<EOL>
Return a list of name,value pairs for all Parameters of this object. When called on an instance with onlychanged set to True, will only return values that are not equal to the default value (onlychanged has no effect when called on a class).
f1240:c6:m24
def force_new_dynamic_value(self_, name):
cls_or_slf = self_.self_or_cls<EOL>param_obj = cls_or_slf.param.objects('<STR_LIT>').get(name)<EOL>if not param_obj:<EOL><INDENT>return getattr(cls_or_slf, name)<EOL><DEDENT>cls, slf = None, None<EOL>if isinstance(cls_or_slf,type):<EOL><INDENT>cls = cls_or_slf<EOL><DEDENT>else:<EOL><INDENT>slf = cls_or_slf<EOL><DEDENT>if not hasattr(param_obj,'<STR_LIT>'):<EOL><INDENT>return param_obj.__get__(slf, cls)<EOL><DEDENT>else:<EOL><INDENT>return param_obj._force(slf, cls)<EOL><DEDENT>
Force a new value to be generated for the dynamic attribute name, and return it. If name is not dynamic, its current value is returned (i.e. equivalent to getattr(name).
f1240:c6:m25
def get_value_generator(self_,name):
cls_or_slf = self_.self_or_cls<EOL>param_obj = cls_or_slf.param.objects('<STR_LIT>').get(name)<EOL>if not param_obj:<EOL><INDENT>value = getattr(cls_or_slf,name)<EOL><DEDENT>elif hasattr(param_obj,'<STR_LIT>'):<EOL><INDENT>value = [cls_or_slf.param.get_value_generator(a) for a in param_obj.attribs]<EOL><DEDENT>elif not hasattr(param_obj,'<STR_LIT>'):<EOL><INDENT>value = getattr(cls_or_slf,name)<EOL><DEDENT>else:<EOL><INDENT>internal_name = "<STR_LIT>"%name<EOL>if hasattr(cls_or_slf,internal_name):<EOL><INDENT>value = getattr(cls_or_slf,internal_name)<EOL><DEDENT>else:<EOL><INDENT>value = param_obj.default<EOL><DEDENT><DEDENT>return value<EOL>
Return the value or value-generating object of the named attribute. For most parameters, this is simply the parameter's value (i.e. the same as getattr()), but Dynamic parameters have their value-generating object returned.
f1240:c6:m26
def inspect_value(self_,name):
cls_or_slf = self_.self_or_cls<EOL>param_obj = cls_or_slf.param.objects('<STR_LIT>').get(name)<EOL>if not param_obj:<EOL><INDENT>value = getattr(cls_or_slf,name)<EOL><DEDENT>elif hasattr(param_obj,'<STR_LIT>'):<EOL><INDENT>value = [cls_or_slf.param.inspect_value(a) for a in param_obj.attribs]<EOL><DEDENT>elif not hasattr(param_obj,'<STR_LIT>'):<EOL><INDENT>value = getattr(cls_or_slf,name)<EOL><DEDENT>else:<EOL><INDENT>if isinstance(cls_or_slf,type):<EOL><INDENT>value = param_obj._inspect(None,cls_or_slf)<EOL><DEDENT>else:<EOL><INDENT>value = param_obj._inspect(cls_or_slf,None)<EOL><DEDENT><DEDENT>return value<EOL>
Return the current value of the named attribute without modifying it. Same as getattr() except for Dynamic parameters, which have their last generated value returned.
f1240:c6:m27
def outputs(self_):
outputs = {}<EOL>for cls in classlist(self_.cls):<EOL><INDENT>for name in dir(cls):<EOL><INDENT>method = getattr(self_.self_or_cls, name)<EOL>dinfo = getattr(method, '<STR_LIT>', {})<EOL>if '<STR_LIT>' not in dinfo:<EOL><INDENT>continue<EOL><DEDENT>for override, otype, idx in dinfo['<STR_LIT>']:<EOL><INDENT>if override is not None:<EOL><INDENT>name = override<EOL><DEDENT>outputs[name] = (otype, method, idx)<EOL><DEDENT><DEDENT><DEDENT>return outputs<EOL>
Returns a mapping between any declared outputs and a tuple of the declared Parameter type, the output method, and the index into the output if multiple outputs are returned.
f1240:c6:m29
def unwatch(self_,watcher):
try:<EOL><INDENT>self_._watch('<STR_LIT>',watcher)<EOL><DEDENT>except:<EOL><INDENT>self_.warning('<STR_LIT>'.format(watcher=watcher))<EOL><DEDENT>
Unwatch watchers set either with watch or watch_values.
f1240:c6:m33
def defaults(self_):
self = self_.self<EOL>d = {}<EOL>for param_name,param in self.param.objects('<STR_LIT>').items():<EOL><INDENT>if param.constant:<EOL><INDENT>pass<EOL><DEDENT>elif param.instantiate:<EOL><INDENT>self.param._instantiate_param(param,dict_=d,key=param_name)<EOL><DEDENT>else:<EOL><INDENT>d[param_name]=param.default<EOL><DEDENT><DEDENT>return d<EOL>
Return {parameter_name:parameter.default} for all non-constant Parameters. Note that a Parameter for which instantiate==True has its default instantiated.
f1240:c6:m35
def __db_print(self_,level,msg,*args,**kw):
self_or_cls = self_.self_or_cls<EOL>if get_logger(name=self_or_cls.name).isEnabledFor(level):<EOL><INDENT>if dbprint_prefix and callable(dbprint_prefix):<EOL><INDENT>msg = dbprint_prefix() + "<STR_LIT>" + msg <EOL><DEDENT>get_logger(name=self_or_cls.name).log(level, msg, *args, **kw)<EOL><DEDENT>
Calls the logger returned by the get_logger() function, prepending the result of calling dbprint_prefix() (if any). See python's logging module for details.
f1240:c6:m36
def print_param_values(self_):
self = self_.self<EOL>for name,val in self.param.get_param_values():<EOL><INDENT>print('<STR_LIT>' % (self.name,name,val))<EOL><DEDENT>
Print the values of all this object's Parameters.
f1240:c6:m37
def warning(self_, msg,*args,**kw):
if not warnings_as_exceptions:<EOL><INDENT>global warning_count<EOL>warning_count+=<NUM_LIT:1><EOL>self_.__db_print(WARNING,msg,*args,**kw)<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>" + msg % args)<EOL><DEDENT>
Print msg merged with args as a warning, unless module variable warnings_as_exceptions is True, then raise an Exception containing the arguments. See Python's logging module for details of message formatting.
f1240:c6:m38
def message(self_,msg,*args,**kw):
self_.__db_print(INFO,msg,*args,**kw)<EOL>
Print msg merged with args as a message. See Python's logging module for details of message formatting.
f1240:c6:m39
def verbose(self_,msg,*args,**kw):
self_.__db_print(VERBOSE,msg,*args,**kw)<EOL>
Print msg merged with args as a verbose message. See Python's logging module for details of message formatting.
f1240:c6:m40
def debug(self_,msg,*args,**kw):
self_.__db_print(DEBUG,msg,*args,**kw)<EOL>
Print msg merged with args as a debugging statement. See Python's logging module for details of message formatting.
f1240:c6:m41
def __init__(mcs,name,bases,dict_):
type.__init__(mcs,name,bases,dict_)<EOL>mcs.name = name<EOL>mcs.param = Parameters(mcs)<EOL>parameters = [(n,o) for (n,o) in dict_.items()<EOL>if isinstance(o,Parameter)]<EOL>for param_name,param in parameters:<EOL><INDENT>mcs._initialize_parameter(param_name,param)<EOL><DEDENT>dependers = [(n,m._dinfo) for (n,m) in dict_.items()<EOL>if hasattr(m,'<STR_LIT>')]<EOL>_watch = []<EOL>for n,dinfo in dependers:<EOL><INDENT>if dinfo.get('<STR_LIT>', False):<EOL><INDENT>_watch.append(n)<EOL><DEDENT><DEDENT>mcs.param._depends = {'<STR_LIT>':_watch}<EOL>if docstring_signature:<EOL><INDENT>mcs.__class_docstring_signature()<EOL><DEDENT>
Initialize the class object (not an instance of the class, but the class itself). Initializes all the Parameters by looking up appropriate default values (see __param_inheritance()) and setting attrib_names (see _set_names()).
f1240:c7:m0
def __class_docstring_signature(mcs, max_repr_len=<NUM_LIT:15>):
processed_kws, keyword_groups = set(), []<EOL>for cls in reversed(mcs.mro()):<EOL><INDENT>keyword_group = []<EOL>for (k,v) in sorted(cls.__dict__.items()):<EOL><INDENT>if isinstance(v, Parameter) and k not in processed_kws:<EOL><INDENT>param_type = v.__class__.__name__<EOL>keyword_group.append("<STR_LIT>" % (k, param_type))<EOL>processed_kws.add(k)<EOL><DEDENT><DEDENT>keyword_groups.append(keyword_group)<EOL><DEDENT>keywords = [el for grp in reversed(keyword_groups) for el in grp]<EOL>class_docstr = "<STR_LIT:\n>"+mcs.__doc__ if mcs.__doc__ else '<STR_LIT>'<EOL>signature = "<STR_LIT>" % ("<STR_LIT:U+002CU+0020>".join(keywords))<EOL>description = param_pager(mcs) if (docstring_describe_params and param_pager) else '<STR_LIT>'<EOL>mcs.__doc__ = signature + class_docstr + '<STR_LIT:\n>' + description<EOL>
Autogenerate a keyword signature in the class docstring for all available parameters. This is particularly useful in the IPython Notebook as IPython will parse this signature to allow tab-completion of keywords. max_repr_len: Maximum length (in characters) of value reprs.
f1240:c7:m1
def __is_abstract(mcs):
<EOL>try:<EOL><INDENT>return getattr(mcs,'<STR_LIT>'%mcs.__name__)<EOL><DEDENT>except AttributeError:<EOL><INDENT>return False<EOL><DEDENT>
Return True if the class has an attribute __abstract set to True. Subclasses will return False unless they themselves have __abstract set to true. This mechanism allows a class to declare itself to be abstract (e.g. to avoid it being offered as an option in a GUI), without the "abstract" property being inherited by its subclasses (at least one of which is presumably not abstract).
f1240:c7:m3
def __setattr__(mcs,attribute_name,value):
<EOL>parameter,owning_class = mcs.get_param_descriptor(attribute_name)<EOL>if parameter and not isinstance(value,Parameter):<EOL><INDENT>if owning_class != mcs:<EOL><INDENT>parameter = copy.copy(parameter)<EOL>parameter.owner = mcs<EOL>type.__setattr__(mcs,attribute_name,parameter)<EOL><DEDENT>mcs.__dict__[attribute_name].__set__(None,value)<EOL><DEDENT>else:<EOL><INDENT>type.__setattr__(mcs,attribute_name,value)<EOL>if isinstance(value,Parameter):<EOL><INDENT>mcs.__param_inheritance(attribute_name,value)<EOL><DEDENT>elif isinstance(value,Parameters):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if not attribute_name.startswith('<STR_LIT:_>'):<EOL><INDENT>get_logger().log(WARNING,<EOL>"<STR_LIT>",<EOL>mcs.__name__,attribute_name,repr(value))<EOL><DEDENT><DEDENT><DEDENT>
Implements 'self.attribute_name=value' in a way that also supports Parameters. If there is already a descriptor named attribute_name, and that descriptor is a Parameter, and the new value is *not* a Parameter, then call that Parameter's __set__ method with the specified value. In all other cases set the attribute normally (i.e. overwrite the descriptor). If the new value is a Parameter, once it has been set we make sure that the value is inherited from Parameterized superclasses as described in __param_inheritance().
f1240:c7:m4
def __param_inheritance(mcs,param_name,param):
<EOL>slots = {}<EOL>for p_class in classlist(type(param))[<NUM_LIT:1>::]:<EOL><INDENT>slots.update(dict.fromkeys(p_class.__slots__))<EOL><DEDENT>setattr(param,'<STR_LIT>',mcs)<EOL>del slots['<STR_LIT>']<EOL>if '<STR_LIT>' in slots:<EOL><INDENT>setattr(param,'<STR_LIT>',mcs)<EOL>del slots['<STR_LIT>']<EOL><DEDENT>for superclass in classlist(mcs)[::-<NUM_LIT:1>]:<EOL><INDENT>super_param = superclass.__dict__.get(param_name)<EOL>if isinstance(super_param, Parameter) and super_param.instantiate is True:<EOL><INDENT>param.instantiate=True<EOL><DEDENT><DEDENT>del slots['<STR_LIT>']<EOL>for slot in slots.keys():<EOL><INDENT>superclasses = iter(classlist(mcs)[::-<NUM_LIT:1>])<EOL>while getattr(param,slot) is None:<EOL><INDENT>try:<EOL><INDENT>param_super_class = next(superclasses)<EOL><DEDENT>except StopIteration:<EOL><INDENT>break<EOL><DEDENT>new_param = param_super_class.__dict__.get(param_name)<EOL>if new_param is not None and hasattr(new_param,slot):<EOL><INDENT>new_value = getattr(new_param,slot)<EOL>setattr(param,slot,new_value)<EOL><DEDENT><DEDENT><DEDENT>
Look for Parameter values in superclasses of this Parameterized class. Ordinarily, when a Python object is instantiated, attributes not given values in the constructor will inherit the value given in the object's class, or in its superclasses. For Parameters owned by Parameterized classes, we have implemented an additional level of default lookup, should this ordinary lookup return only None. In such a case, i.e. when no non-None value was found for a Parameter by the usual inheritance mechanisms, we explicitly look for Parameters with the same name in superclasses of this Parameterized class, and use the first such value that we find. The goal is to be able to set the default value (or other slots) of a Parameter within a Parameterized class, just as we can set values for non-Parameter objects in Parameterized classes, and have the values inherited through the Parameterized hierarchy as usual. Note that instantiate is handled differently: if there is a parameter with the same name in one of the superclasses with instantiate set to True, this parameter will inherit instatiate=True.
f1240:c7:m5
def get_param_descriptor(mcs,param_name):
classes = classlist(mcs)<EOL>for c in classes[::-<NUM_LIT:1>]:<EOL><INDENT>attribute = c.__dict__.get(param_name)<EOL>if isinstance(attribute,Parameter):<EOL><INDENT>return attribute,c<EOL><DEDENT><DEDENT>return None,None<EOL>
Goes up the class hierarchy (starting from the current class) looking for a Parameter class attribute param_name. As soon as one is found as a class attribute, that Parameter is returned along with the class in which it is declared.
f1240:c7:m6
def __getstate__(self):
<EOL>state = self.__dict__.copy()<EOL>for slot in get_occupied_slots(self):<EOL><INDENT>state[slot] = getattr(self,slot)<EOL><DEDENT>return state<EOL>
Save the object's state: return a dictionary that is a shallow copy of the object's __dict__ and that also includes the object's __slots__ (if it has any).
f1240:c8:m1
def __setstate__(self, state):
self.initialized=False<EOL>if '<STR_LIT>' not in state:<EOL><INDENT>state['<STR_LIT>'] = {}<EOL><DEDENT>if '<STR_LIT>' not in state:<EOL><INDENT>state['<STR_LIT>'] = {}<EOL><DEDENT>for name,value in state.items():<EOL><INDENT>setattr(self,name,value)<EOL><DEDENT>self.initialized=True<EOL>
Restore objects from the state dictionary to this object. During this process the object is considered uninitialized.
f1240:c8:m2
def __repr__(self):
try:<EOL><INDENT>settings = ['<STR_LIT>' % (name, repr(val))<EOL>for name,val in self.param.get_param_values()]<EOL><DEDENT>except RuntimeError: <EOL><INDENT>settings = []<EOL><DEDENT>return self.__class__.__name__ + "<STR_LIT:(>" + "<STR_LIT:U+002CU+0020>".join(settings) + "<STR_LIT:)>"<EOL>
Provide a nearly valid Python representation that could be used to recreate the item with its parameters, if executed in the appropriate environment. Returns 'classname(parameter1=x,parameter2=y,...)', listing all the parameters of this object.
f1240:c8:m3
def __str__(self):
return "<STR_LIT>" % (self.__class__.__name__,self.name)<EOL>
Return a short representation of the name and class of this object.
f1240:c8:m4
def script_repr(self,imports=[],prefix="<STR_LIT:U+0020>"):
return self.pprint(imports,prefix, unknown_value=None, qualify=True,<EOL>separator="<STR_LIT:\n>")<EOL>
Variant of __repr__ designed for generating a runnable script.
f1240:c8:m5
def pprint(self, imports=None, prefix="<STR_LIT:U+0020>", unknown_value='<STR_LIT>',<EOL>qualify=False, separator="<STR_LIT>"):
if imports is None:<EOL><INDENT>imports = []<EOL><DEDENT>imports[:] = list(set(imports))<EOL>mod = self.__module__<EOL>bits = mod.split('<STR_LIT:.>')<EOL>imports.append("<STR_LIT>"%mod)<EOL>imports.append("<STR_LIT>"%bits[<NUM_LIT:0>])<EOL>changed_params = dict(self.param.get_param_values(onlychanged=script_repr_suppress_defaults))<EOL>values = dict(self.param.get_param_values())<EOL>spec = inspect.getargspec(self.__init__)<EOL>args = spec.args[<NUM_LIT:1>:] if spec.args[<NUM_LIT:0>] == '<STR_LIT>' else spec.args<EOL>if spec.defaults is not None:<EOL><INDENT>posargs = spec.args[:-len(spec.defaults)]<EOL>kwargs = dict(zip(spec.args[-len(spec.defaults):], spec.defaults))<EOL><DEDENT>else:<EOL><INDENT>posargs, kwargs = args, []<EOL><DEDENT>parameters = self.param.objects('<STR_LIT>')<EOL>ordering = sorted(<EOL>sorted(changed_params), <EOL>key=lambda k: (- float('<STR_LIT>') <EOL>if parameters[k].precedence is None else<EOL>parameters[k].precedence))<EOL>arglist, keywords, processed = [], [], []<EOL>for k in args + ordering:<EOL><INDENT>if k in processed: continue<EOL>if k == '<STR_LIT:name>' and (values[k] is not None<EOL>and re.match('<STR_LIT>'+self.__class__.__name__+'<STR_LIT>', values[k])):<EOL><INDENT>continue<EOL><DEDENT>value = pprint(values[k], imports, prefix=prefix,settings=[],<EOL>unknown_value=unknown_value,<EOL>qualify=qualify) if k in values else None<EOL>if value is None:<EOL><INDENT>if unknown_value is False:<EOL><INDENT>raise Exception("<STR_LIT>" % (self.name,k))<EOL><DEDENT>elif unknown_value is None:<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>value = unknown_value<EOL><DEDENT><DEDENT>if (k in kwargs) and (k in values) and kwargs[k] == values[k]: continue<EOL>if k in posargs:<EOL><INDENT>arglist.append(value)<EOL><DEDENT>elif k in kwargs or (spec.keywords is not None):<EOL><INDENT>keywords.append('<STR_LIT>' % (k, value))<EOL><DEDENT>processed.append(k)<EOL><DEDENT>qualifier = mod + '<STR_LIT:.>' if qualify else '<STR_LIT>'<EOL>arguments = arglist + keywords + (['<STR_LIT>' % spec.varargs] if spec.varargs else [])<EOL>return qualifier + '<STR_LIT>' % (self.__class__.__name__, ('<STR_LIT:U+002C>'+separator+prefix).join(arguments))<EOL>
(Experimental) Pretty printed representation that may be evaluated with eval. See pprint() function for more details.
f1240:c8:m6
def state_push(self):
for pname, p in self.param.objects('<STR_LIT>').items():<EOL><INDENT>g = self.param.get_value_generator(pname)<EOL>if hasattr(g,'<STR_LIT>'):<EOL><INDENT>g._saved_Dynamic_last.append(g._Dynamic_last)<EOL>g._saved_Dynamic_time.append(g._Dynamic_time)<EOL><DEDENT>elif hasattr(g,'<STR_LIT>') and isinstance(g,Parameterized):<EOL><INDENT>g.state_push()<EOL><DEDENT><DEDENT>
Save this instance's state. For Parameterized instances, this includes the state of dynamically generated values. Subclasses that maintain short-term state should additionally save and restore that state using state_push() and state_pop(). Generally, this method is used by operations that need to test something without permanently altering the objects' state.
f1240:c8:m7
def state_pop(self):
for pname, p in self.param.objects('<STR_LIT>').items():<EOL><INDENT>g = self.param.get_value_generator(pname)<EOL>if hasattr(g,'<STR_LIT>'):<EOL><INDENT>g._Dynamic_last = g._saved_Dynamic_last.pop()<EOL>g._Dynamic_time = g._saved_Dynamic_time.pop()<EOL><DEDENT>elif hasattr(g,'<STR_LIT>') and isinstance(g,Parameterized):<EOL><INDENT>g.state_pop()<EOL><DEDENT><DEDENT>
Restore the most recently saved state. See state_push() for more details.
f1240:c8:m8
def __init__(self,overridden,dict_,allow_extra_keywords=False):
<EOL>self._overridden = overridden<EOL>dict.__init__(self,dict_)<EOL>if allow_extra_keywords:<EOL><INDENT>self._extra_keywords=self._extract_extra_keywords(dict_)<EOL><DEDENT>else:<EOL><INDENT>self._check_params(dict_)<EOL><DEDENT>
If allow_extra_keywords is False, then all keys in the supplied dict_ must match parameter names on the overridden object (otherwise a warning will be printed). If allow_extra_keywords is True, then any items in the supplied dict_ that are not also parameters of the overridden object will be available via the extra_keywords() method.
f1240:c9:m0
def extra_keywords(self):
return self._extra_keywords<EOL>
Return a dictionary containing items from the originally supplied dict_ whose names are not parameters of the overridden object.
f1240:c9:m1
def param_keywords(self):
return dict((key, self[key]) for key in self if key not in self.extra_keywords())<EOL>
Return a dictionary containing items from the originally supplied dict_ whose names are parameters of the overridden object (i.e. not extra keywords/parameters).
f1240:c9:m2
def _check_params(self,params):
overridden_object_params = list(self._overridden.param)<EOL>for item in params:<EOL><INDENT>if item not in overridden_object_params:<EOL><INDENT>self.param.warning("<STR_LIT>",item)<EOL><DEDENT><DEDENT>
Print a warning if params contains something that is not a Parameter of the overridden object.
f1240:c9:m9
def _extract_extra_keywords(self,params):
extra_keywords = {}<EOL>overridden_object_params = list(self._overridden.param)<EOL>for name, val in params.items():<EOL><INDENT>if name not in overridden_object_params:<EOL><INDENT>extra_keywords[name]=val<EOL><DEDENT><DEDENT>return extra_keywords<EOL>
Return any items in params that are not also parameters of the overridden object.
f1240:c9:m10
@bothmethod<EOL><INDENT>def instance(self_or_cls,**params):<DEDENT>
if isinstance (self_or_cls,ParameterizedMetaclass):<EOL><INDENT>cls = self_or_cls<EOL><DEDENT>else:<EOL><INDENT>p = params<EOL>params = dict(self_or_cls.get_param_values())<EOL>params.update(p)<EOL>params.pop('<STR_LIT:name>')<EOL>cls = self_or_cls.__class__<EOL><DEDENT>inst=Parameterized.__new__(cls)<EOL>Parameterized.__init__(inst,**params)<EOL>if '<STR_LIT:name>' in params: inst.__name__ = params['<STR_LIT:name>']<EOL>else: inst.__name__ = self_or_cls.name<EOL>return inst<EOL>
Return an instance of this class, copying parameters from any existing instance provided.
f1240:c10:m1
def script_repr(self,imports=[],prefix="<STR_LIT:U+0020>"):
return self.pprint(imports,prefix,unknown_value='<STR_LIT>',qualify=True,<EOL>separator="<STR_LIT:\n>")<EOL>
Same as Parameterized.script_repr, except that X.classname(Y is replaced with X.classname.instance(Y
f1240:c10:m5
def pprint(self, imports=None, prefix="<STR_LIT>",unknown_value='<STR_LIT>',<EOL>qualify=False, separator="<STR_LIT>"):
r = Parameterized.pprint(self,imports,prefix,<EOL>unknown_value=unknown_value,<EOL>qualify=qualify,separator=separator)<EOL>classname=self.__class__.__name__<EOL>return r.replace("<STR_LIT>"%classname,"<STR_LIT>"%classname)<EOL>
Same as Parameterized.pprint, except that X.classname(Y is replaced with X.classname.instance(Y
f1240:c10:m6
def produce_value(value_obj):
if callable(value_obj):<EOL><INDENT>return value_obj()<EOL><DEDENT>else:<EOL><INDENT>return value_obj<EOL><DEDENT>
A helper function that produces an actual parameter from a stored object: if the object is callable, call it, otherwise return the object.
f1241:m0
def as_unicode(obj):
if sys.version_info.major < <NUM_LIT:3> and isinstance(obj, str):<EOL><INDENT>obj = obj.decode('<STR_LIT:utf-8>')<EOL><DEDENT>return unicode(obj)<EOL>
Safely casts any object to unicode including regular string (i.e. bytes) types in python 2.
f1241:m1
def is_ordered_dict(d):
py3_ordered_dicts = (sys.version_info.major == <NUM_LIT:3>) and (sys.version_info.minor >= <NUM_LIT:6>)<EOL>vanilla_odicts = (sys.version_info.major > <NUM_LIT:3>) or py3_ordered_dicts<EOL>return isinstance(d, (OrderedDict))or (vanilla_odicts and isinstance(d, dict))<EOL>
Predicate checking for ordered dictionaries. OrderedDict is always ordered, and vanilla Python dictionaries are ordered for Python 3.6+
f1241:m2
def hashable(x):
if isinstance(x, collections.MutableSequence):<EOL><INDENT>return tuple(x)<EOL><DEDENT>elif isinstance(x, collections.MutableMapping):<EOL><INDENT>return tuple([(k,v) for k,v in x.items()])<EOL><DEDENT>else:<EOL><INDENT>return x<EOL><DEDENT>
Return a hashable version of the given object x, with lists and dictionaries converted to tuples. Allows mutable objects to be used as a lookup key in cases where the object has not actually been mutated. Lookup will fail (appropriately) in cases where some part of the object has changed. Does not (currently) recursively replace mutable subobjects.
f1241:m3
def named_objs(objlist, namesdict=None):
objs = OrderedDict()<EOL>if namesdict is not None:<EOL><INDENT>objtoname = {hashable(v): k for k, v in namesdict.items()}<EOL><DEDENT>for obj in objlist:<EOL><INDENT>if namesdict is not None and hashable(obj) in objtoname:<EOL><INDENT>k = objtoname[hashable(obj)]<EOL><DEDENT>elif hasattr(obj, "<STR_LIT:name>"):<EOL><INDENT>k = obj.name<EOL><DEDENT>elif hasattr(obj, '<STR_LIT>'):<EOL><INDENT>k = obj.__name__<EOL><DEDENT>else:<EOL><INDENT>k = as_unicode(obj)<EOL><DEDENT>objs[k] = obj<EOL><DEDENT>return objs<EOL>
Given a list of objects, returns a dictionary mapping from string name for the object to the object itself. Accepts an optional name,obj dictionary, which will override any other name if that item is present in the dictionary.
f1241:m4
def param_union(*parameterizeds, **kwargs):
warn = kwargs.pop('<STR_LIT>', True)<EOL>if len(kwargs):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>".format(<EOL>kwargs.popitem()[<NUM_LIT:0>]))<EOL><DEDENT>d = dict()<EOL>for o in parameterizeds:<EOL><INDENT>for k in o.param:<EOL><INDENT>if k != '<STR_LIT:name>':<EOL><INDENT>if k in d and warn:<EOL><INDENT>get_logger().warning("<STR_LIT>".format(k))<EOL><DEDENT>d[k] = getattr(o, k)<EOL><DEDENT><DEDENT><DEDENT>return d<EOL>
Given a set of Parameterized objects, returns a dictionary with the union of all param name,value pairs across them. If warn is True (default), warns if the same parameter has been given multiple values; otherwise uses the last value
f1241:m5
def guess_param_types(**kwargs):
params = {}<EOL>for k, v in kwargs.items():<EOL><INDENT>kws = dict(default=v, constant=True)<EOL>if isinstance(v, Parameter):<EOL><INDENT>params[k] = v<EOL><DEDENT>elif isinstance(v, dt_types):<EOL><INDENT>params[k] = Date(**kws)<EOL><DEDENT>elif isinstance(v, bool):<EOL><INDENT>params[k] = Boolean(**kws)<EOL><DEDENT>elif isinstance(v, int):<EOL><INDENT>params[k] = Integer(**kws)<EOL><DEDENT>elif isinstance(v, float):<EOL><INDENT>params[k] = Number(**kws)<EOL><DEDENT>elif isinstance(v, str):<EOL><INDENT>params[k] = String(**kws)<EOL><DEDENT>elif isinstance(v, dict):<EOL><INDENT>params[k] = Dict(**kws)<EOL><DEDENT>elif isinstance(v, tuple):<EOL><INDENT>if all(_is_number(el) for el in v):<EOL><INDENT>params[k] = NumericTuple(**kws)<EOL><DEDENT>elif all(isinstance(el. dt_types) for el in v) and len(v)==<NUM_LIT:2>:<EOL><INDENT>params[k] = DateRange(**kws)<EOL><DEDENT>else:<EOL><INDENT>params[k] = Tuple(**kws)<EOL><DEDENT><DEDENT>elif isinstance(v, list):<EOL><INDENT>params[k] = List(**kws)<EOL><DEDENT>elif isinstance(v, np.ndarray):<EOL><INDENT>params[k] = Array(**kws)<EOL><DEDENT>else:<EOL><INDENT>from pandas import DataFrame as pdDFrame<EOL>from pandas import Series as pdSeries<EOL>if isinstance(v, pdDFrame):<EOL><INDENT>params[k] = DataFrame(**kws)<EOL><DEDENT>elif isinstance(v, pdSeries):<EOL><INDENT>params[k] = Series(**kws)<EOL><DEDENT>else:<EOL><INDENT>params[k] = Parameter(**kws)<EOL><DEDENT><DEDENT><DEDENT>return params<EOL>
Given a set of keyword literals, promote to the appropriate parameter type based on some simple heuristics.
f1241:m6
def parameterized_class(name, params, bases=Parameterized):
if not (isinstance(bases, list) or isinstance(bases, tuple)):<EOL><INDENT>bases=[bases]<EOL><DEDENT>return type(name, tuple(bases), params)<EOL>
Dynamically create a parameterized class with the given name and the supplied parameters, inheriting from the specified base(s).
f1241:m7
def guess_bounds(params, **overrides):
guessed = {}<EOL>for name, p in params.items():<EOL><INDENT>new_param = copy.copy(p)<EOL>if isinstance(p, (Integer, Number)):<EOL><INDENT>if name in overrides:<EOL><INDENT>minv,maxv = overrides[name]<EOL><DEDENT>else:<EOL><INDENT>minv, maxv, _ = _get_min_max_value(None, None, value=p.default)<EOL><DEDENT>new_param.bounds = (minv, maxv)<EOL><DEDENT>guessed[name] = new_param<EOL><DEDENT>return guessed<EOL>
Given a dictionary of Parameter instances, return a corresponding set of copies with the bounds appropriately set. If given a set of override keywords, use those numeric tuple bounds.
f1241:m8
def _get_min_max_value(min, max, value=None, step=None):
<EOL>if value is None:<EOL><INDENT>if min is None or max is None:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>'.format(min, max, value))<EOL><DEDENT>diff = max - min<EOL>value = min + (diff / <NUM_LIT:2>)<EOL>if not isinstance(value, type(diff)):<EOL><INDENT>value = min + (diff // <NUM_LIT:2>)<EOL><DEDENT><DEDENT>else: <EOL><INDENT>if not isinstance(value, Real):<EOL><INDENT>raise TypeError('<STR_LIT>' % value)<EOL><DEDENT>if value == <NUM_LIT:0>:<EOL><INDENT>vrange = (value, value + <NUM_LIT:1>)<EOL><DEDENT>elif value > <NUM_LIT:0>:<EOL><INDENT>vrange = (-value, <NUM_LIT:3>*value)<EOL><DEDENT>else:<EOL><INDENT>vrange = (<NUM_LIT:3>*value, -value)<EOL><DEDENT>if min is None:<EOL><INDENT>min = vrange[<NUM_LIT:0>]<EOL><DEDENT>if max is None:<EOL><INDENT>max = vrange[<NUM_LIT:1>]<EOL><DEDENT><DEDENT>if step is not None:<EOL><INDENT>tick = int((value - min) / step)<EOL>value = min + tick * step<EOL><DEDENT>if not min <= value <= max:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(min, value, max))<EOL><DEDENT>return min, max, value<EOL>
Return min, max, value given input values with possible None.
f1241:m9
def concrete_descendents(parentclass):
return dict((c.__name__,c) for c in descendents(parentclass)<EOL>if not _is_abstract(c))<EOL>
Return a dictionary containing all subclasses of the specified parentclass, including the parentclass. Only classes that are defined in scripts that have been run or modules that have been imported are included, so the caller will usually first do ``from package import *``. Only non-abstract classes will be included.
f1241:m13
def abbreviate_paths(pathspec,named_paths):
from os.path import commonprefix, dirname, sep<EOL>prefix = commonprefix([dirname(name)+sep for name in named_paths.keys()]+[pathspec])<EOL>return OrderedDict([(name[len(prefix):],path) for name,path in named_paths.items()])<EOL>
Given a dict of (pathname,path) pairs, removes any prefix shared by all pathnames. Helps keep menu items short yet unambiguous.
f1241:m14
def __call__(self, val=None, time_type=None):
if time_type and val is None:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>if time_type:<EOL><INDENT>type_param = self.param.objects('<STR_LIT>').get('<STR_LIT>')<EOL>type_param.constant = False<EOL>self.time_type = time_type<EOL>type_param.constant = True<EOL><DEDENT>if val is not None:<EOL><INDENT>self._time = self.time_type(val)<EOL><DEDENT>return self._time<EOL>
When called with no arguments, returns the current time value. When called with a specified val, sets the time to it. When called with a specified time_type, changes the time_type and sets the current time to the given val (which *must* be specified) converted to that time type. To ensure that the current state remains consistent, this is normally the only way to change the time_type of an existing Time instance.
f1241:c1:m5
def __enter__(self):
self._pushed_state.append((self._time, self.timestep, self.until))<EOL>self.in_context = True<EOL>return self<EOL>
Enter the context and push the current state.
f1241:c1:m9
def __exit__(self, exc, *args):
(self._time, self.timestep, self.until) = self._pushed_state.pop()<EOL>self.in_context = len(self._pushed_state) != <NUM_LIT:0><EOL>if exc is StopIteration:<EOL><INDENT>return True<EOL><DEDENT>
Exit from the current context, restoring the previous state. The StopIteration exception raised in context will force the context to exit. Any other exception exc that is raised in the block will not be caught.
f1241:c1:m10
def __init__(self,**params):
super(Dynamic,self).__init__(**params)<EOL>if callable(self.default):<EOL><INDENT>self._set_instantiate(True)<EOL>self._initialize_generator(self.default)<EOL><DEDENT>
Call the superclass's __init__ and set instantiate=True if the default is dynamic.
f1241:c2:m0
def _initialize_generator(self,gen,obj=None):
<EOL>if hasattr(obj,"<STR_LIT>"):<EOL><INDENT>gen._Dynamic_time_fn = obj._Dynamic_time_fn<EOL><DEDENT>gen._Dynamic_last = None<EOL>gen._Dynamic_time = -<NUM_LIT:1><EOL>gen._saved_Dynamic_last = []<EOL>gen._saved_Dynamic_time = []<EOL>
Add 'last time' and 'last value' attributes to the generator.
f1241:c2:m1
def __get__(self,obj,objtype):
gen = super(Dynamic,self).__get__(obj,objtype)<EOL>if not hasattr(gen,'<STR_LIT>'):<EOL><INDENT>return gen<EOL><DEDENT>else:<EOL><INDENT>return self._produce_value(gen)<EOL><DEDENT>
Call the superclass's __get__; if the result is not dynamic return that result, otherwise ask that result to produce a value and return it.
f1241:c2:m2
@instance_descriptor<EOL><INDENT>def __set__(self,obj,val):<DEDENT>
super(Dynamic,self).__set__(obj,val)<EOL>dynamic = callable(val)<EOL>if dynamic: self._initialize_generator(val,obj)<EOL>if obj is None: self._set_instantiate(dynamic)<EOL>
Call the superclass's set and keep this parameter's instantiate value up to date (dynamic parameters must be instantiated). If val is dynamic, initialize it as a generator.
f1241:c2:m3
def _produce_value(self,gen,force=False):
if hasattr(gen,"<STR_LIT>"):<EOL><INDENT>time_fn = gen._Dynamic_time_fn<EOL><DEDENT>else:<EOL><INDENT>time_fn = self.time_fn<EOL><DEDENT>if (time_fn is None) or (not self.time_dependent):<EOL><INDENT>value = produce_value(gen)<EOL>gen._Dynamic_last = value<EOL><DEDENT>else:<EOL><INDENT>time = time_fn()<EOL>if force or time!=gen._Dynamic_time:<EOL><INDENT>value = produce_value(gen)<EOL>gen._Dynamic_last = value<EOL>gen._Dynamic_time = time<EOL><DEDENT>else:<EOL><INDENT>value = gen._Dynamic_last<EOL><DEDENT><DEDENT>return value<EOL>
Return a value from gen. If there is no time_fn, then a new value will be returned (i.e. gen will be asked to produce a new value). If force is True, or the value of time_fn() is different from what it was was last time produce_value was called, a new value will be produced and returned. Otherwise, the last value gen produced will be returned.
f1241:c2:m4
def _value_is_dynamic(self,obj,objtype=None):
return hasattr(super(Dynamic,self).__get__(obj,objtype),'<STR_LIT>')<EOL>
Return True if the parameter is actually dynamic (i.e. the value is being generated).
f1241:c2:m5
def _inspect(self,obj,objtype=None):
gen=super(Dynamic,self).__get__(obj,objtype)<EOL>if hasattr(gen,'<STR_LIT>'):<EOL><INDENT>return gen._Dynamic_last<EOL><DEDENT>else:<EOL><INDENT>return gen<EOL><DEDENT>
Return the last generated value for this parameter.
f1241:c2:m6
def _force(self,obj,objtype=None):
gen=super(Dynamic,self).__get__(obj,objtype)<EOL>if hasattr(gen,'<STR_LIT>'):<EOL><INDENT>return self._produce_value(gen,force=True)<EOL><DEDENT>else:<EOL><INDENT>return gen<EOL><DEDENT>
Force a new value to be generated, and return it.
f1241:c2:m7
def __init__(self,default=<NUM_LIT:0.0>,bounds=None,softbounds=None,<EOL>inclusive_bounds=(True,True), step=None, **params):
super(Number,self).__init__(default=default,**params)<EOL>self.set_hook = identity_hook<EOL>self.bounds = bounds<EOL>self.inclusive_bounds = inclusive_bounds<EOL>self._softbounds = softbounds<EOL>self.step = step<EOL>self._validate(default)<EOL>
Initialize this parameter object and store the bounds. Non-dynamic default values are checked against the bounds.
f1241:c3:m0
def __get__(self,obj,objtype):
result = super(Number,self).__get__(obj,objtype)<EOL>if self._value_is_dynamic(obj,objtype): self._validate(result)<EOL>return result<EOL>
Same as the superclass's __get__, but if the value was dynamically generated, check the bounds.
f1241:c3:m1
def set_in_bounds(self,obj,val):
if not callable(val):<EOL><INDENT>bounded_val = self.crop_to_bounds(val)<EOL><DEDENT>else:<EOL><INDENT>bounded_val = val<EOL><DEDENT>super(Number,self).__set__(obj,bounded_val)<EOL>
Set to the given value, but cropped to be within the legal bounds. All objects are accepted, and no exceptions will be raised. See crop_to_bounds for details on how cropping is done.
f1241:c3:m4
def crop_to_bounds(self,val):
<EOL>if _is_number(val):<EOL><INDENT>if self.bounds is None:<EOL><INDENT>return val<EOL><DEDENT>vmin, vmax = self.bounds<EOL>if vmin is not None:<EOL><INDENT>if val < vmin:<EOL><INDENT>return vmin<EOL><DEDENT><DEDENT>if vmax is not None:<EOL><INDENT>if val > vmax:<EOL><INDENT>return vmax<EOL><DEDENT><DEDENT><DEDENT>elif self.allow_None and val is None:<EOL><INDENT>return val<EOL><DEDENT>else:<EOL><INDENT>return self.default<EOL><DEDENT>return val<EOL>
Return the given value cropped to be within the hard bounds for this parameter. If a numeric value is passed in, check it is within the hard bounds. If it is larger than the high bound, return the high bound. If it's smaller, return the low bound. In either case, the returned value could be None. If a non-numeric value is passed in, set to be the default value (which could be None). In no case is an exception raised; all values are accepted.
f1241:c3:m5
def _validate(self, val):
if callable(val):<EOL><INDENT>return val<EOL><DEDENT>if self.allow_None and val is None:<EOL><INDENT>return<EOL><DEDENT>if not _is_number(val):<EOL><INDENT>raise ValueError("<STR_LIT>"%(self.name))<EOL><DEDENT>if self.step is not None and not _is_number(self.step):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._checkBounds(val)<EOL>
Checks that the value is numeric and that it is within the hard bounds; if not, an exception is raised.
f1241:c3:m7
def get_soft_bounds(self):
if self.bounds is None:<EOL><INDENT>hl,hu=(None,None)<EOL><DEDENT>else:<EOL><INDENT>hl,hu=self.bounds<EOL><DEDENT>if self._softbounds is None:<EOL><INDENT>sl,su=(None,None)<EOL><DEDENT>else:<EOL><INDENT>sl,su=self._softbounds<EOL><DEDENT>if sl is None: l = hl<EOL>else: l = sl<EOL>if su is None: u = hu<EOL>else: u = su<EOL>return (l,u)<EOL>
For each soft bound (upper and lower), if there is a defined bound (not equal to None) then it is returned, otherwise it defaults to the hard bound. The hard bound could still be None.
f1241:c3:m8
def __init__(self,default=(<NUM_LIT:0>,<NUM_LIT:0>),length=None,**params):
super(Tuple,self).__init__(default=default,**params)<EOL>if length is None and default is not None:<EOL><INDENT>self.length = len(default)<EOL><DEDENT>elif length is None and default is None:<EOL><INDENT>raise ValueError("<STR_LIT>" %<EOL>(self.name))<EOL><DEDENT>else:<EOL><INDENT>self.length = length<EOL><DEDENT>self._validate(default)<EOL>
Initialize a tuple parameter with a fixed length (number of elements). The length is determined by the initial default value, if any, and must be supplied explicitly otherwise. The length is not allowed to change after instantiation.
f1241:c7:m0
def __get__(self,obj,objtype):
if obj is None:<EOL><INDENT>return [getattr(objtype,a) for a in self.attribs]<EOL><DEDENT>else:<EOL><INDENT>return [getattr(obj,a) for a in self.attribs]<EOL><DEDENT>
Return the values of all the attribs, as a list.
f1241:c12:m1
def compute_default(self):
if self.default is None and callable(self.compute_default_fn):<EOL><INDENT>self.default=self.compute_default_fn()<EOL>if self.default not in self.objects:<EOL><INDENT>self.objects.append(self.default)<EOL><DEDENT><DEDENT>
If this parameter's compute_default_fn is callable, call it and store the result in self.default. Also removes None from the list of objects (if the default is no longer None).
f1241:c14:m1
def _validate(self, val):
if not self.check_on_set:<EOL><INDENT>self._ensure_value_is_in_objects(val)<EOL>return<EOL><DEDENT>if not (val in self.objects or (self.allow_None and val is None)):<EOL><INDENT>try:<EOL><INDENT>attrib_name = self.name<EOL><DEDENT>except AttributeError:<EOL><INDENT>attrib_name = "<STR_LIT>"<EOL><DEDENT>items = []<EOL>limiter = '<STR_LIT:]>'<EOL>length = <NUM_LIT:0><EOL>for item in self.objects:<EOL><INDENT>string = str(item)<EOL>length += len(string)<EOL>if length < <NUM_LIT:200>:<EOL><INDENT>items.append(string)<EOL><DEDENT>else:<EOL><INDENT>limiter = '<STR_LIT>'<EOL>break<EOL><DEDENT><DEDENT>items = '<STR_LIT:[>' + '<STR_LIT:U+002CU+0020>'.join(items) + limiter<EOL>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"%(val,attrib_name, items))<EOL><DEDENT>
val must be None or one of the objects in self.objects.
f1241:c14:m2
def _ensure_value_is_in_objects(self,val):
if not (val in self.objects):<EOL><INDENT>self.objects.append(val)<EOL><DEDENT>
Make sure that the provided value is present on the objects list. Subclasses can override if they support multiple items on a list, to check each item instead.
f1241:c14:m3
def get_range(self):
return named_objs(self.objects, self.names)<EOL>
Return the possible objects to which this parameter could be set. (Returns the dictionary {object.name:object}.)
f1241:c14:m4
def _validate(self,val):
if isinstance(self.class_, tuple):<EOL><INDENT>class_name = ('<STR_LIT>' % '<STR_LIT:U+002CU+0020>'.join(cl.__name__ for cl in self.class_))<EOL><DEDENT>else:<EOL><INDENT>class_name = self.class_.__name__<EOL><DEDENT>if self.is_instance:<EOL><INDENT>if not (isinstance(val,self.class_)) and not (val is None and self.allow_None):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" %<EOL>(self.name, class_name, val))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not (val is None and self.allow_None) and not (issubclass(val,self.class_)):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" %<EOL>(val.__name__, class_name, val.__class__.__name__))<EOL><DEDENT><DEDENT>
val must be None, an instance of self.class_ if self.is_instance=True or a subclass of self_class if self.is_instance=False
f1241:c16:m1
def get_range(self):
classes = concrete_descendents(self.class_)<EOL>d=OrderedDict((name,class_) for name,class_ in classes.items())<EOL>if self.allow_None:<EOL><INDENT>d['<STR_LIT:None>']=None<EOL><DEDENT>return d<EOL>
Return the possible types for this parameter's value. (I.e. return {name: <class>} for all classes that are concrete_descendents() of self.class_.) Only classes from modules that have been imported are added (see concrete_descendents()).
f1241:c16:m2
def _validate(self, val):
if self.allow_None and val is None:<EOL><INDENT>return<EOL><DEDENT>if not isinstance(val, list):<EOL><INDENT>raise ValueError("<STR_LIT>"%(self.name))<EOL><DEDENT>if self.bounds is not None:<EOL><INDENT>min_length,max_length = self.bounds<EOL>l=len(val)<EOL>if min_length is not None and max_length is not None:<EOL><INDENT>if not (min_length <= l <= max_length):<EOL><INDENT>raise ValueError("<STR_LIT>"%(self.name,min_length,max_length))<EOL><DEDENT><DEDENT>elif min_length is not None:<EOL><INDENT>if not min_length <= l:<EOL><INDENT>raise ValueError("<STR_LIT>"%(self.name,min_length))<EOL><DEDENT><DEDENT>elif max_length is not None:<EOL><INDENT>if not l <= max_length:<EOL><INDENT>raise ValueError("<STR_LIT>"%(self.name,max_length))<EOL><DEDENT><DEDENT><DEDENT>self._check_type(val)<EOL>
Checks that the list is of the right length and has the right contents. Otherwise, an exception is raised.
f1241:c17:m1
def __get__(self, obj, objtype):
raw_path = super(Path,self).__get__(obj,objtype)<EOL>return None if raw_path is None else self._resolve(raw_path)<EOL>
Return an absolute, normalized path (see resolve_path).
f1241:c25:m3
def _validate(self, val):
if self.allow_None and val is None:<EOL><INDENT>return<EOL><DEDENT>if not isinstance(val, dt_types) and not (self.allow_None and val is None):<EOL><INDENT>raise ValueError("<STR_LIT>"%self.name)<EOL><DEDENT>if self.step is not None and not isinstance(self.step, dt_types):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._checkBounds(val)<EOL>
Checks that the value is numeric and that it is within the hard bounds; if not, an exception is raised.
f1241:c31:m1
def _validate(self, val):
if self.allow_None and val is None:<EOL><INDENT>return<EOL><DEDENT>super(Range, self)._validate(val)<EOL>self._checkBounds(val)<EOL>
Checks that the value is numeric and that it is within the hard bounds; if not, an exception is raised.
f1241:c33:m1