class Result(_result.PoseResult): _algorithm: Algorithm _forces: Vector _wrench: Vector def __init__(self, algorithm: Algorithm, pose: _pose.Pose, forces: Vector, wrench: Vector, **kwargs): super().__init__(pose=pose, **kwargs) self._algorithm = algorithm self._forces = forces self._wrench = wrench @property def algorithm(self): return self._algorithm @property def forces(self): return self._forces @property def wrench(self): return self._wrench __repr__ = make_repr( 'algorithm', 'pose', 'forces', 'wrench' )
class Drivetrain(RobotComponent): gearbox: _gearbox.Gearbox drum: _drum.Drum motor: _motor.Motor def __init__(self, drum: Optional[_drum.Drum] = None, motor: Optional[_motor.Motor] = None, gearbox: Optional[_gearbox.Gearbox] = None, **kwargs): super().__init__(**kwargs) self.drum = drum or None self.motor = motor or None self.gearbox = gearbox or None def __eq__(self, other): if not isinstance(other, self.__class__): raise TypeError() if self is other: return True return self.drum == other.drum \ and self.gearbox == other.gearbox \ and self.motor == other.motor def __ne__(self, other): return not self == other def __hash__(self): return hash((self.drum, self.gearbox, self.motor)) __repr__ = make_repr('motor', 'gearbox', 'drum')
class TestMe(object): def __init__(self, name, parent=None): self.name = name self.parent = parent self.foo = False __repr__ = make_repr('parent', 'foo', 'name')
class Gearbox(RobotComponent): inertia: Num ratio: Num def __init__(self, ratio: Optional[Num] = None, inertia: Optional[Num] = None, **kwargs): super().__init__(**kwargs) self.ratio = ratio or 1 self.inertia = inertia or np_.Inf def __eq__(self, other): if not isinstance(other, self.__class__): raise TypeError() if self is other: return True return self.inertia == other.inertia \ and self.ratio == other.ratio def __ne__(self, other): return not self == other def __hash__(self): return hash((self.inertia, self.ratio)) __repr__ = make_repr('ratio', 'inertia')
def xmlall(classname, tag_name, **params): class_ = type( classname, (XMLObject, ConvertableXML), { "__init__": make_init(params), "to_xml": make_to_xml(tag_name, params), "_from_xml": make_from_xml(params), "_tag_name": tag_name, "__len__": lambda self: len(self.values), "__getitem__": lambda self, key: self.values.__getitem__(key), "__setitem__": lambda self, key, value: self.values.__setitem__(key, value), "__delitem__": lambda self, key: self.values.__delitem__(key), "__iter__": lambda self: iter(self.values), "append": lambda self, item: self.values.append(item), "to_object": to_object, }) [ setattr(class_, name, make_prop(prop_class)) for name, prop_class in params.items() ] class_.__repr__ = make_repr('values') return class_
def xmllist(classname, tag_name, children, kws=None): if kws is None: kws = [] children_class, children_tag = None, None if isinstance(children, type): children_class = children else: children_tag = children class_ = type( classname, (XMLObject, ConvertableXML), { "__init__": make_init(kws), "to_xml": make_to_xml(tag_name, children_class, children_tag, kws), "_from_xml": make_from_xml(children_class), "__len__": lambda self: len(self.values), "__getitem__": lambda self, key: self.values.__getitem__(key), "__setitem__": lambda self, key, value: self.values.__setitem__(key, value), "__delitem__": lambda self, key: self.values.__delitem__(key), "__iter__": lambda self: iter(self.values), "append": make_append(children_class), "to_object": to_object, "_tag_name": tag_name }) class_.__repr__ = make_repr('values', *kws) return class_
class TestMe(object): def __init__(self): # this reformatting needed to convence Python3 # that we want to put bytes into this attribute self.foo = u'бар'.encode('utf-8') __repr__ = make_repr('foo')
class Bar(object): def __init__(self): self.first = 1 self.second = 2 self.third = 3 __repr__ = make_repr()
class KinematicChain(RobotComponent): cable: int frame_anchor: int platform: int platform_anchor: int def __init__(self, frame_anchor: int, platform: int, platform_anchor: int, cable: int, **kwargs): super().__init__(**kwargs) self.cable = cable self.frame_anchor = frame_anchor self.platform = platform self.platform_anchor = platform_anchor def __eq__(self, other): if not isinstance(other, self.__class__): raise TypeError() if self is other: return True return self.frame_anchor == other.frame_anchor \ and self.platform == other.platform \ and self.platform_anchor == other.platform_anchor \ and self.cable == other.cable def __ne__(self, other): return not self == other def __hash__(self): return hash((self.cable, self.frame_anchor, self.platform, self.platform_anchor)) __repr__ = make_repr('frame_anchor', 'platform', 'platform_anchor', 'cable')
class TestMe(object): def __init__(self): self.foo = u'фу' self.bar = u'бар' self.bazz = u'базз' __repr__ = make_repr('foo', 'bar', 'bazz')
class TestMe(object): def __init__(self): self.foo = 1 def bar(self): return 2 __repr__ = make_repr()
class Foo(object): def __init__(self): self.bars = { 1: Bar(), 2: Bar(), u'три': Bar(), } __repr__ = make_repr()
class Result(_result.PoseResult): _matrix: Matrix _kernel: Matrix _pinv: Matrix def __init__(self, pose: _pose.Pose, matrix: Union[Matrix, Result], **kwargs): super().__init__(pose=pose, **kwargs) self._matrix = matrix.matrix if isinstance(matrix, Result) else matrix self._kernel = None self._pinv = None @property def inv(self): return self.pinv @property def is_singular(self): # according to Pott.2018, a pose is singular if the structure # matrix's rank is smaller than the number of degrees of freedom # i.e., the structure matrix's number of rows return _np.linalg.matrix_rank(self._matrix) >= self._matrix.shape[0] @property def kernel(self): if self._kernel is None: self._kernel = null_space(self._matrix) return self._kernel @property def matrix(self): return self._matrix @property def null_space(self): return self.kernel @property def nullspace(self): return self.kernel @property def pinv(self): if self._pinv is None: if self._matrix.shape[0] == self._matrix.shape[1]: self._pinv = _np.linalg.inv(self._matrix) else: self._pinv = _np.linalg.pinv(self._matrix) return self._pinv __repr__ = make_repr( 'pose', 'matrix', 'kernel', )
class KinematicChainList(UserList, RobotComponent): data: List[KinematicChain] @property def frame_anchor(self): return (kinematicchain.frame_anchor for kinematicchain in self.data) @property def platform(self): return (kinematicchain.platform for kinematicchain in self.data) @property def platform_anchor(self): return (kinematicchain.platform_anchor for kinematicchain in self.data) @property def cable(self): return (kinematicchain.cable for kinematicchain in self.data) def with_frame_anchor(self, anchor: Union[Sequence[Num], Vector]): anchor = anchor if isinstance(anchor, Sequence) else [anchor] return self.__class__(d for d in self.data if d.frame_anchor in anchor) def with_platform(self, platform: Union[Sequence[Num], Vector]): platform = platform if isinstance(platform, Sequence) else [platform] return self.__class__(d for d in self.data if d.platform in platform) def with_platform_anchor(self, anchor: Union[Sequence[Num], Vector]): anchor = anchor if isinstance(anchor, Sequence) else [anchor] return self.__class__(d for d in self.data if d.platform_anchor in anchor) def with_cable(self, cable: Union[Sequence[Num], Vector]): cable = cable if isinstance(cable, Sequence) else [cable] return self.__class__(d for d in self.data if d.cable in cable) def __eq__(self, other): if not isinstance(other, self.__class__): raise TypeError() if self is other: return True return all(this == that for this, that in zip(self, other)) def __ne__(self, other): return not self == other def __hash__(self): return hash(tuple(self.data)) __repr__ = make_repr('data')
class PlatformList(UserList, RobotComponent): data: List[Platform] @property def all_combinations(self): return itertools.combinations_with_replacement(self.data, 2) @property def anchors(self): return (platform.anchors for platform in self.data) @property def angular_inertia(self): return (platform.angular_inertia for platform in self.data) @property def bi(self): return (platform.bi for platform in self.data) @property def center_of_gravity(self): return (platform.center_of_gravity for platform in self.data) @property def center_of_linkage(self): return (platform.center_of_linkage for platform in self.data) @property def inertia(self): return (platform.inertia for platform in self.data) @property def linear_inertia(self): return (platform.linear_inertia for platform in self.data) @property def motion_pattern(self): return (platform.motion_pattern for platform in self.data) def __eq__(self, other): if not isinstance(other, self.__class__): raise TypeError() if self is other: return True return all(this == that for this, that in zip(self, other)) def __ne__(self, other): return not self == other def __hash__(self): return hash(tuple(self.data)) __repr__ = make_repr('data')
class Pulley(RobotComponent): angular: _angular.Angular geometry: _geometry.Primitive inertia: _inertia.Inertia radius: Num def __init__(self, radius: Num, geometry: Optional[_geometry.Primitive] = None, inertia: Optional[_inertia.Inertia] = None, dcm: Optional[Matrix] = None, angular: Optional[_angular.Angular] = None, **kwargs): super().__init__(**kwargs) self.radius = radius self.geometry = geometry or None self.inertia = inertia or _inertia.Inertia() if angular is None: angular = _angular.Angular( dcm=dcm if dcm is not None else np_.eye(3)) self.angular = angular @property def dcm(self): return self.angular.dcm @dcm.setter def dcm(self, dcm: Matrix): self.angular.dcm = dcm def __eq__(self, other): if not isinstance(other, self.__class__): raise TypeError() if self is other: return True return self.radius == other.radius \ and self.angular == other.angular \ and self.geometry == other.geometry \ and self.inertia == other.inertia def __ne__(self, other): return not self == other def __hash__(self): return hash((self.angular, self.geometry, self.inertia, self.radius)) __repr__ = make_repr( 'radius', 'geometry', 'inertia', 'angular' )
class PoseListResult(Result): _pose_list: PoseList def __init__(self, pose_list: PoseList, **kwargs): super().__init__(**kwargs) self._pose_list = pose_list @property def pose_list(self): return self._pose_list __repr__ = make_repr('pose_list')
class PoseResult(Result): _pose: Pose def __init__(self, pose: Pose, **kwargs): super().__init__(**kwargs) self._pose = pose @property def pose(self): return self._pose __repr__ = make_repr('pose')
class CableList(UserList, RobotComponent): data: List[Cable] @property def name(self): return (cable.name for cable in self.data) @property def material(self): return (cable.material for cable in self.data) @property def diameter(self): return (cable.diameter for cable in self.data) @property def modulus(self): return (cable.modulus for cable in self.data) @property def color(self): return (cable.color for cable in self.data) @property def breaking_load(self): return (cable.breaking_load for cable in self.data) @property def elasticities(self): return (cable.elasticities for cable in self.data) @property def viscosities(self): return (cable.viscosities for cable in self.data) def __eq__(self, other): if not isinstance(other, self.__class__): raise TypeError() if self is other: return True return all(this == that for this, that in zip(self, other)) def __ne__(self, other): return not self == other def __hash__(self): return hash(tuple(self.data)) __repr__ = make_repr('data')
class ScoreEntry(db.Model): """Models a component of the score for a given player. A die is associated with a player (i.e. a user and a game), a score_item, and a value (number of points). """ id = db.Column(db.Integer(), primary_key=True) player_id = db.Column(db.Integer, db.ForeignKey('player.id'), nullable=False) player = db.relationship('Player', backref=db.backref('score_entries', lazy=True)) score_item = db.Column(db.Enum(ScoreItem), nullable=False) value = db.Column(db.Integer) db.UniqueConstraint('player_id', 'score_item', name='uix_1') game = db.relationship('Game', secondary='player', lazy='subquery', backref=db.backref('score_entries', lazy=True)) user = db.relationship('User', secondary='player', lazy='subquery', backref=db.backref('score_entries', lazy=True)) def __init__(self, **kwargs): """Initializes score_entry. Keyword arguments: id -- a unique integer identifying the score_entry. score_item -- this entrie's score item. user -- the user to which this entry belongs. game -- the game to which this entry belongs. player -- the player object to which this entry belongs. value -- number of points for this entry (Null if the entry is still available). """ super(ScoreEntry, self).__init__(**kwargs) def __eq__(self, other): """Return true if other is a score_entry with the same id.""" return (self.__class__ == other.__class__ and self.id == other.id) def __hash__(self): """A hash for this object.""" return hash(self.id) __repr__ = make_repr() @property def is_available(self): """Return true if this entry is still available to the player.""" return self.value is None
class PoseList(UserList, Object): data: Sequence[Pose] @property def acceleration(self): return (pose.acceleration for pose in self.data) @property def angular(self): return (pose.angular for pose in self.data) @property def linear(self): return (pose.linear for pose in self.data) @property def position(self): return (pose.position for pose in self.data) @property def state(self): return (pose.state for pose in self.data) @property def time(self): return (pose.time for pose in self.data) @property def transformation(self): return (pose.transformation for pose in self.data) @property def velocity(self): return (pose.velocity for pose in self.data) def __eq__(self, other): if not isinstance(other, self.__class__): raise TypeError() if self is other: return True return all(this == that for this, that in zip(self, other)) def __ne__(self, other): return not self == other def __hash__(self): return hash(tuple(self.data)) __repr__ = make_repr('data')
class PlatformAnchor(Anchor): def __init__(self, position: Optional[Vector] = None, dcm: Optional[Matrix] = None, linear: Optional[_linear.Linear] = None, angular: Optional[_angular.Angular] = None, **kwargs): super().__init__(position=position, dcm=dcm, linear=linear, angular=angular, **kwargs) __repr__ = make_repr('position', 'dcm')
def test_if_attribute_can_be_generated_by_callable(): # In this case, we check if make_repr can # accept keyword arguments, where value is # a callable which returns attribute's value class TestMe(object): def some_method(self): return u'Минор' TestMe.__repr__ = make_repr(blah=TestMe.some_method) instance = TestMe() expected = "<TestMe blah=u'Минор'>" result = repr(instance) eq_(result, expected.strip())
def xmlenum(classname, tag_name, **enums): class_ = type( classname, (XMLObject, ConvertableXML), { "__init__": make_init(classname, enums), "to_xml": make_to_xml(tag_name), "_from_xml": make_from_xml(enums), "__eq__": make_eq(classname), "__str__": __str__, "_tag_name": tag_name, "__hash__": make_hash(enums), "to_object": to_object, "items": enums, **enums }) class_.__repr__ = make_repr('key') return class_
def xmltuple(classname, tag_name, attributes, children_classes=None, kws=[], types={}): if isinstance(children_classes, (list, tuple)): children_classes = {c_._tag_name: c_ for c_ in children_classes} class_ = type( classname, (XMLObject, ConvertableXML), { "__init__": make_init(attributes, types), "to_xml": make_to_xml(tag_name, attributes, kws), "_from_xml": make_from_xml(children_classes), "_tag_name": tag_name, "to_object": make_to_object(tag_name, attributes, kws, types), "__iter__": make_iter(attributes), **{key: None for key in attributes} }) class_.__repr__ = make_repr(*attributes, *kws) return class_
def xmltag(classname, tag_name, type_): class_ = type( classname, (XMLObject, ConvertableXML), { "__init__": lambda self, value: setattr(self, 'value', type_(value)), "to_xml": to_xml, "_from_xml": classmethod(lambda cls, tag: cls._make_args(tag.text)), "to_object": to_object, "_tag_name": tag_name, "__str__": lambda self: str(self.value), "__hash__": make_hash(type_) } ) class_.__repr__ = make_repr('value') return class_
class ScopeMeta(object): _name: str _file: Union[AnyStr, _pl.Path] _start_record: Union[AnyStr, _datetime.datetime] _end_record: Union[AnyStr, _datetime.datetime] def __init__(self, name: str, file: Union[AnyStr, _pl.Path], start_record: Union[AnyStr, _datetime.datetime], end_record: Union[AnyStr, _datetime.datetime]): self._name = name self._file = file self._start_record = start_record self._end_record = end_record @property def end_record(self): return self._end_record @property def file(self): return self._file @property def name(self): return self._name @property def start_record(self): return self._start_record __repr__ = make_repr( 'name', 'file', 'start_record', 'end_record', )
class Die(db.Model): """Models a die. A die is associated with a game, an index (unique within the game), and a face value. """ id = db.Column(db.Integer, primary_key=True) game_id = db.Column(db.Integer, db.ForeignKey('game.id'), nullable=False) game = db.relationship('Game', backref=db.backref('dice', lazy=True)) index = db.Column(db.Integer, nullable=False) value = db.Column(db.Integer, nullable=False, default=6) db.UniqueConstraint('game_id', 'index', name='uix_1') def __init__(self, **kwargs): """Initializes die object. Keyword arguments: id -- a unique integer identifying the die. game -- the game to which this die belongs. index -- orders the die within a game. value -- the face value of the die (defaults to 6). """ super(Die, self).__init__(**kwargs) def __eq__(self, other): """Return true if other is a die with the same id.""" return (self.__class__ == other.__class__ and self.id == other.id) def __hash__(self): """Return a hash for this object.""" return hash(self.id) __repr__ = make_repr() def roll(self): """Set die value to a random number between 1 and 6 (inclusive).""" self.value = randint(1, 6)
class Primitive(Object, ABC): """ """ """ (3,) vector denoting the point where the geometry primitive is centered around """ _center: Vector """ (3,) vector denoting the centroid of the geometry """ _centroid: Vector """ Surface area of the geometry """ _surface: float """ Geometric volume of the geometry """ _volume: float def __init__(self, center: Vector = None, **kwargs): super().__init__(**kwargs) self.center = center if center is not None else [0.0, 0.0, 0.] self._centroid = None @property @abstractmethod def centroid(self): """ (3,) vector denoting the centroid of the geometry Returns ------- """ raise NotImplementedError() @property @abstractmethod def surface_area(self): """ Surface area of the geometry Returns ------- """ raise NotImplementedError() @property @abstractmethod def volume(self): """ Geometric volume of the geometry Returns ------- """ raise NotImplementedError() @property def center(self): """ (3,) vector denoting the point where the geometry primitive is centered around Returns ------- """ return self._center @center.setter def center(self, center: Vector): self._center = _np.asarray(center) @center.deleter def center(self): del self._center @property def faces(self): raise NotImplementedError() @property def num_faces(self): return len(self.faces) @property def num_vertices(self): return len(self.vertices) @property def vertices(self): raise NotImplementedError() def __eq__(self, other): if not isinstance(other, type(self)): return False if self is other: return True return _np.allclose(self.centroid, other.centroid) \ and _np.isclose(self.surface_area, other.surface_area) \ and _np.isclose(self.volume, other.volume) def __ne__(self, other): return not self == other def __hash__(self): centroid = self.centroid return hash((centroid[0], centroid[1], centroid[2], self.surface_area, self.volume)) __repr__ = make_repr( 'centroid', 'surface', 'volume', )
for tag in self.soup.find_all('entity'): entity = Entity.from_xml(tag) self.add_entity(entity) self.relations = [ Relation.from_xml(tag) for tag in self.soup.find_all('relation') ] def iter_relations(self, filter_): for relation in self.relations: if filter_(relation): yield relation elif len(relation) == 2 and filter_(relation.invert()): yield relation.invert() def to_xml(self): soup = BeautifulSoup(features='xml') soup.append( soup.new_tag('erModel', **self._config.XML['ErRootAttributes']) ) root = soup.find('erModel') XMLObject.soup = self.soup for entity in self.entities.values(): root.append(entity.to_xml()) for relation in self.relations: root.append(relation.to_xml()) return soup ERD.__repr__ = make_repr('entities', 'relations')