def __init__(self, *args, **kwargs): for cls in self._classes: if isinstance(cls, six.string_types): cls = import_item(cls) # TODO: add a second pass where we allow additional properties? if all(key in cls.class_traits() for key in kwargs): try: cls(*args, **kwargs) except (T.TraitError, ValueError): pass else: self.add_traits( **{ key: copy.copy(val) for key, val in cls.class_traits().items() }) break else: raise T.TraitError("{cls}: initialization arguments not " "valid in any wrapped classes" "".format(cls=self.__class__.__name__)) super(AnyOfObject, self).__init__(*args, **kwargs)
def clsvisit_JSONHasTraits(self, cls, dct, *args, **kwargs): try: obj = cls() except TypeError: # Argument missing obj = cls('') additional_traits = cls._get_additional_traits() # Extract all other items, assigning to appropriate trait reverse_name_map = {v:k for k, v in obj._trait_name_map.items()} for schema_key, val in dct.items(): if schema_key in obj._metadata: obj._metadata[schema_key] = val else: trait_key = reverse_name_map.get(schema_key, schema_key) subtrait = obj.traits().get(trait_key, additional_traits) if not subtrait: raise T.TraitError("trait {0} not valid in class {1}" "".format(trait_key, cls)) obj.set_trait(trait_key, self.visit(subtrait, val, *args, **kwargs)) return obj
def clsvisit_JSONHasTraits(self, cls, dct, *args, **kwargs): try: obj = cls() except TypeError: # Argument missing obj = cls('') additional_traits = cls._get_additional_traits() # Extract metadata, if it exists obj._metadata.update( {prop: dct[prop] for prop in obj._metadata if prop in dct}) # Extract all other items, assigning to appropriate trait for prop, val in dct.items(): if prop in obj._metadata: continue subtrait = obj.traits().get(prop, additional_traits) if not subtrait: raise T.TraitError("trait {0} not valid in class {1}" "".format(prop, cls)) obj.set_trait(prop, self.visit(subtrait, val, *args, **kwargs)) return obj
def _valid_mass(self, proposal): mass = proposal["value"] if mass < 0: raise tl.TraitError(f"mass cannot be negative ({mass})") return mass
def _valid_friction(self, proposal): friction = proposal["value"] if friction < 0: raise tl.TraitError(f"friction cannot be negative ({friction})") return friction
def _default_sizes(self): raise tl.TraitError('sizes must be specified')
def _validate_nside(self, proposal): if not np.all(proposal['value'] == self.sizes + 2): raise tl.TraitError('bad nside, should be sizes + 2') return proposal['value']
def change_by_df(self, df, columns=None, otype_default='pandas3js.models.IDObject', otype_column=None, remove_missing=True): """ change collection by datafame of idobject traits Properties ---------- df : pd.DataFrame dataframe containing 'id' column columns : None or str use only these columns as attr, if None use all otype_default : str default ID object class to use otype_column : None or str if str, use this column to set the ID object class remove_missing : bool remove objects not present in dataframe """ assert 'id' in df.columns if otype_column is not None: assert otype_column in df.columns, 'df does not contain specified otype column; {}'.format(otype_column) if not columns is None: assert set(df.columns).issuperset(columns), 'required columns not in df' assert df.id.nunique() == df.shape[0], "df id's are not unique" existing_ids = [] old_objects = [] # remove missing if required for obj in self.idobjects: existing_ids.append(obj.id) if obj.id in df.id.values.tolist() or not remove_missing: old_objects.append(obj) new_objects = [] new_traits = [] for idx, s in df.iterrows(): # create new objects if not s.id in existing_ids: otype_name = otype_default if otype_column is None else s[otype_column] try: idobject = str_to_obj(otype_name)() assert isinstance(idobject, self._allowed_object), ( '{0} is not {1}'.format(idobject, self._allowed_object)) except Exception as err: raise TypeError( '"{0}" (proposed for id {1}) is not a valid object: \n {2}'.format(otype_name, s.id, err)) new_objects.append(idobject) else: idobject = self.get(s.id) # TODO test object class is still the same # the process overhead for such a niche case might not be worth it ? # if otype_column is not None: # otype_name = s[otype_column] # try: # newobject = str_to_obj(otype_name)() # assert isinstance(newobject, self._allowed_object), ( # '{0} is not {1}'.format(newobject, self._allowed_object)) # except Exception as err: # raise TypeError( # '"{0}" (proposed for id {1}) is not a valid object: \n {2}'.format(otype_name, s.id, err)) # if not isinstance(newobject,idobject.__class__): # old_objects.remove(idobject) # new_objects.append(newobject) if not columns is None: s = s[columns] for key, value in s.iteritems(): try: if np.isnan(value): continue except: pass if key==otype_column: continue if not key in idobject.get_object_trait_names(): raise trait.TraitError('object with id {0} does not have trait: {1}'.format(s.id, key)) # wait to set traits until all are objects are tested new_traits.append((idobject, key, value)) # hold trait notifications until all have been updated with self.hold_trait_notifications(): for idobject, key, value in new_traits: idobject.set_trait(key, value) self.set_trait('idobjects', tuple(old_objects + new_objects)) return
def _default_ndim(self): if len(self.sizes.shape) is not 1 or self.sizes.shape[0] < 3: raise tl.TraitError('sizes must have shape (ndim>=3,)') return self.sizes.shape[0]
def _valid_age(self, proposal): age = proposal["value"] if age < 0: raise traitlets.TraitError("must be positive") return proposal["value"]
def _valid_value(self, proposal): if proposal['value'] not in ['src', 'data-src']: raise traits.TraitError('src_name must be src or src or data-src') return proposal['value']
def _valid_eps(self, proposal): if (proposal['value'] > 0) & (proposal['value'] < 1): return proposal['value'] else: raise traitlets.TraitError('`eps` must be between 0 and 1.')
def _valid_density(self, proposal): if (proposal['value'] > 0) & (proposal['value'] <= 1): return proposal['value'] else: raise traitlets.TraitError('`density` must be 0 < density <= 1.')
def _valid_pivot(self, proposal): pivot = proposal['value'] if pivot not in ['centre', 'corner']: raise trait.TraitError('pivot must be at the centre or corner') return proposal['value']
def _valid_normal(self, proposal): x, y, z = proposal['value'] if x == 0 and y == 0 and z == 0: raise trait.TraitError('normal cannot be (0,0,0)') return proposal['value']
def _valid_value(self, proposal): if proposal["value"] not in ["src", "data-src"]: raise traits.TraitError("src_name must be src or src or data-src") return proposal["value"]
def _validate_student_id(self, change_details): new_id = change_details["value"] # fetch the new value if new_id < 1 or new_id > 100: raise traitlets.TraitError( "Student Id out of rang(1, 100), found: {}".format(new_id)) return new_id # this value gets assigned to self.student_id
def validate(self, obj, value): if value is None or isinstance(value, State): return value else: raise traitlets.TraitError('value should be a glue State instance')
def generic_visit(self, trait, dct, *args, **kwargs): # pass-through simple types if isinstance(dct, (integer_types, string_types, bool, float)): return dct else: raise T.TraitError('cannot set {0} to {1}'.format(trait, dct))
def _validate_path(self, proposal): path = proposal['value'] if os.path.exists(path): return (proposal['value']) else: raise traitlets.TraitError('Non-existent path')
def _valid_window_uid(self, proposal): if proposal['value'][:7] != "window_": raise traitlets.TraitError('window_uid must be "window_xxx".') return proposal['value']
def _valid_bounds(self, proposal): lower, upper = proposal["value"] for l, u in zip(lower, upper): if l > u: raise tl.TraitError(f"lower bound cannot be larger than upper bound ({lower} !<= {upper})") return lower, upper