code
stringlengths
114
1.05M
path
stringlengths
3
312
quality_prob
float64
0.5
0.99
learning_prob
float64
0.2
1
filename
stringlengths
3
168
kind
stringclasses
1 value
from dataclasses import dataclass, field from typing import Optional from .geometry import Geometry __NAMESPACE__ = "sdformat/v1.8/collision.xsd" @dataclass class Collision: """The collision properties of a link. Note that this can be different from the visual properties of a link, for example, simpler collision models are often used to reduce computation time. Parameters ---------- laser_retro: intensity value returned by laser sensor. max_contacts: Maximum number of contacts allowed between two entities. This value overrides the max_contacts element defined in physics. pose: A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. geometry: The shape of the visual or collision object. surface: The surface parameters name: Unique name for the collision element within the scope of the parent link. """ class Meta: name = "collision" laser_retro: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_contacts: int = field( default=10, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: Optional["Collision.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) geometry: Optional[Geometry] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) surface: Optional["Collision.Surface"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Surface: """ The surface parameters. """ bounce: Optional["Collision.Surface.Bounce"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) friction: Optional["Collision.Surface.Friction"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) contact: Optional["Collision.Surface.Contact"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) soft_contact: Optional["Collision.Surface.SoftContact"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Bounce: """ Parameters ---------- restitution_coefficient: Bounciness coefficient of restitution, from [0...1], where 0=no bounciness. threshold: Bounce capture velocity, below which effective coefficient of restitution is 0. """ restitution_coefficient: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) threshold: float = field( default=100000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Friction: """ Parameters ---------- torsional: Parameters for torsional friction ode: ODE friction parameters bullet: """ torsional: Optional["Collision.Surface.Friction.Torsional"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) ode: Optional["Collision.Surface.Friction.Ode"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) bullet: Optional["Collision.Surface.Friction.Bullet"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Torsional: """ Parameters for torsional friction. Parameters ---------- coefficient: Torsional friction coefficient, unitless maximum ratio of tangential stress to normal stress. use_patch_radius: If this flag is true, torsional friction is calculated using the "patch_radius" parameter. If this flag is set to false, "surface_radius" (R) and contact depth (d) are used to compute the patch radius as sqrt(R*d). patch_radius: Radius of contact patch surface. surface_radius: Surface radius on the point of contact. ode: Torsional friction parameters for ODE """ coefficient: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) use_patch_radius: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) patch_radius: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) surface_radius: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) ode: Optional["Collision.Surface.Friction.Torsional.Ode"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Ode: """ Torsional friction parameters for ODE. Parameters ---------- slip: Force dependent slip for torsional friction, equivalent to inverse of viscous damping coefficient with units of rad/s/(Nm). A slip value of 0 is infinitely viscous. """ slip: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Ode: """ ODE friction parameters. Parameters ---------- mu: Coefficient of friction in first friction pyramid direction, the unitless maximum ratio of force in first friction pyramid direction to normal force. mu2: Coefficient of friction in second friction pyramid direction, the unitless maximum ratio of force in second friction pyramid direction to normal force. fdir1: Unit vector specifying first friction pyramid direction in collision-fixed reference frame. If the friction pyramid model is in use, and this value is set to a unit vector for one of the colliding surfaces, the ODE Collide callback function will align the friction pyramid directions with a reference frame fixed to that collision surface. If both surfaces have this value set to a vector of zeros, the friction pyramid directions will be aligned with the world frame. If this value is set for both surfaces, the behavior is undefined. slip1: Force dependent slip in first friction pyramid direction, equivalent to inverse of viscous damping coefficient with units of m/s/N. A slip value of 0 is infinitely viscous. slip2: Force dependent slip in second friction pyramid direction, equivalent to inverse of viscous damping coefficient with units of m/s/N. A slip value of 0 is infinitely viscous. """ mu: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) mu2: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) fdir1: str = field( default="0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) slip1: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) slip2: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Bullet: """ Parameters ---------- friction: Coefficient of friction in first friction pyramid direction, the unitless maximum ratio of force in first friction pyramid direction to normal force. friction2: Coefficient of friction in second friction pyramid direction, the unitless maximum ratio of force in second friction pyramid direction to normal force. fdir1: Unit vector specifying first friction pyramid direction in collision-fixed reference frame. If the friction pyramid model is in use, and this value is set to a unit vector for one of the colliding surfaces, the friction pyramid directions will be aligned with a reference frame fixed to that collision surface. If both surfaces have this value set to a vector of zeros, the friction pyramid directions will be aligned with the world frame. If this value is set for both surfaces, the behavior is undefined. rolling_friction: Coefficient of rolling friction """ friction: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) friction2: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) fdir1: str = field( default="0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) rolling_friction: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Contact: """ Parameters ---------- collide_without_contact: Flag to disable contact force generation, while still allowing collision checks and contact visualization to occur. collide_without_contact_bitmask: Bitmask for collision filtering when collide_without_contact is on collide_bitmask: Bitmask for collision filtering. This will override collide_without_contact. Parsed as 16-bit unsigned integer. category_bitmask: Bitmask for category of collision filtering. Collision happens if ((category1 & collision2) | (category2 & collision1)) is not zero. If not specified, the category_bitmask should be interpreted as being the same as collide_bitmask. Parsed as 16-bit unsigned integer. poissons_ratio: Poisson's ratio is the unitless ratio between transverse and axial strain. This value must lie between (-1, 0.5). Defaults to 0.3 for typical steel. Note typical silicone elastomers have Poisson's ratio near 0.49 ~ 0.50. For reference, approximate values for Material:(Young's Modulus, Poisson's Ratio) for some of the typical materials are: Plastic: (1e8 ~ 3e9 Pa, 0.35 ~ 0.41), Wood: (4e9 ~ 1e10 Pa, 0.22 ~ 0.50), Aluminum: (7e10 Pa, 0.32 ~ 0.35), Steel: (2e11 Pa, 0.26 ~ 0.31). elastic_modulus: Young's Modulus in SI derived unit Pascal. Defaults to -1. If value is less or equal to zero, contact using elastic modulus (with Poisson's Ratio) is disabled. For reference, approximate values for Material:(Young's Modulus, Poisson's Ratio) for some of the typical materials are: Plastic: (1e8 ~ 3e9 Pa, 0.35 ~ 0.41), Wood: (4e9 ~ 1e10 Pa, 0.22 ~ 0.50), Aluminum: (7e10 Pa, 0.32 ~ 0.35), Steel: (2e11 Pa, 0.26 ~ 0.31). ode: ODE contact parameters bullet: Bullet contact parameters """ collide_without_contact: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) collide_without_contact_bitmask: int = field( default=1, metadata={ "type": "Element", "namespace": "", "required": True, }, ) collide_bitmask: int = field( default=65535, metadata={ "type": "Element", "namespace": "", "required": True, }, ) category_bitmask: int = field( default=65535, metadata={ "type": "Element", "namespace": "", "required": True, }, ) poissons_ratio: float = field( default=0.3, metadata={ "type": "Element", "namespace": "", "required": True, }, ) elastic_modulus: float = field( default=-1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) ode: Optional["Collision.Surface.Contact.Ode"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) bullet: Optional["Collision.Surface.Contact.Bullet"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Ode: """ ODE contact parameters. Parameters ---------- soft_cfm: Soft constraint force mixing. soft_erp: Soft error reduction parameter kp: dynamically "stiffness"-equivalent coefficient for contact joints kd: dynamically "damping"-equivalent coefficient for contact joints max_vel: maximum contact correction velocity truncation term. min_depth: minimum allowable depth before contact correction impulse is applied """ soft_cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) soft_erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) kp: float = field( default=1000000000000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) kd: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_vel: float = field( default=0.01, metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_depth: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Bullet: """ Bullet contact parameters. Parameters ---------- soft_cfm: Soft constraint force mixing. soft_erp: Soft error reduction parameter kp: dynamically "stiffness"-equivalent coefficient for contact joints kd: dynamically "damping"-equivalent coefficient for contact joints split_impulse: Similar to ODE's max_vel implementation. See http://bulletphysics.org/mediawiki-1.5.8/index.php/BtContactSolverInfo#Split_Impulse for more information. split_impulse_penetration_threshold: Similar to ODE's max_vel implementation. See http://bulletphysics.org/mediawiki-1.5.8/index.php/BtContactSolverInfo#Split_Impulse for more information. """ soft_cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) soft_erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) kp: float = field( default=1000000000000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) kd: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) split_impulse: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) split_impulse_penetration_threshold: float = field( default=-0.01, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class SoftContact: """ Parameters ---------- dart: soft contact pamameters based on paper: http://www.cc.gatech.edu/graphics/projects/Sumit/homepage/papers/sigasia11/jain_softcontacts_siga11.pdf """ dart: Optional["Collision.Surface.SoftContact.Dart"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Dart: """ soft contact pamameters based on paper: http://www .cc.gatech.edu/graphics/projects/Sumit/homepage/papers/sigasia1 1/jain_softcontacts_siga11.pdf. Parameters ---------- bone_attachment: This is variable k_v in the soft contacts paper. Its unit is N/m. stiffness: This is variable k_e in the soft contacts paper. Its unit is N/m. damping: Viscous damping of point velocity in body frame. Its unit is N/m/s. flesh_mass_fraction: Fraction of mass to be distributed among deformable nodes. """ bone_attachment: float = field( default=100.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) stiffness: float = field( default=100.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) damping: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) flesh_mass_fraction: float = field( default=0.05, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v18/collision.py
0.959164
0.568835
collision.py
pypi
from dataclasses import dataclass, field from typing import Optional __NAMESPACE__ = "sdformat/v1.8/light.xsd" @dataclass class Light: """ The light element describes a light source. Parameters ---------- cast_shadows: When true, the light will cast shadows. intensity: Scale factor to set the relative power of a light. diffuse: Diffuse light color specular: Specular light color attenuation: Light attenuation direction: Direction of the light, only applicable for spot and directional lights. spot: Spot light parameters pose: A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. name: A unique name for the light. type: The light type: point, directional, spot. """ class Meta: name = "light" cast_shadows: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) intensity: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) diffuse: str = field( default="1 1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) specular: str = field( default=".1 .1 .1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) attenuation: Optional["Light.Attenuation"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) direction: str = field( default="0 0 -1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) spot: Optional["Light.Spot"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["Light.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Attenuation: """ Light attenuation. Parameters ---------- range: Range of the light linear: The linear attenuation factor: 1 means attenuate evenly over the distance. constant: The constant attenuation factor: 1.0 means never attenuate, 0.0 is complete attenutation. quadratic: The quadratic attenuation factor: adds a curvature to the attenuation. """ range: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) linear: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) constant: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) quadratic: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Spot: """ Spot light parameters. Parameters ---------- inner_angle: Angle covered by the bright inner cone outer_angle: Angle covered by the outer cone falloff: The rate of falloff between the inner and outer cones. 1.0 means a linear falloff, less means slower falloff, higher means faster falloff. """ inner_angle: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) outer_angle: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) falloff: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v18/light.py
0.920393
0.445107
light.py
pypi
from dataclasses import dataclass, field from typing import Optional __NAMESPACE__ = "sdformat/v1.8/scene.xsd" @dataclass class Scene: """ Specifies the look of the environment. Parameters ---------- ambient: Color of the ambient light. background: Color of the background. sky: Properties for the sky shadows: Enable/disable shadows fog: Controls fog grid: Enable/disable the grid origin_visual: Show/hide world origin indicator """ class Meta: name = "scene" ambient: str = field( default="0.4 0.4 0.4 1.0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) background: str = field( default=".7 .7 .7 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) sky: Optional["Scene.Sky"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) shadows: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) fog: Optional["Scene.Fog"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) grid: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) origin_visual: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Sky: """ Properties for the sky. Parameters ---------- time: Time of day [0..24] sunrise: Sunrise time [0..24] sunset: Sunset time [0..24] clouds: Sunset time [0..24] """ time: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) sunrise: float = field( default=6.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) sunset: float = field( default=20.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) clouds: Optional["Scene.Sky.Clouds"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Clouds: """ Sunset time [0..24] Parameters ---------- speed: Speed of the clouds direction: Direction of the cloud movement humidity: Density of clouds mean_size: Average size of the clouds ambient: Ambient cloud color """ speed: float = field( default=0.6, metadata={ "type": "Element", "namespace": "", "required": True, }, ) direction: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) humidity: float = field( default=0.5, metadata={ "type": "Element", "namespace": "", "required": True, }, ) mean_size: float = field( default=0.5, metadata={ "type": "Element", "namespace": "", "required": True, }, ) ambient: str = field( default=".8 .8 .8 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) @dataclass class Fog: """ Controls fog. Parameters ---------- color: Fog color type: Fog type: constant, linear, quadratic start: Distance to start of fog end: Distance to end of fog density: Density of fog """ color: str = field( default="1 1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) type: str = field( default="none", metadata={ "type": "Element", "namespace": "", "required": True, }, ) start: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) end: float = field( default=100.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) density: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v18/scene.py
0.921882
0.455804
scene.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .geometry import Geometry from .material import Material __NAMESPACE__ = "sdformat/v1.8/visual.xsd" @dataclass class Visual: """The visual properties of the link. This element specifies the shape of the object (box, cylinder, etc.) for visualization purposes. Parameters ---------- cast_shadows: If true the visual will cast shadows. laser_retro: will be implemented in the future release. transparency: The amount of transparency( 0=opaque, 1 = fully transparent) visibility_flags: Visibility flags of a visual. When (camera's visibility_mask & visual's visibility_flags) evaluates to non-zero, the visual will be visible to the camera. meta: Optional meta information for the visual. The information contained within this element should be used to provide additional feedback to an end user. pose: A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. material: The material of the visual element. geometry: The shape of the visual or collision object. plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. name: Unique name for the visual element within the scope of the parent link. """ class Meta: name = "visual" cast_shadows: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) laser_retro: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) transparency: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) visibility_flags: int = field( default=4294967295, metadata={ "type": "Element", "namespace": "", "required": True, }, ) meta: Optional["Visual.MetaType"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["Visual.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) material: Optional[Material] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) geometry: Optional[Geometry] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) plugin: List["Visual.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class MetaType: """Optional meta information for the visual. The information contained within this element should be used to provide additional feedback to an end user. Parameters ---------- layer: The layer in which this visual is displayed. The layer number is useful for programs, such as Gazebo, that put visuals in different layers for enhanced visualization. """ layer: int = field( default=0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v18/visual.py
0.956074
0.540136
visual.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .collision import Collision from .light import Light from .material import Material from .sensor import Sensor from .visual import Visual __NAMESPACE__ = "sdformat/v1.8/link.xsd" @dataclass class Link: """A physical link with inertia, collision, and visual properties. A link must be a child of a model, and any number of links may exist in a model. Parameters ---------- gravity: If true, the link is affected by gravity. enable_wind: If true, the link is affected by the wind. self_collide: If true, the link can collide with other links in the model. Two links within a model will collide if link1.self_collide OR link2.self_collide. Links connected by a joint will never collide. kinematic: If true, the link is kinematic only must_be_base_link: If true, the link will have 6DOF and be a direct child of world. velocity_decay: Exponential damping of the link's velocity. pose: A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. inertial: The inertial properties of the link. collision: The collision properties of a link. Note that this can be different from the visual properties of a link, for example, simpler collision models are often used to reduce computation time. visual: The visual properties of the link. This element specifies the shape of the object (box, cylinder, etc.) for visualization purposes. sensor: The sensor tag describes the type and properties of a sensor. projector: audio_sink: An audio sink. audio_source: An audio source. battery: Description of a battery. light: The light element describes a light source. particle_emitter: A particle emitter that can be used to describe fog, smoke, and dust. name: A unique name for the link within the scope of the model. """ class Meta: name = "link" gravity: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) enable_wind: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) self_collide: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) kinematic: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) must_be_base_link: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) velocity_decay: Optional["Link.VelocityDecay"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["Link.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) inertial: Optional["Link.Inertial"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) collision: List[Collision] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) visual: List[Visual] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) sensor: List[Sensor] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) projector: Optional["Link.Projector"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) audio_sink: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) audio_source: List["Link.AudioSource"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) battery: List["Link.Battery"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) light: List[Light] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) particle_emitter: List["Link.ParticleEmitter"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class VelocityDecay: """ Exponential damping of the link's velocity. Parameters ---------- linear: Linear damping angular: Angular damping """ linear: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) angular: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Inertial: """ The inertial properties of the link. Parameters ---------- mass: The mass of the link. pose: This is the pose of the inertial reference frame. The origin of the inertial reference frame needs to be at the center of gravity. The axes of the inertial reference frame do not need to be aligned with the principal axes of the inertia. inertia: The 3x3 rotational inertia matrix. Because the rotational inertia matrix is symmetric, only 6 above- diagonal elements of this matrix are specified here, using the attributes ixx, ixy, ixz, iyy, iyz, izz. """ mass: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) inertia: Optional["Link.Inertial.Inertia"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Inertia: """The 3x3 rotational inertia matrix. Because the rotational inertia matrix is symmetric, only 6 above-diagonal elements of this matrix are specified here, using the attributes ixx, ixy, ixz, iyy, iyz, izz. """ ixx: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) ixy: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) ixz: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) iyy: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) iyz: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) izz: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Projector: """ Parameters ---------- texture: Texture name fov: Field of view near_clip: Near clip distance far_clip: far clip distance pose: A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. name: Name of the projector """ texture: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) fov: float = field( default=0.785, metadata={ "type": "Element", "namespace": "", "required": True, }, ) near_clip: float = field( default=0.1, metadata={ "type": "Element", "namespace": "", "required": True, }, ) far_clip: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: Optional["Link.Projector.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) plugin: List["Link.Projector.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class AudioSource: """ An audio source. Parameters ---------- uri: URI of the audio media. pitch: Pitch for the audio media, in Hz gain: Gain for the audio media, in dB. contact: List of collision objects that will trigger audio playback. loop: True to make the audio source loop playback. pose: A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. """ uri: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) pitch: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) gain: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) contact: Optional["Link.AudioSource.Contact"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) loop: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: Optional["Link.AudioSource.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Contact: """ List of collision objects that will trigger audio playback. Parameters ---------- collision: Name of child collision element that will trigger audio playback. """ collision: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Battery: """ Description of a battery. Parameters ---------- voltage: Initial voltage in volts. name: Unique name for the battery. """ voltage: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class ParticleEmitter: """ A particle emitter that can be used to describe fog, smoke, and dust. Parameters ---------- emitting: True indicates that the particle emitter should generate particles when loaded duration: The number of seconds the emitter is active. A value less than or equal to zero means infinite duration. size: The size of the emitter where the particles are sampled. Default value is (1, 1, 1). Note that the interpretation of the emitter area varies depending on the emmiter type: - point: The area is ignored. - box: The area is interpreted as width X height X depth. - cylinder: The area is interpreted as the bounding box of the cylinder. The cylinder is oriented along the Z-axis. - ellipsoid: The area is interpreted as the bounding box of an ellipsoid shaped area, i.e. a sphere or squashed-sphere area. The parameters are again identical to EM_BOX, except that the dimensions describe the widest points along each of the axes. particle_size: The particle dimensions (width, height, depth). lifetime: The number of seconds each particle will ’live’ for before being destroyed. This value must be greater than zero. rate: The number of particles per second that should be emitted. min_velocity: Sets a minimum velocity for each particle (m/s). max_velocity: Sets a maximum velocity for each particle (m/s). scale_rate: Sets the amount by which to scale the particles in both x and y direction per second. color_start: Sets the starting color for all particles emitted. The actual color will be interpolated between this color and the one set under color_end. Color::White is the default color for the particles unless a specific function is used. To specify a color, RGB values should be passed in. For example, to specify red, a user should enter: <color_start>1 0 0</color_start> Note that this function overrides the particle colors set with color_range_image. color_end: Sets the end color for all particles emitted. The actual color will be interpolated between this color and the one set under color_start. Color::White is the default color for the particles unless a specific function is used (see color_start for more information about defining custom colors with RGB values). Note that this function overrides the particle colors set with color_range_image. color_range_image: Sets the path to the color image used as an affector. This affector modifies the color of particles in flight. The colors are taken from a specified image file. The range of color values begins from the left side of the image and moves to the right over the lifetime of the particle, therefore only the horizontal dimension of the image is used. Note that this function overrides the particle colors set with color_start and color_end. topic: Topic used to update particle emitter properties at runtime. The default topic is /model/{model_name}/particle_emitter/{emitter_name} Note that the emitter id and name may not be changed. particle_scatter_ratio: This is used to determine the ratio of particles that will be detected by sensors. Increasing the ratio means there is a higher chance of particles reflecting and interfering with depth sensing, making the emitter appear more dense. Decreasing the ratio decreases the chance of particles reflecting and interfering with depth sensing, making it appear less dense. pose: A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. material: The material of the visual element. name: A unique name for the particle emitter. type: The type of a particle emitter. One of "box", "cylinder", "ellipsoid", or "point". """ emitting: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) duration: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) size: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) particle_size: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) lifetime: float = field( default=5.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) rate: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_velocity: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_velocity: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) scale_rate: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) color_start: str = field( default="1 1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) color_end: str = field( default="1 1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) color_range_image: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) topic: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) particle_scatter_ratio: float = field( default=0.65, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: Optional["Link.ParticleEmitter.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) material: Optional[Material] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v18/link.py
0.961071
0.558267
link.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .sensor import Sensor __NAMESPACE__ = "sdformat/v1.8/joint.xsd" @dataclass class Joint: """A joint connects two links with kinematic and dynamic properties. By default, the pose of a joint is expressed in the child link frame. Parameters ---------- parent: Name of the parent frame or "world". child: Name of the child frame. The value "world" may not be specified. gearbox_ratio: Parameter for gearbox joints. Given theta_1 and theta_2 defined in description for gearbox_reference_body, theta_2 = -gearbox_ratio * theta_1. gearbox_reference_body: Parameter for gearbox joints. Gearbox ratio is enforced over two joint angles. First joint angle (theta_1) is the angle from the gearbox_reference_body to the parent link in the direction of the axis element and the second joint angle (theta_2) is the angle from the gearbox_reference_body to the child link in the direction of the axis2 element. thread_pitch: Parameter for screw joints. axis: Parameters related to the axis of rotation for revolute joints, the axis of translation for prismatic joints. axis2: Parameters related to the second axis of rotation for revolute2 joints and universal joints. physics: Parameters that are specific to a certain physics engine. pose: A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. sensor: The sensor tag describes the type and properties of a sensor. name: A unique name for the joint within the scope of the model. type: The type of joint, which must be one of the following: (continuous) a hinge joint that rotates on a single axis with a continuous range of motion, (revolute) a hinge joint that rotates on a single axis with a fixed range of motion, (gearbox) geared revolute joints, (revolute2) same as two revolute joints connected in series, (prismatic) a sliding joint that slides along an axis with a limited range specified by upper and lower limits, (ball) a ball and socket joint, (screw) a single degree of freedom joint with coupled sliding and rotational motion, (universal) like a ball joint, but constrains one degree of freedom, (fixed) a joint with zero degrees of freedom that rigidly connects two links. """ class Meta: name = "joint" parent: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) child: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) gearbox_ratio: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) gearbox_reference_body: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) thread_pitch: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) axis: Optional["Joint.Axis"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) axis2: Optional["Joint.Axis2"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) physics: Optional["Joint.Physics"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["Joint.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) sensor: List[Sensor] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Axis: """ Parameters related to the axis of rotation for revolute joints, the axis of translation for prismatic joints. Parameters ---------- xyz: Represents the x,y,z components of the axis unit vector. The axis is expressed in the joint frame unless a different frame is expressed in the expressed_in attribute. The vector should be normalized. dynamics: An element specifying physical properties of the joint. These values are used to specify modeling properties of the joint, particularly useful for simulation. limit: specifies the limits of this joint """ xyz: Optional["Joint.Axis.Xyz"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) dynamics: Optional["Joint.Axis.Dynamics"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) limit: Optional["Joint.Axis.Limit"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Xyz: """ Parameters ---------- value: expressed_in: Name of frame in whose coordinates the xyz unit vector is expressed. """ value: str = field( default="0 0 1", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) expressed_in: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Dynamics: """An element specifying physical properties of the joint. These values are used to specify modeling properties of the joint, particularly useful for simulation. Parameters ---------- damping: The physical velocity dependent viscous damping coefficient of the joint. friction: The physical static friction value of the joint. spring_reference: The spring reference position for this joint axis. spring_stiffness: The spring stiffness for this joint axis. """ damping: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) friction: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) spring_reference: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) spring_stiffness: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Limit: """ specifies the limits of this joint. Parameters ---------- lower: Specifies the lower joint limit (radians for revolute joints, meters for prismatic joints). Omit if joint is continuous. upper: Specifies the upper joint limit (radians for revolute joints, meters for prismatic joints). Omit if joint is continuous. effort: A value for enforcing the maximum joint effort applied. Limit is not enforced if value is negative. velocity: A value for enforcing the maximum joint velocity. stiffness: Joint stop stiffness. dissipation: Joint stop dissipation. """ lower: float = field( default=-1e16, metadata={ "type": "Element", "namespace": "", "required": True, }, ) upper: float = field( default=1e16, metadata={ "type": "Element", "namespace": "", "required": True, }, ) effort: float = field( default=-1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) velocity: float = field( default=-1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) stiffness: float = field( default=100000000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) dissipation: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Axis2: """ Parameters related to the second axis of rotation for revolute2 joints and universal joints. Parameters ---------- xyz: Represents the x,y,z components of the axis unit vector. The axis is expressed in the joint frame unless a different frame is expressed in the expressed_in attribute. The vector should be normalized. dynamics: An element specifying physical properties of the joint. These values are used to specify modeling properties of the joint, particularly useful for simulation. limit: """ xyz: Optional["Joint.Axis2.Xyz"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) dynamics: Optional["Joint.Axis2.Dynamics"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) limit: Optional["Joint.Axis2.Limit"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Xyz: """ Parameters ---------- value: expressed_in: Name of frame in whose coordinates the xyz unit vector is expressed. """ value: str = field( default="0 0 1", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) expressed_in: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Dynamics: """An element specifying physical properties of the joint. These values are used to specify modeling properties of the joint, particularly useful for simulation. Parameters ---------- damping: The physical velocity dependent viscous damping coefficient of the joint. EXPERIMENTAL: if damping coefficient is negative and implicit_spring_damper is true, adaptive damping is used. friction: The physical static friction value of the joint. spring_reference: The spring reference position for this joint axis. spring_stiffness: The spring stiffness for this joint axis. """ damping: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) friction: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) spring_reference: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) spring_stiffness: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Limit: """ Parameters ---------- lower: An attribute specifying the lower joint limit (radians for revolute joints, meters for prismatic joints). Omit if joint is continuous. upper: An attribute specifying the upper joint limit (radians for revolute joints, meters for prismatic joints). Omit if joint is continuous. effort: An attribute for enforcing the maximum joint effort applied by Joint::SetForce. Limit is not enforced if value is negative. velocity: (not implemented) An attribute for enforcing the maximum joint velocity. stiffness: Joint stop stiffness. Supported physics engines: SimBody. dissipation: Joint stop dissipation. Supported physics engines: SimBody. """ lower: float = field( default=-1e16, metadata={ "type": "Element", "namespace": "", "required": True, }, ) upper: float = field( default=1e16, metadata={ "type": "Element", "namespace": "", "required": True, }, ) effort: float = field( default=-1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) velocity: float = field( default=-1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) stiffness: float = field( default=100000000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) dissipation: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Physics: """ Parameters that are specific to a certain physics engine. Parameters ---------- simbody: Simbody specific parameters ode: ODE specific parameters provide_feedback: If provide feedback is set to true, physics engine will compute the constraint forces at this joint. """ simbody: Optional["Joint.Physics.Simbody"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) ode: Optional["Joint.Physics.Ode"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) provide_feedback: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Simbody: """ Simbody specific parameters. Parameters ---------- must_be_loop_joint: Force cut in the multibody graph at this joint. """ must_be_loop_joint: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Ode: """ ODE specific parameters. Parameters ---------- cfm_damping: If cfm damping is set to true, ODE will use CFM to simulate damping, allows for infinite damping, and one additional constraint row (previously used for joint limit) is always active. implicit_spring_damper: If implicit_spring_damper is set to true, ODE will use CFM, ERP to simulate stiffness and damping, allows for infinite damping, and one additional constraint row (previously used for joint limit) is always active. This replaces cfm_damping parameter in SDFormat 1.4. fudge_factor: Scale the excess for in a joint motor at joint limits. Should be between zero and one. cfm: Constraint force mixing for constrained directions erp: Error reduction parameter for constrained directions bounce: Bounciness of the limits max_force: Maximum force or torque used to reach the desired velocity. velocity: The desired velocity of the joint. Should only be set if you want the joint to move on load. limit: suspension: """ cfm_damping: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) implicit_spring_damper: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) fudge_factor: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) bounce: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_force: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) velocity: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) limit: Optional["Joint.Physics.Ode.Limit"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) suspension: Optional["Joint.Physics.Ode.Suspension"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Limit: """ Parameters ---------- cfm: Constraint force mixing parameter used by the joint stop erp: Error reduction parameter used by the joint stop """ cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Suspension: """ Parameters ---------- cfm: Suspension constraint force mixing parameter erp: Suspension error reduction parameter """ cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v18/joint.py
0.96622
0.601125
joint.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .actor import Actor from .light import Light from .material import Material from .model import Model from .physics import Physics from .scene import Scene from .state import State __NAMESPACE__ = "sdformat/v1.8/world.xsd" @dataclass class World: """ The world element encapsulates an entire world description including: models, scene, physics, and plugins. Parameters ---------- audio: Global audio properties. wind: The wind tag specifies the type and properties of the wind. include: Include resources from a URI. Included resources can only contain one 'model', 'light' or 'actor' element. The URI can point to a directory or a file. If the URI is a directory, it must conform to the model database structure (see /tutorials?tut=composition&cat=specification&#defining- models-in-separate-files). gravity: The gravity vector in m/s^2, expressed in a coordinate frame defined by the spherical_coordinates tag. magnetic_field: The magnetic vector in Tesla, expressed in a coordinate frame defined by the spherical_coordinates tag. atmosphere: The atmosphere tag specifies the type and properties of the atmosphere model. gui: physics: The physics tag specifies the type and properties of the dynamics engine. scene: Specifies the look of the environment. light: The light element describes a light source. frame: A frame of reference in which poses may be expressed. model: The model element defines a complete robot or any other physical object. actor: A special kind of model which can have a scripted motion. This includes both global waypoint type animations and skeleton animations. plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. road: spherical_coordinates: state: population: The population element defines how and where a set of models will be automatically populated in Gazebo. name: Unique name of the world """ class Meta: name = "world" audio: Optional["World.Audio"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) wind: Optional["World.Wind"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) include: List["World.Include"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) gravity: str = field( default="0 0 -9.8", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) magnetic_field: str = field( default="5.5645e-6 22.8758e-6 -42.3884e-6", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) atmosphere: Optional["World.Atmosphere"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) gui: Optional["World.Gui"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) physics: List[Physics] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) scene: Optional[Scene] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) light: List[Light] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) frame: List["World.Frame"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) model: List[Model] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) actor: List[Actor] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) plugin: List["World.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) road: List["World.Road"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) spherical_coordinates: Optional["World.SphericalCoordinates"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) state: List[State] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) population: List["World.Population"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Audio: """ Global audio properties. Parameters ---------- device: Device to use for audio playback. A value of "default" will use the system's default audio device. Otherwise, specify a an audio device file" """ device: str = field( default="default", metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Wind: """ The wind tag specifies the type and properties of the wind. Parameters ---------- linear_velocity: Linear velocity of the wind. """ linear_velocity: str = field( default="0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Include: """Include resources from a URI. Included resources can only contain one 'model', 'light' or 'actor' element. The URI can point to a directory or a file. If the URI is a directory, it must conform to the model database structure (see /tutorials?tut=composition&cat=specification&#defining-models-in-separate-files). Parameters ---------- uri: URI to a resource, such as a model name: Override the name of the included entity. static: Override the static value of the included entity. placement_frame: The frame inside the included entity whose pose will be set by the specified pose element. If this element is specified, the pose must be specified. pose: A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. """ uri: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) static: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) placement_frame: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["World.Include.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) plugin: List["World.Include.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Atmosphere: """ The atmosphere tag specifies the type and properties of the atmosphere model. Parameters ---------- temperature: Temperature at sea level in kelvins. pressure: Pressure at sea level in pascals. temperature_gradient: Temperature gradient with respect to increasing altitude at sea level in units of K/m. type: The type of the atmosphere engine. Current options are adiabatic. Defaults to adiabatic if left unspecified. """ temperature: float = field( default=288.15, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pressure: float = field( default=101325.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) temperature_gradient: float = field( default=-0.0065, metadata={ "type": "Element", "namespace": "", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Gui: """ Parameters ---------- camera: plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. fullscreen: """ camera: Optional["World.Gui.Camera"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) plugin: List["World.Gui.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) fullscreen: bool = field( default=False, metadata={ "type": "Attribute", }, ) @dataclass class Camera: """ Parameters ---------- view_controller: projection_type: Set the type of projection for the camera. Valid values are "perspective" and "orthographic". track_visual: pose: A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. name: """ view_controller: str = field( default="orbit", metadata={ "type": "Element", "namespace": "", "required": True, }, ) projection_type: str = field( default="perspective", metadata={ "type": "Element", "namespace": "", "required": True, }, ) track_visual: Optional["World.Gui.Camera.TrackVisual"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["World.Gui.Camera.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class TrackVisual: """ Parameters ---------- name: Name of the tracked visual. If no name is provided, the remaining settings will be applied whenever tracking is triggered in the GUI. min_dist: Minimum distance between the camera and the tracked visual. This parameter is only used if static is set to false. max_dist: Maximum distance between the camera and the tracked visual. This parameter is only used if static is set to false. static: If set to true, the position of the camera is fixed relatively to the model or to the world, depending on the value of the use_model_frame element. Otherwise, the position of the camera may vary but the distance between the camera and the model will depend on the value of the min_dist and max_dist elements. In any case, the camera will always follow the model by changing its orientation. use_model_frame: If set to true, the position of the camera is relative to the model reference frame, which means that its position relative to the model will not change. Otherwise, the position of the camera is relative to the world reference frame, which means that its position relative to the world will not change. This parameter is only used if static is set to true. xyz: The position of the camera's reference frame. This parameter is only used if static is set to true. If use_model_frame is set to true, the position is relative to the model reference frame, otherwise it represents world coordinates. inherit_yaw: If set to true, the camera will inherit the yaw rotation of the tracked model. This parameter is only used if static and use_model_frame are set to true. """ name: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_dist: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_dist: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) static: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) use_model_frame: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) xyz: str = field( default="-5.0 0.0 3.0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) inherit_yaw: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Frame: """ A frame of reference in which poses may be expressed. Parameters ---------- pose: A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. name: Name of the frame. It must be unique whithin its scope (model/world), i.e., it must not match the name of another frame, link, joint, or model within the same scope. attached_to: If specified, this frame is attached to the specified frame. The specified frame must be within the same scope and may be defined implicitly, i.e., the name of any //frame, //model, //joint, or //link within the same scope may be used. If missing, this frame is attached to the containing scope's frame. Within a //world scope this is the implicit world frame, and within a //model scope this is the implicit model frame. A frame moves jointly with the frame it is @attached_to. This is different from //pose/@relative_to. @attached_to defines how the frame is attached to a //link, //model, or //world frame, while //pose/@relative_to defines how the frame's pose is represented numerically. As a result, following the chain of @attached_to attributes must always lead to a //link, //model, //world, or //joint (implicitly attached_to its child //link). """ pose: Optional["World.Frame.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) attached_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Road: """ Parameters ---------- width: Width of the road point: A series of points that define the path of the road. material: The material of the visual element. name: Name of the road """ width: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) point: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) material: Optional[Material] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class SphericalCoordinates: """ Parameters ---------- surface_model: Name of planetary surface model, used to determine the surface altitude at a given latitude and longitude. The default is an ellipsoid model of the earth based on the WGS-84 standard. It is used in Gazebo's GPS sensor implementation. world_frame_orientation: This field identifies how Gazebo world frame is aligned in Geographical sense. The final Gazebo world frame orientation is obtained by rotating a frame aligned with following notation by the field heading_deg (Note that heading_deg corresponds to positive yaw rotation in the NED frame, so it's inverse specifies positive Z-rotation in ENU or NWU). Options are: - ENU (East-North-Up) - NED (North-East-Down) - NWU (North-West-Up) For example, world frame specified by setting world_orientation="ENU" and heading_deg=-90° is effectively equivalent to NWU with heading of 0°. latitude_deg: Geodetic latitude at origin of gazebo reference frame, specified in units of degrees. longitude_deg: Longitude at origin of gazebo reference frame, specified in units of degrees. elevation: Elevation of origin of gazebo reference frame, specified in meters. heading_deg: Heading offset of gazebo reference frame, measured as angle between Gazebo world frame and the world_frame_orientation type (ENU/NED/NWU). Rotations about the downward-vector (e.g. North to East) are positive. The direction of rotation is chosen to be consistent with compass heading convention (e.g. 0 degrees points North and 90 degrees points East, positive rotation indicates counterclockwise rotation when viewed from top-down direction). The angle is specified in degrees. """ surface_model: str = field( default="EARTH_WGS84", metadata={ "type": "Element", "namespace": "", "required": True, }, ) world_frame_orientation: str = field( default="ENU", metadata={ "type": "Element", "namespace": "", "required": True, }, ) latitude_deg: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) longitude_deg: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) elevation: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) heading_deg: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Population: """ The population element defines how and where a set of models will be automatically populated in Gazebo. Parameters ---------- model_count: The number of models to place. distribution: Specifies the type of object distribution and its optional parameters. box: Box shape cylinder: Cylinder shape pose: A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. model: The model element defines a complete robot or any other physical object. name: A unique name for the population. This name must not match another population in the world. """ model_count: int = field( default=1, metadata={ "type": "Element", "namespace": "", "required": True, }, ) distribution: Optional["World.Population.Distribution"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) box: Optional["World.Population.Box"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) cylinder: Optional["World.Population.Cylinder"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["World.Population.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) model: Optional[Model] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Distribution: """ Specifies the type of object distribution and its optional parameters. Parameters ---------- type: Define how the objects will be placed in the specified region. - random: Models placed at random. - uniform: Models approximately placed in a 2D grid pattern with control over the number of objects. - grid: Models evenly placed in a 2D grid pattern. The number of objects is not explicitly specified, it is based on the number of rows and columns of the grid. - linear-x: Models evently placed in a row along the global x-axis. - linear-y: Models evently placed in a row along the global y-axis. - linear-z: Models evently placed in a row along the global z-axis. rows: Number of rows in the grid. cols: Number of columns in the grid. step: Distance between elements of the grid. """ type: str = field( default="random", metadata={ "type": "Element", "namespace": "", "required": True, }, ) rows: int = field( default=1, metadata={ "type": "Element", "namespace": "", "required": True, }, ) cols: int = field( default=1, metadata={ "type": "Element", "namespace": "", "required": True, }, ) step: str = field( default="0.5 0.5 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Box: """ Box shape. Parameters ---------- size: The three side lengths of the box. The origin of the box is in its geometric center (inside the center of the box). """ size: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Cylinder: """ Cylinder shape. Parameters ---------- radius: Radius of the cylinder length: Length of the cylinder along the z axis """ radius: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) length: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v18/world.py
0.919009
0.568655
world.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .light import Light from .model import Model as ModelModel __NAMESPACE__ = "sdformat/v1.8/state.xsd" @dataclass class Model: """ Model state. Parameters ---------- joint: Joint angle model: A nested model state element scale: Scale for the 3 dimensions of the model. frame: A frame of reference in which poses may be expressed. pose: A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. link: Link state name: Name of the model """ class Meta: name = "model" joint: List["Model.Joint"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) model: List["Model"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) scale: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) frame: List["Model.Frame"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["Model.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) link: List["Model.Link"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Joint: """ Joint angle. Parameters ---------- angle: Angle of an axis name: Name of the joint """ angle: List["Model.Joint.Angle"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Angle: """ Parameters ---------- value: axis: Index of the axis. """ value: Optional[float] = field( default=None, metadata={ "required": True, }, ) axis: Optional[int] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Frame: """ A frame of reference in which poses may be expressed. Parameters ---------- pose: A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. name: Name of the frame. It must be unique whithin its scope (model/world), i.e., it must not match the name of another frame, link, joint, or model within the same scope. attached_to: If specified, this frame is attached to the specified frame. The specified frame must be within the same scope and may be defined implicitly, i.e., the name of any //frame, //model, //joint, or //link within the same scope may be used. If missing, this frame is attached to the containing scope's frame. Within a //world scope this is the implicit world frame, and within a //model scope this is the implicit model frame. A frame moves jointly with the frame it is @attached_to. This is different from //pose/@relative_to. @attached_to defines how the frame is attached to a //link, //model, or //world frame, while //pose/@relative_to defines how the frame's pose is represented numerically. As a result, following the chain of @attached_to attributes must always lead to a //link, //model, //world, or //joint (implicitly attached_to its child //link). """ pose: Optional["Model.Frame.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) attached_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Link: """ Link state. Parameters ---------- velocity: Velocity of the link. The x, y, z components of the pose correspond to the linear velocity of the link, and the roll, pitch, yaw components correspond to the angular velocity of the link acceleration: Acceleration of the link. The x, y, z components of the pose correspond to the linear acceleration of the link, and the roll, pitch, yaw components correspond to the angular acceleration of the link wrench: Force and torque applied to the link. The x, y, z components of the pose correspond to the force applied to the link, and the roll, pitch, yaw components correspond to the torque applied to the link collision: Collision state pose: A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. name: Name of the link """ velocity: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) acceleration: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) wrench: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) collision: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["Model.Link.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class State: """ Parameters ---------- sim_time: Simulation time stamp of the state [seconds nanoseconds] wall_time: Wall time stamp of the state [seconds nanoseconds] real_time: Real time stamp of the state [seconds nanoseconds] iterations: Number of simulation iterations. insertions: A list containing the entire description of entities inserted. deletions: A list of names of deleted entities/ model: Model state light: Light state world_name: Name of the world this state applies to """ class Meta: name = "state" sim_time: str = field( default="0 0", metadata={ "type": "Element", "namespace": "", "required": True, "white_space": "collapse", "pattern": r"\d+ \d+", }, ) wall_time: str = field( default="0 0", metadata={ "type": "Element", "namespace": "", "required": True, "white_space": "collapse", "pattern": r"\d+ \d+", }, ) real_time: str = field( default="0 0", metadata={ "type": "Element", "namespace": "", "required": True, "white_space": "collapse", "pattern": r"\d+ \d+", }, ) iterations: int = field( default=0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) insertions: Optional["State.Insertions"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) deletions: Optional["State.Deletions"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) model: List[Model] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) light: List["State.Light"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) world_name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Insertions: """ A list containing the entire description of entities inserted. Parameters ---------- model: The model element defines a complete robot or any other physical object. light: The light element describes a light source. """ model: List[ModelModel] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) light: List[Light] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Deletions: """ A list of names of deleted entities/ Parameters ---------- name: The name of a deleted entity. """ name: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) @dataclass class Light: """ Light state. Parameters ---------- pose: A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. name: Name of the light """ pose: Optional["State.Light.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v18/state.py
0.947039
0.482856
state.py
pypi
from dataclasses import dataclass, field from typing import Optional __NAMESPACE__ = "sdformat/v1.8/physics.xsd" @dataclass class Physics: """ The physics tag specifies the type and properties of the dynamics engine. Parameters ---------- max_step_size: Maximum time step size at which every system in simulation can interact with the states of the world. (was physics.sdf's dt). real_time_factor: target simulation speedup factor, defined by ratio of simulation time to real-time. real_time_update_rate: Rate at which to update the physics engine (UpdatePhysics calls per real-time second). (was physics.sdf's update_rate). max_contacts: Maximum number of contacts allowed between two entities. This value can be over ridden by a max_contacts element in a collision element. dart: DART specific physics properties simbody: Simbody specific physics properties bullet: Bullet specific physics properties ode: ODE specific physics properties name: The name of this set of physics parameters. default: If true, this physics element is set as the default physics profile for the world. If multiple default physics elements exist, the first element marked as default is chosen. If no default physics element exists, the first physics element is chosen. type: The type of the dynamics engine. Current options are ode, bullet, simbody and dart. Defaults to ode if left unspecified. """ class Meta: name = "physics" max_step_size: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) real_time_factor: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) real_time_update_rate: float = field( default=1000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_contacts: int = field( default=20, metadata={ "type": "Element", "namespace": "", "required": True, }, ) dart: Optional["Physics.Dart"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) simbody: Optional["Physics.Simbody"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) bullet: Optional["Physics.Bullet"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) ode: Optional["Physics.Ode"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: str = field( default="default_physics", metadata={ "type": "Attribute", }, ) default: bool = field( default=False, metadata={ "type": "Attribute", }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Dart: """ DART specific physics properties. Parameters ---------- solver: collision_detector: Specify collision detector for DART to use. Can be dart, fcl, bullet or ode. """ solver: Optional["Physics.Dart.Solver"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) collision_detector: str = field( default="fcl", metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Solver: """ Parameters ---------- solver_type: One of the following types: pgs, dantzig. PGS stands for Projected Gauss-Seidel. """ solver_type: str = field( default="dantzig", metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Simbody: """ Simbody specific physics properties. Parameters ---------- min_step_size: (Currently not used in simbody) The time duration which advances with each iteration of the dynamics engine, this has to be no bigger than max_step_size under physics block. If left unspecified, min_step_size defaults to max_step_size. accuracy: Roughly the relative error of the system. -LOG(accuracy) is roughly the number of significant digits. max_transient_velocity: Tolerable "slip" velocity allowed by the solver when static friction is supposed to hold object in place. contact: Relationship among dissipation, coef. restitution, etc. d = dissipation coefficient (1/velocity) vc = capture velocity (velocity where e=e_max) vp = plastic velocity (smallest v where e=e_min) > vc Assume real COR=1 when v=0. e_min = given minimum COR, at v >= vp (a.k.a. plastic_coef_restitution) d = slope = (1-e_min)/vp OR, e_min = 1 - d*vp e_max = maximum COR = 1-d*vc, reached at v=vc e = 0, v <= vc = 1 - d*v, vc < v < vp = e_min, v >= vp dissipation factor = d*min(v,vp) [compliant] cor = e [rigid] Combining rule e = 0, e1==e2==0 = 2*e1*e2/(e1+e2), otherwise """ min_step_size: float = field( default=0.0001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) accuracy: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_transient_velocity: float = field( default=0.01, metadata={ "type": "Element", "namespace": "", "required": True, }, ) contact: Optional["Physics.Simbody.Contact"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Contact: """Relationship among dissipation, coef. restitution, etc. d = dissipation coefficient (1/velocity) vc = capture velocity (velocity where e=e_max) vp = plastic velocity (smallest v where e=e_min) > vc Assume real COR=1 when v=0. e_min = given minimum COR, at v >= vp (a.k.a. plastic_coef_restitution) d = slope = (1-e_min)/vp OR, e_min = 1 - d*vp e_max = maximum COR = 1-d*vc, reached at v=vc e = 0, v <= vc = 1 - d*v, vc < v < vp = e_min, v >= vp dissipation factor = d*min(v,vp) [compliant] cor = e [rigid] Combining rule e = 0, e1==e2==0 = 2*e1*e2/(e1+e2), otherwise Parameters ---------- stiffness: Default contact material stiffness (force/dist or torque/radian). dissipation: dissipation coefficient to be used in compliant contact; if not given it is (1-min_cor)/plastic_impact_velocity plastic_coef_restitution: this is the COR to be used at high velocities for rigid impacts; if not given it is 1 - dissipation*plastic_impact_velocity plastic_impact_velocity: smallest impact velocity at which min COR is reached; set to zero if you want the min COR always to be used static_friction: static friction (mu_s) as described by this plot: http://gazebosim.org/wiki/File:Stribeck_friction.png dynamic_friction: dynamic friction (mu_d) as described by this plot: http://gazebosim.org/wiki/File:Stribeck_friction.png viscous_friction: viscous friction (mu_v) with units of (1/velocity) as described by this plot: http://gazebosim.org/wiki/File:Stribeck_friction.png override_impact_capture_velocity: for rigid impacts only, impact velocity at which COR is set to zero; normally inherited from global default but can be overridden here. Combining rule: use larger velocity override_stiction_transition_velocity: This is the largest slip velocity at which we'll consider a transition to stiction. Normally inherited from a global default setting. For a continuous friction model this is the velocity at which the max static friction force is reached. Combining rule: use larger velocity """ stiffness: float = field( default=100000000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) dissipation: float = field( default=100.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) plastic_coef_restitution: float = field( default=0.5, metadata={ "type": "Element", "namespace": "", "required": True, }, ) plastic_impact_velocity: float = field( default=0.5, metadata={ "type": "Element", "namespace": "", "required": True, }, ) static_friction: float = field( default=0.9, metadata={ "type": "Element", "namespace": "", "required": True, }, ) dynamic_friction: float = field( default=0.9, metadata={ "type": "Element", "namespace": "", "required": True, }, ) viscous_friction: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) override_impact_capture_velocity: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) override_stiction_transition_velocity: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Bullet: """ Bullet specific physics properties. Parameters ---------- solver: constraints: Bullet constraint parameters. """ solver: Optional["Physics.Bullet.Solver"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) constraints: Optional["Physics.Bullet.Constraints"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Solver: """ Parameters ---------- type: One of the following types: sequential_impulse only. min_step_size: The time duration which advances with each iteration of the dynamics engine, this has to be no bigger than max_step_size under physics block. If left unspecified, min_step_size defaults to max_step_size. iters: Number of iterations for each step. A higher number produces greater accuracy at a performance cost. sor: Set the successive over-relaxation parameter. """ type: str = field( default="sequential_impulse", metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_step_size: float = field( default=0.0001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) iters: int = field( default=50, metadata={ "type": "Element", "namespace": "", "required": True, }, ) sor: float = field( default=1.3, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Constraints: """ Bullet constraint parameters. Parameters ---------- cfm: Constraint force mixing parameter. See the ODE page for more information. erp: Error reduction parameter. See the ODE page for more information. contact_surface_layer: The depth of the surface layer around all geometry objects. Contacts are allowed to sink into the surface layer up to the given depth before coming to rest. The default value is zero. Increasing this to some small value (e.g. 0.001) can help prevent jittering problems due to contacts being repeatedly made and broken. split_impulse: Similar to ODE's max_vel implementation. See http://web.archive.org/web/20120430155635/http://bulletphysics.org/mediawiki-1.5.8/index.php/BtContactSolverInfo#Split_Impulse for more information. split_impulse_penetration_threshold: Similar to ODE's max_vel implementation. See http://web.archive.org/web/20120430155635/http://bulletphysics.org/mediawiki-1.5.8/index.php/BtContactSolverInfo#Split_Impulse for more information. """ cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) contact_surface_layer: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) split_impulse: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) split_impulse_penetration_threshold: float = field( default=-0.01, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Ode: """ ODE specific physics properties. Parameters ---------- solver: constraints: ODE constraint parameters. """ solver: Optional["Physics.Ode.Solver"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) constraints: Optional["Physics.Ode.Constraints"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Solver: """ Parameters ---------- type: One of the following types: world, quick min_step_size: The time duration which advances with each iteration of the dynamics engine, this has to be no bigger than max_step_size under physics block. If left unspecified, min_step_size defaults to max_step_size. island_threads: Number of threads to use for "islands" of disconnected models. iters: Number of iterations for each step. A higher number produces greater accuracy at a performance cost. precon_iters: Experimental parameter. sor: Set the successive over-relaxation parameter. thread_position_correction: Flag to use threading to speed up position correction computation. use_dynamic_moi_rescaling: Flag to enable dynamic rescaling of moment of inertia in constrained directions. See gazebo pull request 1114 for the implementation of this feature. https://osrf- migration.github.io/gazebo-gh-pages/#!/osrf/gazebo/pull- request/1114 friction_model: Name of ODE friction model to use. Valid values include: pyramid_model: (default) friction forces limited in two directions in proportion to normal force. box_model: friction forces limited to constant in two directions. cone_model: friction force magnitude limited in proportion to normal force. See gazebo pull request 1522 for the implementation of this feature. https://osrf-migration.github.io/gazebo-gh- pages/#!/osrf/gazebo/pull-request/1522 https://github.com/osrf/gazebo/commit/968dccafdfbfca09c9b3326f855612076fed7e6f """ type: str = field( default="quick", metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_step_size: float = field( default=0.0001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) island_threads: int = field( default=0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) iters: int = field( default=50, metadata={ "type": "Element", "namespace": "", "required": True, }, ) precon_iters: int = field( default=0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) sor: float = field( default=1.3, metadata={ "type": "Element", "namespace": "", "required": True, }, ) thread_position_correction: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) use_dynamic_moi_rescaling: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) friction_model: str = field( default="pyramid_model", metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Constraints: """ ODE constraint parameters. Parameters ---------- cfm: Constraint force mixing parameter. See the ODE page for more information. erp: Error reduction parameter. See the ODE page for more information. contact_max_correcting_vel: The maximum correcting velocities allowed when resolving contacts. contact_surface_layer: The depth of the surface layer around all geometry objects. Contacts are allowed to sink into the surface layer up to the given depth before coming to rest. The default value is zero. Increasing this to some small value (e.g. 0.001) can help prevent jittering problems due to contacts being repeatedly made and broken. """ cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) contact_max_correcting_vel: float = field( default=100.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) contact_surface_layer: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v18/physics.py
0.955899
0.523847
physics.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .joint import Joint from .link import Link __NAMESPACE__ = "sdformat/v1.8/model.xsd" @dataclass class Model: """ The model element defines a complete robot or any other physical object. Parameters ---------- static: If set to true, the model is immovable; i.e., a dynamics engine will not update its position. This will also overwrite this model's `@canonical_link` and instead attach the model's implicit frame to the world's implicit frame. This holds even if this model is nested (or included) by another model instead of being a direct child of `//world`. self_collide: If set to true, all links in the model will collide with each other (except those connected by a joint). Can be overridden by the link or collision element self_collide property. Two links within a model will collide if link1.self_collide OR link2.self_collide. Links connected by a joint will never collide. allow_auto_disable: Allows a model to auto-disable, which is means the physics engine can skip updating the model when the model is at rest. This parameter is only used by models with no joints. include: Include resources from a URI. This can be used to nest models. The included resource can only contain one 'model' element. The URI can point to a directory or a file. If the URI is a directory, it must conform to the model database structure (see /tutorials?tut=composition&cat=specification&#defining- models-in-separate-files). model: A nested model element enable_wind: If set to true, all links in the model will be affected by the wind. Can be overriden by the link wind property. frame: A frame of reference in which poses may be expressed. pose: A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. link: A physical link with inertia, collision, and visual properties. A link must be a child of a model, and any number of links may exist in a model. joint: A joint connects two links with kinematic and dynamic properties. By default, the pose of a joint is expressed in the child link frame. plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. gripper: name: The name of the model and its implicit frame. This name must be unique among all elements defining frames within the same scope, i.e., it must not match another //model, //frame, //joint, or //link within the same scope. canonical_link: The name of the model's canonical link, to which the model's implicit coordinate frame is attached. If unset or set to an empty string, the first `/link` listed as a direct child of this model is chosen as the canonical link. If the model has no direct `/link` children, it will instead be attached to the first nested (or included) model's implicit frame. placement_frame: The frame inside this model whose pose will be set by the pose element of the model. i.e, the pose element specifies the pose of this frame instead of the model frame. """ class Meta: name = "model" static: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) self_collide: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) allow_auto_disable: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) include: List["Model.Include"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) model: List["Model"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) enable_wind: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) frame: List["Model.Frame"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["Model.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) link: List[Link] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) joint: List[Joint] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) plugin: List["Model.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) gripper: List["Model.Gripper"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) canonical_link: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) placement_frame: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Include: """Include resources from a URI. This can be used to nest models. The included resource can only contain one 'model' element. The URI can point to a directory or a file. If the URI is a directory, it must conform to the model database structure (see /tutorials?tut=composition&cat=specification&#defining-models-in-separate-files). Parameters ---------- uri: URI to a resource, such as a model name: Override the name of the included model. static: Override the static value of the included model. placement_frame: The frame inside the included model whose pose will be set by the specified pose element. If this element is specified, the pose must be specified. pose: A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. """ uri: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) static: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) placement_frame: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["Model.Include.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) plugin: List["Model.Include.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Frame: """ A frame of reference in which poses may be expressed. Parameters ---------- pose: A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. name: Name of the frame. It must be unique whithin its scope (model/world), i.e., it must not match the name of another frame, link, joint, or model within the same scope. attached_to: If specified, this frame is attached to the specified frame. The specified frame must be within the same scope and may be defined implicitly, i.e., the name of any //frame, //model, //joint, or //link within the same scope may be used. If missing, this frame is attached to the containing scope's frame. Within a //world scope this is the implicit world frame, and within a //model scope this is the implicit model frame. A frame moves jointly with the frame it is @attached_to. This is different from //pose/@relative_to. @attached_to defines how the frame is attached to a //link, //model, or //world frame, while //pose/@relative_to defines how the frame's pose is represented numerically. As a result, following the chain of @attached_to attributes must always lead to a //link, //model, //world, or //joint (implicitly attached_to its child //link). """ pose: Optional["Model.Frame.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) attached_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Gripper: grasp_check: Optional["Model.Gripper.GraspCheck"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) gripper_link: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) palm_link: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class GraspCheck: detach_steps: int = field( default=40, metadata={ "type": "Element", "namespace": "", "required": True, }, ) attach_steps: int = field( default=20, metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_contact_count: int = field( default=2, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v18/model.py
0.9463
0.51812
model.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .joint import Joint from .link import Link __NAMESPACE__ = "sdformat/v1.8/actor.xsd" @dataclass class Actor: """A special kind of model which can have a scripted motion. This includes both global waypoint type animations and skeleton animations. Parameters ---------- skin: Skin file which defines a visual and the underlying skeleton which moves it. animation: Animation file defines an animation for the skeleton in the skin. The skeleton must be compatible with the skin skeleton. script: Adds scripted trajectories to the actor. pose: A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. link: A physical link with inertia, collision, and visual properties. A link must be a child of a model, and any number of links may exist in a model. joint: A joint connects two links with kinematic and dynamic properties. By default, the pose of a joint is expressed in the child link frame. plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. name: A unique name for the actor. """ class Meta: name = "actor" skin: Optional["Actor.Skin"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) animation: List["Actor.Animation"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) script: Optional["Actor.Script"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: Optional["Actor.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) link: List[Link] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) joint: List[Joint] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) plugin: List["Actor.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Skin: """ Skin file which defines a visual and the underlying skeleton which moves it. Parameters ---------- filename: Path to skin file, accepted formats: COLLADA, BVH. scale: Scale the skin's size. """ filename: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) scale: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Animation: """Animation file defines an animation for the skeleton in the skin. The skeleton must be compatible with the skin skeleton. Parameters ---------- filename: Path to animation file. Accepted formats: COLLADA, BVH. scale: Scale for the animation skeleton. interpolate_x: Set to true so the animation is interpolated on X. name: Unique name for animation. """ filename: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) scale: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) interpolate_x: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Script: """ Adds scripted trajectories to the actor. Parameters ---------- loop: Set this to true for the script to be repeated in a loop. For a fluid continuous motion, make sure the last waypoint matches the first one. delay_start: This is the time to wait before starting the script. If running in a loop, this time will be waited before starting each cycle. auto_start: Set to true if the animation should start as soon as the simulation starts playing. It is useful to set this to false if the animation should only start playing only when triggered by a plugin, for example. trajectory: The trajectory contains a series of keyframes to be followed. """ loop: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) delay_start: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) auto_start: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) trajectory: List["Actor.Script.Trajectory"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Trajectory: """ The trajectory contains a series of keyframes to be followed. Parameters ---------- waypoint: Each point in the trajectory. id: Unique id for a trajectory. type: If it matches the type of an animation, they will be played at the same time. tension: The tension of the trajectory spline. The default value of zero equates to a Catmull-Rom spline, which may also cause the animation to overshoot keyframes. A value of one will cause the animation to stick to the keyframes. """ waypoint: List["Actor.Script.Trajectory.Waypoint"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) id: Optional[int] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) tension: float = field( default=0.0, metadata={ "type": "Attribute", }, ) @dataclass class Waypoint: """ Each point in the trajectory. Parameters ---------- time: The time in seconds, counted from the beginning of the script, when the pose should be reached. pose: The pose which should be reached at the given time. """ time: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v18/actor.py
0.960305
0.51312
actor.py
pypi
from dataclasses import dataclass, field from typing import List, Optional __NAMESPACE__ = "sdformat/v1.8/geometry.xsd" @dataclass class Geometry: """ The shape of the visual or collision object. Parameters ---------- empty: You can use the empty tag to make empty geometries. box: Box shape capsule: Capsule shape cylinder: Cylinder shape ellipsoid: Ellipsoid shape heightmap: A heightmap based on a 2d grayscale image. image: Extrude a set of boxes from a grayscale image. mesh: Mesh shape plane: Plane shape polyline: Defines an extruded polyline shape sphere: Sphere shape """ class Meta: name = "geometry" empty: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) box: Optional["Geometry.Box"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) capsule: Optional["Geometry.Capsule"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) cylinder: Optional["Geometry.Cylinder"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) ellipsoid: Optional["Geometry.Ellipsoid"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) heightmap: Optional["Geometry.Heightmap"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) image: Optional["Geometry.Image"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) mesh: Optional["Geometry.Mesh"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) plane: Optional["Geometry.Plane"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) polyline: Optional["Geometry.Polyline"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) sphere: Optional["Geometry.Sphere"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Box: """ Box shape. Parameters ---------- size: The three side lengths of the box. The origin of the box is in its geometric center (inside the center of the box). """ size: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Capsule: """ Capsule shape. Parameters ---------- radius: Radius of the capsule length: Length of the cylindrical portion of the capsule along the z axis """ radius: float = field( default=0.5, metadata={ "type": "Element", "namespace": "", "required": True, }, ) length: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Cylinder: """ Cylinder shape. Parameters ---------- radius: Radius of the cylinder length: Length of the cylinder along the z axis """ radius: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) length: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Ellipsoid: """ Ellipsoid shape. Parameters ---------- radii: The three radii of the ellipsoid. The origin of the ellipsoid is in its geometric center (inside the center of the ellipsoid). """ radii: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Heightmap: """ A heightmap based on a 2d grayscale image. Parameters ---------- uri: URI to a grayscale image file size: The size of the heightmap in world units. When loading an image: "size" is used if present, otherwise defaults to 1x1x1. When loading a DEM: "size" is used if present, otherwise defaults to true size of DEM. pos: A position offset. texture: The heightmap can contain multiple textures. The order of the texture matters. The first texture will appear at the lowest height, and the last texture at the highest height. Use blend to control the height thresholds and fade between textures. blend: The blend tag controls how two adjacent textures are mixed. The number of blend elements should equal one less than the number of textures. use_terrain_paging: Set if the rendering engine will use terrain paging sampling: Samples per heightmap datum. For rasterized heightmaps, this indicates the number of samples to take per pixel. Using a higher value, e.g. 2, will generally improve the quality of the heightmap but lower performance. """ uri: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) size: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) pos: str = field( default="0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) texture: List["Geometry.Heightmap.Texture"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) blend: List["Geometry.Heightmap.Blend"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) use_terrain_paging: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) sampling: int = field( default=1, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Texture: """The heightmap can contain multiple textures. The order of the texture matters. The first texture will appear at the lowest height, and the last texture at the highest height. Use blend to control the height thresholds and fade between textures. Parameters ---------- size: Size of the applied texture in meters. diffuse: Diffuse texture image filename normal: Normalmap texture image filename """ size: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) diffuse: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) normal: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Blend: """The blend tag controls how two adjacent textures are mixed. The number of blend elements should equal one less than the number of textures. Parameters ---------- min_height: Min height of a blend layer fade_dist: Distance over which the blend occurs """ min_height: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) fade_dist: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Image: """ Extrude a set of boxes from a grayscale image. Parameters ---------- uri: URI of the grayscale image file scale: Scaling factor applied to the image threshold: Grayscale threshold height: Height of the extruded boxes granularity: The amount of error in the model """ uri: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) scale: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) threshold: int = field( default=200, metadata={ "type": "Element", "namespace": "", "required": True, }, ) height: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) granularity: int = field( default=1, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Mesh: """ Mesh shape. Parameters ---------- uri: Mesh uri submesh: Use a named submesh. The submesh must exist in the mesh specified by the uri scale: Scaling factor applied to the mesh """ uri: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) submesh: Optional["Geometry.Mesh.Submesh"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) scale: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Submesh: """Use a named submesh. The submesh must exist in the mesh specified by the uri Parameters ---------- name: Name of the submesh within the parent mesh center: Set to true to center the vertices of the submesh at 0,0,0. This will effectively remove any transformations on the submesh before the poses from parent links and models are applied. """ name: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) center: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Plane: """ Plane shape. Parameters ---------- normal: Normal direction for the plane. When a Plane is used as a geometry for a Visual or Collision object, then the normal is specified in the Visual or Collision frame, respectively. size: Length of each side of the plane. Note that this property is meaningful only for visualizing the Plane, i.e., when the Plane is used as a geometry for a Visual object. The Plane has infinite size when used as a geometry for a Collision object. """ normal: str = field( default="0 0 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) size: str = field( default="1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+)((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Polyline: """ Defines an extruded polyline shape. Parameters ---------- point: A series of points that define the path of the polyline. height: Height of the polyline """ point: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+)((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) height: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Sphere: """ Sphere shape. Parameters ---------- radius: radius of the sphere """ radius: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v18/geometry.py
0.942705
0.579073
geometry.py
pypi
from dataclasses import dataclass, field from typing import Optional from .geometry import Geometry __NAMESPACE__ = "sdformat/v1.0/collision.xsd" @dataclass class Collision: class Meta: name = "collision" max_contacts: int = field( default=10, metadata={ "type": "Element", "namespace": "", "required": True, }, ) mass: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) origin: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) geometry: Optional[Geometry] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) surface: Optional["Collision.Surface"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) laser_retro: float = field( default=0.0, metadata={ "type": "Attribute", }, ) @dataclass class Surface: bounce: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) friction: Optional["Collision.Surface.Friction"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) contact: Optional["Collision.Surface.Contact"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Friction: ode: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Contact: ode: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v10/collision.py
0.870005
0.273649
collision.py
pypi
from dataclasses import dataclass, field from typing import List, Optional __NAMESPACE__ = "sdformat/v1.0/sensor.xsd" @dataclass class Sensor: class Meta: name = "sensor" origin: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) topic: str = field( default="__default", metadata={ "type": "Element", "namespace": "", "required": True, }, ) plugin: List["Sensor.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) camera: Optional["Sensor.Camera"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) ray: Optional["Sensor.Ray"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) contact: Optional["Sensor.Contact"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) rfidtag: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) rfid: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) always_on: bool = field( default=False, metadata={ "type": "Attribute", }, ) update_rate: float = field( default=0.0, metadata={ "type": "Attribute", }, ) visualize: bool = field( default=False, metadata={ "type": "Attribute", }, ) @dataclass class Plugin: any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Camera: horizontal_fov: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) image: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) clip: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) save: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) depth_camera: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Ray: scan: Optional["Sensor.Ray.Scan"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) range: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Scan: horizontal: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) vertical: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Contact: collision: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) topic: str = field( default="__default_topic__", metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v10/sensor.py
0.859044
0.314077
sensor.py
pypi
from dataclasses import dataclass, field from typing import Optional from .geometry import Geometry __NAMESPACE__ = "sdformat/v1.0/visual.xsd" @dataclass class Visual: class Meta: name = "visual" origin: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) material: Optional["Visual.Material"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) geometry: Optional[Geometry] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) cast_shadows: bool = field( default=True, metadata={ "type": "Attribute", }, ) laser_retro: float = field( default=0.0, metadata={ "type": "Attribute", }, ) transparency: float = field( default=0.0, metadata={ "type": "Attribute", }, ) @dataclass class Material: shader: Optional["Visual.Material.Shader"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) ambient: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) diffuse: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) specular: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) emissive: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) script: str = field( default="__default__", metadata={ "type": "Attribute", }, ) @dataclass class Shader: normal_map: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v10/visual.py
0.873201
0.271531
visual.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .collision import Collision from .sensor import Sensor from .visual import Visual __NAMESPACE__ = "sdformat/v1.0/link.xsd" @dataclass class Link: class Meta: name = "link" origin: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) damping: Optional["Link.Damping"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) inertial: Optional["Link.Inertial"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) collision: List[Collision] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) visual: List[Visual] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) sensor: List[Sensor] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) projector: Optional["Link.Projector"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) gravity: bool = field( default=True, metadata={ "type": "Attribute", }, ) self_collide: bool = field( default=False, metadata={ "type": "Attribute", }, ) kinematic: bool = field( default=False, metadata={ "type": "Attribute", }, ) @dataclass class Damping: linear: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) angular: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Inertial: origin: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) inertia: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) mass: float = field( default=1.0, metadata={ "type": "Attribute", }, ) density: float = field( default=1.0, metadata={ "type": "Attribute", }, ) @dataclass class Projector: texture: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) fov: float = field( default=0.785, metadata={ "type": "Element", "namespace": "", "required": True, }, ) near_clip: float = field( default=0.1, metadata={ "type": "Element", "namespace": "", "required": True, }, ) far_clip: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) plugin: List["Link.Projector.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Plugin: any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v10/link.py
0.837254
0.330593
link.py
pypi
from dataclasses import dataclass, field from typing import Optional __NAMESPACE__ = "sdformat/v1.0/joint.xsd" @dataclass class Joint: class Meta: name = "joint" parent: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) child: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) origin: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) thread_pitch: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) axis: Optional["Joint.Axis"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) axis2: Optional["Joint.Axis2"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) physics: Optional["Joint.Physics"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Axis: dynamics: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) limit: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) xyz: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Axis2: dynamics: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) limit: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) xyz: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Physics: ode: Optional["Joint.Physics.Ode"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Ode: fudge_factor: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) bounce: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_force: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) velocity: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) limit: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) suspension: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v10/joint.py
0.82425
0.342022
joint.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .actor import Actor from .joint import Joint from .light import Light from .model import Model from .physics import Physics from .scene import Scene from .state import State __NAMESPACE__ = "sdformat/v1.0/world.xsd" @dataclass class World: class Meta: name = "world" gui: Optional["World.Gui"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) physics: Optional[Physics] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) scene: Optional[Scene] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) light: List[Light] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) model: List[Model] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) actor: List[Actor] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) plugin: List["World.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) joint: List[Joint] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) road: List["World.Road"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) state: List[State] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Gui: camera: Optional["World.Gui.Camera"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) fullscreen: bool = field( default=False, metadata={ "type": "Attribute", }, ) @dataclass class Camera: view_controller: str = field( default="oribit", metadata={ "type": "Element", "namespace": "", "required": True, }, ) origin: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) track_visual: Optional["World.Gui.Camera.TrackVisual"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class TrackVisual: name: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_dist: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_dist: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Plugin: any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Road: width: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) point: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v10/world.py
0.832032
0.304378
world.py
pypi
from dataclasses import dataclass, field from typing import List, Optional __NAMESPACE__ = "sdformat/v1.0/state.xsd" @dataclass class State: class Meta: name = "state" model: List["State.Model"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) world_name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) time: str = field( default="0 0", metadata={ "type": "Attribute", "white_space": "collapse", "pattern": r"\d+ \d+", }, ) @dataclass class Model: pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) link: List["State.Model.Link"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Link: pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) velocity: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) wrench: List["State.Model.Link.Wrench"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Wrench: pos: str = field( default="0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) mag: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v10/state.py
0.719975
0.390795
state.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .joint import Joint from .link import Link __NAMESPACE__ = "sdformat/v1.0/model.xsd" @dataclass class Model: class Meta: name = "model" origin: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) link: List[Link] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) joint: List[Joint] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) plugin: List["Model.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) gripper: List["Model.Gripper"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) static: bool = field( default=False, metadata={ "type": "Attribute", }, ) @dataclass class Plugin: any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Gripper: grasp_check: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) gripper_link: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) palm_link: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v10/model.py
0.821403
0.267413
model.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .joint import Joint from .link import Link __NAMESPACE__ = "sdformat/v1.0/actor.xsd" @dataclass class Actor: class Meta: name = "actor" origin: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) skin: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) animation: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) script: Optional["Actor.Script"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) link: List[Link] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) joint: List[Joint] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) plugin: List["Actor.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) static: bool = field( default=False, metadata={ "type": "Attribute", }, ) @dataclass class Script: trajectory: List["Actor.Script.Trajectory"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) loop: bool = field( default=True, metadata={ "type": "Attribute", }, ) delay_start: float = field( default=0.0, metadata={ "type": "Attribute", }, ) auto_start: bool = field( default=True, metadata={ "type": "Attribute", }, ) @dataclass class Trajectory: waypoint: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) id: Optional[int] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Plugin: any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v10/actor.py
0.849316
0.269709
actor.py
pypi
from dataclasses import dataclass, field from typing import List, Optional __NAMESPACE__ = "sdformat/v1.0/geometry.xsd" @dataclass class Geometry: class Meta: name = "geometry" box: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) sphere: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) cylinder: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) mesh: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) plane: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) image: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) heightmap: Optional["Geometry.Heightmap"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Heightmap: texture: List["Geometry.Heightmap.Texture"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) blend: List["Geometry.Heightmap.Blend"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) size: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) origin: str = field( default="0 0 0", metadata={ "type": "Attribute", "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Texture: size: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) diffuse: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) normal: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Blend: min_height: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) fade_dist: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v10/geometry.py
0.823612
0.363845
geometry.py
pypi
from dataclasses import dataclass, field from typing import Optional from .geometry import Geometry __NAMESPACE__ = "sdformat/v1.4/collision.xsd" @dataclass class Collision: """The collision properties of a link. Note that this can be different from the visual properties of a link, for example, simpler collision models are often used to reduce computation time. Parameters ---------- laser_retro: intensity value returned by laser sensor. max_contacts: Maximum number of contacts allowed between two entities. This value overrides the max_contacts element defined in physics. pose: The reference frame of the collision element, relative to the reference frame of the link. geometry: The shape of the visual or collision object. surface: The surface parameters name: Unique name for the collision element within the scope of the parent link. """ class Meta: name = "collision" laser_retro: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_contacts: int = field( default=10, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) geometry: Optional[Geometry] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) surface: Optional["Collision.Surface"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Surface: """ The surface parameters. """ bounce: Optional["Collision.Surface.Bounce"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) friction: Optional["Collision.Surface.Friction"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) contact: Optional["Collision.Surface.Contact"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) soft_contact: Optional["Collision.Surface.SoftContact"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Bounce: """ Parameters ---------- restitution_coefficient: Bounciness coefficient of restitution, from [0...1], where 0=no bounciness. threshold: Bounce capture velocity, below which effective coefficient of restitution is 0. """ restitution_coefficient: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) threshold: float = field( default=100000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Friction: """ Parameters ---------- ode: ODE friction parameters bullet: """ ode: Optional["Collision.Surface.Friction.Ode"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) bullet: Optional["Collision.Surface.Friction.Bullet"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Ode: """ ODE friction parameters. Parameters ---------- mu: Coefficient of friction in the range of [0..1]. mu2: Second coefficient of friction in the range of [0..1] fdir1: 3-tuple specifying direction of mu1 in the collision local reference frame. slip1: Force dependent slip direction 1 in collision local frame, between the range of [0..1]. slip2: Force dependent slip direction 2 in collision local frame, between the range of [0..1]. """ mu: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) mu2: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) fdir1: str = field( default="0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) slip1: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) slip2: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Bullet: """ Parameters ---------- friction: Coefficient of friction in the range of [0..1]. friction2: Coefficient of friction in the range of [0..1]. fdir1: 3-tuple specifying direction of mu1 in the collision local reference frame. rolling_friction: coefficient of friction in the range of [0..1] """ friction: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) friction2: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) fdir1: str = field( default="0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) rolling_friction: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Contact: """ Parameters ---------- collide_without_contact: Flag to disable contact force generation, while still allowing collision checks and contact visualization to occur. collide_without_contact_bitmask: Bitmask for collision filtering when collide_without_contact is on collide_bitmask: Bitmask for collision filtering. This will override collide_without_contact. Parsed as 16-bit unsigned integer. ode: ODE contact parameters bullet: Bullet contact parameters """ collide_without_contact: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) collide_without_contact_bitmask: int = field( default=1, metadata={ "type": "Element", "namespace": "", "required": True, }, ) collide_bitmask: int = field( default=1, metadata={ "type": "Element", "namespace": "", "required": True, }, ) ode: Optional["Collision.Surface.Contact.Ode"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) bullet: Optional["Collision.Surface.Contact.Bullet"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Ode: """ ODE contact parameters. Parameters ---------- soft_cfm: Soft constraint force mixing. soft_erp: Soft error reduction parameter kp: dynamically "stiffness"-equivalent coefficient for contact joints kd: dynamically "damping"-equivalent coefficient for contact joints max_vel: maximum contact correction velocity truncation term. min_depth: minimum allowable depth before contact correction impulse is applied """ soft_cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) soft_erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) kp: float = field( default=1000000000000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) kd: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_vel: float = field( default=0.01, metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_depth: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Bullet: """ Bullet contact parameters. Parameters ---------- soft_cfm: Soft constraint force mixing. soft_erp: Soft error reduction parameter kp: dynamically "stiffness"-equivalent coefficient for contact joints kd: dynamically "damping"-equivalent coefficient for contact joints split_impulse: Similar to ODE's max_vel implementation. See http://bulletphysics.org/mediawiki-1.5.8/index.php/BtContactSolverInfo#Split_Impulse for more information. split_impulse_penetration_threshold: Similar to ODE's max_vel implementation. See http://bulletphysics.org/mediawiki-1.5.8/index.php/BtContactSolverInfo#Split_Impulse for more information. """ soft_cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) soft_erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) kp: float = field( default=1000000000000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) kd: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) split_impulse: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) split_impulse_penetration_threshold: float = field( default=-0.01, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class SoftContact: """ Parameters ---------- dart: soft contact pamameters based on paper: http://www.cc.gatech.edu/graphics/projects/Sumit/homepage/papers/sigasia11/jain_softcontacts_siga11.pdf """ dart: Optional["Collision.Surface.SoftContact.Dart"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Dart: """ soft contact pamameters based on paper: http://www .cc.gatech.edu/graphics/projects/Sumit/homepage/papers/sigasia1 1/jain_softcontacts_siga11.pdf. Parameters ---------- bone_attachment: This is variable k_v in the soft contacts paper. Its unit is N/m. stiffness: This is variable k_e in the soft contacts paper. Its unit is N/m. damping: Viscous damping of point velocity in body frame. Its unit is N/m/s. flesh_mass_fraction: Fraction of mass to be distributed among deformable nodes. """ bone_attachment: float = field( default=100.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) stiffness: float = field( default=100.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) damping: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) flesh_mass_fraction: float = field( default=0.05, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v14/collision.py
0.943165
0.58439
collision.py
pypi
from dataclasses import dataclass, field from typing import Optional __NAMESPACE__ = "sdformat/v1.4/light.xsd" @dataclass class Light: """ The light element describes a light source. Parameters ---------- cast_shadows: When true, the light will cast shadows. pose: A position and orientation in the global coordinate frame for the light. diffuse: Diffuse light color specular: Specular light color attenuation: Light attenuation direction: Direction of the light, only applicable for spot and directional lights. spot: Spot light parameters name: A unique name for the light. type: The light type: point, directional, spot. """ class Meta: name = "light" cast_shadows: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) diffuse: str = field( default="1 1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) specular: str = field( default=".1 .1 .1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) attenuation: Optional["Light.Attenuation"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) direction: str = field( default="0 0 -1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) spot: Optional["Light.Spot"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: str = field( default="__default__", metadata={ "type": "Attribute", }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Attenuation: """ Light attenuation. Parameters ---------- range: Range of the light linear: The linear attenuation factor: 1 means attenuate evenly over the distance. constant: The constant attenuation factor: 1.0 means never attenuate, 0.0 is complete attenutation. quadratic: The quadratic attenuation factor: adds a curvature to the attenuation. """ range: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) linear: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) constant: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) quadratic: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Spot: """ Spot light parameters. Parameters ---------- inner_angle: Angle covered by the bright inner cone outer_angle: Angle covered by the outer cone falloff: The rate of falloff between the inner and outer cones. 1.0 means a linear falloff, less means slower falloff, higher means faster falloff. """ inner_angle: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) outer_angle: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) falloff: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v14/light.py
0.947161
0.468973
light.py
pypi
from dataclasses import dataclass, field from typing import Optional __NAMESPACE__ = "sdformat/v1.4/scene.xsd" @dataclass class Scene: """ Specifies the look of the environment. Parameters ---------- ambient: Color of the ambient light. background: Color of the background. sky: Properties for the sky shadows: Enable/disable shadows fog: Controls fog grid: Enable/disable the grid """ class Meta: name = "scene" ambient: str = field( default="0.4 0.4 0.4 1.0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) background: str = field( default=".7 .7 .7 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) sky: Optional["Scene.Sky"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) shadows: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) fog: Optional["Scene.Fog"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) grid: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Sky: """ Properties for the sky. Parameters ---------- time: Time of day [0..24] sunrise: Sunrise time [0..24] sunset: Sunset time [0..24] clouds: Sunset time [0..24] """ time: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) sunrise: float = field( default=6.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) sunset: float = field( default=20.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) clouds: Optional["Scene.Sky.Clouds"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Clouds: """ Sunset time [0..24] Parameters ---------- speed: Speed of the clouds direction: Direction of the cloud movement humidity: Density of clouds mean_size: Average size of the clouds ambient: Ambient cloud color """ speed: float = field( default=0.6, metadata={ "type": "Element", "namespace": "", "required": True, }, ) direction: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) humidity: float = field( default=0.5, metadata={ "type": "Element", "namespace": "", "required": True, }, ) mean_size: float = field( default=0.5, metadata={ "type": "Element", "namespace": "", "required": True, }, ) ambient: str = field( default=".8 .8 .8 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) @dataclass class Fog: """ Controls fog. Parameters ---------- color: Fog color type: Fog type: constant, linear, quadratic start: Distance to start of fog end: Distance to end of fog density: Density of fog """ color: str = field( default="1 1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) type: str = field( default="none", metadata={ "type": "Element", "namespace": "", "required": True, }, ) start: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) end: float = field( default=100.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) density: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v14/scene.py
0.934125
0.460713
scene.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .geometry import Geometry __NAMESPACE__ = "sdformat/v1.4/visual.xsd" @dataclass class Visual: """The visual properties of the link. This element specifies the shape of the object (box, cylinder, etc.) for visualization purposes. Parameters ---------- cast_shadows: If true the visual will cast shadows. laser_retro: will be implemented in the future release. transparency: The amount of transparency( 0=opaque, 1 = fully transparent) pose: The reference frame of the visual element, relative to the reference frame of the link. material: The material of the visual element. geometry: The shape of the visual or collision object. plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. name: Unique name for the visual element within the scope of the parent link. """ class Meta: name = "visual" cast_shadows: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) laser_retro: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) transparency: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) material: Optional["Visual.Material"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) geometry: Optional[Geometry] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) plugin: List["Visual.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Material: """ The material of the visual element. Parameters ---------- script: Name of material from an installed script file. This will override the color element if the script exists. shader: lighting: If false, dynamic lighting will be disabled ambient: The ambient color of a material specified by set of four numbers representing red/green/blue, each in the range of [0,1]. diffuse: The diffuse color of a material specified by set of four numbers representing red/green/blue/alpha, each in the range of [0,1]. specular: The specular color of a material specified by set of four numbers representing red/green/blue/alpha, each in the range of [0,1]. emissive: The emissive color of a material specified by set of four numbers representing red/green/blue, each in the range of [0,1]. """ script: Optional["Visual.Material.Script"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) shader: Optional["Visual.Material.Shader"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) lighting: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) ambient: str = field( default="0 0 0 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) diffuse: str = field( default="0 0 0 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) specular: str = field( default="0 0 0 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) emissive: str = field( default="0 0 0 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) @dataclass class Script: """Name of material from an installed script file. This will override the color element if the script exists. Parameters ---------- uri: URI of the material script file name: Name of the script within the script file """ uri: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) name: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Shader: """ Parameters ---------- normal_map: filename of the normal map type: vertex, pixel, normal_map_object_space, normal_map_tangent_space """ normal_map: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v14/visual.py
0.910292
0.627923
visual.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .collision import Collision from .sensor import Sensor from .visual import Visual __NAMESPACE__ = "sdformat/v1.4/link.xsd" @dataclass class Link: """A physical link with inertia, collision, and visual properties. A link must be a child of a model, and any number of links may exist in a model. Parameters ---------- gravity: If true, the link is affected by gravity. self_collide: If true, the link can collide with other links in the model. kinematic: If true, the link is kinematic only pose: This is the pose of the link reference frame, relative to the model reference frame. must_be_base_link: If true, the link will have 6DOF and be a direct child of world. velocity_decay: Exponential damping of the link's velocity. inertial: The inertial properties of the link. collision: The collision properties of a link. Note that this can be different from the visual properties of a link, for example, simpler collision models are often used to reduce computation time. visual: The visual properties of the link. This element specifies the shape of the object (box, cylinder, etc.) for visualization purposes. sensor: The sensor tag describes the type and properties of a sensor. projector: audio_sink: An audio sink. audio_source: An audio source. name: A unique name for the link within the scope of the model. """ class Meta: name = "link" gravity: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) self_collide: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) kinematic: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) must_be_base_link: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) velocity_decay: Optional["Link.VelocityDecay"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) inertial: Optional["Link.Inertial"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) collision: List[Collision] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) visual: List[Visual] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) sensor: List[Sensor] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) projector: Optional["Link.Projector"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) audio_sink: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) audio_source: List["Link.AudioSource"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class VelocityDecay: """ Exponential damping of the link's velocity. Parameters ---------- linear: Linear damping angular: Angular damping """ linear: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) angular: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Inertial: """ The inertial properties of the link. Parameters ---------- mass: The mass of the link. pose: This is the pose of the inertial reference frame, relative to the link reference frame. The origin of the inertial reference frame needs to be at the center of gravity. The axes of the inertial reference frame do not need to be aligned with the principal axes of the inertia. inertia: The 3x3 rotational inertia matrix. Because the rotational inertia matrix is symmetric, only 6 above- diagonal elements of this matrix are specified here, using the attributes ixx, ixy, ixz, iyy, iyz, izz. """ mass: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) inertia: Optional["Link.Inertial.Inertia"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Inertia: """The 3x3 rotational inertia matrix. Because the rotational inertia matrix is symmetric, only 6 above-diagonal elements of this matrix are specified here, using the attributes ixx, ixy, ixz, iyy, iyz, izz. """ ixx: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) ixy: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) ixz: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) iyy: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) iyz: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) izz: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Projector: """ Parameters ---------- texture: Texture name pose: Pose of the projector fov: Field of view near_clip: Near clip distance far_clip: far clip distance plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. name: Name of the projector """ texture: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) fov: float = field( default=0.785, metadata={ "type": "Element", "namespace": "", "required": True, }, ) near_clip: float = field( default=0.1, metadata={ "type": "Element", "namespace": "", "required": True, }, ) far_clip: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) plugin: List["Link.Projector.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class AudioSource: """ An audio source. Parameters ---------- uri: URI of the audio media. pitch: Pitch for the audio media, in Hz gain: Gain for the audio media, in dB. contact: List of collision objects that will trigger audio playback. loop: True to make the audio source loop playback. pose: A position and orientation in the parent coordinate frame for the audio source. Position(x,y,z) and rotation (roll, pitch yaw) in the parent coordinate frame. """ uri: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) pitch: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) gain: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) contact: Optional["Link.AudioSource.Contact"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) loop: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Contact: """ List of collision objects that will trigger audio playback. Parameters ---------- collision: Name of child collision element that will trigger audio playback. """ collision: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v14/link.py
0.943321
0.492127
link.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .sensor import Sensor __NAMESPACE__ = "sdformat/v1.4/joint.xsd" @dataclass class Joint: """ A joint connections two links with kinematic and dynamic properties. Parameters ---------- parent: Name of the parent link child: Name of the child link pose: offset from child link origin in child link frame. gearbox_ratio: Parameter for gearbox joints. Given theta_1 and theta_2 defined in description for gearbox_reference_body, theta_2 = -gearbox_ratio * theta_1. gearbox_reference_body: Parameter for gearbox joints. Gearbox ratio is enforced over two joint angles. First joint angle (theta_1) is the angle from the gearbox_reference_body to the parent link in the direction of the axis element and the second joint angle (theta_2) is the angle from the gearbox_reference_body to the child link in the direction of the axis2 element. thread_pitch: Parameter for screw joints. axis: The joint axis specified in the parent model frame. This is the axis of rotation for revolute joints, the axis of translation for prismatic joints. The axis is currently specified in the parent model frame of reference, but this will be changed to the joint frame in future version of SDFormat (see gazebo issue #494). axis2: The second joint axis specified in the parent model frame. This is the second axis of rotation for revolute2 joints and universal joints. The axis is currently specified in the parent model frame of reference, but this will be changed to the joint frame in future version of SDFormat (see gazebo issue #494). physics: Parameters that are specific to a certain physics engine. sensor: The sensor tag describes the type and properties of a sensor. name: A unique name for the joint within the scope of the model. type: The type of joint, which must be one of the following: (revolute) a hinge joint that rotates on a single axis with either a fixed or continuous range of motion, (gearbox) geared revolute joints, (revolute2) same as two revolute joints connected in series, (prismatic) a sliding joint that slides along an axis with a limited range specified by upper and lower limits, (ball) a ball and socket joint, (universal), like a ball joint, but constrains one degree of freedom, (piston) similar to a Slider joint except that rotation around the translation axis is possible. """ class Meta: name = "joint" parent: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) child: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) gearbox_ratio: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) gearbox_reference_body: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) thread_pitch: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) axis: Optional["Joint.Axis"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) axis2: Optional["Joint.Axis2"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) physics: Optional["Joint.Physics"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) sensor: List[Sensor] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Axis: """The joint axis specified in the parent model frame. This is the axis of rotation for revolute joints, the axis of translation for prismatic joints. The axis is currently specified in the parent model frame of reference, but this will be changed to the joint frame in future version of SDFormat (see gazebo issue #494). Parameters ---------- xyz: Represents the x,y,z components of a vector. The vector should be normalized. dynamics: An element specifying physical properties of the joint. These values are used to specify modeling properties of the joint, particularly useful for simulation. limit: specifies the limits of this joint """ xyz: str = field( default="0 0 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) dynamics: Optional["Joint.Axis.Dynamics"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) limit: Optional["Joint.Axis.Limit"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Dynamics: """An element specifying physical properties of the joint. These values are used to specify modeling properties of the joint, particularly useful for simulation. Parameters ---------- damping: The physical velocity dependent viscous damping coefficient of the joint. friction: The physical static friction value of the joint. """ damping: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) friction: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Limit: """ specifies the limits of this joint. Parameters ---------- lower: An attribute specifying the lower joint limit (radians for revolute joints, meters for prismatic joints). Omit if joint is continuous. upper: An attribute specifying the upper joint limit (radians for revolute joints, meters for prismatic joints). Omit if joint is continuous. effort: An attribute for enforcing the maximum joint effort applied by Joint::SetForce. Limit is not enforced if value is negative. velocity: (not implemented) An attribute for enforcing the maximum joint velocity. stiffness: Joint stop stiffness. Support physics engines: SimBody. dissipation: Joint stop dissipation. """ lower: float = field( default=-1e16, metadata={ "type": "Element", "namespace": "", "required": True, }, ) upper: float = field( default=1e16, metadata={ "type": "Element", "namespace": "", "required": True, }, ) effort: float = field( default=-1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) velocity: float = field( default=-1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) stiffness: float = field( default=100000000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) dissipation: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Axis2: """The second joint axis specified in the parent model frame. This is the second axis of rotation for revolute2 joints and universal joints. The axis is currently specified in the parent model frame of reference, but this will be changed to the joint frame in future version of SDFormat (see gazebo issue #494). Parameters ---------- xyz: Represents the x,y,z components of a vector. The vector should be normalized. dynamics: An element specifying physical properties of the joint. These values are used to specify modeling properties of the joint, particularly useful for simulation. limit: """ xyz: str = field( default="0 0 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) dynamics: Optional["Joint.Axis2.Dynamics"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) limit: Optional["Joint.Axis2.Limit"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Dynamics: """An element specifying physical properties of the joint. These values are used to specify modeling properties of the joint, particularly useful for simulation. Parameters ---------- damping: The physical velocity dependent viscous damping coefficient of the joint. EXPERIMENTAL: if damping coefficient is negative and implicit_spring_damper is true, adaptive damping is used. friction: The physical static friction value of the joint. """ damping: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) friction: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Limit: """ Parameters ---------- lower: An attribute specifying the lower joint limit (radians for revolute joints, meters for prismatic joints). Omit if joint is continuous. upper: An attribute specifying the upper joint limit (radians for revolute joints, meters for prismatic joints). Omit if joint is continuous. effort: An attribute for enforcing the maximum joint effort applied by Joint::SetForce. Limit is not enforced if value is negative. velocity: (not implemented) An attribute for enforcing the maximum joint velocity. stiffness: Joint stop stiffness. Supported physics engines: SimBody. dissipation: Joint stop dissipation. Supported physics engines: SimBody. """ lower: float = field( default=-1e16, metadata={ "type": "Element", "namespace": "", "required": True, }, ) upper: float = field( default=1e16, metadata={ "type": "Element", "namespace": "", "required": True, }, ) effort: float = field( default=-1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) velocity: float = field( default=-1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) stiffness: float = field( default=100000000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) dissipation: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Physics: """ Parameters that are specific to a certain physics engine. Parameters ---------- simbody: Simbody specific parameters ode: ODE specific parameters provide_feedback: If provide feedback is set to true, physics engine will compute the constraint forces at this joint. For now, provide_feedback under ode block will override this tag and given user warning about the migration. provide_feedback under ode is scheduled to be removed in SDFormat 1.5. """ simbody: Optional["Joint.Physics.Simbody"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) ode: Optional["Joint.Physics.Ode"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) provide_feedback: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Simbody: """ Simbody specific parameters. Parameters ---------- must_be_loop_joint: Force cut in the multibody graph at this joint. """ must_be_loop_joint: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Ode: """ ODE specific parameters. Parameters ---------- provide_feedback: (DEPRECATION WARNING: In SDFormat 1.5 this tag will be replaced by the same tag directly under the physics-block. For now, this tag overrides the one outside of ode-block, but in SDFormat 1.5 this tag will be removed completely.) If provide feedback is set to true, ODE will compute the constraint forces at this joint. cfm_damping: If cfm damping is set to true, ODE will use CFM to simulate damping, allows for infinite damping, and one additional constraint row (previously used for joint limit) is always active. implicit_spring_damper: If implicit_spring_damper is set to true, ODE will use CFM, ERP to simulate stiffness and damping, allows for infinite damping, and one additional constraint row (previously used for joint limit) is always active. This replaces cfm_damping parameter in SDFormat 1.4. fudge_factor: Scale the excess for in a joint motor at joint limits. Should be between zero and one. cfm: Constraint force mixing for constrained directions erp: Error reduction parameter for constrained directions bounce: Bounciness of the limits max_force: Maximum force or torque used to reach the desired velocity. velocity: The desired velocity of the joint. Should only be set if you want the joint to move on load. limit: suspension: """ provide_feedback: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) cfm_damping: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) implicit_spring_damper: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) fudge_factor: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) bounce: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_force: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) velocity: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) limit: Optional["Joint.Physics.Ode.Limit"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) suspension: Optional["Joint.Physics.Ode.Suspension"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Limit: """ Parameters ---------- cfm: Constraint force mixing parameter used by the joint stop erp: Error reduction parameter used by the joint stop """ cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Suspension: """ Parameters ---------- cfm: Suspension constraint force mixing parameter erp: Suspension error reduction parameter """ cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v14/joint.py
0.965835
0.597784
joint.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .actor import Actor from .joint import Joint from .light import Light from .model import Model from .physics import Physics from .scene import Scene from .state import State __NAMESPACE__ = "sdformat/v1.4/world.xsd" @dataclass class World: """ The world element encapsulates an entire world description including: models, scene, physics, joints, and plugins. Parameters ---------- audio: Global audio properties. include: Include resources from a URI gui: physics: The physics tag specifies the type and properties of the dynamics engine. scene: Specifies the look of the environment. light: The light element describes a light source. model: The model element defines a complete robot or any other physical object. actor: plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. joint: A joint connections two links with kinematic and dynamic properties. road: spherical_coordinates: state: name: Unique name of the world """ class Meta: name = "world" audio: Optional["World.Audio"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) include: List["World.Include"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) gui: Optional["World.Gui"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) physics: Optional[Physics] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) scene: Optional[Scene] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) light: List[Light] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) model: List[Model] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) actor: List[Actor] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) plugin: List["World.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) joint: List[Joint] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) road: List["World.Road"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) spherical_coordinates: Optional["World.SphericalCoordinates"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) state: List[State] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Audio: """ Global audio properties. Parameters ---------- device: Device to use for audio playback. A value of "default" will use the system's default audio device. Otherwise, specify a an audio device file" """ device: str = field( default="default", metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Include: """ Include resources from a URI. Parameters ---------- uri: URI to a resource, such as a model """ uri: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Gui: camera: Optional["World.Gui.Camera"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) fullscreen: bool = field( default=False, metadata={ "type": "Attribute", }, ) @dataclass class Camera: view_controller: str = field( default="orbit", metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) track_visual: Optional["World.Gui.Camera.TrackVisual"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class TrackVisual: name: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_dist: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_dist: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Road: """ Parameters ---------- width: Width of the road point: A series of points define the path of the road. name: Name of the road """ width: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) point: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class SphericalCoordinates: """ Parameters ---------- surface_model: Name of planetary surface model, used to determine the surface altitude at a given latitude and longitude. The default is an ellipsoid model of the earth based on the WGS-84 standard. It is used in Gazebo's GPS sensor implementation. latitude_deg: Geodetic latitude at origin of gazebo reference frame, specified in units of degrees. longitude_deg: Longitude at origin of gazebo reference frame, specified in units of degrees. elevation: Elevation of origin of gazebo reference frame, specified in meters. heading_deg: Heading offset of gazebo reference frame, measured as angle between East and gazebo x axis, or equivalently, the angle between North and gazebo y axis. The angle is specified in degrees. """ surface_model: str = field( default="EARTH_WGS84", metadata={ "type": "Element", "namespace": "", "required": True, }, ) latitude_deg: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) longitude_deg: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) elevation: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) heading_deg: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v14/world.py
0.942856
0.396419
world.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .model import Model __NAMESPACE__ = "sdformat/v1.4/state.xsd" @dataclass class State: """ Parameters ---------- sim_time: Simulation time stamp of the state [seconds nanoseconds] wall_time: Wall time stamp of the state [seconds nanoseconds] real_time: Real time stamp of the state [seconds nanoseconds] insertions: A list of new model names deletions: A list of deleted model names model: Model state world_name: Name of the world this state applies to """ class Meta: name = "state" sim_time: str = field( default="0 0", metadata={ "type": "Element", "namespace": "", "required": True, "white_space": "collapse", "pattern": r"\d+ \d+", }, ) wall_time: str = field( default="0 0", metadata={ "type": "Element", "namespace": "", "required": True, "white_space": "collapse", "pattern": r"\d+ \d+", }, ) real_time: str = field( default="0 0", metadata={ "type": "Element", "namespace": "", "required": True, "white_space": "collapse", "pattern": r"\d+ \d+", }, ) insertions: Optional["State.Insertions"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) deletions: Optional["State.Deletions"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) model: List["State.Model"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) world_name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Insertions: """ A list of new model names. Parameters ---------- model: The model element defines a complete robot or any other physical object. """ model: List[Model] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Deletions: """ A list of deleted model names. Parameters ---------- name: The name of a deleted model """ name: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) @dataclass class Model: """ Model state. Parameters ---------- pose: Pose of the model joint: Joint angle link: Link state name: Name of the model """ pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) joint: List["State.Model.Joint"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) link: List["State.Model.Link"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Joint: """ Joint angle. Parameters ---------- angle: Angle of an axis name: Name of the joint """ angle: List["State.Model.Joint.Angle"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Angle: """ Parameters ---------- value: axis: Index of the axis. """ value: Optional[float] = field( default=None, metadata={ "required": True, }, ) axis: Optional[int] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Link: """ Link state. Parameters ---------- pose: Pose of the link relative to the model velocity: Velocity of the link acceleration: Acceleration of the link wrench: Force applied to the link collision: Collision state name: Name of the link """ pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) velocity: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) acceleration: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) wrench: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) collision: List["State.Model.Link.Collision"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Collision: """ Collision state. Parameters ---------- pose: Pose of the link relative to the model name: Name of the collision """ pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v14/state.py
0.929808
0.536677
state.py
pypi
from dataclasses import dataclass, field from typing import Optional __NAMESPACE__ = "sdformat/v1.4/physics.xsd" @dataclass class Physics: """ The physics tag specifies the type and properties of the dynamics engine. Parameters ---------- max_step_size: Maximum time step size at which every system in simulation can interact with the states of the world. (was physics.sdf's dt). real_time_factor: target simulation speedup factor, defined by ratio of simulation time to real-time. real_time_update_rate: Rate at which to update the physics engine (UpdatePhysics calls per real-time second). (was physics.sdf's update_rate). max_contacts: Maximum number of contacts allowed between two entities. This value can be over ridden by a max_contacts element in a collision element. gravity: The gravity vector simbody: Simbody specific physics properties bullet: Bullet specific physics properties ode: ODE specific physics properties type: The type of the dynamics engine. Current options are ode, bullet, simbody and rtql8. Defaults to ode if left unspecified. """ class Meta: name = "physics" max_step_size: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) real_time_factor: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) real_time_update_rate: float = field( default=1000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_contacts: int = field( default=20, metadata={ "type": "Element", "namespace": "", "required": True, }, ) gravity: str = field( default="0 0 -9.8", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) simbody: Optional["Physics.Simbody"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) bullet: Optional["Physics.Bullet"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) ode: Optional["Physics.Ode"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Simbody: """ Simbody specific physics properties. Parameters ---------- min_step_size: (Currently not used in simbody) The time duration which advances with each iteration of the dynamics engine, this has to be no bigger than max_step_size under physics block. If left unspecified, min_step_size defaults to max_step_size. accuracy: Roughly the relative error of the system. -LOG(accuracy) is roughly the number of significant digits. max_transient_velocity: Tolerable "slip" velocity allowed by the solver when static friction is supposed to hold object in place. contact: Relationship among dissipation, coef. restitution, etc. d = dissipation coefficient (1/velocity) vc = capture velocity (velocity where e=e_max) vp = plastic velocity (smallest v where e=e_min) > vc Assume real COR=1 when v=0. e_min = given minimum COR, at v >= vp (a.k.a. plastic_coef_restitution) d = slope = (1-e_min)/vp OR, e_min = 1 - d*vp e_max = maximum COR = 1-d*vc, reached at v=vc e = 0, v <= vc = 1 - d*v, vc < v < vp = e_min, v >= vp dissipation factor = d*min(v,vp) [compliant] cor = e [rigid] Combining rule e = 0, e1==e2==0 = 2*e1*e2/(e1+e2), otherwise """ min_step_size: float = field( default=0.0001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) accuracy: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_transient_velocity: float = field( default=0.01, metadata={ "type": "Element", "namespace": "", "required": True, }, ) contact: Optional["Physics.Simbody.Contact"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Contact: """Relationship among dissipation, coef. restitution, etc. d = dissipation coefficient (1/velocity) vc = capture velocity (velocity where e=e_max) vp = plastic velocity (smallest v where e=e_min) > vc Assume real COR=1 when v=0. e_min = given minimum COR, at v >= vp (a.k.a. plastic_coef_restitution) d = slope = (1-e_min)/vp OR, e_min = 1 - d*vp e_max = maximum COR = 1-d*vc, reached at v=vc e = 0, v <= vc = 1 - d*v, vc < v < vp = e_min, v >= vp dissipation factor = d*min(v,vp) [compliant] cor = e [rigid] Combining rule e = 0, e1==e2==0 = 2*e1*e2/(e1+e2), otherwise Parameters ---------- stiffness: Default contact material stiffness (force/dist or torque/radian). dissipation: dissipation coefficient to be used in compliant contact; if not given it is (1-min_cor)/plastic_impact_velocity plastic_coef_restitution: this is the COR to be used at high velocities for rigid impacts; if not given it is 1 - dissipation*plastic_impact_velocity plastic_impact_velocity: smallest impact velocity at which min COR is reached; set to zero if you want the min COR always to be used static_friction: static friction (mu_s) as described by this plot: http://gazebosim.org/wiki/File:Stribeck_friction.png dynamic_friction: dynamic friction (mu_d) as described by this plot: http://gazebosim.org/wiki/File:Stribeck_friction.png viscous_friction: viscous friction (mu_v) with units of (1/velocity) as described by this plot: http://gazebosim.org/wiki/File:Stribeck_friction.png override_impact_capture_velocity: for rigid impacts only, impact velocity at which COR is set to zero; normally inherited from global default but can be overridden here. Combining rule: use larger velocity override_stiction_transition_velocity: This is the largest slip velocity at which we'll consider a transition to stiction. Normally inherited from a global default setting. For a continuous friction model this is the velocity at which the max static friction force is reached. Combining rule: use larger velocity """ stiffness: float = field( default=100000000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) dissipation: float = field( default=100.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) plastic_coef_restitution: float = field( default=0.5, metadata={ "type": "Element", "namespace": "", "required": True, }, ) plastic_impact_velocity: float = field( default=0.5, metadata={ "type": "Element", "namespace": "", "required": True, }, ) static_friction: float = field( default=0.9, metadata={ "type": "Element", "namespace": "", "required": True, }, ) dynamic_friction: float = field( default=0.9, metadata={ "type": "Element", "namespace": "", "required": True, }, ) viscous_friction: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) override_impact_capture_velocity: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) override_stiction_transition_velocity: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Bullet: """ Bullet specific physics properties. Parameters ---------- solver: constraints: Bullet constraint parameters. """ solver: Optional["Physics.Bullet.Solver"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) constraints: Optional["Physics.Bullet.Constraints"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Solver: """ Parameters ---------- type: One of the following types: sequential_impulse only. min_step_size: The time duration which advances with each iteration of the dynamics engine, this has to be no bigger than max_step_size under physics block. If left unspecified, min_step_size defaults to max_step_size. iters: Number of iterations for each step. A higher number produces greater accuracy at a performance cost. sor: Set the successive over-relaxation parameter. """ type: str = field( default="sequential_impulse", metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_step_size: float = field( default=0.0001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) iters: int = field( default=50, metadata={ "type": "Element", "namespace": "", "required": True, }, ) sor: float = field( default=1.3, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Constraints: """ Bullet constraint parameters. Parameters ---------- cfm: Constraint force mixing parameter. See the ODE page for more information. erp: Error reduction parameter. See the ODE page for more information. contact_surface_layer: The depth of the surface layer around all geometry objects. Contacts are allowed to sink into the surface layer up to the given depth before coming to rest. The default value is zero. Increasing this to some small value (e.g. 0.001) can help prevent jittering problems due to contacts being repeatedly made and broken. split_impulse: Similar to ODE's max_vel implementation. See http://web.archive.org/web/20120430155635/http://bulletphysics.org/mediawiki-1.5.8/index.php/BtContactSolverInfo#Split_Impulse for more information. split_impulse_penetration_threshold: Similar to ODE's max_vel implementation. See http://web.archive.org/web/20120430155635/http://bulletphysics.org/mediawiki-1.5.8/index.php/BtContactSolverInfo#Split_Impulse for more information. """ cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) contact_surface_layer: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) split_impulse: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) split_impulse_penetration_threshold: float = field( default=-0.01, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Ode: """ ODE specific physics properties. Parameters ---------- solver: constraints: ODE constraint parameters. """ solver: Optional["Physics.Ode.Solver"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) constraints: Optional["Physics.Ode.Constraints"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Solver: """ Parameters ---------- type: One of the following types: world, quick min_step_size: The time duration which advances with each iteration of the dynamics engine, this has to be no bigger than max_step_size under physics block. If left unspecified, min_step_size defaults to max_step_size. iters: Number of iterations for each step. A higher number produces greater accuracy at a performance cost. precon_iters: Experimental parameter. sor: Set the successive over-relaxation parameter. use_dynamic_moi_rescaling: Flag to enable dynamic rescaling of moment of inertia in constrained directions. See gazebo pull request 1114 for the implementation of this feature. https://osrf- migration.github.io/gazebo-gh-pages/#!/osrf/gazebo/pull- request/1114 """ type: str = field( default="quick", metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_step_size: float = field( default=0.0001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) iters: int = field( default=50, metadata={ "type": "Element", "namespace": "", "required": True, }, ) precon_iters: int = field( default=0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) sor: float = field( default=1.3, metadata={ "type": "Element", "namespace": "", "required": True, }, ) use_dynamic_moi_rescaling: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Constraints: """ ODE constraint parameters. Parameters ---------- cfm: Constraint force mixing parameter. See the ODE page for more information. erp: Error reduction parameter. See the ODE page for more information. contact_max_correcting_vel: The maximum correcting velocities allowed when resolving contacts. contact_surface_layer: The depth of the surface layer around all geometry objects. Contacts are allowed to sink into the surface layer up to the given depth before coming to rest. The default value is zero. Increasing this to some small value (e.g. 0.001) can help prevent jittering problems due to contacts being repeatedly made and broken. """ cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) contact_max_correcting_vel: float = field( default=100.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) contact_surface_layer: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v14/physics.py
0.930695
0.600774
physics.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .joint import Joint from .link import Link __NAMESPACE__ = "sdformat/v1.4/model.xsd" @dataclass class Model: """ The model element defines a complete robot or any other physical object. Parameters ---------- static: If set to true, the model is immovable. Otherwise the model is simulated in the dynamics engine. allow_auto_disable: Allows a model to auto-disable, which is means the physics engine can skip updating the model when the model is at rest. This parameter is only used by models with no joints. pose: A position and orientation in the global coordinate frame for the model. Position(x,y,z) and rotation (roll, pitch yaw) in the global coordinate frame. link: A physical link with inertia, collision, and visual properties. A link must be a child of a model, and any number of links may exist in a model. joint: A joint connections two links with kinematic and dynamic properties. plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. gripper: name: A unique name for the model. This name must not match another model in the world. """ class Meta: name = "model" static: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) allow_auto_disable: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) link: List[Link] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) joint: List[Joint] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) plugin: List["Model.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) gripper: List["Model.Gripper"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Gripper: grasp_check: Optional["Model.Gripper.GraspCheck"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) gripper_link: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) palm_link: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class GraspCheck: detach_steps: int = field( default=40, metadata={ "type": "Element", "namespace": "", "required": True, }, ) attach_steps: int = field( default=20, metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_contact_count: int = field( default=2, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v14/model.py
0.944638
0.544559
model.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .joint import Joint from .link import Link __NAMESPACE__ = "sdformat/v1.4/actor.xsd" @dataclass class Actor: """ Parameters ---------- pose: Origin of the actor skin: animation: script: link: A physical link with inertia, collision, and visual properties. A link must be a child of a model, and any number of links may exist in a model. joint: A joint connections two links with kinematic and dynamic properties. plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. name: static: """ class Meta: name = "actor" pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) skin: Optional["Actor.Skin"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) animation: List["Actor.Animation"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) script: Optional["Actor.Script"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) link: List[Link] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) joint: List[Joint] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) plugin: List["Actor.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) static: bool = field( default=False, metadata={ "type": "Attribute", }, ) @dataclass class Skin: filename: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) scale: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Animation: filename: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) scale: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) interpolate_x: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Script: loop: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) delay_start: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) auto_start: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) trajectory: List["Actor.Script.Trajectory"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Trajectory: waypoint: List["Actor.Script.Trajectory.Waypoint"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) id: Optional[int] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Waypoint: time: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v14/actor.py
0.905746
0.414484
actor.py
pypi
from dataclasses import dataclass, field from typing import List, Optional __NAMESPACE__ = "sdformat/v1.4/geometry.xsd" @dataclass class Geometry: """ The shape of the visual or collision object. Parameters ---------- empty: You can use the empty tag to make empty geometries. box: Box shape cylinder: Cylinder shape heightmap: A heightmap based on a 2d grayscale image. image: Extrude a set of boxes from a grayscale image. mesh: Mesh shape plane: Plane shape sphere: Sphere shape """ class Meta: name = "geometry" empty: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) box: Optional["Geometry.Box"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) cylinder: Optional["Geometry.Cylinder"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) heightmap: Optional["Geometry.Heightmap"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) image: Optional["Geometry.Image"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) mesh: Optional["Geometry.Mesh"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) plane: Optional["Geometry.Plane"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) sphere: Optional["Geometry.Sphere"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Box: """ Box shape. Parameters ---------- size: The three side lengths of the box. The origin of the box is in its geometric center (inside the center of the box). """ size: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Cylinder: """ Cylinder shape. Parameters ---------- radius: Radius of the cylinder length: Length of the cylinder along the z axis """ radius: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) length: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Heightmap: """ A heightmap based on a 2d grayscale image. Parameters ---------- uri: URI to a grayscale image file size: The size of the heightmap in world units. When loading an image: "size" is used if present, otherwise defaults to 1x1x1. When loading a DEM: "size" is used if present, otherwise defaults to true size of DEM. pos: A position offset. texture: The heightmap can contain multiple textures. The order of the texture matters. The first texture will appear at the lowest height, and the last texture at the highest height. Use blend to control the height thresholds and fade between textures. blend: The blend tag controls how two adjacent textures are mixed. The number of blend elements should equal one less than the number of textures. use_terrain_paging: Set if the rendering engine will use terrain paging """ uri: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) size: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) pos: str = field( default="0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) texture: List["Geometry.Heightmap.Texture"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) blend: List["Geometry.Heightmap.Blend"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) use_terrain_paging: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Texture: """The heightmap can contain multiple textures. The order of the texture matters. The first texture will appear at the lowest height, and the last texture at the highest height. Use blend to control the height thresholds and fade between textures. Parameters ---------- size: Size of the applied texture in meters. diffuse: Diffuse texture image filename normal: Normalmap texture image filename """ size: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) diffuse: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) normal: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Blend: """The blend tag controls how two adjacent textures are mixed. The number of blend elements should equal one less than the number of textures. Parameters ---------- min_height: Min height of a blend layer fade_dist: Distance over which the blend occurs """ min_height: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) fade_dist: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Image: """ Extrude a set of boxes from a grayscale image. Parameters ---------- uri: URI of the grayscale image file scale: Scaling factor applied to the image threshold: Grayscale threshold height: Height of the extruded boxes granularity: The amount of error in the model """ uri: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) scale: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) threshold: int = field( default=200, metadata={ "type": "Element", "namespace": "", "required": True, }, ) height: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) granularity: int = field( default=1, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Mesh: """ Mesh shape. Parameters ---------- uri: Mesh uri submesh: Use a named submesh. The submesh must exist in the mesh specified by the uri scale: Scaling factor applied to the mesh """ uri: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) submesh: Optional["Geometry.Mesh.Submesh"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) scale: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Submesh: """Use a named submesh. The submesh must exist in the mesh specified by the uri Parameters ---------- name: Name of the submesh within the parent mesh center: Set to true to center the vertices of the submesh at 0,0,0. This will effectively remove any transformations on the submesh before the poses from parent links and models are applied. """ name: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) center: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Plane: """ Plane shape. Parameters ---------- normal: Normal direction for the plane size: Length of each side of the plane """ normal: str = field( default="0 0 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) size: str = field( default="1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+)((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Sphere: """ Sphere shape. Parameters ---------- radius: radius of the sphere """ radius: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v14/geometry.py
0.95334
0.595198
geometry.py
pypi
from dataclasses import dataclass, field from typing import Optional from .geometry import Geometry __NAMESPACE__ = "sdformat/v1.3/collision.xsd" @dataclass class Collision: """The collision properties of a link. Note that this can be different from the visual properties of a link, for example, simpler collision models are often used to reduce computation time. Parameters ---------- laser_retro: intensity value returned by laser sensor. max_contacts: Maximum number of contacts allowed between two entities. This value overrides the max_contacts element defined in physics. pose: The reference frame of the collision element, relative to the reference frame of the link. geometry: The shape of the visual or collision object. surface: The surface parameters name: Unique name for the collision element within the scope of the parent link. """ class Meta: name = "collision" laser_retro: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_contacts: int = field( default=10, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) geometry: Optional[Geometry] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) surface: Optional["Collision.Surface"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Surface: """ The surface parameters. """ bounce: Optional["Collision.Surface.Bounce"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) friction: Optional["Collision.Surface.Friction"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) contact: Optional["Collision.Surface.Contact"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Bounce: """ Parameters ---------- restitution_coefficient: Bounciness coefficient of restitution, from [0...1], where 0=no bounciness. threshold: Bounce velocity threshold, below which effective coefficient of restitution is 0. """ restitution_coefficient: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) threshold: float = field( default=100000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Friction: """ Parameters ---------- ode: ODE friction parameters """ ode: Optional["Collision.Surface.Friction.Ode"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Ode: """ ODE friction parameters. Parameters ---------- mu: Coefficient of friction in the range of [0..1]. mu2: Second coefficient of friction in the range of [0..1] fdir1: 3-tuple specifying direction of mu1 in the collision local reference frame. slip1: Force dependent slip direction 1 in collision local frame, between the range of [0..1]. slip2: Force dependent slip direction 2 in collision local frame, between the range of [0..1]. """ mu: float = field( default=-1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) mu2: float = field( default=-1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) fdir1: str = field( default="0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) slip1: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) slip2: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Contact: """ Parameters ---------- ode: ODE contact parameters """ ode: Optional["Collision.Surface.Contact.Ode"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Ode: """ ODE contact parameters. Parameters ---------- soft_cfm: Soft constraint force mixing. soft_erp: Soft error reduction parameter kp: dynamically "stiffness"-equivalent coefficient for contact joints kd: dynamically "damping"-equivalent coefficient for contact joints max_vel: maximum contact correction velocity truncation term. min_depth: minimum allowable depth before contact correction impulse is applied """ soft_cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) soft_erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) kp: float = field( default=1000000000000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) kd: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_vel: float = field( default=0.01, metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_depth: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v13/collision.py
0.945964
0.464355
collision.py
pypi
from dataclasses import dataclass, field from typing import Optional __NAMESPACE__ = "sdformat/v1.3/light.xsd" @dataclass class Light: """ The light element describes a light source. Parameters ---------- cast_shadows: When true, the light will cast shadows. pose: A position and orientation in the global coordinate frame for the light. diffuse: Diffuse light color specular: Specular light color attenuation: Light attenuation direction: Direction of the light, only applicable for spot and directional lights. spot: Spot light parameters name: A unique name for the light. type: The light type: point, directional, spot. """ class Meta: name = "light" cast_shadows: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) diffuse: str = field( default="1 1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) specular: str = field( default=".1 .1 .1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) attenuation: Optional["Light.Attenuation"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) direction: str = field( default="0 0 -1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) spot: Optional["Light.Spot"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: str = field( default="__default__", metadata={ "type": "Attribute", }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Attenuation: """ Light attenuation. Parameters ---------- range: Range of the light linear: The linear attenuation factor: 1 means attenuate evenly over the distance. constant: The constant attenuation factor: 1.0 means never attenuate, 0.0 is complete attenutation. quadratic: The quadratic attenuation factor: adds a curvature to the attenuation. """ range: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) linear: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) constant: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) quadratic: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Spot: """ Spot light parameters. Parameters ---------- inner_angle: Angle covered by the bright inner cone outer_angle: Angle covered by the outer cone falloff: The rate of falloff between the inner and outer cones. 1.0 means a linear falloff, less means slower falloff, higher means faster falloff. """ inner_angle: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) outer_angle: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) falloff: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v13/light.py
0.947357
0.469824
light.py
pypi
from dataclasses import dataclass, field from typing import Optional __NAMESPACE__ = "sdformat/v1.3/scene.xsd" @dataclass class Scene: """ Specifies the look of the environment. Parameters ---------- ambient: Color of the ambient light. background: Color of the background. sky: Properties for the sky shadows: Enable/disable shadows fog: Controls fog grid: Enable/disable the grid """ class Meta: name = "scene" ambient: str = field( default="0.2 0.2 0.2 1.0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) background: str = field( default=".7 .7 .7 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) sky: Optional["Scene.Sky"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) shadows: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) fog: Optional["Scene.Fog"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) grid: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Sky: """ Properties for the sky. Parameters ---------- time: Time of day [0..24] sunrise: Sunrise time [0..24] sunset: Sunset time [0..24] clouds: Sunset time [0..24] """ time: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) sunrise: float = field( default=6.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) sunset: float = field( default=20.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) clouds: Optional["Scene.Sky.Clouds"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Clouds: """ Sunset time [0..24] Parameters ---------- speed: Speed of the clouds direction: Direction of the cloud movement humidity: Density of clouds mean_size: Average size of the clouds ambient: Ambient cloud color """ speed: float = field( default=0.6, metadata={ "type": "Element", "namespace": "", "required": True, }, ) direction: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) humidity: float = field( default=0.5, metadata={ "type": "Element", "namespace": "", "required": True, }, ) mean_size: float = field( default=0.5, metadata={ "type": "Element", "namespace": "", "required": True, }, ) ambient: str = field( default=".8 .8 .8 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) @dataclass class Fog: """ Controls fog. Parameters ---------- color: Fog color type: Fog type: constant, linear, quadratic start: Distance to start of fog end: Distance to end of fog density: Density of fog """ color: str = field( default="1 1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) type: str = field( default="none", metadata={ "type": "Element", "namespace": "", "required": True, }, ) start: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) end: float = field( default=100.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) density: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v13/scene.py
0.934155
0.465084
scene.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .geometry import Geometry __NAMESPACE__ = "sdformat/v1.3/visual.xsd" @dataclass class Visual: """The visual properties of the link. This element specifies the shape of the object (box, cylinder, etc.) for visualization purposes. Parameters ---------- cast_shadows: If true the visual will cast shadows. laser_retro: will be implemented in the future release. transparency: The amount of transparency( 0=opaque, 1 = fully transparent) pose: Origin of the visual relative to its parent. material: The material of the visual element. geometry: The shape of the visual or collision object. plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. name: Unique name for the visual element within the scope of the parent link. """ class Meta: name = "visual" cast_shadows: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) laser_retro: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) transparency: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) material: Optional["Visual.Material"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) geometry: Optional[Geometry] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) plugin: List["Visual.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Material: """ The material of the visual element. Parameters ---------- script: Name of material from an installed script file. This will override the color element if the script exists. shader: ambient: The ambient color of a material specified by set of four numbers representing red/green/blue, each in the range of [0,1]. diffuse: The diffuse color of a material specified by set of four numbers representing red/green/blue/alpha, each in the range of [0,1]. specular: The specular color of a material specified by set of four numbers representing red/green/blue/alpha, each in the range of [0,1]. emissive: The emissive color of a material specified by set of four numbers representing red/green/blue, each in the range of [0,1]. """ script: Optional["Visual.Material.Script"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) shader: Optional["Visual.Material.Shader"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) ambient: str = field( default="0 0 0 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) diffuse: str = field( default="0 0 0 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) specular: str = field( default="0 0 0 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) emissive: str = field( default="0 0 0 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) @dataclass class Script: """Name of material from an installed script file. This will override the color element if the script exists. Parameters ---------- uri: URI of the material script file name: Name of the script within the script file """ uri: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) name: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Shader: """ Parameters ---------- normal_map: filename of the normal map type: vertex, pixel, normal_map_object_space, normal_map_tangent_space """ normal_map: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v13/visual.py
0.932592
0.525917
visual.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .collision import Collision from .sensor import Sensor from .visual import Visual __NAMESPACE__ = "sdformat/v1.3/link.xsd" @dataclass class Link: """A physical link with inertia, collision, and visual properties. A link must be a child of a model, and any number of links may exist in a model. Parameters ---------- gravity: If true, the link is affected by gravity. self_collide: If true, the link can collide with other links in the model. kinematic: If true, the link is kinematic only pose: This is the pose of the link reference frame, relative to the model reference frame. velocity_decay: Exponential damping of the link's velocity. inertial: The inertial properties of the link. collision: The collision properties of a link. Note that this can be different from the visual properties of a link, for example, simpler collision models are often used to reduce computation time. visual: The visual properties of the link. This element specifies the shape of the object (box, cylinder, etc.) for visualization purposes. sensor: The sensor tag describes the type and properties of a sensor. projector: name: A unique name for the link within the scope of the model. """ class Meta: name = "link" gravity: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) self_collide: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) kinematic: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) velocity_decay: Optional["Link.VelocityDecay"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) inertial: Optional["Link.Inertial"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) collision: List[Collision] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) visual: List[Visual] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) sensor: List[Sensor] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) projector: Optional["Link.Projector"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class VelocityDecay: """ Exponential damping of the link's velocity. Parameters ---------- linear: Linear damping angular: Angular damping """ linear: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) angular: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Inertial: """ The inertial properties of the link. Parameters ---------- mass: The mass of the link. pose: This is the pose of the inertial reference frame, relative to the link reference frame. The origin of the inertial reference frame needs to be at the center of gravity. The axes of the inertial reference frame do not need to be aligned with the principal axes of the inertia. inertia: The 3x3 rotational inertia matrix. Because the rotational inertia matrix is symmetric, only 6 above- diagonal elements of this matrix are specified here, using the attributes ixx, ixy, ixz, iyy, iyz, izz. """ mass: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) inertia: Optional["Link.Inertial.Inertia"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Inertia: """The 3x3 rotational inertia matrix. Because the rotational inertia matrix is symmetric, only 6 above-diagonal elements of this matrix are specified here, using the attributes ixx, ixy, ixz, iyy, iyz, izz. """ ixx: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) ixy: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) ixz: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) iyy: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) iyz: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) izz: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Projector: """ Parameters ---------- texture: Texture name pose: Pose of the projector fov: Field of view near_clip: Near clip distance far_clip: far clip distance plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. name: Name of the projector """ texture: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) fov: float = field( default=0.785, metadata={ "type": "Element", "namespace": "", "required": True, }, ) near_clip: float = field( default=0.1, metadata={ "type": "Element", "namespace": "", "required": True, }, ) far_clip: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) plugin: List["Link.Projector.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v13/link.py
0.945901
0.602354
link.py
pypi
from dataclasses import dataclass, field from typing import Optional __NAMESPACE__ = "sdformat/v1.3/joint.xsd" @dataclass class Joint: """ A joint connections two links with kinematic and dynamic properties. Parameters ---------- parent: Name of the parent link child: Name of the child link pose: offset from child link origin in child link frame. thread_pitch: axis: The joint axis specified in the model frame. This is the axis of rotation for revolute joints, the axis of translation for prismatic joints. The axis is currently specified in the model frame of reference, but this will be changed to the joint frame in future version of SDFormat (see gazebo issue #494). axis2: The second joint axis specified in the model frame. This is the second axis of rotation for revolute2 joints and universal joints. The axis is currently specified in the model frame of reference, but this will be changed to the joint frame in future version of SDFormat (see gazebo issue #494). physics: Parameters that are specific to a certain physics engine. name: A unique name for the joint within the scope of the model. type: The type of joint, which must be one of the following: (revolute) a hinge joint that rotates on a single axis with either a fixed or continuous range of motion, (revolute2) same as two revolute joints connected in series, (prismatic) a sliding joint that slides along an axis with a limited range specified by upper and lower limits, (ball) a ball and socket joint, (universal), like a ball joint, but constrains one degree of freedom, (piston) similar to a Slider joint except that rotation around the translation axis is possible. """ class Meta: name = "joint" parent: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) child: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) thread_pitch: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) axis: Optional["Joint.Axis"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) axis2: Optional["Joint.Axis2"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) physics: Optional["Joint.Physics"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Axis: """The joint axis specified in the model frame. This is the axis of rotation for revolute joints, the axis of translation for prismatic joints. The axis is currently specified in the model frame of reference, but this will be changed to the joint frame in future version of SDFormat (see gazebo issue #494). Parameters ---------- xyz: Represents the x,y,z components of a vector. The vector should be normalized. dynamics: An element specifying physical properties of the joint. These values are used to specify modeling properties of the joint, particularly useful for simulation. limit: specifies the limits of this joint """ xyz: str = field( default="0 0 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) dynamics: Optional["Joint.Axis.Dynamics"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) limit: Optional["Joint.Axis.Limit"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Dynamics: """An element specifying physical properties of the joint. These values are used to specify modeling properties of the joint, particularly useful for simulation. Parameters ---------- damping: The physical velocity dependent viscous damping coefficient of the joint. friction: The physical static friction value of the joint. """ damping: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) friction: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Limit: """ specifies the limits of this joint. Parameters ---------- lower: An attribute specifying the lower joint limit (radians for revolute joints, meters for prismatic joints). Omit if joint is continuous. upper: An attribute specifying the upper joint limit (radians for revolute joints, meters for prismatic joints). Omit if joint is continuous. effort: An attribute for enforcing the maximum joint effort applied by Joint::SetForce. Limit is not enforced if value is negative. velocity: (not implemented) An attribute for enforcing the maximum joint velocity. """ lower: float = field( default=-1e16, metadata={ "type": "Element", "namespace": "", "required": True, }, ) upper: float = field( default=1e16, metadata={ "type": "Element", "namespace": "", "required": True, }, ) effort: float = field( default=-1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) velocity: float = field( default=-1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Axis2: """The second joint axis specified in the model frame. This is the second axis of rotation for revolute2 joints and universal joints. The axis is currently specified in the model frame of reference, but this will be changed to the joint frame in future version of SDFormat (see gazebo issue #494). Parameters ---------- xyz: Represents the x,y,z components of a vector. The vector should be normalized. dynamics: An element specifying physical properties of the joint. These values are used to specify modeling properties of the joint, particularly useful for simulation. limit: """ xyz: str = field( default="0 0 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) dynamics: Optional["Joint.Axis2.Dynamics"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) limit: Optional["Joint.Axis2.Limit"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Dynamics: """An element specifying physical properties of the joint. These values are used to specify modeling properties of the joint, particularly useful for simulation. Parameters ---------- damping: The physical velocity dependent viscous damping coefficient of the joint. friction: The physical static friction value of the joint. """ damping: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) friction: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Limit: """ Parameters ---------- lower: An attribute specifying the lower joint limit (radians for revolute joints, meters for prismatic joints). Omit if joint is continuous. upper: An attribute specifying the upper joint limit (radians for revolute joints, meters for prismatic joints). Omit if joint is continuous. effort: An attribute for enforcing the maximum joint effort applied by Joint::SetForce. Limit is not enforced if value is negative. velocity: (not implemented) An attribute for enforcing the maximum joint velocity. """ lower: float = field( default=-1e16, metadata={ "type": "Element", "namespace": "", "required": True, }, ) upper: float = field( default=1e16, metadata={ "type": "Element", "namespace": "", "required": True, }, ) effort: float = field( default=-1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) velocity: float = field( default=-1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Physics: """ Parameters that are specific to a certain physics engine. Parameters ---------- ode: ODE specific parameters """ ode: Optional["Joint.Physics.Ode"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Ode: """ ODE specific parameters. Parameters ---------- provide_feedback: If provide feedback is set to true, ODE will compute the constraint forces at this joint. cfm_damping: If cfm damping is set to true, ODE will use CFM to simulate damping, allows for infinite damping, and one additional constraint row (previously used for joint limit) is always active. fudge_factor: Scale the excess for in a joint motor at joint limits. Should be between zero and one. cfm: Constraint force mixing used when not at a stop bounce: Bounciness of the limits max_force: Maximum force or torque used to reach the desired velocity. velocity: The desired velocity of the joint. Should only be set if you want the joint to move on load. limit: suspension: """ provide_feedback: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) cfm_damping: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) fudge_factor: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) bounce: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_force: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) velocity: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) limit: Optional["Joint.Physics.Ode.Limit"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) suspension: Optional["Joint.Physics.Ode.Suspension"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Limit: """ Parameters ---------- cfm: Constraint force mixing parameter used by the joint stop erp: Error reduction parameter used by the joint stop """ cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Suspension: """ Parameters ---------- cfm: Suspension constraint force mixing parameter erp: Suspension error reduction parameter """ cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v13/joint.py
0.969671
0.580203
joint.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .actor import Actor from .joint import Joint from .light import Light from .model import Model from .physics import Physics from .scene import Scene from .state import State __NAMESPACE__ = "sdformat/v1.3/world.xsd" @dataclass class World: """ The world element encapsulates an entire world description including: models, scene, physics, joints, and plugins. Parameters ---------- gui: physics: The physics tag specifies the type and properties of the dynamics engine. scene: Specifies the look of the environment. light: The light element describes a light source. model: The model element defines a complete robot or any other physical object. actor: plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. joint: A joint connections two links with kinematic and dynamic properties. road: state: name: Unique name of the world """ class Meta: name = "world" gui: Optional["World.Gui"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) physics: Optional[Physics] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) scene: Optional[Scene] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) light: List[Light] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) model: List[Model] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) actor: List[Actor] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) plugin: List["World.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) joint: List[Joint] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) road: List["World.Road"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) state: List[State] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Gui: camera: Optional["World.Gui.Camera"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) fullscreen: bool = field( default=False, metadata={ "type": "Attribute", }, ) @dataclass class Camera: view_controller: str = field( default="orbit", metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) track_visual: Optional["World.Gui.Camera.TrackVisual"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class TrackVisual: name: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_dist: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_dist: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Road: """ Parameters ---------- width: Width of the road point: A series of points define the path of the road. name: Name of the road """ width: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) point: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v13/world.py
0.930852
0.418222
world.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .model import Model __NAMESPACE__ = "sdformat/v1.3/state.xsd" @dataclass class State: """ Parameters ---------- sim_time: Simulation time stamp of the state [seconds nanoseconds] wall_time: Wall time stamp of the state [seconds nanoseconds] real_time: Real time stamp of the state [seconds nanoseconds] insertions: A list of new model names deletions: A list of deleted model names model: Model state world_name: Name of the world this state applies to """ class Meta: name = "state" sim_time: str = field( default="0 0", metadata={ "type": "Element", "namespace": "", "required": True, "white_space": "collapse", "pattern": r"\d+ \d+", }, ) wall_time: str = field( default="0 0", metadata={ "type": "Element", "namespace": "", "required": True, "white_space": "collapse", "pattern": r"\d+ \d+", }, ) real_time: str = field( default="0 0", metadata={ "type": "Element", "namespace": "", "required": True, "white_space": "collapse", "pattern": r"\d+ \d+", }, ) insertions: Optional["State.Insertions"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) deletions: Optional["State.Deletions"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) model: List["State.Model"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) world_name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Insertions: """ A list of new model names. Parameters ---------- model: The model element defines a complete robot or any other physical object. """ model: List[Model] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Deletions: """ A list of deleted model names. Parameters ---------- name: The name of a deleted model """ name: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) @dataclass class Model: """ Model state. Parameters ---------- pose: Pose of the model joint: Joint angle link: Link state name: Name of the model """ pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) joint: List["State.Model.Joint"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) link: List["State.Model.Link"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Joint: """ Joint angle. Parameters ---------- angle: Angle of an axis name: Name of the joint """ angle: List["State.Model.Joint.Angle"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Angle: """ Parameters ---------- value: axis: Index of the axis. """ value: Optional[float] = field( default=None, metadata={ "required": True, }, ) axis: Optional[int] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Link: """ Link state. Parameters ---------- pose: Pose of the link relative to the model velocity: Velocity of the link acceleration: Acceleration of the link wrench: Force applied to the link collision: Collision state name: Name of the link """ pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) velocity: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) acceleration: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) wrench: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) collision: List["State.Model.Link.Collision"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Collision: """ Collision state. Parameters ---------- pose: Pose of the link relative to the model name: Name of the collision """ pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v13/state.py
0.930332
0.537284
state.py
pypi
from dataclasses import dataclass, field from typing import Optional __NAMESPACE__ = "sdformat/v1.3/physics.xsd" @dataclass class Physics: """ The physics tag specifies the type and properties of the dynamics engine. Parameters ---------- update_rate: Rate at which to update the physics engine max_contacts: Maximum number of contacts allowed between two entities. This value can be over ridden by a max_contacts element in a collision element. gravity: The gravity vector bullet: Bullet specific physics properties ode: ODE specific physics properties type: The type of the dynamics engine. Currently must be set to ode """ class Meta: name = "physics" update_rate: float = field( default=1000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_contacts: int = field( default=20, metadata={ "type": "Element", "namespace": "", "required": True, }, ) gravity: str = field( default="0 0 -9.8", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) bullet: Optional["Physics.Bullet"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) ode: Optional["Physics.Ode"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Bullet: """ Bullet specific physics properties. Parameters ---------- dt: Time step """ dt: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Ode: """ ODE specific physics properties. """ solver: Optional["Physics.Ode.Solver"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) constraints: Optional["Physics.Ode.Constraints"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Solver: """ Parameters ---------- type: One of the following types: world, quick dt: The time duration which advances with each iteration of the dynamics engine. iters: Number of iterations for each step. A higher number produces greater accuracy at a performance cost. precon_iters: sor: Set the successive over-relaxation parameter. """ type: str = field( default="quick", metadata={ "type": "Element", "namespace": "", "required": True, }, ) dt: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) iters: int = field( default=50, metadata={ "type": "Element", "namespace": "", "required": True, }, ) precon_iters: int = field( default=0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) sor: float = field( default=1.3, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Constraints: """ Parameters ---------- cfm: Constraint force mixing parameter. See the ODE page for more information. erp: Error reduction parameter. See the ODE page for more information. contact_max_correcting_vel: The maximum correcting velocities allowed when resolving contacts. contact_surface_layer: The depth of the surface layer around all geometry objects. Contacts are allowed to sink into the surface layer up to the given depth before coming to rest. The default value is zero. Increasing this to some small value (e.g. 0.001) can help prevent jittering problems due to contacts being repeatedly made and broken. """ cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) contact_max_correcting_vel: float = field( default=100.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) contact_surface_layer: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v13/physics.py
0.944061
0.473657
physics.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .joint import Joint from .link import Link __NAMESPACE__ = "sdformat/v1.3/model.xsd" @dataclass class Model: """ The model element defines a complete robot or any other physical object. Parameters ---------- static: If set to true, the model is immovable. Otherwise the model is simulated in the dynamics engine. allow_auto_disable: Allows a model to auto-disable, which is means the physics engine can skip updating the model when the model is at rest. This parameter is only used by models with no joints. pose: A position and orientation in the global coordinate frame for the model. Position(x,y,z) and rotation (roll, pitch yaw) in the global coordinate frame. link: A physical link with inertia, collision, and visual properties. A link must be a child of a model, and any number of links may exist in a model. joint: A joint connections two links with kinematic and dynamic properties. plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. gripper: name: A unique name for the model. This name must not match another model in the world. """ class Meta: name = "model" static: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) allow_auto_disable: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) link: List[Link] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) joint: List[Joint] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) plugin: List["Model.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) gripper: List["Model.Gripper"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Gripper: grasp_check: Optional["Model.Gripper.GraspCheck"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) gripper_link: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) palm_link: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class GraspCheck: detach_steps: int = field( default=40, metadata={ "type": "Element", "namespace": "", "required": True, }, ) attach_steps: int = field( default=20, metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_contact_count: int = field( default=2, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v13/model.py
0.945248
0.545407
model.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .joint import Joint from .link import Link __NAMESPACE__ = "sdformat/v1.3/actor.xsd" @dataclass class Actor: """ Parameters ---------- pose: Origin of the actor skin: animation: script: link: A physical link with inertia, collision, and visual properties. A link must be a child of a model, and any number of links may exist in a model. joint: A joint connections two links with kinematic and dynamic properties. plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. name: static: """ class Meta: name = "actor" pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) skin: Optional["Actor.Skin"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) animation: List["Actor.Animation"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) script: Optional["Actor.Script"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) link: List[Link] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) joint: List[Joint] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) plugin: List["Actor.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) static: bool = field( default=False, metadata={ "type": "Attribute", }, ) @dataclass class Skin: filename: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) scale: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Animation: filename: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) scale: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) interpolate_x: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Script: loop: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) delay_start: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) auto_start: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) trajectory: List["Actor.Script.Trajectory"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Trajectory: waypoint: List["Actor.Script.Trajectory.Waypoint"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) id: Optional[int] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Waypoint: time: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v13/actor.py
0.909083
0.414958
actor.py
pypi
from dataclasses import dataclass, field from typing import List, Optional __NAMESPACE__ = "sdformat/v1.3/geometry.xsd" @dataclass class Geometry: """ The shape of the visual or collision object. Parameters ---------- box: Box shape sphere: Sphere shape cylinder: Cylinder shape mesh: Mesh shape plane: Plane shape image: Extrude a set of boxes from a grayscale image. heightmap: A heightmap based on a 2d grayscale image. empty: You can use the empty tag to make empty geometries. """ class Meta: name = "geometry" box: Optional["Geometry.Box"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) sphere: Optional["Geometry.Sphere"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) cylinder: Optional["Geometry.Cylinder"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) mesh: Optional["Geometry.Mesh"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) plane: Optional["Geometry.Plane"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) image: Optional["Geometry.Image"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) heightmap: Optional["Geometry.Heightmap"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) empty: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Box: """ Box shape. Parameters ---------- size: The three side lengths of the box. The origin of the box is in its geometric center (inside the center of the box). """ size: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Sphere: """ Sphere shape. Parameters ---------- radius: radius of the sphere """ radius: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Cylinder: """ Cylinder shape. Parameters ---------- radius: Radius of the cylinder length: Length of the cylinder """ radius: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) length: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Mesh: """ Mesh shape. Parameters ---------- uri: Mesh uri submesh: Use a named submesh. The submesh must exist in the mesh specified by the uri scale: Scaling factor applied to the mesh """ uri: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) submesh: Optional["Geometry.Mesh.Submesh"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) scale: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Submesh: """Use a named submesh. The submesh must exist in the mesh specified by the uri Parameters ---------- name: Name of the submesh within the parent mesh center: Set to true to center the vertices of the submesh at 0,0,0. This will effectively remove any transformations on the submesh before the poses from parent links and models are applied. """ name: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) center: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Plane: """ Plane shape. Parameters ---------- normal: Normal direction for the plane size: Length of each side of the plane """ normal: str = field( default="0 0 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) size: str = field( default="1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+)((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Image: """ Extrude a set of boxes from a grayscale image. Parameters ---------- uri: URI of the grayscale image file scale: Scaling factor applied to the image threshold: Grayscale threshold height: Height of the extruded boxes granularity: The amount of error in the model """ uri: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) scale: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) threshold: int = field( default=200, metadata={ "type": "Element", "namespace": "", "required": True, }, ) height: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) granularity: int = field( default=1, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Heightmap: """ A heightmap based on a 2d grayscale image. Parameters ---------- uri: URI to a grayscale image file size: The size of the heightmap in world units pos: A position offset. texture: The heightmap can contain multiple textures. The order of the texture matters. The first texture will appear at the lowest height, and the last texture at the highest height. Use blend to control the height thresholds and fade between textures. blend: The blend tag controls how two adjacent textures are mixed. The number of blend elements should equal one less than the number of textures. """ uri: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) size: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) pos: str = field( default="0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) texture: List["Geometry.Heightmap.Texture"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) blend: List["Geometry.Heightmap.Blend"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Texture: """The heightmap can contain multiple textures. The order of the texture matters. The first texture will appear at the lowest height, and the last texture at the highest height. Use blend to control the height thresholds and fade between textures. Parameters ---------- size: Size of the applied texture in meters. diffuse: Diffuse texture image filename normal: Normalmap texture image filename """ size: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) diffuse: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) normal: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Blend: """The blend tag controls how two adjacent textures are mixed. The number of blend elements should equal one less than the number of textures. Parameters ---------- min_height: Min height of a blend layer fade_dist: Distance over which the blend occurs """ min_height: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) fade_dist: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v13/geometry.py
0.954911
0.643273
geometry.py
pypi
from dataclasses import dataclass, field from typing import List, Optional __NAMESPACE__ = "sdformat/v1.7/material.xsd" @dataclass class Material: """ The material of the visual element. Parameters ---------- script: Name of material from an installed script file. This will override the color element if the script exists. shader: render_order: Set render order for coplanar polygons. The higher value will be rendered on top of the other coplanar polygons lighting: If false, dynamic lighting will be disabled ambient: The ambient color of a material specified by set of four numbers representing red/green/blue, each in the range of [0,1]. diffuse: The diffuse color of a material specified by set of four numbers representing red/green/blue/alpha, each in the range of [0,1]. specular: The specular color of a material specified by set of four numbers representing red/green/blue/alpha, each in the range of [0,1]. emissive: The emissive color of a material specified by set of four numbers representing red/green/blue, each in the range of [0,1]. double_sided: If true, the mesh that this material is applied to will be rendered as double sided pbr: Physically Based Rendering (PBR) material. There are two PBR workflows: metal and specular. While both workflows and their parameters can be specified at the same time, typically only one of them will be used (depending on the underlying renderer capability). It is also recommended to use the same workflow for all materials in the world. """ class Meta: name = "material" script: Optional["Material.Script"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) shader: Optional["Material.Shader"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) render_order: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) lighting: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) ambient: str = field( default="0 0 0 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) diffuse: str = field( default="0 0 0 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) specular: str = field( default="0 0 0 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) emissive: str = field( default="0 0 0 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) double_sided: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pbr: Optional["Material.Pbr"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Script: """Name of material from an installed script file. This will override the color element if the script exists. Parameters ---------- uri: URI of the material script file name: Name of the script within the script file """ uri: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) name: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Shader: """ Parameters ---------- normal_map: filename of the normal map type: vertex, pixel, normal_map_object_space, normal_map_tangent_space """ normal_map: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Pbr: """Physically Based Rendering (PBR) material. There are two PBR workflows: metal and specular. While both workflows and their parameters can be specified at the same time, typically only one of them will be used (depending on the underlying renderer capability). It is also recommended to use the same workflow for all materials in the world. Parameters ---------- metal: PBR using the Metallic/Roughness workflow. specular: PBR using the Specular/Glossiness workflow. """ metal: Optional["Material.Pbr.Metal"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) specular: Optional["Material.Pbr.Specular"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Metal: """ PBR using the Metallic/Roughness workflow. Parameters ---------- albedo_map: Filename of the diffuse/albedo map. roughness_map: Filename of the roughness map. roughness: Material roughness in the range of [0,1], where 0 represents a smooth surface and 1 represents a rough surface. This is the inverse of a specular map in a PBR specular workflow. metalness_map: Filename of the metalness map. metalness: Material metalness in the range of [0,1], where 0 represents non-metal and 1 represents raw metal environment_map: Filename of the environment / reflection map, typically in the form of a cubemap ambient_occlusion_map: Filename of the ambient occlusion map. The map defines the amount of ambient lighting on the surface. normal_map: Filename of the normal map. The normals can be in the object space or tangent space as specified in the 'type' attribute emissive_map: Filename of the emissive map. light_map: Filename of the light map. The light map is a prebaked light texture that is applied over the albedo map """ albedo_map: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) roughness_map: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) roughness: str = field( default="0.5", metadata={ "type": "Element", "namespace": "", "required": True, }, ) metalness_map: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) metalness: str = field( default="0.5", metadata={ "type": "Element", "namespace": "", "required": True, }, ) environment_map: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) ambient_occlusion_map: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) normal_map: Optional["Material.Pbr.Metal.NormalMap"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) emissive_map: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) light_map: Optional["Material.Pbr.Metal.LightMap"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class NormalMap: """ Parameters ---------- value: type: The space that the normals are in. Values are: 'object' or 'tangent' """ value: str = field( default="", metadata={ "required": True, }, ) type: str = field( default="tangent", metadata={ "type": "Attribute", }, ) @dataclass class LightMap: """ Parameters ---------- value: uv_set: Index of the texture coordinate set to use. """ value: str = field( default="", metadata={ "required": True, }, ) uv_set: int = field( default=0, metadata={ "type": "Attribute", }, ) @dataclass class Specular: """ PBR using the Specular/Glossiness workflow. Parameters ---------- albedo_map: Filename of the diffuse/albedo map. specular_map: Filename of the specular map. glossiness_map: Filename of the glossiness map. glossiness: Material glossiness in the range of [0-1], where 0 represents a rough surface and 1 represents a smooth surface. This is the inverse of a roughness map in a PBR metal workflow. environment_map: Filename of the environment / reflection map, typically in the form of a cubemap ambient_occlusion_map: Filename of the ambient occlusion map. The map defines the amount of ambient lighting on the surface. normal_map: Filename of the normal map. The normals can be in the object space or tangent space as specified in the 'type' attribute emissive_map: Filename of the emissive map. light_map: Filename of the light map. The light map is a prebaked light texture that is applied over the albedo map """ albedo_map: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) specular_map: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) glossiness_map: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) glossiness: str = field( default="0", metadata={ "type": "Element", "namespace": "", "required": True, }, ) environment_map: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) ambient_occlusion_map: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) normal_map: Optional["Material.Pbr.Specular.NormalMap"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) emissive_map: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) light_map: Optional["Material.Pbr.Specular.LightMap"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class NormalMap: """ Parameters ---------- value: type: The space that the normals are in. Values are: 'object' or 'tangent' """ value: str = field( default="", metadata={ "required": True, }, ) type: str = field( default="tangent", metadata={ "type": "Attribute", }, ) @dataclass class LightMap: """ Parameters ---------- value: uv_set: Index of the texture coordinate set to use. """ value: str = field( default="", metadata={ "required": True, }, ) uv_set: int = field( default=0, metadata={ "type": "Attribute", }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v17/material.py
0.939192
0.583737
material.py
pypi
from dataclasses import dataclass, field from typing import Optional from .geometry import Geometry __NAMESPACE__ = "sdformat/v1.7/collision.xsd" @dataclass class Collision: """The collision properties of a link. Note that this can be different from the visual properties of a link, for example, simpler collision models are often used to reduce computation time. Parameters ---------- laser_retro: intensity value returned by laser sensor. max_contacts: Maximum number of contacts allowed between two entities. This value overrides the max_contacts element defined in physics. pose: A position(x,y,z) and orientation(roll, pitch yaw) with respect to the frame named in the relative_to attribute. geometry: The shape of the visual or collision object. surface: The surface parameters name: Unique name for the collision element within the scope of the parent link. """ class Meta: name = "collision" laser_retro: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_contacts: int = field( default=10, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: Optional["Collision.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) geometry: Optional[Geometry] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) surface: Optional["Collision.Surface"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Surface: """ The surface parameters. """ bounce: Optional["Collision.Surface.Bounce"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) friction: Optional["Collision.Surface.Friction"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) contact: Optional["Collision.Surface.Contact"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) soft_contact: Optional["Collision.Surface.SoftContact"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Bounce: """ Parameters ---------- restitution_coefficient: Bounciness coefficient of restitution, from [0...1], where 0=no bounciness. threshold: Bounce capture velocity, below which effective coefficient of restitution is 0. """ restitution_coefficient: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) threshold: float = field( default=100000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Friction: """ Parameters ---------- torsional: Parameters for torsional friction ode: ODE friction parameters bullet: """ torsional: Optional["Collision.Surface.Friction.Torsional"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) ode: Optional["Collision.Surface.Friction.Ode"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) bullet: Optional["Collision.Surface.Friction.Bullet"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Torsional: """ Parameters for torsional friction. Parameters ---------- coefficient: Torsional friction coefficient, unitless maximum ratio of tangential stress to normal stress. use_patch_radius: If this flag is true, torsional friction is calculated using the "patch_radius" parameter. If this flag is set to false, "surface_radius" (R) and contact depth (d) are used to compute the patch radius as sqrt(R*d). patch_radius: Radius of contact patch surface. surface_radius: Surface radius on the point of contact. ode: Torsional friction parameters for ODE """ coefficient: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) use_patch_radius: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) patch_radius: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) surface_radius: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) ode: Optional["Collision.Surface.Friction.Torsional.Ode"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Ode: """ Torsional friction parameters for ODE. Parameters ---------- slip: Force dependent slip for torsional friction, equivalent to inverse of viscous damping coefficient with units of rad/s/(Nm). A slip value of 0 is infinitely viscous. """ slip: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Ode: """ ODE friction parameters. Parameters ---------- mu: Coefficient of friction in first friction pyramid direction, the unitless maximum ratio of force in first friction pyramid direction to normal force. mu2: Coefficient of friction in second friction pyramid direction, the unitless maximum ratio of force in second friction pyramid direction to normal force. fdir1: Unit vector specifying first friction pyramid direction in collision-fixed reference frame. If the friction pyramid model is in use, and this value is set to a unit vector for one of the colliding surfaces, the ODE Collide callback function will align the friction pyramid directions with a reference frame fixed to that collision surface. If both surfaces have this value set to a vector of zeros, the friction pyramid directions will be aligned with the world frame. If this value is set for both surfaces, the behavior is undefined. slip1: Force dependent slip in first friction pyramid direction, equivalent to inverse of viscous damping coefficient with units of m/s/N. A slip value of 0 is infinitely viscous. slip2: Force dependent slip in second friction pyramid direction, equivalent to inverse of viscous damping coefficient with units of m/s/N. A slip value of 0 is infinitely viscous. """ mu: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) mu2: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) fdir1: str = field( default="0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) slip1: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) slip2: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Bullet: """ Parameters ---------- friction: Coefficient of friction in first friction pyramid direction, the unitless maximum ratio of force in first friction pyramid direction to normal force. friction2: Coefficient of friction in second friction pyramid direction, the unitless maximum ratio of force in second friction pyramid direction to normal force. fdir1: Unit vector specifying first friction pyramid direction in collision-fixed reference frame. If the friction pyramid model is in use, and this value is set to a unit vector for one of the colliding surfaces, the friction pyramid directions will be aligned with a reference frame fixed to that collision surface. If both surfaces have this value set to a vector of zeros, the friction pyramid directions will be aligned with the world frame. If this value is set for both surfaces, the behavior is undefined. rolling_friction: Coefficient of rolling friction """ friction: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) friction2: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) fdir1: str = field( default="0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) rolling_friction: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Contact: """ Parameters ---------- collide_without_contact: Flag to disable contact force generation, while still allowing collision checks and contact visualization to occur. collide_without_contact_bitmask: Bitmask for collision filtering when collide_without_contact is on collide_bitmask: Bitmask for collision filtering. This will override collide_without_contact. Parsed as 16-bit unsigned integer. category_bitmask: Bitmask for category of collision filtering. Collision happens if ((category1 & collision2) | (category2 & collision1)) is not zero. If not specified, the category_bitmask should be interpreted as being the same as collide_bitmask. Parsed as 16-bit unsigned integer. poissons_ratio: Poisson's ratio is the unitless ratio between transverse and axial strain. This value must lie between (-1, 0.5). Defaults to 0.3 for typical steel. Note typical silicone elastomers have Poisson's ratio near 0.49 ~ 0.50. For reference, approximate values for Material:(Young's Modulus, Poisson's Ratio) for some of the typical materials are: Plastic: (1e8 ~ 3e9 Pa, 0.35 ~ 0.41), Wood: (4e9 ~ 1e10 Pa, 0.22 ~ 0.50), Aluminum: (7e10 Pa, 0.32 ~ 0.35), Steel: (2e11 Pa, 0.26 ~ 0.31). elastic_modulus: Young's Modulus in SI derived unit Pascal. Defaults to -1. If value is less or equal to zero, contact using elastic modulus (with Poisson's Ratio) is disabled. For reference, approximate values for Material:(Young's Modulus, Poisson's Ratio) for some of the typical materials are: Plastic: (1e8 ~ 3e9 Pa, 0.35 ~ 0.41), Wood: (4e9 ~ 1e10 Pa, 0.22 ~ 0.50), Aluminum: (7e10 Pa, 0.32 ~ 0.35), Steel: (2e11 Pa, 0.26 ~ 0.31). ode: ODE contact parameters bullet: Bullet contact parameters """ collide_without_contact: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) collide_without_contact_bitmask: int = field( default=1, metadata={ "type": "Element", "namespace": "", "required": True, }, ) collide_bitmask: int = field( default=65535, metadata={ "type": "Element", "namespace": "", "required": True, }, ) category_bitmask: int = field( default=65535, metadata={ "type": "Element", "namespace": "", "required": True, }, ) poissons_ratio: float = field( default=0.3, metadata={ "type": "Element", "namespace": "", "required": True, }, ) elastic_modulus: float = field( default=-1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) ode: Optional["Collision.Surface.Contact.Ode"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) bullet: Optional["Collision.Surface.Contact.Bullet"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Ode: """ ODE contact parameters. Parameters ---------- soft_cfm: Soft constraint force mixing. soft_erp: Soft error reduction parameter kp: dynamically "stiffness"-equivalent coefficient for contact joints kd: dynamically "damping"-equivalent coefficient for contact joints max_vel: maximum contact correction velocity truncation term. min_depth: minimum allowable depth before contact correction impulse is applied """ soft_cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) soft_erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) kp: float = field( default=1000000000000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) kd: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_vel: float = field( default=0.01, metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_depth: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Bullet: """ Bullet contact parameters. Parameters ---------- soft_cfm: Soft constraint force mixing. soft_erp: Soft error reduction parameter kp: dynamically "stiffness"-equivalent coefficient for contact joints kd: dynamically "damping"-equivalent coefficient for contact joints split_impulse: Similar to ODE's max_vel implementation. See http://bulletphysics.org/mediawiki-1.5.8/index.php/BtContactSolverInfo#Split_Impulse for more information. split_impulse_penetration_threshold: Similar to ODE's max_vel implementation. See http://bulletphysics.org/mediawiki-1.5.8/index.php/BtContactSolverInfo#Split_Impulse for more information. """ soft_cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) soft_erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) kp: float = field( default=1000000000000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) kd: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) split_impulse: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) split_impulse_penetration_threshold: float = field( default=-0.01, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class SoftContact: """ Parameters ---------- dart: soft contact pamameters based on paper: http://www.cc.gatech.edu/graphics/projects/Sumit/homepage/papers/sigasia11/jain_softcontacts_siga11.pdf """ dart: Optional["Collision.Surface.SoftContact.Dart"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Dart: """ soft contact pamameters based on paper: http://www .cc.gatech.edu/graphics/projects/Sumit/homepage/papers/sigasia1 1/jain_softcontacts_siga11.pdf. Parameters ---------- bone_attachment: This is variable k_v in the soft contacts paper. Its unit is N/m. stiffness: This is variable k_e in the soft contacts paper. Its unit is N/m. damping: Viscous damping of point velocity in body frame. Its unit is N/m/s. flesh_mass_fraction: Fraction of mass to be distributed among deformable nodes. """ bone_attachment: float = field( default=100.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) stiffness: float = field( default=100.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) damping: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) flesh_mass_fraction: float = field( default=0.05, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v17/collision.py
0.957843
0.506897
collision.py
pypi
from dataclasses import dataclass, field from typing import Optional __NAMESPACE__ = "sdformat/v1.7/light.xsd" @dataclass class Light: """ The light element describes a light source. Parameters ---------- cast_shadows: When true, the light will cast shadows. diffuse: Diffuse light color specular: Specular light color attenuation: Light attenuation direction: Direction of the light, only applicable for spot and directional lights. spot: Spot light parameters pose: A position(x,y,z) and orientation(roll, pitch yaw) with respect to the frame named in the relative_to attribute. name: A unique name for the light. type: The light type: point, directional, spot. """ class Meta: name = "light" cast_shadows: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) diffuse: str = field( default="1 1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) specular: str = field( default=".1 .1 .1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) attenuation: Optional["Light.Attenuation"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) direction: str = field( default="0 0 -1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) spot: Optional["Light.Spot"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["Light.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Attenuation: """ Light attenuation. Parameters ---------- range: Range of the light linear: The linear attenuation factor: 1 means attenuate evenly over the distance. constant: The constant attenuation factor: 1.0 means never attenuate, 0.0 is complete attenutation. quadratic: The quadratic attenuation factor: adds a curvature to the attenuation. """ range: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) linear: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) constant: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) quadratic: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Spot: """ Spot light parameters. Parameters ---------- inner_angle: Angle covered by the bright inner cone outer_angle: Angle covered by the outer cone falloff: The rate of falloff between the inner and outer cones. 1.0 means a linear falloff, less means slower falloff, higher means faster falloff. """ inner_angle: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) outer_angle: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) falloff: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v17/light.py
0.927289
0.465509
light.py
pypi
from dataclasses import dataclass, field from typing import Optional __NAMESPACE__ = "sdformat/v1.7/scene.xsd" @dataclass class Scene: """ Specifies the look of the environment. Parameters ---------- ambient: Color of the ambient light. background: Color of the background. sky: Properties for the sky shadows: Enable/disable shadows fog: Controls fog grid: Enable/disable the grid origin_visual: Show/hide world origin indicator """ class Meta: name = "scene" ambient: str = field( default="0.4 0.4 0.4 1.0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) background: str = field( default=".7 .7 .7 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) sky: Optional["Scene.Sky"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) shadows: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) fog: Optional["Scene.Fog"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) grid: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) origin_visual: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Sky: """ Properties for the sky. Parameters ---------- time: Time of day [0..24] sunrise: Sunrise time [0..24] sunset: Sunset time [0..24] clouds: Sunset time [0..24] """ time: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) sunrise: float = field( default=6.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) sunset: float = field( default=20.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) clouds: Optional["Scene.Sky.Clouds"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Clouds: """ Sunset time [0..24] Parameters ---------- speed: Speed of the clouds direction: Direction of the cloud movement humidity: Density of clouds mean_size: Average size of the clouds ambient: Ambient cloud color """ speed: float = field( default=0.6, metadata={ "type": "Element", "namespace": "", "required": True, }, ) direction: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) humidity: float = field( default=0.5, metadata={ "type": "Element", "namespace": "", "required": True, }, ) mean_size: float = field( default=0.5, metadata={ "type": "Element", "namespace": "", "required": True, }, ) ambient: str = field( default=".8 .8 .8 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) @dataclass class Fog: """ Controls fog. Parameters ---------- color: Fog color type: Fog type: constant, linear, quadratic start: Distance to start of fog end: Distance to end of fog density: Density of fog """ color: str = field( default="1 1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) type: str = field( default="none", metadata={ "type": "Element", "namespace": "", "required": True, }, ) start: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) end: float = field( default=100.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) density: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v17/scene.py
0.921671
0.457985
scene.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .geometry import Geometry from .material import Material __NAMESPACE__ = "sdformat/v1.7/visual.xsd" @dataclass class Visual: """The visual properties of the link. This element specifies the shape of the object (box, cylinder, etc.) for visualization purposes. Parameters ---------- cast_shadows: If true the visual will cast shadows. laser_retro: will be implemented in the future release. transparency: The amount of transparency( 0=opaque, 1 = fully transparent) visibility_flags: Visibility flags of a visual. When (camera's visibility_mask & visual's visibility_flags) evaluates to non-zero, the visual will be visible to the camera. meta: Optional meta information for the visual. The information contained within this element should be used to provide additional feedback to an end user. pose: A position(x,y,z) and orientation(roll, pitch yaw) with respect to the frame named in the relative_to attribute. material: The material of the visual element. geometry: The shape of the visual or collision object. plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. name: Unique name for the visual element within the scope of the parent link. """ class Meta: name = "visual" cast_shadows: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) laser_retro: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) transparency: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) visibility_flags: int = field( default=4294967295, metadata={ "type": "Element", "namespace": "", "required": True, }, ) meta: Optional["Visual.MetaType"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["Visual.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) material: Optional[Material] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) geometry: Optional[Geometry] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) plugin: List["Visual.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class MetaType: """Optional meta information for the visual. The information contained within this element should be used to provide additional feedback to an end user. Parameters ---------- layer: The layer in which this visual is displayed. The layer number is useful for programs, such as Gazebo, that put visuals in different layers for enhanced visualization. """ layer: int = field( default=0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v17/visual.py
0.950755
0.54952
visual.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .collision import Collision from .light import Light from .material import Material from .sensor import Sensor from .visual import Visual __NAMESPACE__ = "sdformat/v1.7/link.xsd" @dataclass class Link: """A physical link with inertia, collision, and visual properties. A link must be a child of a model, and any number of links may exist in a model. Parameters ---------- gravity: If true, the link is affected by gravity. enable_wind: If true, the link is affected by the wind. self_collide: If true, the link can collide with other links in the model. Two links within a model will collide if link1.self_collide OR link2.self_collide. Links connected by a joint will never collide. kinematic: If true, the link is kinematic only must_be_base_link: If true, the link will have 6DOF and be a direct child of world. velocity_decay: Exponential damping of the link's velocity. pose: A position(x,y,z) and orientation(roll, pitch yaw) with respect to the frame named in the relative_to attribute. inertial: The inertial properties of the link. collision: The collision properties of a link. Note that this can be different from the visual properties of a link, for example, simpler collision models are often used to reduce computation time. visual: The visual properties of the link. This element specifies the shape of the object (box, cylinder, etc.) for visualization purposes. sensor: The sensor tag describes the type and properties of a sensor. projector: audio_sink: An audio sink. audio_source: An audio source. battery: Description of a battery. light: The light element describes a light source. particle_emitter: A particle emitter that can be used to describe fog, smoke, and dust. name: A unique name for the link within the scope of the model. """ class Meta: name = "link" gravity: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) enable_wind: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) self_collide: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) kinematic: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) must_be_base_link: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) velocity_decay: Optional["Link.VelocityDecay"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["Link.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) inertial: Optional["Link.Inertial"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) collision: List[Collision] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) visual: List[Visual] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) sensor: List[Sensor] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) projector: Optional["Link.Projector"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) audio_sink: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) audio_source: List["Link.AudioSource"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) battery: List["Link.Battery"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) light: List[Light] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) particle_emitter: List["Link.ParticleEmitter"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class VelocityDecay: """ Exponential damping of the link's velocity. Parameters ---------- linear: Linear damping angular: Angular damping """ linear: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) angular: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Inertial: """ The inertial properties of the link. Parameters ---------- mass: The mass of the link. inertia: The 3x3 rotational inertia matrix. Because the rotational inertia matrix is symmetric, only 6 above- diagonal elements of this matrix are specified here, using the attributes ixx, ixy, ixz, iyy, iyz, izz. pose: This is the pose of the inertial reference frame, relative to the specified reference frame. The origin of the inertial reference frame needs to be at the center of gravity. The axes of the inertial reference frame do not need to be aligned with the principal axes of the inertia. """ mass: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) inertia: Optional["Link.Inertial.Inertia"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["Link.Inertial.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Inertia: """The 3x3 rotational inertia matrix. Because the rotational inertia matrix is symmetric, only 6 above-diagonal elements of this matrix are specified here, using the attributes ixx, ixy, ixz, iyy, iyz, izz. """ ixx: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) ixy: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) ixz: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) iyy: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) iyz: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) izz: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Projector: """ Parameters ---------- texture: Texture name fov: Field of view near_clip: Near clip distance far_clip: far clip distance pose: A position(x,y,z) and orientation(roll, pitch yaw) with respect to the frame named in the relative_to attribute. plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. name: Name of the projector """ texture: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) fov: float = field( default=0.785, metadata={ "type": "Element", "namespace": "", "required": True, }, ) near_clip: float = field( default=0.1, metadata={ "type": "Element", "namespace": "", "required": True, }, ) far_clip: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: Optional["Link.Projector.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) plugin: List["Link.Projector.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class AudioSource: """ An audio source. Parameters ---------- uri: URI of the audio media. pitch: Pitch for the audio media, in Hz gain: Gain for the audio media, in dB. contact: List of collision objects that will trigger audio playback. loop: True to make the audio source loop playback. pose: A position(x,y,z) and orientation(roll, pitch yaw) with respect to the frame named in the relative_to attribute. """ uri: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) pitch: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) gain: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) contact: Optional["Link.AudioSource.Contact"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) loop: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: Optional["Link.AudioSource.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Contact: """ List of collision objects that will trigger audio playback. Parameters ---------- collision: Name of child collision element that will trigger audio playback. """ collision: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Battery: """ Description of a battery. Parameters ---------- voltage: Initial voltage in volts. name: Unique name for the battery. """ voltage: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class ParticleEmitter: """ A particle emitter that can be used to describe fog, smoke, and dust. Parameters ---------- emitting: True indicates that the particle emitter should generate particles when loaded duration: The number of seconds the emitter is active. A value less than or equal to zero means infinite duration. size: The size of the emitter where the particles are sampled. Default value is (1, 1, 1). Note that the interpretation of the emitter area varies depending on the emmiter type: - point: The area is ignored. - box: The area is interpreted as width X height X depth. - cylinder: The area is interpreted as the bounding box of the cylinder. The cylinder is oriented along the Z-axis. - ellipsoid: The area is interpreted as the bounding box of an ellipsoid shaped area, i.e. a sphere or squashed-sphere area. The parameters are again identical to EM_BOX, except that the dimensions describe the widest points along each of the axes. particle_size: The particle dimensions (width, height, depth). lifetime: The number of seconds each particle will ’live’ for before being destroyed. This value must be greater than zero. rate: The number of particles per second that should be emitted. min_velocity: Sets a minimum velocity for each particle (m/s). max_velocity: Sets a maximum velocity for each particle (m/s). scale_rate: Sets the amount by which to scale the particles in both x and y direction per second. color_start: Sets the starting color for all particles emitted. The actual color will be interpolated between this color and the one set under color_end. Color::White is the default color for the particles unless a specific function is used. To specify a color, RGB values should be passed in. For example, to specify red, a user should enter: <color_start>1 0 0</color_start> Note that this function overrides the particle colors set with color_range_image. color_end: Sets the end color for all particles emitted. The actual color will be interpolated between this color and the one set under color_start. Color::White is the default color for the particles unless a specific function is used (see color_start for more information about defining custom colors with RGB values). Note that this function overrides the particle colors set with color_range_image. color_range_image: Sets the path to the color image used as an affector. This affector modifies the color of particles in flight. The colors are taken from a specified image file. The range of color values begins from the left side of the image and moves to the right over the lifetime of the particle, therefore only the horizontal dimension of the image is used. Note that this function overrides the particle colors set with color_start and color_end. topic: Topic used to update particle emitter properties at runtime. The default topic is /model/{model_name}/particle_emitter/{emitter_name} Note that the emitter id and name may not be changed. particle_scatter_ratio: This is used to determine the ratio of particles that will be detected by sensors. Increasing the ratio means there is a higher chance of particles reflecting and interfering with depth sensing, making the emitter appear more dense. Decreasing the ratio decreases the chance of particles reflecting and interfering with depth sensing, making it appear less dense. pose: A position(x,y,z) and orientation(roll, pitch yaw) with respect to the frame named in the relative_to attribute. material: The material of the visual element. name: A unique name for the particle emitter. type: The type of a particle emitter. One of "box", "cylinder", "ellipsoid", or "point". """ emitting: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) duration: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) size: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) particle_size: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) lifetime: float = field( default=5.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) rate: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_velocity: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_velocity: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) scale_rate: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) color_start: str = field( default="1 1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) color_end: str = field( default="1 1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*", }, ) color_range_image: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) topic: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) particle_scatter_ratio: float = field( default=0.65, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: Optional["Link.ParticleEmitter.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) material: Optional[Material] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v17/link.py
0.960998
0.497803
link.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .sensor import Sensor __NAMESPACE__ = "sdformat/v1.7/joint.xsd" @dataclass class Joint: """A joint connects two links with kinematic and dynamic properties. By default, the pose of a joint is expressed in the child link frame. Parameters ---------- parent: Name of the parent link or "world". child: Name of the child link. The value "world" may not be specified. gearbox_ratio: Parameter for gearbox joints. Given theta_1 and theta_2 defined in description for gearbox_reference_body, theta_2 = -gearbox_ratio * theta_1. gearbox_reference_body: Parameter for gearbox joints. Gearbox ratio is enforced over two joint angles. First joint angle (theta_1) is the angle from the gearbox_reference_body to the parent link in the direction of the axis element and the second joint angle (theta_2) is the angle from the gearbox_reference_body to the child link in the direction of the axis2 element. thread_pitch: Parameter for screw joints. axis: Parameters related to the axis of rotation for revolute joints, the axis of translation for prismatic joints. axis2: Parameters related to the second axis of rotation for revolute2 joints and universal joints. physics: Parameters that are specific to a certain physics engine. pose: A position(x,y,z) and orientation(roll, pitch yaw) with respect to the frame named in the relative_to attribute. sensor: The sensor tag describes the type and properties of a sensor. name: A unique name for the joint within the scope of the model. type: The type of joint, which must be one of the following: (continuous) a hinge joint that rotates on a single axis with a continuous range of motion, (revolute) a hinge joint that rotates on a single axis with a fixed range of motion, (gearbox) geared revolute joints, (revolute2) same as two revolute joints connected in series, (prismatic) a sliding joint that slides along an axis with a limited range specified by upper and lower limits, (ball) a ball and socket joint, (screw) a single degree of freedom joint with coupled sliding and rotational motion, (universal) like a ball joint, but constrains one degree of freedom, (fixed) a joint with zero degrees of freedom that rigidly connects two links. """ class Meta: name = "joint" parent: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) child: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) gearbox_ratio: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) gearbox_reference_body: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) thread_pitch: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) axis: Optional["Joint.Axis"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) axis2: Optional["Joint.Axis2"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) physics: Optional["Joint.Physics"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["Joint.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) sensor: List[Sensor] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Axis: """ Parameters related to the axis of rotation for revolute joints, the axis of translation for prismatic joints. Parameters ---------- initial_position: Default joint position for this joint axis. xyz: Represents the x,y,z components of the axis unit vector. The axis is expressed in the joint frame unless a different frame is expressed in the expressed_in attribute. The vector should be normalized. dynamics: An element specifying physical properties of the joint. These values are used to specify modeling properties of the joint, particularly useful for simulation. limit: specifies the limits of this joint """ initial_position: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) xyz: Optional["Joint.Axis.Xyz"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) dynamics: Optional["Joint.Axis.Dynamics"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) limit: Optional["Joint.Axis.Limit"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Xyz: """ Parameters ---------- value: expressed_in: Name of frame in whose coordinates the xyz unit vector is expressed. """ value: str = field( default="0 0 1", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) expressed_in: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Dynamics: """An element specifying physical properties of the joint. These values are used to specify modeling properties of the joint, particularly useful for simulation. Parameters ---------- damping: The physical velocity dependent viscous damping coefficient of the joint. friction: The physical static friction value of the joint. spring_reference: The spring reference position for this joint axis. spring_stiffness: The spring stiffness for this joint axis. """ damping: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) friction: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) spring_reference: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) spring_stiffness: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Limit: """ specifies the limits of this joint. Parameters ---------- lower: Specifies the lower joint limit (radians for revolute joints, meters for prismatic joints). Omit if joint is continuous. upper: Specifies the upper joint limit (radians for revolute joints, meters for prismatic joints). Omit if joint is continuous. effort: A value for enforcing the maximum joint effort applied. Limit is not enforced if value is negative. velocity: A value for enforcing the maximum joint velocity. stiffness: Joint stop stiffness. dissipation: Joint stop dissipation. """ lower: float = field( default=-1e16, metadata={ "type": "Element", "namespace": "", "required": True, }, ) upper: float = field( default=1e16, metadata={ "type": "Element", "namespace": "", "required": True, }, ) effort: float = field( default=-1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) velocity: float = field( default=-1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) stiffness: float = field( default=100000000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) dissipation: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Axis2: """ Parameters related to the second axis of rotation for revolute2 joints and universal joints. Parameters ---------- initial_position: Default joint position for this joint axis. xyz: Represents the x,y,z components of the axis unit vector. The axis is expressed in the joint frame unless a different frame is expressed in the expressed_in attribute. The vector should be normalized. dynamics: An element specifying physical properties of the joint. These values are used to specify modeling properties of the joint, particularly useful for simulation. limit: """ initial_position: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) xyz: Optional["Joint.Axis2.Xyz"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) dynamics: Optional["Joint.Axis2.Dynamics"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) limit: Optional["Joint.Axis2.Limit"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Xyz: """ Parameters ---------- value: expressed_in: Name of frame in whose coordinates the xyz unit vector is expressed. """ value: str = field( default="0 0 1", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) expressed_in: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Dynamics: """An element specifying physical properties of the joint. These values are used to specify modeling properties of the joint, particularly useful for simulation. Parameters ---------- damping: The physical velocity dependent viscous damping coefficient of the joint. EXPERIMENTAL: if damping coefficient is negative and implicit_spring_damper is true, adaptive damping is used. friction: The physical static friction value of the joint. spring_reference: The spring reference position for this joint axis. spring_stiffness: The spring stiffness for this joint axis. """ damping: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) friction: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) spring_reference: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) spring_stiffness: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Limit: """ Parameters ---------- lower: An attribute specifying the lower joint limit (radians for revolute joints, meters for prismatic joints). Omit if joint is continuous. upper: An attribute specifying the upper joint limit (radians for revolute joints, meters for prismatic joints). Omit if joint is continuous. effort: An attribute for enforcing the maximum joint effort applied by Joint::SetForce. Limit is not enforced if value is negative. velocity: (not implemented) An attribute for enforcing the maximum joint velocity. stiffness: Joint stop stiffness. Supported physics engines: SimBody. dissipation: Joint stop dissipation. Supported physics engines: SimBody. """ lower: float = field( default=-1e16, metadata={ "type": "Element", "namespace": "", "required": True, }, ) upper: float = field( default=1e16, metadata={ "type": "Element", "namespace": "", "required": True, }, ) effort: float = field( default=-1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) velocity: float = field( default=-1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) stiffness: float = field( default=100000000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) dissipation: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Physics: """ Parameters that are specific to a certain physics engine. Parameters ---------- simbody: Simbody specific parameters ode: ODE specific parameters provide_feedback: If provide feedback is set to true, physics engine will compute the constraint forces at this joint. """ simbody: Optional["Joint.Physics.Simbody"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) ode: Optional["Joint.Physics.Ode"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) provide_feedback: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Simbody: """ Simbody specific parameters. Parameters ---------- must_be_loop_joint: Force cut in the multibody graph at this joint. """ must_be_loop_joint: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Ode: """ ODE specific parameters. Parameters ---------- cfm_damping: If cfm damping is set to true, ODE will use CFM to simulate damping, allows for infinite damping, and one additional constraint row (previously used for joint limit) is always active. implicit_spring_damper: If implicit_spring_damper is set to true, ODE will use CFM, ERP to simulate stiffness and damping, allows for infinite damping, and one additional constraint row (previously used for joint limit) is always active. This replaces cfm_damping parameter in SDFormat 1.4. fudge_factor: Scale the excess for in a joint motor at joint limits. Should be between zero and one. cfm: Constraint force mixing for constrained directions erp: Error reduction parameter for constrained directions bounce: Bounciness of the limits max_force: Maximum force or torque used to reach the desired velocity. velocity: The desired velocity of the joint. Should only be set if you want the joint to move on load. limit: suspension: """ cfm_damping: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) implicit_spring_damper: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) fudge_factor: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) bounce: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_force: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) velocity: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) limit: Optional["Joint.Physics.Ode.Limit"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) suspension: Optional["Joint.Physics.Ode.Suspension"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Limit: """ Parameters ---------- cfm: Constraint force mixing parameter used by the joint stop erp: Error reduction parameter used by the joint stop """ cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Suspension: """ Parameters ---------- cfm: Suspension constraint force mixing parameter erp: Suspension error reduction parameter """ cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v17/joint.py
0.974147
0.655093
joint.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .actor import Actor from .light import Light from .material import Material from .model import Model from .physics import Physics from .scene import Scene from .state import State __NAMESPACE__ = "sdformat/v1.7/world.xsd" @dataclass class World: """ The world element encapsulates an entire world description including: models, scene, physics, and plugins. Parameters ---------- audio: Global audio properties. wind: The wind tag specifies the type and properties of the wind. include: Include resources from a URI gravity: The gravity vector in m/s^2, expressed in a coordinate frame defined by the spherical_coordinates tag. magnetic_field: The magnetic vector in Tesla, expressed in a coordinate frame defined by the spherical_coordinates tag. atmosphere: The atmosphere tag specifies the type and properties of the atmosphere model. gui: physics: The physics tag specifies the type and properties of the dynamics engine. scene: Specifies the look of the environment. light: The light element describes a light source. frame: A frame of reference in which poses may be expressed. model: The model element defines a complete robot or any other physical object. actor: A special kind of model which can have a scripted motion. This includes both global waypoint type animations and skeleton animations. plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. road: spherical_coordinates: state: population: The population element defines how and where a set of models will be automatically populated in Gazebo. name: Unique name of the world """ class Meta: name = "world" audio: Optional["World.Audio"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) wind: Optional["World.Wind"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) include: List["World.Include"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) gravity: str = field( default="0 0 -9.8", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) magnetic_field: str = field( default="5.5645e-6 22.8758e-6 -42.3884e-6", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) atmosphere: Optional["World.Atmosphere"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) gui: Optional["World.Gui"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) physics: List[Physics] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) scene: Optional[Scene] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) light: List[Light] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) frame: List["World.Frame"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) model: List[Model] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) actor: List[Actor] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) plugin: List["World.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) road: List["World.Road"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) spherical_coordinates: Optional["World.SphericalCoordinates"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) state: List[State] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) population: List["World.Population"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Audio: """ Global audio properties. Parameters ---------- device: Device to use for audio playback. A value of "default" will use the system's default audio device. Otherwise, specify a an audio device file" """ device: str = field( default="default", metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Wind: """ The wind tag specifies the type and properties of the wind. Parameters ---------- linear_velocity: Linear velocity of the wind. """ linear_velocity: str = field( default="0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Include: """ Include resources from a URI. Parameters ---------- uri: URI to a resource, such as a model name: Override the name of the included entity. static: Override the static value of the included entity. pose: A position(x,y,z) and orientation(roll, pitch yaw) with respect to the frame named in the relative_to attribute. plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. """ uri: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) static: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: Optional["World.Include.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) plugin: List["World.Include.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Atmosphere: """ The atmosphere tag specifies the type and properties of the atmosphere model. Parameters ---------- temperature: Temperature at sea level in kelvins. pressure: Pressure at sea level in pascals. temperature_gradient: Temperature gradient with respect to increasing altitude at sea level in units of K/m. type: The type of the atmosphere engine. Current options are adiabatic. Defaults to adiabatic if left unspecified. """ temperature: float = field( default=288.15, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pressure: float = field( default=101325.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) temperature_gradient: float = field( default=-0.0065, metadata={ "type": "Element", "namespace": "", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Gui: """ Parameters ---------- camera: plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. fullscreen: """ camera: Optional["World.Gui.Camera"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) plugin: List["World.Gui.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) fullscreen: bool = field( default=False, metadata={ "type": "Attribute", }, ) @dataclass class Camera: """ Parameters ---------- view_controller: projection_type: Set the type of projection for the camera. Valid values are "perspective" and "orthographic". track_visual: pose: A position(x,y,z) and orientation(roll, pitch yaw) with respect to the frame named in the relative_to attribute. name: """ view_controller: str = field( default="orbit", metadata={ "type": "Element", "namespace": "", "required": True, }, ) projection_type: str = field( default="perspective", metadata={ "type": "Element", "namespace": "", "required": True, }, ) track_visual: Optional["World.Gui.Camera.TrackVisual"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["World.Gui.Camera.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class TrackVisual: """ Parameters ---------- name: Name of the tracked visual. If no name is provided, the remaining settings will be applied whenever tracking is triggered in the GUI. min_dist: Minimum distance between the camera and the tracked visual. This parameter is only used if static is set to false. max_dist: Maximum distance between the camera and the tracked visual. This parameter is only used if static is set to false. static: If set to true, the position of the camera is fixed relatively to the model or to the world, depending on the value of the use_model_frame element. Otherwise, the position of the camera may vary but the distance between the camera and the model will depend on the value of the min_dist and max_dist elements. In any case, the camera will always follow the model by changing its orientation. use_model_frame: If set to true, the position of the camera is relative to the model reference frame, which means that its position relative to the model will not change. Otherwise, the position of the camera is relative to the world reference frame, which means that its position relative to the world will not change. This parameter is only used if static is set to true. xyz: The position of the camera's reference frame. This parameter is only used if static is set to true. If use_model_frame is set to true, the position is relative to the model reference frame, otherwise it represents world coordinates. inherit_yaw: If set to true, the camera will inherit the yaw rotation of the tracked model. This parameter is only used if static and use_model_frame are set to true. """ name: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_dist: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_dist: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) static: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) use_model_frame: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) xyz: str = field( default="-5.0 0.0 3.0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) inherit_yaw: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Frame: """ A frame of reference in which poses may be expressed. Parameters ---------- pose: A position(x,y,z) and orientation(roll, pitch yaw) with respect to the frame named in the relative_to attribute. name: Name of the frame. It must be unique whithin its scope (model/world), i.e., it must not match the name of another frame, link, joint, or model within the same scope. attached_to: If specified, this frame is attached to the specified frame. The specified frame must be within the same scope and may be defined implicitly, i.e., the name of any //frame, //model, //joint, or //link within the same scope may be used. If missing, this frame is attached to the containing scope's frame. Within a //world scope this is the implicit world frame, and within a //model scope this is the implicit model frame. A frame moves jointly with the frame it is @attached_to. This is different from //pose/@relative_to. @attached_to defines how the frame is attached to a //link, //model, or //world frame, while //pose/@relative_to defines how the frame's pose is represented numerically. As a result, following the chain of @attached_to attributes must always lead to a //link, //model, //world, or //joint (implicitly attached_to its child //link). """ pose: Optional["World.Frame.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) attached_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Road: """ Parameters ---------- width: Width of the road point: A series of points that define the path of the road. material: The material of the visual element. name: Name of the road """ width: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) point: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) material: Optional[Material] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class SphericalCoordinates: """ Parameters ---------- surface_model: Name of planetary surface model, used to determine the surface altitude at a given latitude and longitude. The default is an ellipsoid model of the earth based on the WGS-84 standard. It is used in Gazebo's GPS sensor implementation. world_frame_orientation: This field identifies how Gazebo world frame is aligned in Geographical sense. The final Gazebo world frame orientation is obtained by rotating a frame aligned with following notation by the field heading_deg (Note that heading_deg corresponds to positive yaw rotation in the NED frame, so it's inverse specifies positive Z-rotation in ENU or NWU). Options are: - ENU (East-North-Up) - NED (North-East-Down) - NWU (North-West-Up) For example, world frame specified by setting world_orientation="ENU" and heading_deg=-90° is effectively equivalent to NWU with heading of 0°. latitude_deg: Geodetic latitude at origin of gazebo reference frame, specified in units of degrees. longitude_deg: Longitude at origin of gazebo reference frame, specified in units of degrees. elevation: Elevation of origin of gazebo reference frame, specified in meters. heading_deg: Heading offset of gazebo reference frame, measured as angle between Gazebo world frame and the world_frame_orientation type (ENU/NED/NWU). Rotations about the downward-vector (e.g. North to East) are positive. The direction of rotation is chosen to be consistent with compass heading convention (e.g. 0 degrees points North and 90 degrees points East, positive rotation indicates counterclockwise rotation when viewed from top-down direction). The angle is specified in degrees. """ surface_model: str = field( default="EARTH_WGS84", metadata={ "type": "Element", "namespace": "", "required": True, }, ) world_frame_orientation: str = field( default="ENU", metadata={ "type": "Element", "namespace": "", "required": True, }, ) latitude_deg: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) longitude_deg: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) elevation: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) heading_deg: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Population: """ The population element defines how and where a set of models will be automatically populated in Gazebo. Parameters ---------- model_count: The number of models to place. distribution: Specifies the type of object distribution and its optional parameters. box: Box shape cylinder: Cylinder shape pose: A position(x,y,z) and orientation(roll, pitch yaw) with respect to the frame named in the relative_to attribute. model: The model element defines a complete robot or any other physical object. name: A unique name for the population. This name must not match another population in the world. """ model_count: int = field( default=1, metadata={ "type": "Element", "namespace": "", "required": True, }, ) distribution: Optional["World.Population.Distribution"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) box: Optional["World.Population.Box"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) cylinder: Optional["World.Population.Cylinder"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["World.Population.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) model: Optional[Model] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Distribution: """ Specifies the type of object distribution and its optional parameters. Parameters ---------- type: Define how the objects will be placed in the specified region. - random: Models placed at random. - uniform: Models approximately placed in a 2D grid pattern with control over the number of objects. - grid: Models evenly placed in a 2D grid pattern. The number of objects is not explicitly specified, it is based on the number of rows and columns of the grid. - linear-x: Models evently placed in a row along the global x-axis. - linear-y: Models evently placed in a row along the global y-axis. - linear-z: Models evently placed in a row along the global z-axis. rows: Number of rows in the grid. cols: Number of columns in the grid. step: Distance between elements of the grid. """ type: str = field( default="random", metadata={ "type": "Element", "namespace": "", "required": True, }, ) rows: int = field( default=1, metadata={ "type": "Element", "namespace": "", "required": True, }, ) cols: int = field( default=1, metadata={ "type": "Element", "namespace": "", "required": True, }, ) step: str = field( default="0.5 0.5 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Box: """ Box shape. Parameters ---------- size: The three side lengths of the box. The origin of the box is in its geometric center (inside the center of the box). """ size: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Cylinder: """ Cylinder shape. Parameters ---------- radius: Radius of the cylinder length: Length of the cylinder along the z axis """ radius: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) length: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v17/world.py
0.933051
0.610802
world.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .light import Light from .model import Model as ModelModel __NAMESPACE__ = "sdformat/v1.7/state.xsd" @dataclass class Model: """ Model state. Parameters ---------- joint: Joint angle model: A nested model state element scale: Scale for the 3 dimensions of the model. frame: A frame of reference in which poses may be expressed. pose: A position(x,y,z) and orientation(roll, pitch yaw) with respect to the frame named in the relative_to attribute. link: Link state name: Name of the model """ class Meta: name = "model" joint: List["Model.Joint"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) model: List["Model"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) scale: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) frame: List["Model.Frame"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["Model.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) link: List["Model.Link"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Joint: """ Joint angle. Parameters ---------- angle: Angle of an axis name: Name of the joint """ angle: List["Model.Joint.Angle"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Angle: """ Parameters ---------- value: axis: Index of the axis. """ value: Optional[float] = field( default=None, metadata={ "required": True, }, ) axis: Optional[int] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Frame: """ A frame of reference in which poses may be expressed. Parameters ---------- pose: A position(x,y,z) and orientation(roll, pitch yaw) with respect to the frame named in the relative_to attribute. name: Name of the frame. It must be unique whithin its scope (model/world), i.e., it must not match the name of another frame, link, joint, or model within the same scope. attached_to: If specified, this frame is attached to the specified frame. The specified frame must be within the same scope and may be defined implicitly, i.e., the name of any //frame, //model, //joint, or //link within the same scope may be used. If missing, this frame is attached to the containing scope's frame. Within a //world scope this is the implicit world frame, and within a //model scope this is the implicit model frame. A frame moves jointly with the frame it is @attached_to. This is different from //pose/@relative_to. @attached_to defines how the frame is attached to a //link, //model, or //world frame, while //pose/@relative_to defines how the frame's pose is represented numerically. As a result, following the chain of @attached_to attributes must always lead to a //link, //model, //world, or //joint (implicitly attached_to its child //link). """ pose: Optional["Model.Frame.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) attached_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Link: """ Link state. Parameters ---------- velocity: Velocity of the link. The x, y, z components of the pose correspond to the linear velocity of the link, and the roll, pitch, yaw components correspond to the angular velocity of the link acceleration: Acceleration of the link. The x, y, z components of the pose correspond to the linear acceleration of the link, and the roll, pitch, yaw components correspond to the angular acceleration of the link wrench: Force and torque applied to the link. The x, y, z components of the pose correspond to the force applied to the link, and the roll, pitch, yaw components correspond to the torque applied to the link collision: Collision state pose: A position(x,y,z) and orientation(roll, pitch yaw) with respect to the frame named in the relative_to attribute. name: Name of the link """ velocity: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) acceleration: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) wrench: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) collision: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["Model.Link.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class State: """ Parameters ---------- sim_time: Simulation time stamp of the state [seconds nanoseconds] wall_time: Wall time stamp of the state [seconds nanoseconds] real_time: Real time stamp of the state [seconds nanoseconds] iterations: Number of simulation iterations. insertions: A list containing the entire description of entities inserted. deletions: A list of names of deleted entities/ model: Model state light: Light state world_name: Name of the world this state applies to """ class Meta: name = "state" sim_time: str = field( default="0 0", metadata={ "type": "Element", "namespace": "", "required": True, "white_space": "collapse", "pattern": r"\d+ \d+", }, ) wall_time: str = field( default="0 0", metadata={ "type": "Element", "namespace": "", "required": True, "white_space": "collapse", "pattern": r"\d+ \d+", }, ) real_time: str = field( default="0 0", metadata={ "type": "Element", "namespace": "", "required": True, "white_space": "collapse", "pattern": r"\d+ \d+", }, ) iterations: int = field( default=0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) insertions: Optional["State.Insertions"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) deletions: Optional["State.Deletions"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) model: List[Model] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) light: List["State.Light"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) world_name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Insertions: """ A list containing the entire description of entities inserted. Parameters ---------- model: The model element defines a complete robot or any other physical object. light: The light element describes a light source. """ model: List[ModelModel] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) light: List[Light] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Deletions: """ A list of names of deleted entities/ Parameters ---------- name: The name of a deleted entity. """ name: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) @dataclass class Light: """ Light state. Parameters ---------- pose: A position(x,y,z) and orientation(roll, pitch yaw) with respect to the frame named in the relative_to attribute. name: Name of the light """ pose: Optional["State.Light.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v17/state.py
0.943217
0.571049
state.py
pypi
from dataclasses import dataclass, field from typing import Optional __NAMESPACE__ = "sdformat/v1.7/physics.xsd" @dataclass class Physics: """ The physics tag specifies the type and properties of the dynamics engine. Parameters ---------- max_step_size: Maximum time step size at which every system in simulation can interact with the states of the world. (was physics.sdf's dt). real_time_factor: target simulation speedup factor, defined by ratio of simulation time to real-time. real_time_update_rate: Rate at which to update the physics engine (UpdatePhysics calls per real-time second). (was physics.sdf's update_rate). max_contacts: Maximum number of contacts allowed between two entities. This value can be over ridden by a max_contacts element in a collision element. dart: DART specific physics properties simbody: Simbody specific physics properties bullet: Bullet specific physics properties ode: ODE specific physics properties name: The name of this set of physics parameters. default: If true, this physics element is set as the default physics profile for the world. If multiple default physics elements exist, the first element marked as default is chosen. If no default physics element exists, the first physics element is chosen. type: The type of the dynamics engine. Current options are ode, bullet, simbody and dart. Defaults to ode if left unspecified. """ class Meta: name = "physics" max_step_size: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) real_time_factor: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) real_time_update_rate: float = field( default=1000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_contacts: int = field( default=20, metadata={ "type": "Element", "namespace": "", "required": True, }, ) dart: Optional["Physics.Dart"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) simbody: Optional["Physics.Simbody"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) bullet: Optional["Physics.Bullet"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) ode: Optional["Physics.Ode"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) name: str = field( default="default_physics", metadata={ "type": "Attribute", }, ) default: bool = field( default=False, metadata={ "type": "Attribute", }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Dart: """ DART specific physics properties. Parameters ---------- solver: collision_detector: Specify collision detector for DART to use. Can be dart, fcl, bullet or ode. """ solver: Optional["Physics.Dart.Solver"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) collision_detector: str = field( default="fcl", metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Solver: """ Parameters ---------- solver_type: One of the following types: pgs, dantzig. PGS stands for Projected Gauss-Seidel. """ solver_type: str = field( default="dantzig", metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Simbody: """ Simbody specific physics properties. Parameters ---------- min_step_size: (Currently not used in simbody) The time duration which advances with each iteration of the dynamics engine, this has to be no bigger than max_step_size under physics block. If left unspecified, min_step_size defaults to max_step_size. accuracy: Roughly the relative error of the system. -LOG(accuracy) is roughly the number of significant digits. max_transient_velocity: Tolerable "slip" velocity allowed by the solver when static friction is supposed to hold object in place. contact: Relationship among dissipation, coef. restitution, etc. d = dissipation coefficient (1/velocity) vc = capture velocity (velocity where e=e_max) vp = plastic velocity (smallest v where e=e_min) > vc Assume real COR=1 when v=0. e_min = given minimum COR, at v >= vp (a.k.a. plastic_coef_restitution) d = slope = (1-e_min)/vp OR, e_min = 1 - d*vp e_max = maximum COR = 1-d*vc, reached at v=vc e = 0, v <= vc = 1 - d*v, vc < v < vp = e_min, v >= vp dissipation factor = d*min(v,vp) [compliant] cor = e [rigid] Combining rule e = 0, e1==e2==0 = 2*e1*e2/(e1+e2), otherwise """ min_step_size: float = field( default=0.0001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) accuracy: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) max_transient_velocity: float = field( default=0.01, metadata={ "type": "Element", "namespace": "", "required": True, }, ) contact: Optional["Physics.Simbody.Contact"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Contact: """Relationship among dissipation, coef. restitution, etc. d = dissipation coefficient (1/velocity) vc = capture velocity (velocity where e=e_max) vp = plastic velocity (smallest v where e=e_min) > vc Assume real COR=1 when v=0. e_min = given minimum COR, at v >= vp (a.k.a. plastic_coef_restitution) d = slope = (1-e_min)/vp OR, e_min = 1 - d*vp e_max = maximum COR = 1-d*vc, reached at v=vc e = 0, v <= vc = 1 - d*v, vc < v < vp = e_min, v >= vp dissipation factor = d*min(v,vp) [compliant] cor = e [rigid] Combining rule e = 0, e1==e2==0 = 2*e1*e2/(e1+e2), otherwise Parameters ---------- stiffness: Default contact material stiffness (force/dist or torque/radian). dissipation: dissipation coefficient to be used in compliant contact; if not given it is (1-min_cor)/plastic_impact_velocity plastic_coef_restitution: this is the COR to be used at high velocities for rigid impacts; if not given it is 1 - dissipation*plastic_impact_velocity plastic_impact_velocity: smallest impact velocity at which min COR is reached; set to zero if you want the min COR always to be used static_friction: static friction (mu_s) as described by this plot: http://gazebosim.org/wiki/File:Stribeck_friction.png dynamic_friction: dynamic friction (mu_d) as described by this plot: http://gazebosim.org/wiki/File:Stribeck_friction.png viscous_friction: viscous friction (mu_v) with units of (1/velocity) as described by this plot: http://gazebosim.org/wiki/File:Stribeck_friction.png override_impact_capture_velocity: for rigid impacts only, impact velocity at which COR is set to zero; normally inherited from global default but can be overridden here. Combining rule: use larger velocity override_stiction_transition_velocity: This is the largest slip velocity at which we'll consider a transition to stiction. Normally inherited from a global default setting. For a continuous friction model this is the velocity at which the max static friction force is reached. Combining rule: use larger velocity """ stiffness: float = field( default=100000000.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) dissipation: float = field( default=100.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) plastic_coef_restitution: float = field( default=0.5, metadata={ "type": "Element", "namespace": "", "required": True, }, ) plastic_impact_velocity: float = field( default=0.5, metadata={ "type": "Element", "namespace": "", "required": True, }, ) static_friction: float = field( default=0.9, metadata={ "type": "Element", "namespace": "", "required": True, }, ) dynamic_friction: float = field( default=0.9, metadata={ "type": "Element", "namespace": "", "required": True, }, ) viscous_friction: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) override_impact_capture_velocity: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) override_stiction_transition_velocity: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Bullet: """ Bullet specific physics properties. Parameters ---------- solver: constraints: Bullet constraint parameters. """ solver: Optional["Physics.Bullet.Solver"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) constraints: Optional["Physics.Bullet.Constraints"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Solver: """ Parameters ---------- type: One of the following types: sequential_impulse only. min_step_size: The time duration which advances with each iteration of the dynamics engine, this has to be no bigger than max_step_size under physics block. If left unspecified, min_step_size defaults to max_step_size. iters: Number of iterations for each step. A higher number produces greater accuracy at a performance cost. sor: Set the successive over-relaxation parameter. """ type: str = field( default="sequential_impulse", metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_step_size: float = field( default=0.0001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) iters: int = field( default=50, metadata={ "type": "Element", "namespace": "", "required": True, }, ) sor: float = field( default=1.3, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Constraints: """ Bullet constraint parameters. Parameters ---------- cfm: Constraint force mixing parameter. See the ODE page for more information. erp: Error reduction parameter. See the ODE page for more information. contact_surface_layer: The depth of the surface layer around all geometry objects. Contacts are allowed to sink into the surface layer up to the given depth before coming to rest. The default value is zero. Increasing this to some small value (e.g. 0.001) can help prevent jittering problems due to contacts being repeatedly made and broken. split_impulse: Similar to ODE's max_vel implementation. See http://web.archive.org/web/20120430155635/http://bulletphysics.org/mediawiki-1.5.8/index.php/BtContactSolverInfo#Split_Impulse for more information. split_impulse_penetration_threshold: Similar to ODE's max_vel implementation. See http://web.archive.org/web/20120430155635/http://bulletphysics.org/mediawiki-1.5.8/index.php/BtContactSolverInfo#Split_Impulse for more information. """ cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) contact_surface_layer: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) split_impulse: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) split_impulse_penetration_threshold: float = field( default=-0.01, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Ode: """ ODE specific physics properties. Parameters ---------- solver: constraints: ODE constraint parameters. """ solver: Optional["Physics.Ode.Solver"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) constraints: Optional["Physics.Ode.Constraints"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Solver: """ Parameters ---------- type: One of the following types: world, quick min_step_size: The time duration which advances with each iteration of the dynamics engine, this has to be no bigger than max_step_size under physics block. If left unspecified, min_step_size defaults to max_step_size. island_threads: Number of threads to use for "islands" of disconnected models. iters: Number of iterations for each step. A higher number produces greater accuracy at a performance cost. precon_iters: Experimental parameter. sor: Set the successive over-relaxation parameter. thread_position_correction: Flag to use threading to speed up position correction computation. use_dynamic_moi_rescaling: Flag to enable dynamic rescaling of moment of inertia in constrained directions. See gazebo pull request 1114 for the implementation of this feature. https://osrf- migration.github.io/gazebo-gh-pages/#!/osrf/gazebo/pull- request/1114 friction_model: Name of ODE friction model to use. Valid values include: pyramid_model: (default) friction forces limited in two directions in proportion to normal force. box_model: friction forces limited to constant in two directions. cone_model: friction force magnitude limited in proportion to normal force. See gazebo pull request 1522 for the implementation of this feature. https://osrf-migration.github.io/gazebo-gh- pages/#!/osrf/gazebo/pull-request/1522 https://github.com/osrf/gazebo/commit/968dccafdfbfca09c9b3326f855612076fed7e6f """ type: str = field( default="quick", metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_step_size: float = field( default=0.0001, metadata={ "type": "Element", "namespace": "", "required": True, }, ) island_threads: int = field( default=0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) iters: int = field( default=50, metadata={ "type": "Element", "namespace": "", "required": True, }, ) precon_iters: int = field( default=0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) sor: float = field( default=1.3, metadata={ "type": "Element", "namespace": "", "required": True, }, ) thread_position_correction: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) use_dynamic_moi_rescaling: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) friction_model: str = field( default="pyramid_model", metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Constraints: """ ODE constraint parameters. Parameters ---------- cfm: Constraint force mixing parameter. See the ODE page for more information. erp: Error reduction parameter. See the ODE page for more information. contact_max_correcting_vel: The maximum correcting velocities allowed when resolving contacts. contact_surface_layer: The depth of the surface layer around all geometry objects. Contacts are allowed to sink into the surface layer up to the given depth before coming to rest. The default value is zero. Increasing this to some small value (e.g. 0.001) can help prevent jittering problems due to contacts being repeatedly made and broken. """ cfm: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) erp: float = field( default=0.2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) contact_max_correcting_vel: float = field( default=100.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) contact_surface_layer: float = field( default=0.001, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v17/physics.py
0.95594
0.527012
physics.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .joint import Joint from .link import Link __NAMESPACE__ = "sdformat/v1.7/model.xsd" @dataclass class Model: """ The model element defines a complete robot or any other physical object. Parameters ---------- static: If set to true, the model is immovable; i.e., a dynamics engine will not update its position. This will also overwrite this model's `@canonical_link` and instead attach the model's implicit frame to the world's implicit frame. This holds even if this model is nested (or included) by another model instead of being a direct child of `//world`. self_collide: If set to true, all links in the model will collide with each other (except those connected by a joint). Can be overridden by the link or collision element self_collide property. Two links within a model will collide if link1.self_collide OR link2.self_collide. Links connected by a joint will never collide. allow_auto_disable: Allows a model to auto-disable, which is means the physics engine can skip updating the model when the model is at rest. This parameter is only used by models with no joints. include: Include resources from a URI. This can be used to nest models. model: A nested model element enable_wind: If set to true, all links in the model will be affected by the wind. Can be overriden by the link wind property. frame: A frame of reference in which poses may be expressed. pose: A position(x,y,z) and orientation(roll, pitch yaw) with respect to the frame named in the relative_to attribute. link: A physical link with inertia, collision, and visual properties. A link must be a child of a model, and any number of links may exist in a model. joint: A joint connects two links with kinematic and dynamic properties. By default, the pose of a joint is expressed in the child link frame. plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. gripper: name: The name of the model and its implicit frame. This name must be unique among all elements defining frames within the same scope, i.e., it must not match another //model, //frame, //joint, or //link within the same scope. canonical_link: The name of the model's canonical link, to which the model's implicit coordinate frame is attached. If unset or set to an empty string, the first `/link` listed as a direct child of this model is chosen as the canonical link. If the model has no direct `/link` children, it will instead be attached to the first nested (or included) model's implicit frame. """ class Meta: name = "model" static: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) self_collide: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) allow_auto_disable: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) include: List["Model.Include"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) model: List["Model"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) enable_wind: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) frame: List["Model.Frame"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) pose: Optional["Model.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) link: List[Link] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) joint: List[Joint] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) plugin: List["Model.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) gripper: List["Model.Gripper"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) canonical_link: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Include: """Include resources from a URI. This can be used to nest models. Parameters ---------- uri: URI to a resource, such as a model name: Override the name of the included model. static: Override the static value of the included model. pose: A position(x,y,z) and orientation(roll, pitch yaw) with respect to the frame named in the relative_to attribute. plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. """ uri: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) static: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: Optional["Model.Include.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) plugin: List["Model.Include.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Frame: """ A frame of reference in which poses may be expressed. Parameters ---------- pose: A position(x,y,z) and orientation(roll, pitch yaw) with respect to the frame named in the relative_to attribute. name: Name of the frame. It must be unique whithin its scope (model/world), i.e., it must not match the name of another frame, link, joint, or model within the same scope. attached_to: If specified, this frame is attached to the specified frame. The specified frame must be within the same scope and may be defined implicitly, i.e., the name of any //frame, //model, //joint, or //link within the same scope may be used. If missing, this frame is attached to the containing scope's frame. Within a //world scope this is the implicit world frame, and within a //model scope this is the implicit model frame. A frame moves jointly with the frame it is @attached_to. This is different from //pose/@relative_to. @attached_to defines how the frame is attached to a //link, //model, or //world frame, while //pose/@relative_to defines how the frame's pose is represented numerically. As a result, following the chain of @attached_to attributes must always lead to a //link, //model, //world, or //joint (implicitly attached_to its child //link). """ pose: Optional["Model.Frame.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) attached_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Gripper: grasp_check: Optional["Model.Gripper.GraspCheck"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) gripper_link: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, }, ) palm_link: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class GraspCheck: detach_steps: int = field( default=40, metadata={ "type": "Element", "namespace": "", "required": True, }, ) attach_steps: int = field( default=20, metadata={ "type": "Element", "namespace": "", "required": True, }, ) min_contact_count: int = field( default=2, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v17/model.py
0.952937
0.525856
model.py
pypi
from dataclasses import dataclass, field from typing import List, Optional from .joint import Joint from .link import Link __NAMESPACE__ = "sdformat/v1.7/actor.xsd" @dataclass class Actor: """A special kind of model which can have a scripted motion. This includes both global waypoint type animations and skeleton animations. Parameters ---------- skin: Skin file which defines a visual and the underlying skeleton which moves it. animation: Animation file defines an animation for the skeleton in the skin. The skeleton must be compatible with the skin skeleton. script: Adds scripted trajectories to the actor. pose: A position(x,y,z) and orientation(roll, pitch yaw) with respect to the frame named in the relative_to attribute. link: A physical link with inertia, collision, and visual properties. A link must be a child of a model, and any number of links may exist in a model. joint: A joint connects two links with kinematic and dynamic properties. By default, the pose of a joint is expressed in the child link frame. plugin: A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. name: A unique name for the actor. """ class Meta: name = "actor" skin: Optional["Actor.Skin"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) animation: List["Actor.Animation"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) script: Optional["Actor.Script"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: Optional["Actor.Pose"] = field( default=None, metadata={ "type": "Element", "namespace": "", "required": True, }, ) link: List[Link] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) joint: List[Joint] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) plugin: List["Actor.Plugin"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Skin: """ Skin file which defines a visual and the underlying skeleton which moves it. Parameters ---------- filename: Path to skin file, accepted formats: COLLADA, BVH. scale: Scale the skin's size. """ filename: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) scale: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Animation: """Animation file defines an animation for the skeleton in the skin. The skeleton must be compatible with the skin skeleton. Parameters ---------- filename: Path to animation file. Accepted formats: COLLADA, BVH. scale: Scale for the animation skeleton. interpolate_x: Set to true so the animation is interpolated on X. name: Unique name for animation. """ filename: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) scale: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) interpolate_x: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) @dataclass class Script: """ Adds scripted trajectories to the actor. Parameters ---------- loop: Set this to true for the script to be repeated in a loop. For a fluid continuous motion, make sure the last waypoint matches the first one. delay_start: This is the time to wait before starting the script. If running in a loop, this time will be waited before starting each cycle. auto_start: Set to true if the animation should start as soon as the simulation starts playing. It is useful to set this to false if the animation should only start playing only when triggered by a plugin, for example. trajectory: The trajectory contains a series of keyframes to be followed. """ loop: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) delay_start: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) auto_start: bool = field( default=True, metadata={ "type": "Element", "namespace": "", "required": True, }, ) trajectory: List["Actor.Script.Trajectory"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Trajectory: """ The trajectory contains a series of keyframes to be followed. Parameters ---------- waypoint: Each point in the trajectory. id: Unique id for a trajectory. type: If it matches the type of an animation, they will be played at the same time. tension: The tension of the trajectory spline. The default value of zero equates to a Catmull-Rom spline, which may also cause the animation to overshoot keyframes. A value of one will cause the animation to stick to the keyframes. """ waypoint: List["Actor.Script.Trajectory.Waypoint"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) id: Optional[int] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) type: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) tension: float = field( default=0.0, metadata={ "type": "Attribute", }, ) @dataclass class Waypoint: """ Each point in the trajectory. Parameters ---------- time: The time in seconds, counted from the beginning of the script, when the pose should be reached. pose: The pose which should be reached at the given time. """ time: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) pose: str = field( default="0 0 0 0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Pose: """ Parameters ---------- value: relative_to: If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. """ value: str = field( default="0 0 0 0 0 0", metadata={ "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){5}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) relative_to: Optional[str] = field( default=None, metadata={ "type": "Attribute", }, ) @dataclass class Plugin: """A plugin is a dynamically loaded chunk of code. It can exist as a child of world, model, and sensor. Parameters ---------- any_element: This is a special element that should not be specified in an SDFormat file. It automatically copies child elements into the SDFormat element so that a plugin can access the data. name: A unique name for the plugin, scoped to its parent. filename: Name of the shared library to load. If the filename is not a full path name, the file will be searched for in the configuration paths. """ any_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", }, ) name: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, ) filename: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v17/actor.py
0.960287
0.516108
actor.py
pypi
from dataclasses import dataclass, field from typing import List, Optional __NAMESPACE__ = "sdformat/v1.7/geometry.xsd" @dataclass class Geometry: """ The shape of the visual or collision object. Parameters ---------- empty: You can use the empty tag to make empty geometries. box: Box shape cylinder: Cylinder shape heightmap: A heightmap based on a 2d grayscale image. image: Extrude a set of boxes from a grayscale image. mesh: Mesh shape plane: Plane shape polyline: Defines an extruded polyline shape sphere: Sphere shape """ class Meta: name = "geometry" empty: Optional[str] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) box: Optional["Geometry.Box"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) cylinder: Optional["Geometry.Cylinder"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) heightmap: Optional["Geometry.Heightmap"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) image: Optional["Geometry.Image"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) mesh: Optional["Geometry.Mesh"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) plane: Optional["Geometry.Plane"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) polyline: Optional["Geometry.Polyline"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) sphere: Optional["Geometry.Sphere"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) @dataclass class Box: """ Box shape. Parameters ---------- size: The three side lengths of the box. The origin of the box is in its geometric center (inside the center of the box). """ size: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Cylinder: """ Cylinder shape. Parameters ---------- radius: Radius of the cylinder length: Length of the cylinder along the z axis """ radius: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) length: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Heightmap: """ A heightmap based on a 2d grayscale image. Parameters ---------- uri: URI to a grayscale image file size: The size of the heightmap in world units. When loading an image: "size" is used if present, otherwise defaults to 1x1x1. When loading a DEM: "size" is used if present, otherwise defaults to true size of DEM. pos: A position offset. texture: The heightmap can contain multiple textures. The order of the texture matters. The first texture will appear at the lowest height, and the last texture at the highest height. Use blend to control the height thresholds and fade between textures. blend: The blend tag controls how two adjacent textures are mixed. The number of blend elements should equal one less than the number of textures. use_terrain_paging: Set if the rendering engine will use terrain paging sampling: Samples per heightmap datum. For rasterized heightmaps, this indicates the number of samples to take per pixel. Using a lower value, e.g. 1, will generally improve the performance of the heightmap but lower the heightmap quality. """ uri: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) size: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) pos: str = field( default="0 0 0", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) texture: List["Geometry.Heightmap.Texture"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) blend: List["Geometry.Heightmap.Blend"] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", }, ) use_terrain_paging: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) sampling: int = field( default=2, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Texture: """The heightmap can contain multiple textures. The order of the texture matters. The first texture will appear at the lowest height, and the last texture at the highest height. Use blend to control the height thresholds and fade between textures. Parameters ---------- size: Size of the applied texture in meters. diffuse: Diffuse texture image filename normal: Normalmap texture image filename """ size: float = field( default=10.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) diffuse: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) normal: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Blend: """The blend tag controls how two adjacent textures are mixed. The number of blend elements should equal one less than the number of textures. Parameters ---------- min_height: Min height of a blend layer fade_dist: Distance over which the blend occurs """ min_height: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) fade_dist: float = field( default=0.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Image: """ Extrude a set of boxes from a grayscale image. Parameters ---------- uri: URI of the grayscale image file scale: Scaling factor applied to the image threshold: Grayscale threshold height: Height of the extruded boxes granularity: The amount of error in the model """ uri: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) scale: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) threshold: int = field( default=200, metadata={ "type": "Element", "namespace": "", "required": True, }, ) height: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) granularity: int = field( default=1, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Mesh: """ Mesh shape. Parameters ---------- uri: Mesh uri submesh: Use a named submesh. The submesh must exist in the mesh specified by the uri scale: Scaling factor applied to the mesh """ uri: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) submesh: Optional["Geometry.Mesh.Submesh"] = field( default=None, metadata={ "type": "Element", "namespace": "", }, ) scale: str = field( default="1 1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Submesh: """Use a named submesh. The submesh must exist in the mesh specified by the uri Parameters ---------- name: Name of the submesh within the parent mesh center: Set to true to center the vertices of the submesh at 0,0,0. This will effectively remove any transformations on the submesh before the poses from parent links and models are applied. """ name: str = field( default="__default__", metadata={ "type": "Element", "namespace": "", "required": True, }, ) center: bool = field( default=False, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Plane: """ Plane shape. Parameters ---------- normal: Normal direction for the plane. When a Plane is used as a geometry for a Visual or Collision object, then the normal is specified in the Visual or Collision frame, respectively. size: Length of each side of the plane. Note that this property is meaningful only for visualizing the Plane, i.e., when the Plane is used as a geometry for a Visual object. The Plane has infinite size when used as a geometry for a Collision object. """ normal: str = field( default="0 0 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){2}((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) size: str = field( default="1 1", metadata={ "type": "Element", "namespace": "", "required": True, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+)((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) @dataclass class Polyline: """ Defines an extruded polyline shape. Parameters ---------- point: A series of points that define the path of the polyline. height: Height of the polyline """ point: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, "pattern": r"(\s*(-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+)((-|\+)?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+))\s*", }, ) height: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, ) @dataclass class Sphere: """ Sphere shape. Parameters ---------- radius: radius of the sphere """ radius: float = field( default=1.0, metadata={ "type": "Element", "namespace": "", "required": True, }, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/bindings/v17/geometry.py
0.949937
0.55917
geometry.py
pypi
import warnings from typing import List, Any, Dict, Tuple from itertools import chain from .base import ( BoolElement, ElementBase, FloatElement, NamedPoseBearing, Pose, StringElement, should_warn_unsupported, ) from .frame import Frame from .origin import Origin from .plugin import Plugin from .camera import Camera from .sensors import Ray from .sensors import Contact from .sensors import RfidTag from .sensors import Rfid from .sensors import Imu from .sensors import ForceTorque from .sensors import Gps from .sensors import Sonar from .sensors import Transceiver from .sensors import Altimeter from .sensors import LogicalCamera from .sensors import Magnetometer from .sensors import AirPressure from .sensors import Lidar from .sensors import Navsat from .... import transform as tf class Sensor(ElementBase): """A sensor. Parameters ---------- name : str A unique name for the sensor. This name must not match another sensor under the same parent. type : str The type name of the sensor. The "ray", "gpu_ray", and "gps" types are equivalent to "lidar", "gpu_lidar", and "navsat", respectively. It is preferred to use "lidar", "gpu_lidar", and "navsat" since "ray", "gpu_ray", and "gps" will be deprecated. The "ray", "gpu_ray", and "gps" types are maintained for legacy support. Must be one of: - air_pressure - altimeter - camera - contact - depth_camera, depth - force_torque - gps - gpu_lidar - gpu_ray - imu - lidar - logical_camera - magnetometer - multicamera - navsat - ray - rfid - rfidtag - rgbd_camera, rgbd - sonar - thermal_camera, thermal - wireless_receiver - wireless_transmitter always_on : bool If true the sensor will always be updated according to the update rate. Default is ``False``. update_rate : float The frequency at which the sensor data is generated. If set to 0, the sensor will generate data every cycle. Default is ``0``. visualize : bool If true, the sensor is visualized in the GUI. Default is ``False``. enable_metrics : bool If true, the sensor will publish performance metrics. Default is ``False``. .. versionadded:: SDFormat v1.7 pose : Pose The links's initial position (x,y,z) and orientation (roll, pitch, yaw). .. versionadded:: SDFormat 1.2 topic : str Name of the topic on which data is published. plugins : List[Plugin] A list of plugins used to customize the runtime behavior of the simulation. air_pressure : AirPressure Parameters of a Barometer sensor. .. versionadded:: SDFormat v1.6 camera : Camera Parameters of a Camera sensor. ray : Ray Parameters of a Laser sensor. contact : Contact Parameters of a Contact sensor. rfid : Rfid Parameters of a RFID sensor. rfidtag : RfidTag Parameters of a RFID Tag. imu : Imu Parameters of a Inertial Measurement Unit (IMU). .. versionadded:: SDFormat v1.3 force_torque : ForceTorque Parameters of a torque sensor. .. versionadded:: SDFormat v1.4 gps : Gps Parameters of a GPS. .. versionadded:: SDFormat v1.4 sonar : Sonar parameters of a Sonar. .. versionadded:: SDFormat v1.4 transceiver : Transceiver Parameters for a wireless transceiver. .. versionadded:: SDFormat v1.4 altimeter : Altimeter Parameters for an Altimeter, .. versionadded:: SDFormat v1.5 lidar : Lidar Parameters of a LIDAR sensor. .. versionadded:: SDFormat v1.6 logical_camera : LogicalCamera Parameters of a logical camera. magnetometer : Magnetometer Parameters of a magnetometer. .. versionadded:: SDFormat v1.5 navsat : Navsat Parameters of a GPS. .. versionadded:: SDFormat v1.7 sdf_version : str The SDFormat version to use when constructing this element. origin : Origin The link's origin. .. deprecated:: SDFormat v1.2 Use `Sensor.pose` instead. frames : List[Frame] A list of frames of reference in which poses may be expressed. .. deprecated:: SDFormat v1.7 Use :attr:`Model.frame` instead. .. versionadded:: SDFormat v1.5 Attributes ---------- particle_emitters : List[ParticleEmitter] See ``Parameters`` section. name : str See ``Parameters`` section. type : str See ``Parameters`` section. always_on : bool See ``Parameters`` section. update_rate : float See ``Parameters`` section. visualize : bool See ``Parameters`` section. enable_metrics : bool See ``Parameters`` section. pose : Pose See ``Parameters`` section. topic : str See ``Parameters`` section. plugins : List[Plugin] See ``Parameters`` section. air_pressure : AirPressure See ``Parameters`` section. camera : Camera See ``Parameters`` section. ray : Ray See ``Parameters`` section. contact : Contact See ``Parameters`` section. rfid : Rfid See ``Parameters`` section. rfidtag : RfidTag See ``Parameters`` section. imu : Imu See ``Parameters`` section. force_torque : ForceTorque See ``Parameters`` section. gps : Gps See ``Parameters`` section. sonar : Sonar See ``Parameters`` section. transceiver : Transceiver See ``Parameters`` section. altimeter : Altimeter See ``Parameters`` section. lidar : Lidar See ``Parameters`` section. logical_camera : LogicalCamera See ``Parameters`` section. magnetometer : Magnetometer See ``Parameters`` section. navsat : Navsat See ``Parameters`` section. """ def __init__( self, *, name: str, type: str, always_on: bool = False, update_rate: float = 0, visualize: bool = False, enable_metrics: bool = False, origin: Origin = None, pose: Pose = None, topic: str = None, plugins: List[Plugin], air_pressure: AirPressure = None, camera: Camera = None, ray: Ray = None, contact: Contact = None, rfid: Rfid = None, rfidtag: RfidTag = None, imu: Imu = None, force_torque: ForceTorque = None, gps: Gps = None, sonar: Sonar = None, transceiver: Transceiver = None, frames: List[Frame] = None, altimeter: Altimeter = None, lidar: Lidar = None, logical_camera: LogicalCamera = None, magnetometer: Magnetometer = None, navsat: Navsat = None, sdf_version: str, ) -> None: super().__init__(sdf_version=sdf_version) self.name = name self.type = type self.always_on = always_on self.update_rate = update_rate self.visualize = visualize self.enable_metrics = enable_metrics if origin is None: self._origin = Origin(sdf_version=sdf_version) elif sdf_version == "1.0": self._origin = origin else: warnings.warn( "`origin` is deprecated. Use `Sensor.pose` instead.", DeprecationWarning ) self._origin = origin if sdf_version == "1.0": self.pose = self._origin.pose elif pose is None: self.pose = Pose(sdf_version=sdf_version) else: self.pose = pose self.topic = self.type if topic is None else topic self.plugins = [] if plugins is None else plugins self.air_pressure = ( AirPressure(sdf_version=sdf_version) if air_pressure is None else air_pressure ) self.camera = Camera(sdf_version=sdf_version) if camera is None else camera self.ray = Ray(sdf_version=sdf_version) if ray is None else ray self.contact = Contact(sdf_version=sdf_version) if contact is None else contact self.rfid = Rfid(sdf_version=sdf_version) if rfid is None else rfid self.rfidtag = RfidTag(sdf_version=sdf_version) if rfidtag is None else rfidtag self.imu = Imu(sdf_version=sdf_version) if imu is None else imu self.force_torque = ( ForceTorque(sdf_version=sdf_version) if force_torque is None else force_torque ) self.gps = Gps(sdf_version=sdf_version) if gps is None else gps self.sonar = Sonar(sdf_version=sdf_version) if sonar is None else sonar self.transceiver = ( Transceiver(sdf_version=sdf_version) if transceiver is None else transceiver ) self._frames = [] if frames is None else frames self.altimeter = ( Altimeter(sdf_version=sdf_version) if altimeter is None else altimeter ) self.lidar = Lidar(sdf_version=sdf_version) if lidar is None else lidar self.logical_camera = ( LogicalCamera(sdf_version=sdf_version) if logical_camera is None else logical_camera ) self.magnetometer = ( Magnetometer(sdf_version=sdf_version) if magnetometer is None else magnetometer ) self.navsat = Navsat(sdf_version=sdf_version) if navsat is None else navsat self._origin.pose = self.pose @property def origin(self): warnings.warn( "`Sensor.origin` is deprecated since SDFormat v1.2. Use `Sensor.pose` instead.", DeprecationWarning, ) return self._origin @property def frames(self): warnings.warn( "`Sensor.frames` is deprecated since SDF v1.7." " Use `Model.frames` instead and set `Frame.attached_to` to the name of this link.", DeprecationWarning, ) return self._frames @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": sensor_args = { "name": specific.name, "type": specific.type, } args_with_default = { "always_on": BoolElement, "update_rate": FloatElement, "visualize": BoolElement, "enable_metrics": BoolElement, "origin": Origin, "pose": Pose, "topic": StringElement, "air_pressure": AirPressure, "camera": Camera, "ray": Ray, "contact": Contact, "rfid": Rfid, "rfidtag": RfidTag, "imu": Imu, "force_torque": ForceTorque, "gps": Gps, "sonar": Sonar, "transceiver": Transceiver, "altimeter": Altimeter, "lidar": Lidar, "logical_camera": LogicalCamera, "magnetometer": Magnetometer, "navsat": Navsat, } list_args = { "plugin": ("plugins", Plugin), "frame": ("frames", Frame), } standard_args = cls._prepare_standard_args( specific, args_with_default, list_args, version=version ) sensor_args.update(standard_args) return Sensor(**sensor_args, sdf_version=version) def declared_frames(self) -> Dict[str, tf.Frame]: declared_frames = {self.name: tf.Frame(3, name=self.name)} relevant_config = None if self.type == "camera": relevant_config = self.camera else: if should_warn_unsupported(): warnings.warn(f"Sensor type `{self.type}` is not implemented.") if relevant_config is not None: nested_elements = relevant_config.declared_frames() for name, frame in nested_elements.items(): declared_frames[f"{self.name}::{name}"] = frame for frame in self._frames: for name, frame in frame.declared_frames().items(): declared_frames[f"{self.name}::{name}"] = frame return declared_frames def to_static_graph( self, declared_frames: Dict[str, tf.Frame], sensor_frame: str, *, seed: int = None, shape: Tuple, axis: int = -1, ) -> tf.Frame: self.pose.to_static_graph(declared_frames, sensor_frame, shape=shape, axis=axis) relevant_config = None if self.type == "camera": relevant_config = self.camera else: if should_warn_unsupported(): warnings.warn(f"Sensor type `{self.type}` is not implemented.") if relevant_config is not None: relevant_config.to_static_graph( declared_frames, sensor_frame, seed=seed, shape=shape, axis=axis, ) for frame in self._frames: frame.pose.to_static_graph( declared_frames, f"{sensor_frame}::{frame.name}", shape=shape, axis=axis ) return declared_frames[sensor_frame] def to_dynamic_graph( self, declared_frames: Dict[str, tf.Frame], sensor_frame: str, *, seed: int = None, shape: Tuple, axis: int = -1, apply_state: bool = True, _scaffolding: Dict[str, tf.Frame], ) -> tf.Frame: relevant_config = None if self.type == "camera": relevant_config = self.camera else: if should_warn_unsupported(): warnings.warn(f"Sensor type `{self.type}` is not implemented.") if relevant_config is not None: relevant_config.to_dynamic_graph( declared_frames, sensor_frame, seed=seed, shape=shape, axis=axis, apply_state=apply_state, _scaffolding=_scaffolding, ) return declared_frames[sensor_frame]
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/generic_sdf/sensor.py
0.906219
0.307046
sensor.py
pypi
import numpy as np from typing import Any, Dict, Tuple import warnings from .... import transform as tf WARN_UNSUPPORTED = True def should_warn_unsupported(): return WARN_UNSUPPORTED def vector3(value: str): return np.fromstring(value, dtype=float, count=3, sep=" ") def quaternion(value: str): # Note: SDFormat quaternions are XYZW return np.fromstring(value, dtype=float, count=4, sep=" ") def vector2d(value: str): return np.fromstring(value, dtype=float, count=2, sep=" ") def vector2i(value: str): return np.fromstring(value, dtype=int, count=2, sep=" ") class ElementBase: def __init__(self, *, sdf_version: str) -> None: self.sdf_version = sdf_version @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": """Create from version-specific object This function converts a version-specific instantce of this element into its generic counterpart. Parameters ---------- specific : Any The version-specific object to convert. It can come from any of scikit-bot's version-specific bindings. version : str The SDFormat version of the specific object. Returns ------- generic : ElementBase The generic counterpart of the specific element. """ if should_warn_unsupported(): warnings.warn(f"`{cls.__name__}` is not implemented yet.") return cls(sdf_version=version) def to_static_graph( self, declared_frames: Dict[str, tf.Frame], *, seed: int = None, shape: Tuple, axis: int = -1, ) -> tf.Frame: """Convert to transform graph Turns this element into a :mod:`skbot.transform` graph using the _static_ constraints defined by this element. The resulting graph places a :class:`tf.Frame <skbot.transform.Frame>` at the position of each joint, link, sensor, etc., defined by this Element. It then connects these frames using translation and rotation :class:`tf.Links <skbot.transform.Link>` in such a way that conversion between any two coordinate frames becomes possible. It differs from :func:`to_dynamic_graph` in that all links in this graph are rigid and that joint connections are not modelled explicitly. Further, the resulting graph will (if applicable) ignore any defined :class:`State` and instead model this element's initial configuration. As such, it can not be used for dynamic calculations, e.g., with :mod:`skbot.inverse_kinematics`. Parameters ---------- declared_frames : Dict[str, tf.Frame] The frames declared in the scope in which this element has been defined. seed: bool The seed to use when procedually generating elements of the simulation. This is currently limited to the `Population` element only. shape : tuple A tuple describing the shape of elements that the resulting graph should transform. This can be used to add batch dimensions to the graph, for example to perform vectorized computation on multiple instances of the same world in different states, or for batched coordinate transformation. Defaults to (3,), which is the shape of a single 3D vector in euclidian space. axis : int The axis along which elements are stored. The axis must have length 3 (since SDFormat describes 3 dimensional worlds), and all other axis are considered batch dimensions. Defaults to -1. Returns ------- frame_graph : tf.Frame A frame graph modelling the (static) initial configuration of this element. Notes ----- This function modifies ``declared_frames`` as a side-effect by appending any frames declared by this frame to it. """ if should_warn_unsupported(): warnings.warn( f"`{self.__class__.__name__}` does not implement `to_static_graph` yet." ) return tf.Frame(3, name="missing") def to_dynamic_graph( self, declared_frames: Dict[str, tf.Frame], *, seed: int = None, shape: Tuple, axis: int = -1, apply_state: bool = True, _scaffolding: Dict[str, tf.Frame], ) -> tf.Frame: """Convert to transform graph Turns this element into a :mod:`skbot.transform` graph using the _dynamic_ constraints defined by this element. The resulting graph places a :class:`tf.Frame <skbot.transform.Frame>` at the position of each joint, link, sensor, etc., defined by this Element. It then connects these frames according to the dynamic constraints defined within this element, e.g., constraints from nested :class:`Joints <Joint>`. It differs from :func:`to_static_graph` in that all connections are dynamic. As a result, the resuling graph can have :class:`State` applied to it and it may be used for dynamic calculation, e.g., with :mod:`skbot.inverse_kinematics`. Parameters ---------- declared_frames : Dict[str, tf.Frame] The frames declared in the scope in which this element has been defined. seed: bool The seed to use when procedually generating elements of the simulation. This is currently limited to the `Population` element only. shape : tuple A tuple describing the shape of elements that the resulting graph should transform. This can be used to add batch dimensions to the graph, for example to perform vectorized computation on multiple instances of the same world in different states, or for batched coordinate transformation. Defaults to (3,), which is the shape of a single 3D vector in euclidian space. axis : int The axis along which elements are stored. The axis must have length 3 (since SDFormat describes 3 dimensional worlds), and all other axis are considered batch dimensions. Defaults to -1. apply_state: bool If True (default) each object's state is set according to `World.state` (if present). _scaffolding : Dict[str, tf.Frame] A dictionary of (connected) frames that used to determine the relative (initial) position of objects in the simulation. This parameter is for internal use and may be removed or change at any time without notice. Returns ------- frame_graph : tf.Frame A frame graph modelling the dynamic structure of this element. Notes ----- If this element contains children that are not dynamically connected to this element, they will be discarded. This function modifies ``declared_frames`` as a side-effect by appending any frames declared by this frame to it. """ if should_warn_unsupported(): warnings.warn( f"`{self.__class__.__name__}` does not implement `to_dynamic_graph` yet." ) return tf.Frame(3, name="missing") def declared_frames(self) -> Dict[str, tf.Frame]: """Frames contained in this element. Returns ------- frame_dict : Dict[str, tf.Frame] A (namespaced) dictionary of frames declared within this element. The dict key of each frame is the full (namespaced) name of the element in the corresponding SDF. Notes ----- Namespaces follow the SDFormat convention and are separated using `::`. """ if should_warn_unsupported(): warnings.warn( f"`{self.__class__.__name__}` does not implement `declared_frames` yet." ) return dict() @staticmethod def _prepare_standard_args( specific: Any, args_with_default: Dict[str, "ElementBase"] = None, list_args: Dict[str, Tuple[str, "ElementBase"]] = None, *, version: str, ) -> Dict[str, Any]: if args_with_default is None: args_with_default = dict() if list_args is None: list_args = dict() generic_args: Dict[str, Any] = dict() # convert arguments with default values for name, clazz in args_with_default.items(): if not hasattr(specific, name): continue if clazz in [StringElement, BoolElement, FloatElement, IntegerElement]: value = getattr(specific, name) if value == "__default__": continue elif value is not None: generic_args[name] = value else: continue elif getattr(specific, name) is None: generic_args[name] = clazz(sdf_version=version) else: generic_args[name] = clazz.from_specific( getattr(specific, name), version=version ) for their_name in list_args: our_name, clazz = list_args[their_name] if not hasattr(specific, their_name): generic_args[our_name] = [] continue generic_args[our_name] = [ clazz.from_specific(x, version=version) for x in getattr(specific, their_name) ] return generic_args class StringElement(ElementBase): """Plumbing for smoother conversion""" class FloatElement(ElementBase): """Plumbing for smoother conversion""" class IntegerElement(ElementBase): """Plumbing for smoother conversion""" class BoolElement(ElementBase): """Plumbing for smoother conversion""" class Pose(ElementBase): """Position and orientation of a simulated object A position (x,y,z) and orientation (roll, pitch yaw) with respect to the frame named in the relative_to attribute. Parameters ---------- value : str The numerical value of the pose. It is a string of 6 numbers separated by spaces. Default: "0 0 0 0 0 0" relative_to : str If specified, this pose is expressed in the named frame. The named frame must be declared within the same scope (world/model) as the element that has its pose specified by this tag. If missing, the pose is expressed in the frame of the parent XML element of the element that contains the pose. For exceptions to this rule and more details on the default behavior, see http://sdformat.org/tutorials?tut=pose_frame_semantics. Note that @relative_to merely affects an element's initial pose and does not affect the element's dynamic movement thereafter. .. versionadded:: SDFormat v1.8 New in v1.8: @relative_to may use frames of nested scopes. In this case, the frame is specified using `::` as delimiter to define the scope of the frame, e.g. `nested_model_A::nested_model_B::awesome_frame`. frame : str Old name for `relative_to`. .. deprecated:: SDFormat v1.7 """ def __init__( self, *, value: str = "0 0 0 0 0 0", relative_to: str = None, frame: str = None, sdf_version: str, ) -> None: super().__init__(sdf_version=sdf_version) self.value = np.fromstring(value, dtype=float, count=6, sep=" ") self.relative_to = relative_to if frame is not None: self.relative_to = frame if self.relative_to == "": self.relative_to = None @property def frame(self): warnings.warn( "`Pose.frame` is deprecated. Use `Pose.relative_to` instead.", DeprecationWarning, ) return self.relative_to @classmethod def from_specific(cls, specific: Any, *, version: str): if specific is None: return Pose(sdf_version=version) elif version in ["1.0", "1.2", "1.3", "1.4"]: return Pose(value=specific, sdf_version=version) elif version in ["1.5", "1.6"]: return Pose(value=specific.value, frame=specific.frame, sdf_version=version) else: return Pose( value=specific.value, relative_to=specific.relative_to, sdf_version=version, ) def to_tf_link(self) -> tf.Link: """tf.Link from **child** to **parent** frame""" offset = self.value[:3] angles = self.value[3:] return tf.CompundLink( [ tf.EulerRotation("xyz", angles), tf.Translation(offset), ] ) def to_static_graph( self, declared_frames: Dict[str, tf.Frame], child_name: str, *, shape: Tuple, axis: int = -1, ) -> None: parent_name = self.relative_to parent = declared_frames[parent_name] child = declared_frames[child_name] link = self.to_tf_link() link(child, parent) class PoseBearing(ElementBase): def __init__(self, *, pose: Pose = None) -> None: self.pose = pose if self.pose is None: self.pose = Pose() class NamedPoseBearing(PoseBearing): def __init__(self, *, name: str, pose: Pose = None) -> None: super().__init__(pose=pose) self.name = name """ Elements not yet represented: <?xml version='1.0' encoding='UTF-8'?> <xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <xsd:simpleType name="time"> <xsd:restriction base="xsd:string"> <xsd:whiteSpace value="collapse"/> <xsd:pattern value="\d+ \d+"/> </xsd:restriction> </xsd:simpleType> <xsd:simpleType name="color"> <xsd:restriction base="xsd:string"> <xsd:pattern value="(\s*\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s+){3}\+?(\d+(\.\d*)?|\.\d+|\d+\.\d+[eE][-\+]?[0-9]+)\s*"/> </xsd:restriction> </xsd:simpleType> </xsd:schema> """
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/generic_sdf/base.py
0.932928
0.576661
base.py
pypi
from typing import Dict, Any, Tuple from .base import ElementBase, Pose, StringElement from .... import transform as tf class Frame(ElementBase): """A frame of reference. Frames are coordinate frames that are rigidly attached to a rigid body (or inertial frame) and move together with it. Their primary purpose is to make it easier to specify the relative position of objects in the simulation. .. versionadded:: SDFormat v1.5 Parameters ---------- name : str Name of the frame. It must be unique whithin its scope (model/world), i.e., it must not match the name of another frame, link, joint, or model within the same scope. pose : Pose The initial position and orientation of this frame attached_to : str If specified, this frame is attached to the specified frame. The specified frame must be within the same scope and may be defined implicitly, i.e., the name of any //frame, //model, //joint, or //link within the same scope may be used. If missing, this frame is attached to the containing scope's frame. Within a //world scope this is the implicit world frame, and within a //model scope this is the implicit model frame. A frame moves jointly with the frame it is @attached_to. This is different from //pose/@relative_to. @attached_to defines how the frame is attached to a //link, //model, or //world frame, while //pose/@relative_to defines how the frame's pose is represented numerically. As a result, following the chain of @attached_to attributes must always lead to a //link, //model, //world, or //joint (implicitly attached_to its child //link). .. versionadded:: SDFormat v1.7 sdf_version : str The SDFormat version to use when constructing this element. Attributes ---------- name : str See ``Parameters`` section. pose : Pose See ``Parameters`` section. attached_to : str See ``Parameters`` section. """ def __init__( self, *, name: str, pose: Pose = None, attached_to: str = None, sdf_version: str, ) -> None: super().__init__(sdf_version=sdf_version) self.name = name self.pose = Pose(sdf_version=sdf_version) if pose is None else pose self.attached_to = attached_to if self.attached_to == "": self.attached_to = None @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": frame_args = {"name": specific.name} args_with_default = {"pose": Pose, "attached_to": StringElement} standard_args = cls._prepare_standard_args( specific, args_with_default, version=version ) frame_args.update(standard_args) return Frame(**frame_args, sdf_version=version) def declared_frames(self) -> Dict[str, tf.Frame]: return {self.name: tf.Frame(3, name=self.name)} def to_static_graph( self, declared_frames: Dict[str, tf.Frame], *, seed: int = None, shape: Tuple, axis: int = -1, ) -> tf.Frame: parent_name = self.pose.relative_to child_name = self.name parent = declared_frames[parent_name] child = declared_frames[child_name] link = self.pose.to_tf_link() link(child, parent) return declared_frames[self.name] def to_dynamic_graph( self, declared_frames: Dict[str, tf.Frame], *, seed: int = None, shape: Tuple, axis: int = -1, apply_state: bool = True, _scaffolding: Dict[str, tf.Frame], ) -> tf.Frame: parent_name = self.attached_to child_name = self.name parent = declared_frames[parent_name] child = declared_frames[child_name] parent_static = _scaffolding[parent_name] child_static = _scaffolding[child_name] link = tf.CompundLink(parent_static.links_between(child_static)) link(parent, child)
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/generic_sdf/frame.py
0.959602
0.536799
frame.py
pypi
from typing import List, Union, Dict, Any, Tuple import warnings from .base import ElementBase from .world import World from .actor import Actor from .model import Model from .light import Light from ..exceptions import ParseError from .... import transform as tf class Sdf(ElementBase): """SDFormat Root Element This element is a container for multiple simulation worlds (can be one) or for a single fragment of a world (Model, Actor, Light). Parameters ---------- payload : Union[List[World], Model, Light, Actor] The element contained in this SDF. This can be one :class:`Model`, one :class:`Actor`, one :class:`Light`, or a list of :class:`Worlds`. version : str The SDFormat version. worlds : List[World] The worlds contained in this SDF. .. deprecated:: SDFormat v1.8 Worlds, models, lights, and/or actors can no longer be combined. Use `payload` instead. models : List[Model] .. deprecated:: SDFormat v1.8 Starting with SDFormat v1.8 only a single model is supported. Use the `model` kwarg instead. The models contained in this SDF. lights : List[Light] .. deprecated:: SDFormat v1.8 Starting with SDFormat v1.8 only a single light is supported. Use the `light` kwarg instead. The lights contained in this SDF. actors : List[Actor] .. deprecated:: SDFormat v1.8 Starting with SDFormat v1.8 only a single actor is supported. Use the `actor` kwarg instead. The actors contained in this SDF. Attributes ---------- worlds : List[World] The worlds contained in the SDF file. model: Model The model contained in the SDF file. light: Light The light contained in the SDF file. actor: Actor The actor contained in the SDF file. version : str The SDFormat version. models : List[Model] .. deprecated:: SDFormat v1.8 Use the `Sdf.model` instead. lights : List[Light] .. deprecated:: SDFormat v1.8 Use the `Sdf.light` instead. actors : List[Actor] .. deprecated:: SDFormat v1.8 Use the `Sdf.actor` instead. """ def __init__( self, *, payload: Union[List[World], Model, Light, Actor] = None, version: str = "1.8", worlds: List[World] = None, models: List[Model] = None, lights: List[Light] = None, actors: List[Actor] = None, ) -> None: super().__init__(sdf_version=version) self.version = version self.worlds: List[World] = [] self._actors: List[Actor] = [] self._models: List[Model] = [] self._lights: List[Light] = [] if self.sdf_version == "1.8": if isinstance(payload, list) and all( [isinstance(x, World) for x in payload] ): self.worlds = payload elif isinstance(payload, Actor): self._actors.append(payload) elif isinstance(payload, Model): self._models.append(payload) elif isinstance(payload, Light): self._lights.append(payload) else: raise ParseError("Invalid `Sdf` element.") elif version in ["1.7", "1.6", "1.5", "1.4", "1.3"]: self.worlds.extend(worlds) self._models.extend(models) self._lights.extend(lights) self._actors.extend(actors) else: raise ParseError("`Sdf` does not exist prior to SDFormat v1.3.") for model in self._models: if model.pose.relative_to is None: model.pose.relative_to = "world" @property def actor(self) -> Actor: try: return self._actors[0] except IndexError: return None @property def model(self) -> Model: try: return self._models[0] except IndexError: return None @property def light(self) -> Light: try: return self._lights[0] except IndexError: return None # deprecated properties @property def actors(self) -> List[Actor]: warnings.warn( "`sdf.actors` is deprecated since SDFormat v1.8. Use `sdf.actor` instead.", DeprecationWarning, ) return self._actors @property def models(self) -> List[Model]: warnings.warn( "`sdf.models` is deprecated since SDFormat v1.8. Use `sdf.models` instead.", DeprecationWarning, ) return self._models @property def lights(self) -> List[Light]: warnings.warn( "`sdf.lights` is deprecated since SDFormat v1.8. Use `sdf.lights` instead.", DeprecationWarning, ) return self._lights @classmethod def from_specific(cls, sdf: Any, *, version: str) -> "Sdf": """Create a generic Sdf object from a specific one. Parameters ---------- sdf : Any The SDF object that should be turned into a generic object. It can come from any version of the specific SDFormat bindings provided by scikit-bot. version : str The version of the given SDF element. Returns ------- generic_sdf : Sdf The generic equivalent of the provided specific Sdf object. """ if version == "1.8": payload: Union[List[World], Model, Light, Actor] if sdf.world is not None and len(sdf.world) > 0: payload = [World.from_specific(x, version=version) for x in sdf.world] elif sdf.actor is not None: payload = Actor.from_specific(sdf.actor, version=version) elif sdf.model is not None: payload = Model.from_specific(sdf.model, version=version) elif sdf.light is not None: payload = Light.from_specific(sdf.light, version=version) else: raise ParseError("Can not convert `sdf` element without payload.") return Sdf(payload=payload, version=version) else: return Sdf( worlds=[World.from_specific(x, version=version) for x in sdf.world], actors=[Actor.from_specific(x, version=version) for x in sdf.actor], models=[Model.from_specific(x, version=version) for x in sdf.model], lights=[Light.from_specific(x, version=version) for x in sdf.light], version=version, ) def declared_frames( self, ) -> Dict[str, Union[List[Dict[str, tf.Frame]], Dict[str, tf.Frame]]]: declared_frames = { "worlds": [x.declared_frames() for x in self.worlds], "models": [x.declared_frames() for x in self._models], } if self.model is not None: declared_frames["model"] = declared_frames["models"][0] return declared_frames def to_static_graph( self, declared_frames: Dict[str, List[tf.Frame]], *, seed: int = None, shape: Tuple[int] = (3,), axis: int = -1, ) -> Dict[str, List[tf.Frame]]: graphs = { "worlds": list(), "models": list(), } for idx, world in enumerate(self.worlds): try: static_frames = declared_frames["worlds"][idx] except IndexError: break root = world.to_static_graph( static_frames, seed=seed, shape=shape, axis=axis ) graphs["worlds"].append(root) for idx, model in enumerate(self._models): try: static_frames = declared_frames["models"][idx] except IndexError: break if "world" not in static_frames: static_frames["world"] = tf.Frame(3, name="world") root = model.to_static_graph( static_frames, seed=seed, shape=shape, axis=axis ) graphs["models"].append(root) model.pose.to_static_graph( static_frames, "__model__", shape=shape, axis=axis ) return graphs def to_dynamic_graph( self, declared_frames: Dict[str, List[tf.Frame]], *, seed: int = None, shape: Tuple[int] = (3,), axis: int = -1, apply_state: bool = True, ) -> Dict[str, List[tf.Frame]]: graphs = { "worlds": list(), "models": list(), } scaffold = self.declared_frames() self.to_static_graph(scaffold, seed=seed, shape=shape, axis=axis) for idx, world in enumerate(self.worlds): try: frames = declared_frames["worlds"][idx] except IndexError: break root = world.to_dynamic_graph(frames, seed=seed, shape=shape, axis=axis) graphs["worlds"].append(root) for idx, model in enumerate(self._models): try: frames = declared_frames["models"][idx] except IndexError: break static_frames = scaffold["models"][idx] if "world" not in frames: frames["world"] = tf.Frame(3, name="world") root = model.to_dynamic_graph( frames, seed=seed, shape=shape, axis=axis, _scaffolding=static_frames ) graphs["models"].append(root) return graphs
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/generic_sdf/sdf.py
0.920061
0.456773
sdf.py
pypi
import warnings from typing import List, Union, Dict, Any, Tuple from itertools import chain import numpy as np from .base import ( BoolElement, ElementBase, FloatElement, Pose, StringElement, vector3, should_warn_unsupported, ) from .sensor import Sensor from .frame import Frame from .origin import Origin from .... import transform as tf class Joint(ElementBase): """A constraint between two rigid bodys. A joint connects two links with kinematic and dynamic properties. This defines a constraint between the two bodies, and constructing a :mod``transform graph <skbot.transform>`` using ``to_dynamic_graph`` will build this constraint into the underlying graph structure. Parameters ---------- name : str The name of the joint. type : str The type of joint, which must be one of the following: continuous A hinge joint that rotates around :class:`Joint.Axis` with a continuous range of motion. This means that the upper and lower axis limits are ignored. revolute a hinge joint that rotates around :class:`Joint.Axis` with a fixed range of motion. gearbox A geared revolute joints. revolute2 Two revolute joints connected in series. The first one rotates around :class:``Joint.Axis``, and the second one rotates around :class:``Joint.Axis``. prismatic A sliding joint that slides along :class:``Joint.Axis`` with a limited range of motion. ball A ball and socket joint. screw A 1DoF joint with coupled sliding and rotational motion. universal Like a joint with type ``ball`` but constrains one degree of freedom. fixed A joint with zero DoF that rigidly connects two links. parent : Union[str, Joint.Parent] The first :class:`Link` that this joint constraints. It may be set to "world", in which case the movement of the rigid body in ``Joint.child`` is constrained relative to the inertial world frame. .. versionchanged:: SDFormat v1.7 Parent may now be set to "world" and, if so, will connect to the inertial world frame. .. versionchanged:: SDFormat v1.2 Parent is now a string instead of :class:`Joint.Parent`. child : Union[str, Joint.Child] The second :class:`Link` that this joint constraints. .. versionchanged:: SDFormat v1.2 Child is now a string instead of :class:`Joint.Child`. pose : Pose The links's initial position (x,y,z) and orientation (roll, pitch, yaw). .. versionadded:: SDFormat 1.2 gearbox_ratio : float Parameter for gearbox joints. Given theta_1 and theta_2 defined in description for gearbox_reference_body, ``theta_2 = -gearbox_ratio * theta_1``. Default: 1.0 .. versionadded:: SDFormat v1.4 gearbox_reference_body : str Parameter for gearbox joints. Gearbox ratio is enforced over two joint angles. First joint angle (theta_1) is the angle from the gearbox_reference_body to the parent link defined by :class:`Joint.Axis` and the second joint angle (theta_2) is the angle from the gearbox_reference_body to the child link defined by :class:`Joint.Axis`. .. versionadded:: SDFormat v1.4 thread_pitch : float Parameter for screw joints. The amount of linear displacement for each full rotation of the joint. axis : Joint.Axis Configuration parameters for joints that rotate around or translate along at least one axis. axis2 : Joint.Axis Configuration parameters for joints that rotate around or translate along at least two axis. physics : Joint.Physics Configuration parameters for various physics engines. (Currently: ODE and Simbody.) frames : List[Frame] A list of frames of reference in which poses may be expressed. .. deprecated:: SDFormat v1.7 Use :attr:`Model.frame` instead. .. versionadded:: SDFormat v1.5 sensors : List[Sensor] A list of sensors attached to this joint. .. versionadded:: SDFormat v1.4 sdf_version : str The SDFormat version to use when constructing this element. origin : Origin The joint's origin. .. deprecated:: SDFormat v1.2 Use ``Joint.pose`` instead. Attributes ---------- name : str See ``Parameters`` section. type : str See ``Parameters`` section. parent : str See ``Parameters`` section. child : str See ``Parameters`` section. pose : Pose See ``Parameters`` section. gearbox_ratio : float See ``Parameters`` section. gearbox_reference_body : str See ``Parameters`` section. thread_pitch : float See ``Parameters`` section. axis : Joint.Axis See ``Parameters`` section. axis2 : Joint.Axis See ``Parameters`` section. physics : Joint.Physics See ``Parameters`` section. frames : List[Frame] See ``Parameters`` section. sensors : List[Sensor] See ``Parameters`` section. sdf_version : str See ``Parameters`` section. origin : Origin See ``Parameters`` section. Notes ----- A joint defines an implicit frame of reference to which other :class:`Frame`s may be ``attached_to``. As such its name must be unique among all frames and frame-bearing elements. """ def __init__( self, *, name: str, type: str, parent: Union[str, "Joint.Parent"], child: Union[str, "Joint.Child"], origin: Origin = None, pose: Pose = None, gearbox_ratio: float = 1.0, gearbox_reference_body: str = None, thread_pitch: float = 1.0, axis: "Joint.Axis" = None, axis2: "Joint.Axis" = None, physics: "Joint.Physics" = None, frames: List[Frame] = None, sensors: List[Sensor] = None, sdf_version: str, ) -> None: super().__init__(sdf_version=sdf_version) self.name = name self.type = type if origin is None: self._origin = Origin(sdf_version=sdf_version) elif sdf_version == "1.0": self._origin = origin else: warnings.warn( "`origin` is deprecated. Use `pose` instead.", DeprecationWarning ) self._origin = origin if sdf_version == "1.0": self.pose = self._origin.pose elif pose is None: self.pose = Pose(sdf_version=sdf_version) else: self.pose = pose self.gearbox_ratio = gearbox_ratio self.gearbox_reference_body = gearbox_reference_body self.thread_pitch = thread_pitch self.axis = Joint.Axis(sdf_version=sdf_version) if axis is None else axis self.axis2 = Joint.Axis(sdf_version=sdf_version) if axis2 is None else axis2 self.physics = ( Joint.Physics(sdf_version=sdf_version) if physics is None else physics ) self._frames = [] if frames is None else frames self.sensors = [] if sensors is None else sensors self._origin.pose = self.pose if isinstance(parent, Joint.Parent): self.parent = parent.link else: self.parent = parent if isinstance(child, Joint.Child): self.child = child.link else: self.child = child if self.axis._use_parent_model_frame: self.axis.xyz.expressed_in = self.parent elif self.axis.xyz.expressed_in is None: self.axis.xyz.expressed_in = self.child if self.axis2._use_parent_model_frame: self.axis2.xyz.expressed_in = self.parent elif self.axis2.xyz.expressed_in is None: self.axis2.xyz.expressed_in = self.child for frame in self._frames: if frame.attached_to is None: frame.attached_to = self.name if frame.pose.relative_to is None: frame.pose.relative_to = self.name for sensor in sensors: if sensor.pose.relative_to is None: sensor.pose.relative_to = self.name if sensor.camera.pose.relative_to is None: sensor.camera.pose.relative_to = f"{self.name}::{sensor.name}" for frame in sensor.camera._frames: if frame.pose.relative_to is None: frame.pose.relative_to = ( f"{self.name}::{sensor.name}::{sensor.camera.name}" ) if frame.attached_to is None: frame.attached_to = f"{self.name}::{sensor.name}" for frame in sensor._frames: if frame.pose.relative_to is None: frame.pose.relative_to = f"{self.name}::{sensor.name}" if frame.attached_to is None: frame.attached_to = f"{self.name}::{sensor.name}" @property def origin(self): warnings.warn( "`Joint.origin` is deprecated since SDFormat v1.2." " Use `Joint.pose` instead.", DeprecationWarning, ) return self._origin @property def frames(self): warnings.warn( "`Link.frames` is deprecated since SDF v1.7." " Use `Model.frames` instead and set `Frame.attached_to`" " to the name of this joint.", DeprecationWarning, ) return self._frames @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": joint_args = { "name": specific.name, "type": specific.type, "parent": specific.parent, "child": specific.child, } args_with_default = { "origin": Origin, "pose": Pose, "gearbox_ratio": FloatElement, "gearbox_reference_body": StringElement, "thread_pitch": FloatElement, "axis": Joint.Axis, "axis2": Joint.Axis, "physics": Joint.Physics, } list_args = {"frame": ("frames", Frame), "sensor": ("sensors", Sensor)} standard_args = cls._prepare_standard_args( specific, args_with_default, list_args, version=version ) joint_args.update(standard_args) return Joint(**joint_args, sdf_version=version) def declared_frames(self) -> Dict[str, tf.Frame]: joint_frame = tf.Frame(3, name=self.name) declared_frames = { self.name: joint_frame, self.name + "_child": joint_frame, self.name + "_parent": tf.Frame(3, name=self.name + "_parent"), } for el in chain(self._frames): declared_frames.update(el.declared_frames()) for sensor in self.sensors: for name, frame in sensor.declared_frames().items(): declared_frames[f"{self.name}::{name}"] = frame return declared_frames def to_static_graph( self, declared_frames: Dict[str, tf.Frame], *, seed: int = None, shape: Tuple, axis: int = -1, ) -> tf.Frame: parent_name = self.pose.relative_to joint_child = self.name + "_child" joint_parent = self.name + "_parent" parent = declared_frames[parent_name] joint_child = declared_frames[joint_child] joint_parent = declared_frames[joint_parent] link = self.pose.to_tf_link() link(joint_child, parent) link(joint_parent, parent) for frame in self._frames: frame.to_static_graph(declared_frames, seed=seed, shape=shape, axis=axis) for sensor in self.sensors: sensor.to_static_graph( declared_frames, f"{self.name}::{sensor.name}", seed=seed, shape=shape, axis=axis, ) return declared_frames[self.name] def to_dynamic_graph( self, declared_frames: Dict[str, tf.Frame], *, seed: int = None, shape: Tuple, axis: int = -1, apply_state: bool = True, _scaffolding: Dict[str, tf.Frame], ) -> tf.Frame: parent_name = self.parent child_name = self.child joint_name = self.name joint_name_child = self.name + "_child" joint_name_parent = self.name + "_parent" parent = declared_frames[parent_name] child = declared_frames[child_name] joint_parent = declared_frames[joint_name_parent] joint_child = declared_frames[joint_name_child] parent_static = _scaffolding[parent_name] joint_static = _scaffolding[joint_name] child_static = _scaffolding[child_name] link = tf.CompundLink(parent_static.links_between(joint_static)) link(parent, joint_parent) joint_link: tf.Link = self.to_tf_link(_scaffolding, shape=shape, axis=axis) joint_link(joint_child, joint_parent) link = tf.CompundLink(joint_static.links_between(child_static)) link(joint_child, child) for el in chain(self._frames): el.to_dynamic_graph( declared_frames, seed=seed, shape=shape, axis=axis, apply_state=apply_state, _scaffolding=_scaffolding, ) for sensor in self.sensors: parent_name = self.name child_name = f"{self.name}::{sensor.name}" parent = declared_frames[parent_name] child = declared_frames[child_name] parent_static = _scaffolding[parent_name] child_static = _scaffolding[child_name] link = tf.CompundLink(parent_static.links_between(child_static)) link(parent, child) sensor.to_dynamic_graph( declared_frames, f"{self.name}::{sensor.name}", seed=seed, shape=shape, axis=axis, apply_state=apply_state, _scaffolding=_scaffolding, ) return declared_frames[self.name] def to_tf_link( self, scaffolding: Dict[str, tf.Frame], *, shape: Tuple = (3,), axis=-1 ) -> tf.Link: """tf.Link from **child** to **parent** frame Parameters ---------- scaffolding : Dict[str, tf.Frame] A static graph that allows the resolution of ``Joint.Axis.Xyz.expressed_in`` (``Joint.Axis.Xyz.Value`` needs to be converted to the the implicit frame of ``Joint.child`` as per the spec.) shape : tuple A tuple describing the shape of elements that the resulting graph should transform. This can be used to add batch dimensions to the graph, for example to perform vectorized computation on multiple instances of the same world in different states, or for batched coordinate transformation. Defaults to (3,), which is the shape of a single 3D vector in euclidian space. axis : int The axis along which elements are stored. The axis must have length 3 (since SDFormat describes 3 dimensional worlds), and all other axis are considered batch dimensions. Defaults to -1. Returns ------- joint_link : tf.Link A parameterized link that represents transformation from the joint's child into the joint's parent using the constraint defined by this joint. """ expressed_frame = scaffolding[self.axis.xyz.expressed_in] child_frame = scaffolding[self.child] joint_axis1 = expressed_frame.transform(self.axis.xyz.value, child_frame) if self.type == "continuous": if should_warn_unsupported(): warnings.warn("Hinge joints have not been added yet.") link = tf.Translation((0, 0, 0)) elif self.type == "revolute": angle = np.clip(0, self.axis.limit.lower, self.axis.limit.upper) link = tf.RotationalJoint( joint_axis1, angle=angle, upper_limit=self.axis.limit.upper, lower_limit=self.axis.limit.lower, axis=axis, ) elif self.type == "hinge": if should_warn_unsupported(): warnings.warn("Hinge joints have not been added yet.") link = tf.Translation((0, 0, 0)) elif self.type == "gearbox": if should_warn_unsupported(): warnings.warn("Gearbox joints have not been added yet.") link = tf.Translation((0, 0, 0)) elif self.type == "revolute2": if should_warn_unsupported(): warnings.warn("Revolute2 type joint is not added yet.") link = tf.Translation((0, 0, 0)) elif self.type == "prismatic": amount = np.clip(1, self.axis.limit.lower, self.axis.limit.upper) link = tf.PrismaticJoint( joint_axis1, amount=amount, upper_limit=self.axis.limit.upper, lower_limit=self.axis.limit.lower, axis=axis, ) elif self.type == "ball": if should_warn_unsupported(): warnings.warn("Ball joints have not been added yet.") link = tf.Translation((0, 0, 0)) elif self.type == "screw": if should_warn_unsupported(): warnings.warn("Screw joints have not been added yet.") link = tf.Translation((0, 0, 0)) elif self.type == "universal": if should_warn_unsupported(): warnings.warn("Universal joints have not been added yet.") link = tf.Translation((0, 0, 0)) elif self.type == "fixed": link = tf.Translation((0, 0, 0)) else: raise ValueError(f"Unknown Joint type: {self.type}") return link class Parent(ElementBase): def __init__(self, *, link: str, sdf_version: str) -> None: super().__init__(sdf_version=sdf_version) self.link = link @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": return Joint.Parent(link=specific.link, version=version) class Child(ElementBase): def __init__(self, *, link: str, sdf_version: str) -> None: super().__init__(sdf_version=sdf_version) self.link = link @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": return Joint.Parent(link=specific.link, version=version) class Axis(ElementBase): """Parameters for rotating and/or translating joints. Parameters ---------- initial_position : float Default joint position for this joint axis. .. deprecated:: SDFormat v1.8 Use `World.State` instead to set the initial position. .. versionadded:: SDFormat v1.6 xyz: Union[str, Joint.Axis.Xyz] The direction of the Axis. .. versionchanged:: SDFormat v1.7 ``xyz`` is now a class. The direction vector is stored in ``xyz.value``. use_parent_model_frame : bool Flag to interpret the axis xyz element in the parent model frame instead of joint frame. Provided for Gazebo compatibility (see https://github.com/osrf/gazebo/issue/494 ). Default is: ``False``. .. deprecated:: SDFormat v1.7 Use :attr:`Joint.Axis.Xyz.expressed_in` instead. .. versionadded:: SDFormat v1.5 dynamics: Joint.Axis.Dynamics Dynamic Parameters related to the Axis. limit : Joint.Axis.Limit Constraints applied to parameters of this joint, e.g., upper/lower limits. .. versionchanged:: SDFormat v1.6 The limit element is now optional. sdf_version : str The SDFormat version to use when constructing this element. Attributes ---------- initial_position : float See ``Parameters`` section. xyz: Joint.Axis.Xyz See ``Parameters`` section. dynamics: Joint.Axis.Dynamics See ``Parameters`` section. limit : Joint.Axis.Limit See ``Parameters`` section. """ def __init__( self, *, initial_position: float = 0, xyz: Union[str, "Joint.Axis.Xyz"] = None, use_parent_model_frame: bool = False, dynamics: "Joint.Axis.Dynamics" = None, limit: "Joint.Axis.Limit" = None, sdf_version: str, ) -> None: super().__init__(sdf_version=sdf_version) self.initial_position = initial_position if sdf_version in ["1.0", "1.2", "1.3", "1.4", "1.5", "1.6"]: if xyz is None: # old default xyz = "0 0 1" self.xyz = Joint.Axis.Xyz( value=xyz, expressed_in=None, sdf_version=sdf_version ) elif xyz is None: self.xyz = Joint.Axis.Xyz(sdf_version=sdf_version) else: self.xyz = xyz self._use_parent_model_frame = use_parent_model_frame self.dynamics = ( Joint.Axis.Dynamics(sdf_version=sdf_version) if dynamics is None else dynamics ) self.limit = ( Joint.Axis.Limit(sdf_version=sdf_version) if limit is None else limit ) @property def use_parent_model_frame(self): warnings.warn( "`Joint.Axis.use_parent_model_frame` is deprecated." " Use `Joint.Axis.Xyz.expressed_in` instead.", DeprecationWarning, ) return self._use_parent_model_frame @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": args_with_default = { "initial_position": FloatElement, "xyz": Joint.Axis.Xyz, "use_parent_model_Frame": BoolElement, "dynamics": Joint.Axis.Dynamics, "limit": Joint.Axis.Limit, } if version in ["1.0", "1.2", "1.3", "1.4", "1.5", "1.6"]: args_with_default["xyz"] = StringElement standard_args = cls._prepare_standard_args( specific, args_with_default, version=version ) return Joint.Axis(**standard_args, sdf_version=version) class Xyz(ElementBase): """The direction of an axis. Represents the x,y,z components of the axis unit vector. The vector should be normalized. .. versionadded:: SDFormat v1.7 Parameters ---------- value : str The numerical value of the direction. Default: "0 0 1". expressed_in : str The frame of reference in which the direction is expressed. sdf_version : str The SDFormat version to use when constructing this element. Attributes ---------- value : np.ndarray See ``Parameters`` section. expressed_in : str See ``Parameters`` section. """ def __init__( self, *, value: str = "0 0 1", expressed_in: str = None, sdf_version: str, ) -> None: super().__init__(sdf_version=sdf_version) self.value = vector3(value) self.expressed_in = expressed_in if self.expressed_in == "": self.expressed_in = None @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": return Joint.Axis.Xyz( value=specific.value, expressed_in=specific.expressed_in, sdf_version=version, ) class Dynamics(ElementBase): """Dynamic Parameters along an axis. An element specifying physical properties of the joint related to the axis. These values are used to specify modeling properties of the joint, particularly useful for simulation. Parameters ---------- damping : float Viscous damping coefficient along this axis. The default is ``0``. friction : float Static friction along this axis. The default is ``0``. spring_reference : float The neutral position of the spring along this axis. The default is ``0``. .. versionadded:: SDFormat v1.5 spring_stiffness : float The stiffness of the spring along this axis. The default is ``0``. .. versionadded:: SDFormat v1.5 sdf_version : str The SDFormat version to use when constructing this element. The default is ``0``. Attributes ---------- damping : float See ``Parameters`` section. friction : float See ``Parameters`` section. spring_reference : float See ``Parameters`` section. spring_stiffness : float See ``Parameters`` section. """ def __init__( self, *, damping: float = 0, friction: float = 0, spring_reference: float = 0, spring_stiffness: float = 0, sdf_version: str, ) -> None: super().__init__(sdf_version=sdf_version) self.damping = damping self.friction = friction self.spring_reference = spring_reference self.spring_stiffness = spring_stiffness @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": args_with_default = { "damping": FloatElement, "friction": FloatElement, "spring_reference": FloatElement, "spring_stiffness": FloatElement, } standard_args = cls._prepare_standard_args( specific, args_with_default, version=version ) return Joint.Axis.Dynamics(**standard_args, sdf_version=version) class Limit(ElementBase): """Joint limits along an axis. This class specifies limites/constraints for joint parameters along the containing axis. Parameters ---------- lower : float A lower limit for any joint parameter along this axis. In radians for revolute joints and in meters for prismatic joints. Default: ``-1e16``. upper : float A upper limit for any joint parameter along this axis. In radians for revolute joints and in meters for prismatic joints. Default: ``1e16``. effort : float The maximum effort that may be applied to/by a joint along this axis. This limit is not enforced if its value is negative. Default: ``-1``. .. versionchanged:: SDFormat v1.3 The default changed from 0 to -1. velocity : float The maximum velocity (angular or directional respectively) that may be applied to/by this joint. This limit is not enforced if its value is negative. Default: ``-1``. .. versionchanged:: SDFormat v1.3 The default changed from 0 to -1. stiffness : float Joint stop stiffness. Default: ```1e8``. .. versionadded:: SDFormat v1.4 dissipation : float Joint stop dissipation. Default: ```1.0``. .. versionadded:: SDFormat v1.4 sdf_version : str The SDFormat version to use when constructing this element. Attributes ---------- lower : float See ``Parameters`` section. upper : float See ``Parameters`` section. effort : float See ``Parameters`` section. velocity : float See ``Parameters`` section. stiffness : float See ``Parameters`` section. dissipation : float See ``Parameters`` section. """ def __init__( self, *, lower: float = -1e16, upper: float = 1e16, effort: float = -1, velocity: float = -1, stiffness: float = 1e8, dissipation: float = 1.0, sdf_version: str, ) -> None: super().__init__(sdf_version=sdf_version) self.lower = lower self.upper = upper if effort < 0: self.effort = float("inf") else: self.effort = effort if velocity < 0: self.velocity = float("inf") else: self.velocity = velocity self.stiffness = stiffness self.dissipation = dissipation @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": args_with_default = { "lower": FloatElement, "upper": FloatElement, "effort": FloatElement, "velocity": FloatElement, "stiffness": FloatElement, "dissipation": FloatElement, } standard_args = cls._prepare_standard_args( specific, args_with_default, version=version ) return Joint.Axis.Limit(**standard_args, sdf_version=version) class Physics(ElementBase): """ <element name="physics" required="0"> <description>Parameters that are specific to a certain physics engine.</description> <element name="simbody" required="0"> <description>Simbody specific parameters</description> <element name="must_be_loop_joint" type="bool" default="false" required="0"> <description>Force cut in the multibody graph at this joint.</description> </element> </element> <element name="ode" required="0"> <description>ODE specific parameters</description> <element name="cfm_damping" type="bool" default="false" required="0"> <description>If cfm damping is set to true, ODE will use CFM to simulate damping, allows for infinite damping, and one additional constraint row (previously used for joint limit) is always active.</description> </element> <element name="implicit_spring_damper" type="bool" default="false" required="0"> <description>If implicit_spring_damper is set to true, ODE will use CFM, ERP to simulate stiffness and damping, allows for infinite damping, and one additional constraint row (previously used for joint limit) is always active. This replaces cfm_damping parameter in SDFormat 1.4.</description> </element> <element name="fudge_factor" type="double" default="0" required="0"> <description>Scale the excess for in a joint motor at joint limits. Should be between zero and one.</description> </element> <element name="cfm" type="double" default="0" required="0"> <description>Constraint force mixing for constrained directions</description> </element> <element name="erp" type="double" default="0.2" required="0"> <description>Error reduction parameter for constrained directions</description> </element> <element name="bounce" type="double" default="0" required="0"> <description>Bounciness of the limits</description> </element> <element name="max_force" type="double" default="0" required="0"> <description>Maximum force or torque used to reach the desired velocity.</description> </element> <element name="velocity" type="double" default="0" required="0"> <description>The desired velocity of the joint. Should only be set if you want the joint to move on load.</description> </element> <element name="limit" required="0"> <description></description> <element name="cfm" type="double" default="0.0" required="1"> <description>Constraint force mixing parameter used by the joint stop</description> </element> <element name="erp" type="double" default="0.2" required="1"> <description>Error reduction parameter used by the joint stop</description> </element> </element> <element name="suspension" required="0"> <description></description> <element name="cfm" type="double" default="0.0" required="1"> <description>Suspension constraint force mixing parameter</description> </element> <element name="erp" type="double" default="0.2" required="1"> <description>Suspension error reduction parameter</description> </element> </element> </element> <element name="provide_feedback" type="bool" default="false" required="0"> <description>If provide feedback is set to true, physics engine will compute the constraint forces at this joint.</description> </element> </element> <!-- End Physics --> """ def __init__( self, *, simbody: "Joint.Physics.Simbody" = None, ode: "Joint.Physics.Ode" = None, provide_feedback: bool = False, sdf_version: str, ) -> None: if should_warn_unsupported(): warnings.warn("`Joint.Physics` is not implemented yet.") super().__init__(sdf_version=sdf_version) class Simbody(ElementBase): def __init__( self, *, must_be_loop_joint: bool = False, sdf_version: str, ) -> None: if should_warn_unsupported(): warnings.warn("`Joint.Physics.Simbody` is not implemented yet.") super().__init__(sdf_version=sdf_version) class Ode(ElementBase): def __init__( self, *, provide_feedback: bool = False, cfm_damping: bool = False, implicit_spring_damper: bool = False, fudge_factor: float = 0, cfm: float = 0, erp: float = 0.2, bounce: float = 0, max_force: float = 0, velocity: float = 0, limit: "Joint.Physics.Ode.Limit" = None, suspension: "Joint.Physics.Ode.Suspension" = None, sdf_version: str, ) -> None: if should_warn_unsupported(): warnings.warn("`Joint.Physics.Ode` is not implemented yet.") super().__init__(sdf_version=sdf_version) class Limit(ElementBase): def __init__( self, *, cfm: float = 0, erp: float = 0.2, sdf_version: str, ) -> None: if should_warn_unsupported(): warnings.warn( "`Joint.Physics.Ode.Limit` is not implemented yet." ) super().__init__(sdf_version=sdf_version) class Suspension(ElementBase): def __init__( self, *, cfm: float = 0, erp: float = 0.2, sdf_version: str, ) -> None: if should_warn_unsupported(): warnings.warn( "`Joint.Physics.Ode.Suspension` is not implemented yet." ) super().__init__(sdf_version=sdf_version)
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/generic_sdf/joint.py
0.927831
0.583203
joint.py
pypi
import warnings from typing import DefaultDict, List, Dict, Any, Tuple, Union from .base import ElementBase, FloatElement, IntegerElement, Pose, StringElement from .frame import Frame from .... import transform as tf from ...transformations import FrustumProjection class Camera(ElementBase): """A Camera Sensor. This element describes the parameters of a perspective camera system with optional lense, noise, and distortion effects. Contrary to common formulations the camera's direction of view is along the x-axis and the image plane runs parallel to the y-z-plane. If u and v describe the two axis of the of the image plane, then the u-axis runs along the negative y axis, and the v-axis runs along the negative z-axis. The origin of the image plane is along the top left corner of the viewing frustum. Parameters ---------- name : str The name of the camera. Default: ``camera`` .. versionadded:: SDFormat 1.3 pose : Pose The camera's initial position (x,y,z) and orientation (roll, pitch, yaw). .. versionadded:: SDFormat 1.3 horizontal_fov : Union[float, Camera.HorizontalFov] The viewing frustum's horizontal angle of view along the image's u-axis or world's y-axis. Default: ``1.047``. .. versionchanged:: SDFormat 1.2 horizontal_fov is now a float instead of a class. image : Camera.Image Layout of the captured images (shape and color format). clip : Camera.Clip Near and Far clip plane of the camera. save : Camera.Save Configuration parameters related to saving rendered images. depth_camera : Camera.DepthCamera Configuration parameters related to the depth camera. noise : Camera.Noise Parameters for the noise model. .. versionadded:: SDFormat 1.4 distortion : Camera.Distortion Parameters for the distortion model. .. versionadded:: SDFormat 1.5 lense : Camera.Lense Parameters for the lense model. .. versionadded:: SDFormat 1.5 visibility_mask: int Visibility mask of a camera. When (camera's visibility_mask & visual's visibility_flags) evaluates to non-zero, the visual will be visible to the camera. .. versionadded:: SDFormat 1.7 sdf_version : str The SDFormat version to use when constructing this element. frames : List[Frame] A list of frames of reference in which poses may be expressed. .. deprecated:: SDFormat v1.7 Use :attr:`Model.frame` instead. .. versionadded:: SDFormat v1.5 Attributes ---------- name : str See ``Parameters`` section. pose : Pose See ``Parameters`` section. horizontal_fov : Union[float, Camera.HorizontalFov] See ``Parameters`` section. image : Camera.Image See ``Parameters`` section. clip : Camera.Clip See ``Parameters`` section. save : Camera.Save See ``Parameters`` section. depth_camera : Camera.DepthCamera See ``Parameters`` section. noise : Camera.Noise See ``Parameters`` section. distortion : Camera.Distortion See ``Parameters`` section. lense : Camera.Lense See ``Parameters`` section. visibility_mask: int See ``Parameters`` section. Notes ----- The frustum's vertical angle of view (along the v-axis / z-axis) chosen using ``horizontal_fov`` and the pixel dimension, i.e., the aspect ratio, of the image. """ def __init__( self, *, name: str = "camera", pose: Pose = None, horizontal_fov: Union[float, "Camera.HorizontalFov"] = 1.047, image: "Camera.Image" = None, clip: "Camera.Clip" = None, save: "Camera.Save" = None, depth_camera: "Camera.DepthCamera" = None, noise: "Camera.Noise" = None, distortion: "Camera.Distortion" = None, lense: "Camera.Lense" = None, frames: List[Frame] = None, visibility_mask: int = 4294967295, sdf_version: str, ) -> None: super().__init__(sdf_version=sdf_version) self.name = name self.pose = Pose(sdf_version=sdf_version) if pose is None else pose if sdf_version == "1.0": self.horizontal_fov = ( Camera.HorizontalFov(sdf_version=sdf_version) if horizontal_fov is None else horizontal_fov ) else: self.horizontal_fov = horizontal_fov self.image = Camera.Image(sdf_version=sdf_version) if image is None else image self.clip = Camera.Clip(sdf_version=sdf_version) if clip is None else clip self.save = Camera.Save(sdf_version=sdf_version) if save is None else save self.depth_camera = ( Camera.DepthCamera(sdf_version=sdf_version) if depth_camera is None else depth_camera ) self.noise = Camera.Noise(sdf_version=sdf_version) if noise is None else noise self.distortion = ( Camera.Distortion(sdf_version=sdf_version) if distortion is None else distortion ) self.lense = Camera.Lense(sdf_version=sdf_version) if lense is None else lense self._frames = [] if frames is None else frames self.visibility_mask = visibility_mask @property def frames(self): warnings.warn( "`Sensor.frames` is deprecated since SDF v1.7." " Use `Model.frames` instead and set `Frame.attached_to` to the name of this link.", DeprecationWarning, ) return self._frames @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": # camera_args = {"visibility_mask": specific.visibility_mask} default_args = { "name": StringElement, "pose": Pose, "image": Camera.Image, "clip": Camera.Clip, "save": Camera.Save, "depth_camera": Camera.DepthCamera, "noise": Camera.Noise, "distortion": Camera.Distortion, "lense": Camera.Lense, "visbility_mask": IntegerElement, } if version == "1.0": default_args["horizontal_fov"] = Camera.HorizontalFov else: default_args["horizontal_fov"] = FloatElement list_args = {"frame": ("frames", Frame)} standard_args = cls._prepare_standard_args( specific, default_args, list_args, version=version ) return Camera(**standard_args, sdf_version=version) def declared_frames(self) -> Dict[str, tf.Frame]: declared_frames = { self.name: tf.Frame(3, name=self.name), "pixel_space": tf.Frame(2, name="pixel_space"), } for frame in self._frames: declared_frames.update(frame.declared_frames()) return declared_frames def to_static_graph( self, declared_frames: Dict[str, tf.Frame], sensor_frame: str, *, seed: int = None, shape: Tuple, axis: int = -1, ) -> tf.Frame: self.pose.to_static_graph( declared_frames, sensor_frame + f"::{self.name}", shape=shape, axis=axis ) if self.sdf_version == "1.0": hfov = self.horizontal_fov.angle else: hfov = self.horizontal_fov parent = declared_frames[sensor_frame + f"::{self.name}"] child = declared_frames[sensor_frame + "::pixel_space"] projection = FrustumProjection(hfov, (self.image.height, self.image.width)) projection(parent, child) for frame in self._frames: frame.pose.to_static_graph( declared_frames, sensor_frame + f"::{frame.name}", shape=shape, axis=axis, ) return declared_frames[sensor_frame + f"::{self.name}"] def to_dynamic_graph( self, declared_frames: Dict[str, tf.Frame], sensor_frame: str, *, seed: int = None, shape: Tuple, axis: int = -1, apply_state: bool = True, _scaffolding: Dict[str, tf.Frame], ) -> tf.Frame: parent_name = sensor_frame child_name = sensor_frame + f"::{self.name}" parent = declared_frames[parent_name] child = declared_frames[child_name] parent_static = _scaffolding[parent_name] child_static = _scaffolding[child_name] link = tf.CompundLink(parent_static.links_between(child_static)) link(parent, child) if self.sdf_version == "1.0": hfov = self.horizontal_fov.angle else: hfov = self.horizontal_fov parent = declared_frames[sensor_frame + f"::{self.name}"] child = declared_frames[sensor_frame + "::pixel_space"] projection = FrustumProjection(hfov, (self.image.height, self.image.width)) projection(parent, child) return declared_frames[sensor_frame + f"::{self.name}"] class HorizontalFov(ElementBase): def __init__(self, *, angle: float = 1.047, sdf_version: str) -> None: super().__init__(sdf_version=sdf_version) self.angle = angle @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": return Camera.HorizontalFov(angle=specific.angle, sdf_version=version) class Image(ElementBase): """Image shape and color format An image is a rectangular subset of a 2D plane measured in pixels. Coordinates on this plane are referred to using a two dimensional coordinate system with basis vectors u and v (the uv-plane). Parameters ---------- width : int Number of pixels along the v-axis. Default: ``320``. height : int Number of pixels along the u-axis. Default: ``240``. format : str The data format of the color channel. This value determines the number of channels, their order, and their meaning. Possible values are: L8, L16, R_FLOAT16, R_FLOAT32, R8G8B8, B8G8R8, BAYER_RGGB8, BAYER_BGGR8, BAYER_GBRG8, BAYER_GRBG8. Default: ``R8G8B8``. .. versionadded:: SDFormat v1.7 Formats: L16, R_FLOAT16, R_FLOAT32 sdf_version : str The SDFormat version to use when constructing this element. Attributes ---------- width : int See ``Parameters`` section. height : int See ``Parameters`` section. format : str See ``Parameters`` section. """ def __init__( self, *, width: int = 320, height: int = 240, format: str = "R8G8B8", sdf_version: str, ) -> None: super().__init__(sdf_version=sdf_version) self.width = width self.height = height self.format = format @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": return Camera.Image( width=specific.width, height=specific.height, format=specific.format, sdf_version=version, ) class Clip(ElementBase): """Near and Far Clipping distance. Parameters ---------- near : float Near clip distance. Default: ``0.1``. far : float Far clip distance. Default: ``100``. sdf_version : str The SDFormat version to use when constructing this element. Attributes ---------- near : float See ``Parameters`` section. far : float See ``Parameters`` section. """ def __init__( self, *, near: float = 0.1, far: float = 100, sdf_version: str ) -> None: super().__init__(sdf_version=sdf_version) self.near = near self.far = far @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": return Camera.Clip( near=specific.near, far=specific.far, sdf_version=version ) class Save(ElementBase): """Save/Export frames as images. Parameters ---------- enabled : bool Enable export as images. Default: ``False``. path : str The path name which will hold the frame data. If path name is relative, then directory is relative to current working directory. Default: None sdf_version : str The SDFormat version to use when constructing this element. Attributes ---------- enabled : bool See ``Parameters`` section. path : str See ``Parameters`` section. """ def __init__( self, *, enabled: bool = False, path: str = None, sdf_version: str ) -> None: super().__init__(sdf_version=sdf_version) self.enabled = enabled self.path = path @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": return Camera.Save( enabled=specific.enabled, path=specific.path, sdf_version=version ) class DepthCamera(ElementBase): """Depth Camera configuration Parameters ---------- output : str The type of data to output. Default: ``depths``. clip: Camera.Clip Depth camera clipping distance. sdf_version : str The SDFormat version to use when constructing this element. Attributes ---------- output : str See ``Parameters`` section. clip: Camera.Clip See ``Parameters`` section. """ def __init__( self, *, output: str = "depths", clip: "Camera.Clip" = None, sdf_version: str, ) -> None: super().__init__(sdf_version=sdf_version) self.output = output self.clip = clip @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": args_with_default = {"clip": Camera.Clip} standard_args = cls._prepare_standard_args( specific, args_with_default, version=version ) return Camera.DepthCamera( output=specific.output, **standard_args, sdf_version=version ) class Noise(ElementBase): """The camera's noise model. Parameters ---------- type : str The shape of the random noise distribution. Currently supported types are: "gaussian" (draw additive noise values independently for each pixel from a Gaussian distribution). Default: ``gaussian``. mean : float The distribution mean. Default: ``0``. stddev : float The distribution's standard deviation. Default: ``0``. sdf_version : str The SDFormat version to use when constructing this element. Attributes ---------- type : str See ``Parameters`` section. mean : float See ``Parameters`` section. stddev : float See ``Parameters`` section. """ def __init__( self, *, type: str = "gaussian", mean: float = 0, stddev: float = 0, sdf_version: str, ) -> None: super().__init__(sdf_version=sdf_version) self.type = type self.mean = (mean,) self.stddev = stddev @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": return Camera.Noise( type=specific.type, mean=specific.mean, stddev=specific.stddev, sdf_version=version, ) class Distortion(ElementBase): """The camera's distortion model Lens distortion to be applied to camera images. See http://en.wikipedia.org/wiki/Distortion_(optics)#Software_correction Parameters ---------- k1 : float The first radial distortion coefficient. Default: ``0``. k2 : float The second radial distortion coefficient. Default: ``0``. k3 : float The third radial distortion coefficient. Default: ``0``. p1 : float The first tangential distortion coefficient. Default: ``0`` p2 : float The second tangential distortion coefficient. Default: ``0``. center : str The distortion center or principal point. Default: ``0.5, 0.5``. sdf_version : str The SDFormat version to use when constructing this element. Attributes ---------- k1 : float See ``Parameters`` section. k2 : float See ``Parameters`` section. k3 : float See ``Parameters`` section. p1 : float See ``Parameters`` section. p2 : float See ``Parameters`` section. center : str See ``Parameters`` section. """ def __init__( self, *, k1: float = 0, k2: float = 0, k3: float = 0, p1: float = 0, p2: float = 0, center: str = "0.5, 0.5", sdf_version: str, ) -> None: super().__init__(sdf_version=sdf_version) self.k1 = k1 self.k2 = k2 self.k3 = k3 self.p1 = p1 self.p2 = p2 self.center = center @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": return Camera.Distortion( k1=specific.k1, k2=specific.k2, k3=specific.k3, p1=specific.p1, p2=specific.p2, center=specific.center, sdf_version=version, ) class Lense(ElementBase): """A Camera's lense properties. Parameters ---------- type : str Type of the lens mapping. Supported values are gnomonical, stereographic, equidistant, equisolid_angle, orthographic, custom. For gnomonical (perspective) projection, it is recommended to specify a horizontal_fov of less than or equal to 90°. Default: ``stereographic``. scale_to_hfov : bool If true the image will be scaled to fit horizontal FOV, otherwise it will be shown according to projection type parameters. Default: ``True``. custom_function : Camera.Lense.CustomFunction A custom lense map. cuttoff_angle : float Everything outside of the specified angle will be hidden. Default: ``.5707``. env_texture_size : int Resolution of the environment cube map used to draw the world. Default: ``56``. intrinsics : Camera.Lense.Intrinsics Parameters of a custom perspective matrix. sdf_version : str The SDFormat version to use when constructing this element. Attributes ---------- type : str See ``Parameters`` section. scale_to_hfov : bool See ``Parameters`` section. custom_function : Camera.Lense.CustomFunction See ``Parameters`` section. cuttoff_angle : float See ``Parameters`` section. env_texture_size : int See ``Parameters`` section. intrinsics : Camera.Lense.Intrinsics See ``Parameters`` section. """ def __init__( self, *, type: str = "stereographic", scale_to_hfov: bool = True, custom_function: "Camera.Lense.CustomFunction" = None, cuttoff_angle: float = 1.5707, env_texture_size: int = 256, intrinsics: "Camera.Lense.Intrinsics" = None, sdf_version: str, ) -> None: super().__init__(sdf_version=sdf_version) self.type = type self.scale_to_hfov = scale_to_hfov self.custom_function = ( Camera.Lense.CustomFunction(sdf_version=sdf_version) if custom_function is None else custom_function ) self.cuttoff_angle = cuttoff_angle self.env_texture_size = env_texture_size self.intrinsics = ( Camera.Lense.Intrinsics(sdf_version=sdf_version) if intrinsics is None else intrinsics ) @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": lense_args = { "type": specific.type, "scale_to_hfov": specific.scale_to_hfov, "custom_function": specific.custom_function, "cuttoff_angle": specific.cuttoff_angle, "env_texture_size": specific.env_texture_size, } args_with_default = { "custom_function": Camera.Lense.CustomFunction, "intrinsics": Camera.Lense.Intrinsics, } standard_args = cls._prepare_standard_args( specific, args_with_default, version=version ) return Camera.Lense(**lense_args, **standard_args) class CustomFunction(ElementBase): """A custom lense map. Definition of custom mapping function in a form of r=c1*f*fun(theta/c2 + c3). See https://en.wikipedia.org/wiki/Fisheye_lens#Mapping_function Parameters ---------- c1 : float Linear scaling constant. Default: ``1``. c2 : float Angle scaling constant. Default: ``1``. c3 : float Angle offset constant. Default: ``0``. f : float Focal length of the optical system. Note: It's not a focal length of the lens in a common sense! This value is ignored if 'scale_to_fov' is set to true. Default: ``1``. fun : str The non-linear element to use. Possible values are 'sin', 'tan' and 'id'. Default: ``tan``. sdf_version : str The SDFormat version to use when constructing this element. Attributes ---------- c1 : float See ``Parameters`` section. c2 : float See ``Parameters`` section. c3 : float See ``Parameters`` section. f : float See ``Parameters`` section. fun : str See ``Parameters`` section. """ def __init__( self, *, c1: float = 1, c2: float = 1, c3: float = 0, f: float = 1, fun: str = "tan", sdf_version: str, ) -> None: super().__init__(sdf_version=sdf_version) self.c1 = (c1,) self.c2 = (c2,) self.c3 = (c3,) self.f = (f,) self.fun = fun @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": return Camera.Lense.CustomFunction( c1=specific.c1, c2=specific.c2, c3=specific.c3, f=specific.f, fun=specific.fun, sdf_version=version, ) class Intrinsics(ElementBase): """Custom projection matrix. Camera intrinsic parameters for setting a custom perspective projection matrix (cannot be used with WideAngleCamera since this class uses image stitching from 6 different cameras for achieving a wide field of view). The focal lengths can be computed using focal_length_in_pixels = (image_width_in_pixels * 0.5) / tan(field_of_view_in_degrees * 0.5 * PI/180) Parameters ---------- fx : float X focal length (in pixels, overrides horizontal_fov). Default: ``277``. fy : float Y focal length (in pixels, overrides horizontal_fov). Default: ``277``. cx : float X principal point (in pixels). Default: ``160``. cy : float Y principal point (in pixels). Default: ``120``. s : float XY axis skew. Default: ``0``. sdf_version : str The SDFormat version to use when constructing this element. Attributes ---------- fx : float See ``Parameters`` section. fy : float See ``Parameters`` section. cx : float See ``Parameters`` section. cy : float See ``Parameters`` section. s : float See ``Parameters`` section. """ def __init__( self, *, fx: float = 277, fy: float = 277, cx: float = 160, cy: float = 120, s: float = 0, sdf_version: str, ) -> None: super().__init__(sdf_version=sdf_version) self.fx = fx self.fy = fy self.cx = cx self.cy = cy self.s = s @classmethod def from_specific(cls, specific: Any, *, version: str) -> "ElementBase": return Camera.Intrinsics( fx=specific.fx, fy=specific.fy, cx=specific.cx, cy=specific.cy, s=specific.s, sdf_version=version, )
/scikit-bot-0.14.0.tar.gz/scikit-bot-0.14.0/skbot/ignition/sdformat/generic_sdf/camera.py
0.929111
0.633013
camera.py
pypi
import multiprocessing __all__ = [ 'process_pool', 'process_pool_lock', ] def process_pool(func, all_net_params, nb_process): """Run multiple models in multi-processes. Parameters ---------- func : callable The function to run model. all_net_params : a_list, tuple The parameters of the function arguments. The parameters for each process can be a tuple, or a dictionary. nb_process : int The number of the processes. Returns ------- results : list Process results. """ print('{} jobs total.'.format(len(all_net_params))) pool = multiprocessing.Pool(processes=nb_process) results = [] for net_params in all_net_params: if isinstance(net_params, (list, tuple)): results.append(pool.apply_async(func, args=tuple(net_params))) elif isinstance(net_params, dict): results.append(pool.apply_async(func, kwds=net_params)) else: raise ValueError('Unknown parameter type: ', type(net_params)) pool.close() pool.join() return results def process_pool_lock(func, all_net_params, nb_process): """Run multiple models in multi-processes with lock. Sometimes, you want to synchronize the processes. For example, if you want to write something in a document, you cannot let multi-process simultaneously open this same file. So, you need add a `lock` argument in your defined `func`: .. _code-block:: python def some_func(..., lock, ...): ... do something .. lock.acquire() ... something cannot simultaneously do by multi-process .. lock.release() In such case, you can use `process_pool_lock()` to run your model. Parameters ---------- func : callable The function to run model. all_net_params : a_list, tuple The parameters of the function arguments. nb_process : int The number of the processes. Returns ------- results : list Process results. """ print('{} jobs total.'.format(len(all_net_params))) pool = multiprocessing.Pool(processes=nb_process) m = multiprocessing.Manager() lock = m.Lock() results = [] for net_params in all_net_params: if isinstance(net_params, (list, tuple)): results.append(pool.apply_async(func, args=tuple(net_params) + (lock,))) elif isinstance(net_params, dict): net_params.update(lock=lock) results.append(pool.apply_async(func, kwds=net_params)) else: raise ValueError('Unknown parameter type: ', type(net_params)) pool.close() pool.join() return results
/scikit-brain-0.3.3.tar.gz/scikit-brain-0.3.3/brainpy/running.py
0.812979
0.241009
running.py
pypi
from numba import cuda __all__ = [ 'set', 'run_on_cpu', 'run_on_gpu', 'set_backend', 'get_backend', 'set_device', 'get_device', 'set_dt', 'get_dt', 'set_numerical_method', 'get_numerical_method', 'set_numba_profile', 'get_numba_profile', 'get_num_thread_gpu', 'is_jit', 'is_merge_integrators', 'is_merge_steps', 'is_substitute_equation', 'show_code_scope', 'show_format_code', ] _jit = False _backend = 'numpy' _device = 'cpu' _dt = 0.1 _method = 'euler' _numba_setting = { 'nopython': True, 'fastmath': True, 'nogil': True, 'parallel': False } _show_format_code = False _show_code_scope = False _substitute_equation = False _merge_integrators = True _merge_steps = False _num_thread_gpu = None def set( jit=None, device=None, numerical_method=None, dt=None, float_type=None, int_type=None, merge_integrators=None, merge_steps=None, substitute=None, show_code=None, show_code_scope=None ): # JIT and device if device is not None and jit is None: assert isinstance(device, str), "'device' must a string." set_device(_jit, device=device) if jit is not None: assert isinstance(jit, bool), "'jit' must be True or False." if device is not None: assert isinstance(device, str), "'device' must a string." set_device(jit, device=device) # numerical integration method if numerical_method is not None: assert isinstance(numerical_method, str), '"numerical_method" must be a string.' set_numerical_method(numerical_method) # numerical integration precision if dt is not None: assert isinstance(dt, (float, int)), '"dt" must be float or int.' set_dt(dt) # default float type if float_type is not None: from .backend import _set_default_float _set_default_float(float_type) # default int type if int_type is not None: from .backend import _set_default_int _set_default_int(int_type) # option to merge integral functions if merge_integrators is not None: assert isinstance(merge_integrators, bool), '"merge_integrators" must be True or False.' if run_on_gpu() and not merge_integrators: raise ValueError('GPU mode do not support "merge_integrators = False".') global _merge_integrators _merge_integrators = merge_integrators # option to merge step functions if merge_steps is not None: assert isinstance(merge_steps, bool), '"merge_steps" must be True or False.' global _merge_steps _merge_steps = merge_steps # option of the equation substitution if substitute is not None: assert isinstance(substitute, bool), '"substitute" must be True or False.' global _substitute_equation _substitute_equation = substitute # option of the formatted code output if show_code is not None: assert isinstance(show_code, bool), '"show_code" must be True or False.' global _show_format_code _show_format_code = show_code # option of the formatted code scope if show_code_scope is not None: assert isinstance(show_code_scope, bool), '"show_code_scope" must be True or False.' global _show_code_scope _show_code_scope = show_code_scope def set_device(jit, device=None): """Set the backend and the device to deploy the models. Parameters ---------- jit : bool Whether use the jit acceleration. device : str, optional The device name. """ # jit # --- global _jit if _jit != jit: _jit = jit # device # ------ global _device global _num_thread_gpu if device is None: return device = device.lower() if _device != device: if not jit: if device != 'cpu': print(f'Non-JIT mode now only supports "cpu" device, not "{device}".') else: _device = device else: if device == 'cpu': set_numba_profile(parallel=False) elif device == 'multi-cpu': set_numba_profile(parallel=True) else: if device.startswith('gpu'): # get cuda id cuda_id = device.replace('gpu', '') if cuda_id == '': cuda_id = 0 device = f'{device}0' else: cuda_id = float(cuda_id) # set cuda if cuda.is_available(): cuda.select_device(cuda_id) else: raise ValueError('Cuda is not available. Cannot set gpu backend.') gpu = cuda.get_current_device() _num_thread_gpu = gpu.MAX_THREADS_PER_BLOCK else: raise ValueError(f'Unknown device in Numba mode: {device}.') _device = device def get_device(): """Get the device name. Returns ------- device: str Device name. """ return _device def is_jit(): """Check whether the backend is ``numba``. Returns ------- jit : bool True or False. """ return _jit def run_on_cpu(): """Check whether the device is "CPU". Returns ------- device : bool True or False. """ return _device.endswith('cpu') def run_on_gpu(): """Check whether the device is "GPU". Returns ------- device : bool True or False. """ return _device.startswith('gpu') def set_backend(backend): """Set the running backend. Parameters ---------- backend : str The backend name. """ if backend not in ['numpy', 'pytorch']: raise ValueError(f'BrainPy now supports "numpy" or "pytorch" backend, not "{backend}".') global _backend _backend = backend def get_backend(): """Get the used backend of BrainPy. Returns ------- backend : str The backend name. """ return _backend def set_numba_profile(**kwargs): """Set the compilation options of Numba JIT function. Parameters ---------- kwargs : Any The arguments, including ``cache``, ``fastmath``, ``parallel``, ``nopython``. """ global _numba_setting if 'fastmath' in kwargs: _numba_setting['fastmath'] = kwargs.pop('fastmath') if 'nopython' in kwargs: _numba_setting['nopython'] = kwargs.pop('nopython') if 'nogil' in kwargs: _numba_setting['nogil'] = kwargs.pop('nogil') if 'parallel' in kwargs: _numba_setting['parallel'] = kwargs.pop('parallel') def get_numba_profile(): """Get the compilation setting of numba JIT function. Returns ------- numba_setting : dict Numba setting. """ return _numba_setting def set_dt(dt): """Set the numerical integrator precision. Parameters ---------- dt : float Numerical integration precision. """ assert isinstance(dt, float) global _dt _dt = dt def get_dt(): """Get the numerical integrator precision. Returns ------- dt : float Numerical integration precision. """ return _dt def set_numerical_method(method): """Set the default numerical integrator method for differential equations. Parameters ---------- method : str, callable Numerical integrator method. """ from brainpy.integration import _SUPPORT_METHODS if not isinstance(method, str): raise ValueError(f'Only support string, not {type(method)}.') if method not in _SUPPORT_METHODS: raise ValueError(f'Unsupported numerical method: {method}.') global _method _method = method def get_numerical_method(): """Get the default numerical integrator method. Returns ------- method : str The default numerical integrator method. """ return _method def is_merge_integrators(): return _merge_integrators def is_merge_steps(): return _merge_steps def is_substitute_equation(): return _substitute_equation def show_code_scope(): return _show_code_scope def show_format_code(): return _show_format_code def get_num_thread_gpu(): return _num_thread_gpu
/scikit-brain-0.3.3.tar.gz/scikit-brain-0.3.3/brainpy/profile.py
0.771801
0.342957
profile.py
pypi
from collections import namedtuple import numba as nb import numpy as np __all__ = [ 'brentq', 'find_root' ] _ECONVERGED = 0 _ECONVERR = -1 results = namedtuple('results', ['root', 'function_calls', 'iterations', 'converged']) @nb.njit def brentq(f, a, b, args=(), xtol=2e-12, maxiter=100, rtol=4 * np.finfo(float).eps): """ Find a root of a function in a bracketing interval using Brent's method adapted from Scipy's brentq. Uses the classic Brent's method to find a zero of the function `f` on the sign changing interval [a , b]. Parameters ---------- f : callable Python function returning a number. `f` must be continuous. a : number One end of the bracketing interval [a,b]. b : number The other end of the bracketing interval [a,b]. args : tuple, optional(default=()) Extra arguments to be used in the function call. xtol : number, optional(default=2e-12) The computed root ``x0`` will satisfy ``np.allclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The parameter must be nonnegative. rtol : number, optional(default=4*np.finfo(float).eps) The computed root ``x0`` will satisfy ``np.allclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the exact root. maxiter : number, optional(default=100) Maximum number of iterations. Returns ------- results : namedtuple """ if xtol <= 0: raise ValueError("xtol is too small (<= 0)") if maxiter < 1: raise ValueError("maxiter must be greater than 0") # Convert to float xpre = a * 1.0 xcur = b * 1.0 # Conditional checks for intervals in methods involving bisection fpre = f(xpre, *args) fcur = f(xcur, *args) funcalls = 2 if fpre * fcur > 0: raise ValueError("f(a) and f(b) must have different signs") root = 0.0 status = _ECONVERR # Root found at either end of [a,b] if fpre == 0: root = xpre status = _ECONVERGED if fcur == 0: root = xcur status = _ECONVERGED root, status = root, status # Check for sign error and early termination if status == _ECONVERGED: itr = 0 else: # Perform Brent's method for itr in range(maxiter): if fpre * fcur < 0: xblk = xpre fblk = fpre spre = scur = xcur - xpre if abs(fblk) < abs(fcur): xpre = xcur xcur = xblk xblk = xpre fpre = fcur fcur = fblk fblk = fpre delta = (xtol + rtol * abs(xcur)) / 2 sbis = (xblk - xcur) / 2 # Root found if fcur == 0 or abs(sbis) < delta: status = _ECONVERGED root = xcur itr += 1 break if abs(spre) > delta and abs(fcur) < abs(fpre): if xpre == xblk: # interpolate stry = -fcur * (xcur - xpre) / (fcur - fpre) else: # extrapolate dpre = (fpre - fcur) / (xpre - xcur) dblk = (fblk - fcur) / (xblk - xcur) stry = -fcur * (fblk * dblk - fpre * dpre) / \ (dblk * dpre * (fblk - fpre)) if 2 * abs(stry) < min(abs(spre), 3 * abs(sbis) - delta): # good short step spre = scur scur = stry else: # bisect spre = sbis scur = sbis else: # bisect spre = sbis scur = sbis xpre = xcur fpre = fcur if abs(scur) > delta: xcur += scur else: xcur += (delta if sbis > 0 else -delta) fcur = f(xcur, *args) funcalls += 1 if status == _ECONVERR: raise RuntimeError("Failed to converge") x, funcalls, iterations = root, funcalls, itr return x @nb.njit def find_root(f, f_points, args=()): """Find the roots of the given function by numerical methods. Parameters ---------- f : callable The function. f_points : onp.ndarray, list, tuple The value points. Returns ------- roots : list The roots. """ vals = f(f_points, *args) fs_len = len(f_points) fs_sign = np.sign(vals) roots = [] fl_sign = fs_sign[0] f_i = 1 while f_i < fs_len and fl_sign == 0.: roots.append(f_points[f_i - 1]) fl_sign = fs_sign[f_i] f_i += 1 while f_i < fs_len: fr_sign = fs_sign[f_i] if fr_sign == 0.: roots.append(f_points[f_i]) if f_i + 1 < fs_len: fl_sign = fs_sign[f_i + 1] else: break f_i += 2 else: if not np.isnan(fr_sign) and fl_sign != fr_sign: root = brentq(f, f_points[f_i - 1], f_points[f_i], args) roots.append(root) fl_sign = fr_sign f_i += 1 return roots
/scikit-brain-0.3.3.tar.gz/scikit-brain-0.3.3/brainpy/dynamics/solver.py
0.829871
0.480113
solver.py
pypi
import numpy as np _SADDLE_NODE = 'saddle-node' _1D_STABLE_POINT = 'stable-point' _1D_UNSTABLE_POINT = 'unstable-point' _2D_CENTER = 'center' _2D_STABLE_NODE = 'stable-node' _2D_STABLE_FOCUS = 'stable-focus' _2D_STABLE_STAR = 'stable-star' _2D_STABLE_LINE = 'stable-line' _2D_UNSTABLE_NODE = 'unstable-node' _2D_UNSTABLE_FOCUS = 'unstable-focus' _2D_UNSTABLE_STAR = 'star' _2D_UNSTABLE_LINE = 'unstable-line' plot_scheme = { _1D_STABLE_POINT: {"color": 'tab:red'}, _2D_STABLE_NODE: {"color": 'tab:red'}, _1D_UNSTABLE_POINT: {"color": 'tab:olive'}, _2D_UNSTABLE_NODE: {"color": 'tab:olive'}, _2D_STABLE_FOCUS: {"color": 'tab:purple'}, _2D_UNSTABLE_FOCUS: {"color": 'tab:cyan'}, _SADDLE_NODE: {"color": 'tab:blue'}, _2D_STABLE_LINE: {'color': 'orangered'}, _2D_UNSTABLE_LINE: {'color': 'dodgerblue'}, _2D_CENTER: {'color': 'lime'}, _2D_UNSTABLE_STAR: {'color': 'green'}, _2D_STABLE_STAR: {'color': 'orange'}, } def get_1d_classification(): return [_SADDLE_NODE, _1D_STABLE_POINT, _1D_UNSTABLE_POINT] def get_2d_classification(): return [_SADDLE_NODE, _2D_CENTER, _2D_STABLE_NODE, _2D_STABLE_FOCUS, _2D_STABLE_STAR, _2D_STABLE_LINE, _2D_UNSTABLE_NODE, _2D_UNSTABLE_FOCUS, _2D_UNSTABLE_STAR, _2D_UNSTABLE_LINE] def stability_analysis(derivative): """Stability analysis for fixed point. Parameters ---------- derivative : float, tuple, list, np.ndarray The derivative of the f. Returns ------- fp_type : str The type of the fixed point. """ if np.size(derivative) == 1: if derivative == 0: return _SADDLE_NODE elif derivative > 0: return _1D_STABLE_POINT else: return _1D_UNSTABLE_POINT elif np.size(derivative) == 4: a = derivative[0][0] b = derivative[0][1] c = derivative[1][0] d = derivative[1][1] # trace p = a + d # det q = a * d - b * c # parabola e = p * p - 4 * q # judgement if q < 0: return _SADDLE_NODE elif q == 0: if p < 0: return _2D_STABLE_LINE else: return _2D_UNSTABLE_LINE else: if p == 0: return _2D_CENTER elif p > 0: if e < 0: return _2D_UNSTABLE_FOCUS elif e == 0: return _2D_UNSTABLE_STAR else: return _2D_UNSTABLE_NODE else: if e < 0: return _2D_STABLE_FOCUS elif e == 0: return _2D_STABLE_STAR else: return _2D_STABLE_NODE else: raise ValueError('Unknown derivatives.') def rescale(min_max, scale=0.01): """Rescale lim.""" min_, max_ = min_max length = max_ - min_ min_ -= scale * length max_ += scale * length return min_, max_
/scikit-brain-0.3.3.tar.gz/scikit-brain-0.3.3/brainpy/dynamics/utils.py
0.70069
0.346818
utils.py
pypi
import ast import math import numpy as np import sympy import sympy.functions.elementary.complexes import sympy.functions.elementary.exponential import sympy.functions.elementary.hyperbolic import sympy.functions.elementary.integers import sympy.functions.elementary.miscellaneous import sympy.functions.elementary.trigonometric from sympy.codegen import cfunctions from sympy.printing.precedence import precedence from sympy.printing.str import StrPrinter from .. import profile __all__ = [ 'FUNCTION_MAPPING', 'CONSTANT_MAPPING', 'SympyParser', 'SympyPrinter', 'str2sympy', 'sympy2str', 'get_mapping_scope', ] FUNCTION_MAPPING = { # 'real': sympy.functions.elementary.complexes.re, # 'imag': sympy.functions.elementary.complexes.im, # 'conjugate': sympy.functions.elementary.complexes.conjugate, # functions in inherit python # --------------------------- 'abs': sympy.functions.elementary.complexes.Abs, # functions in numpy # ------------------ 'sign': sympy.sign, 'sinc': sympy.functions.elementary.trigonometric.sinc, 'arcsin': sympy.functions.elementary.trigonometric.asin, 'arccos': sympy.functions.elementary.trigonometric.acos, 'arctan': sympy.functions.elementary.trigonometric.atan, 'arctan2': sympy.functions.elementary.trigonometric.atan2, 'arcsinh': sympy.functions.elementary.hyperbolic.asinh, 'arccosh': sympy.functions.elementary.hyperbolic.acosh, 'arctanh': sympy.functions.elementary.hyperbolic.atanh, 'log2': cfunctions.log2, 'log1p': cfunctions.log1p, 'expm1': cfunctions.expm1, 'exp2': cfunctions.exp2, # functions in math # ------------------ 'asin': sympy.functions.elementary.trigonometric.asin, 'acos': sympy.functions.elementary.trigonometric.acos, 'atan': sympy.functions.elementary.trigonometric.atan, 'atan2': sympy.functions.elementary.trigonometric.atan2, 'asinh': sympy.functions.elementary.hyperbolic.asinh, 'acosh': sympy.functions.elementary.hyperbolic.acosh, 'atanh': sympy.functions.elementary.hyperbolic.atanh, # functions in both numpy and math # -------------------------------- 'cos': sympy.functions.elementary.trigonometric.cos, 'sin': sympy.functions.elementary.trigonometric.sin, 'tan': sympy.functions.elementary.trigonometric.tan, 'cosh': sympy.functions.elementary.hyperbolic.cosh, 'sinh': sympy.functions.elementary.hyperbolic.sinh, 'tanh': sympy.functions.elementary.hyperbolic.tanh, 'log': sympy.functions.elementary.exponential.log, 'log10': cfunctions.log10, 'sqrt': sympy.functions.elementary.miscellaneous.sqrt, 'exp': sympy.functions.elementary.exponential.exp, 'hypot': cfunctions.hypot, 'ceil': sympy.functions.elementary.integers.ceiling, 'floor': sympy.functions.elementary.integers.floor, } CONSTANT_MAPPING = { # constants in both numpy and math # -------------------------------- 'pi': sympy.pi, 'e': sympy.E, 'inf': sympy.S.Infinity, } def get_mapping_scope(): if profile.run_on_cpu(): return {'sign': np.sign, 'cos': np.cos, 'sin': np.sin, 'tan': np.tan, 'sinc': np.sinc, 'arcsin': np.arcsin, 'arccos': np.arccos, 'arctan': np.arctan, 'arctan2': np.arctan2, 'cosh': np.cosh, 'sinh': np.cosh, 'tanh': np.tanh, 'arcsinh': np.arcsinh, 'arccosh': np.arccosh, 'arctanh': np.arctanh, 'ceil': np.ceil, 'floor': np.floor, 'log': np.log, 'log2': np.log2, 'log1p': np.log1p, 'log10': np.log10, 'exp': np.exp, 'expm1': np.expm1, 'exp2': np.exp2, 'hypot': np.hypot, 'sqrt': np.sqrt, 'pi': np.pi, 'e': np.e, 'inf': np.inf, 'asin': math.asin, 'acos': math.acos, 'atan': math.atan, 'atan2': math.atan2, 'asinh': math.asinh, 'acosh': math.acosh, 'atanh': math.atanh} else: return { # functions in numpy # ------------------ 'arcsin': math.asin, 'arccos': math.acos, 'arctan': math.atan, 'arctan2': math.atan2, 'arcsinh': math.asinh, 'arccosh': math.acosh, 'arctanh': math.atanh, 'sign': np.sign, 'sinc': np.sinc, 'log2': np.log2, 'log1p': np.log1p, 'expm1': np.expm1, 'exp2': np.exp2, # functions in math # ------------------ 'asin': math.asin, 'acos': math.acos, 'atan': math.atan, 'atan2': math.atan2, 'asinh': math.asinh, 'acosh': math.acosh, 'atanh': math.atanh, # functions in both numpy and math # -------------------------------- 'cos': math.cos, 'sin': math.sin, 'tan': math.tan, 'cosh': math.cosh, 'sinh': math.sinh, 'tanh': math.tanh, 'log': math.log, 'log10': math.log10, 'sqrt': math.sqrt, 'exp': math.exp, 'hypot': math.hypot, 'ceil': math.ceil, 'floor': math.floor, # constants in both numpy and math # -------------------------------- 'pi': math.pi, 'e': math.e, 'inf': math.inf} class SympyParser(object): expression_ops = { 'Add': sympy.Add, 'Mult': sympy.Mul, 'Pow': sympy.Pow, 'Mod': sympy.Mod, # Compare 'Lt': sympy.StrictLessThan, 'LtE': sympy.LessThan, 'Gt': sympy.StrictGreaterThan, 'GtE': sympy.GreaterThan, 'Eq': sympy.Eq, 'NotEq': sympy.Ne, # Bool ops 'And': sympy.And, 'Or': sympy.Or, # BinOp 'Sub': '-', 'Div': '/', 'FloorDiv': '//', # Compare 'Not': 'not', 'UAdd': '+', 'USub': '-', # Augmented assign 'AugAdd': '+=', 'AugSub': '-=', 'AugMult': '*=', 'AugDiv': '/=', 'AugPow': '**=', 'AugMod': '%=', } def __init__(self): pass def render_expr(self, expr, strip=True): if strip: expr = expr.strip() node = ast.parse(expr, mode='eval') return self.render_node(node.body) def render_code(self, code): lines = [] for node in ast.parse(code).body: lines.append(self.render_node(node)) return '\n'.join(lines) def render_node(self, node): nodename = node.__class__.__name__ methname = 'render_' + nodename try: return getattr(self, methname)(node) except AttributeError: raise SyntaxError(f"Unknown syntax: {nodename}, {node}") def render_Attribute(self, node): if node.attr in CONSTANT_MAPPING: return CONSTANT_MAPPING[node.attr] else: names = self._get_attr_value(node, []) return sympy.Symbol('.'.join(names), real=True) def render_Constant(self, node): if node.value is True or node.value is False or node.value is None: return self.render_NameConstant(node) else: return self.render_Num(node) def render_element_parentheses(self, node): """Render an element with parentheses around it or leave them away for numbers, names and function calls. """ if node.__class__.__name__ in ['Name', 'NameConstant']: return self.render_node(node) elif node.__class__.__name__ in ['Num', 'Constant'] and \ getattr(node, 'n', getattr(node, 'value', None)) >= 0: return self.render_node(node) elif node.__class__.__name__ == 'Call': return self.render_node(node) else: return f'({self.render_node(node)})' def render_BinOp_parentheses(self, left, right, op): """Use a simplified checking whether it is possible to omit parentheses: only omit parentheses for numbers, variable names or function calls. This means we still put needless parentheses because we ignore precedence rules, e.g. we write "3 + (4 * 5)" but at least we do not do "(3) + ((4) + (5))" """ ops = {'BitXor': ('^', '**'), 'BitAnd': ('&', 'and'), 'BitOr': ('|', 'or')} op_class = op.__class__.__name__ # Give a more useful error message when using bit-wise operators if op_class in ['BitXor', 'BitAnd', 'BitOr']: correction = ops.get(op_class) raise SyntaxError('The operator "{}" is not supported, use "{}" ' 'instead.'.format(correction[0], correction[1])) return f'{self.render_element_parentheses(left)} ' \ f'{self.expression_ops[op_class]} ' \ f'{self.render_element_parentheses(right)}' def render_Assign(self, node): if len(node.targets) > 1: raise SyntaxError("Only support syntax like a=b not a=b=c") return f'{self.render_node(node.targets[0])} = {self.render_node(node.value)}' def render_AugAssign(self, node): target = node.target.id rhs = self.render_node(node.value) op = self.expression_ops['Aug' + node.op.__class__.__name__] return f'{target} {op} {rhs}' def _get_attr_value(self, node, names): if hasattr(node, 'value'): names.insert(0, node.attr) return self._get_attr_value(node.value, names) else: assert hasattr(node, 'id') names.insert(0, node.id) return names def render_func(self, node): if hasattr(node, 'id'): if node.id in FUNCTION_MAPPING: f = FUNCTION_MAPPING[node.id] return f # special workaround for the "int" function if node.id == 'int': return sympy.Function("int_") else: return sympy.Function(node.id) else: if node.attr in FUNCTION_MAPPING: return FUNCTION_MAPPING[node.attr] if node.attr == 'int': return sympy.Function("int_") else: names = self._get_attr_value(node, []) return sympy.Function('.'.join(names)) def render_Call(self, node): if len(node.keywords): raise ValueError("Keyword arguments not supported.") elif getattr(node, 'starargs', None) is not None: raise ValueError("Variable number of arguments not supported") elif getattr(node, 'kwargs', None) is not None: raise ValueError("Keyword arguments not supported") elif len(node.args) == 0: return self.render_func(node.func)(sympy.Symbol('_placeholder_arg')) else: return self.render_func(node.func)(*(self.render_node(arg) for arg in node.args)) def render_Compare(self, node): if len(node.comparators) > 1: raise SyntaxError("Can only handle single comparisons like a<b not a<b<c") op = node.ops[0] ops = self.expression_ops[op.__class__.__name__] left = self.render_node(node.left) right = self.render_node(node.comparators[0]) return ops(left, right) def render_Name(self, node): if node.id in CONSTANT_MAPPING: return CONSTANT_MAPPING[node.id] else: return sympy.Symbol(node.id, real=True) def render_NameConstant(self, node): if node.value in [True, False]: return node.value else: return str(node.value) def render_Num(self, node): return sympy.Float(node.n) def render_BinOp(self, node): op_name = node.op.__class__.__name__ # Sympy implements division and subtraction as multiplication/addition if op_name == 'Div': op = self.expression_ops['Mult'] left = self.render_node(node.left) right = 1 / self.render_node(node.right) return op(left, right) elif op_name == 'FloorDiv': op = self.expression_ops['Mult'] left = self.render_node(node.left) right = self.render_node(node.right) return sympy.floor(op(left, 1 / right)) elif op_name == 'Sub': op = self.expression_ops['Add'] left = self.render_node(node.left) right = -self.render_node(node.right) return op(left, right) else: op = self.expression_ops[op_name] left = self.render_node(node.left) right = self.render_node(node.right) return op(left, right) def render_BoolOp(self, node): op = self.expression_ops[node.op.__class__.__name__] return op(*(self.render_node(value) for value in node.values)) def render_UnaryOp(self, node): op_name = node.op.__class__.__name__ if op_name == 'UAdd': return self.render_node(node.operand) elif op_name == 'USub': return -self.render_node(node.operand) elif op_name == 'Not': return sympy.Not(self.render_node(node.operand)) else: raise ValueError('Unknown unary operator: ' + op_name) class SympyPrinter(StrPrinter): """ Printer that overrides the printing of some basic sympy objects. reversal_potential.g. print "a and b" instead of "And(a, b)". """ def _print_And(self, expr): return ' and '.join(['(%s)' % self.doprint(arg) for arg in expr.args]) def _print_Or(self, expr): return ' or '.join(['(%s)' % self.doprint(arg) for arg in expr.args]) def _print_Not(self, expr): if len(expr.args) != 1: raise AssertionError('"Not" with %d arguments?' % len(expr.args)) return f'not ({self.doprint(expr.args[0])})' def _print_Relational(self, expr): return f'{self.parenthesize(expr.lhs, precedence(expr))} ' \ f'{self._relationals.get(expr.rel_op) or expr.rel_op} ' \ f'{self.parenthesize(expr.rhs, precedence(expr))}' def _print_Function(self, expr): # Special workaround for the int function if expr.func.__name__ == 'int_': return f'int({self.stringify(expr.args, ", ")})' elif expr.func.__name__ == 'Mod': return f'(({self.doprint(expr.args[0])})%({self.doprint(expr.args[1])}))' else: return expr.func.__name__ + f"({self.stringify(expr.args, ', ')})" _PARSER = SympyParser() _PRINTER = SympyPrinter() def str2sympy(str_expr): return _PARSER.render_expr(str_expr) def sympy2str(sympy_expr): # replace the standard functions by our names if necessary replacements = dict((f, sympy.Function(name)) for name, f in FUNCTION_MAPPING.items() if str(f) != name) # replace constants with our names as well replacements.update(dict((c, sympy.Symbol(name)) for name, c in CONSTANT_MAPPING.items() if str(c) != name)) # Replace the placeholder argument by an empty symbol replacements[sympy.Symbol('_placeholder_arg')] = sympy.Symbol('') atoms = (sympy_expr.atoms() | {f.func for f in sympy_expr.atoms(sympy.Function)}) for old, new in replacements.items(): if old in atoms: sympy_expr = sympy_expr.subs(old, new) return _PRINTER.doprint(sympy_expr)
/scikit-brain-0.3.3.tar.gz/scikit-brain-0.3.3/brainpy/integration/sympy_tools.py
0.488039
0.429429
sympy_tools.py
pypi
import inspect from collections import Counter import sympy from .constants import CONSTANT_NOISE from .constants import FUNCTIONAL_NOISE from .sympy_tools import str2sympy from .sympy_tools import sympy2str from .. import profile from .. import tools from ..errors import DiffEquationError __all__ = [ 'Expression', 'DiffEquation', ] class Expression(object): def __init__(self, var, code): self.var_name = var self.code = code.strip() self._substituted_code = None @property def identifiers(self): return tools.get_identifiers(self.code) def __str__(self): return f'{self.var_name} = {self.code}' def __repr__(self): return self.__str__() def __eq__(self, other): if not isinstance(other, Expression): return NotImplemented if self.code != other.code: return False if self.var_name != other.var_name: return False return True def __ne__(self, other): return not self.__eq__(other) def get_code(self, subs=True): if subs: if self._substituted_code is None: return self.code else: return self._substituted_code else: return self.code class DiffEquation(object): """Differential Equation. A differential equation is defined as the standard form: dx/dt = f(x) + g(x) dW Parameters ---------- func : callable The user defined differential equation. """ def __init__(self, func): # check try: assert func is not None except AssertionError: raise DiffEquationError('"func" cannot be None.') try: assert callable(func) and type(func).__name__ == 'function' except AssertionError: raise DiffEquationError('"func" must be a function.') # function self.func = func # function string self.code = tools.deindent(tools.get_main_code(func)) try: assert 'return' in self.code except AssertionError: raise DiffEquationError(f'"func" function must return something, ' f'but found nothing.\n{self.code}') # function arguments self.func_args = inspect.getfullargspec(func).args # function name if tools.is_lambda_function(func): self.func_name = f'_integral_{self.func_args[0]}_' else: self.func_name = func.__name__ # function scope scope = inspect.getclosurevars(func) self.func_scope = dict(scope.nonlocals) self.func_scope.update(scope.globals) # differential variable name and time name self.var_name = self.func_args[0] self.t_name = self.func_args[1] # analyse function code res = tools.analyse_diff_eq(self.code) self.expressions = [Expression(v, expr) for v, expr in zip(res.variables, res.expressions)] self.returns = res.returns self.return_type = res.return_type self.f_expr = None self.g_expr = None if res.f_expr is not None: self.f_expr = Expression(res.f_expr[0], res.f_expr[1]) if res.g_expr is not None: self.g_expr = Expression(res.g_expr[0], res.g_expr[1]) for k, num in Counter(res.variables).items(): if num > 1: raise DiffEquationError(f'Found "{k}" {num} times. Please assign each expression ' f'in differential function with a unique name. ') # analyse noise type self.g_type = CONSTANT_NOISE self.g_value = None if self.g_expr is not None: self._substitute(self.g_expr, self.expressions) g_code = self.g_expr.get_code(subs=True) for idf in tools.get_identifiers(g_code): if idf not in self.func_scope: self.g_type = FUNCTIONAL_NOISE break else: self.g_value = eval(g_code, self.func_scope) def _substitute(self, final_exp, expressions, substitute_vars=None): """Substitute expressions to get the final single expression Parameters ---------- final_exp : Expression The final expression. expressions : list, tuple The list/tuple of expressions. """ if substitute_vars is None: return if final_exp is None: return assert substitute_vars == 'all' or \ substitute_vars == self.var_name or \ isinstance(substitute_vars, (tuple, list)) # Goal: Substitute dependent variables into the expresion # Hint: This step doesn't require the left variables are unique dependencies = {} for expr in expressions: substitutions = {} for dep_var, dep_expr in dependencies.items(): if dep_var in expr.identifiers: code = dep_expr.get_code(subs=True) substitutions[sympy.Symbol(dep_var, real=True)] = str2sympy(code) if len(substitutions): new_sympy_expr = str2sympy(expr.code).xreplace(substitutions) new_str_expr = sympy2str(new_sympy_expr) expr._substituted_code = new_str_expr dependencies[expr.var_name] = expr else: if substitute_vars == 'all': dependencies[expr.var_name] = expr elif substitute_vars == self.var_name: if self.var_name in expr.identifiers: dependencies[expr.var_name] = expr else: ids = expr.identifiers for var in substitute_vars: if var in ids: dependencies[expr.var_name] = expr break # Goal: get the final differential equation # Hint: the step requires the expression variables must be unique substitutions = {} for dep_var, dep_expr in dependencies.items(): code = dep_expr.get_code(subs=True) substitutions[sympy.Symbol(dep_var, real=True)] = str2sympy(code) if len(substitutions): new_sympy_expr = str2sympy(final_exp.code).xreplace(substitutions) new_str_expr = sympy2str(new_sympy_expr) final_exp._substituted_code = new_str_expr def get_f_expressions(self, substitute_vars=None): if self.f_expr is None: return [] self._substitute(self.f_expr, self.expressions, substitute_vars=substitute_vars) return_expressions = [] # the derivative expression dif_eq_code = self.f_expr.get_code(subs=True) return_expressions.append(Expression(f'_df{self.var_name}_dt', dif_eq_code)) # needed variables need_vars = tools.get_identifiers(dif_eq_code) need_vars |= tools.get_identifiers(', '.join(self.returns)) # get the total return expressions for expr in self.expressions[::-1]: if expr.var_name in need_vars: if not profile._substitute_equation or expr._substituted_code is None: code = expr.code else: code = expr._substituted_code return_expressions.append(Expression(expr.var_name, code)) need_vars |= tools.get_identifiers(code) return return_expressions[::-1] def get_g_expressions(self): if self.is_functional_noise: return_expressions = [] # the derivative expression eq_code = self.g_expr.get_code(subs=True) return_expressions.append(Expression(f'_dg{self.var_name}_dt', eq_code)) # needed variables need_vars = tools.get_identifiers(eq_code) # get the total return expressions for expr in self.expressions[::-1]: if expr.var_name in need_vars: if not profile._substitute_equation or expr._substituted_code is None: code = expr.code else: code = expr._substituted_code return_expressions.append(Expression(expr.var_name, code)) need_vars |= tools.get_identifiers(code) return return_expressions[::-1] else: return [Expression(f'_dg{self.var_name}_dt', self.g_expr.get_code(subs=True))] def _replace_expressions(self, expressions, name, y_sub, t_sub=None): """Replace expressions of df part. Parameters ---------- expressions : list, tuple The list/tuple of expressions. name : str The name of the new expression. y_sub : str The new name of the variable "y". t_sub : str, optional The new name of the variable "t". Returns ------- list_of_expr : list A list of expressions. """ return_expressions = [] # replacements replacement = {self.var_name: y_sub} if t_sub is not None: replacement[self.t_name] = t_sub # replace variables in expressions for expr in expressions: replace = False identifiers = expr.identifiers for repl_var in replacement.keys(): if repl_var in identifiers: replace = True break if replace: code = tools.word_replace(expr.code, replacement) new_expr = Expression(f"{expr.var_name}_{name}", code) return_expressions.append(new_expr) replacement[expr.var_name] = new_expr.var_name return return_expressions def replace_f_expressions(self, name, y_sub, t_sub=None): """Replace expressions of df part. Parameters ---------- name : str The name of the new expression. y_sub : str The new name of the variable "y". t_sub : str, optional The new name of the variable "t". Returns ------- list_of_expr : list A list of expressions. """ return self._replace_expressions(self.get_f_expressions(), name=name, y_sub=y_sub, t_sub=t_sub) def replace_g_expressions(self, name, y_sub, t_sub=None): if self.is_functional_noise: return self._replace_expressions(self.get_g_expressions(), name=name, y_sub=y_sub, t_sub=t_sub) else: return [] @property def is_multi_return(self): return len(self.returns) > 0 @property def is_stochastic(self): if self.g_expr is not None: try: if eval(self.g_expr.code, self.func_scope) == 0.: return False except Exception as e: pass return True else: return False @property def is_functional_noise(self): return self.g_type == FUNCTIONAL_NOISE @property def stochastic_type(self): if not self.is_stochastic: return None else: pass @property def expr_names(self): return [expr.var_name for expr in self.expressions]
/scikit-brain-0.3.3.tar.gz/scikit-brain-0.3.3/brainpy/integration/diff_equation.py
0.701611
0.212988
diff_equation.py
pypi
import numpy as np from .diff_equation import DiffEquation from .. import profile from ..backend import normal_like from ..errors import IntegratorError __all__ = [ 'euler', 'heun', 'rk2', 'rk3', 'rk4', 'rk4_alternative', 'exponential_euler', 'milstein_Ito', 'milstein_Stra', ] def euler(diff_eqs): __f = diff_eqs.func __dt = profile.get_dt() # SDE if diff_eqs.is_stochastic: __dt_sqrt = np.sqrt(profile.get_dt()) if diff_eqs.is_multi_return: if diff_eqs.return_type == '(x,x),': def int_func(y0, t, *args): val = __f(y0, t, *args) dfdg = val[0] df = dfdg[0] * __dt dW = normal_like(y0) dg = __dt_sqrt * dfdg[1] * dW y = y0 + df + dg return (y,) + tuple(val[1:]) else: raise ValueError else: if diff_eqs.return_type == '(x,x),': def int_func(y0, t, *args): val = __f(y0, t, *args)[0] df = val[0] * __dt dW = normal_like(y0) dg = __dt_sqrt * val[1] * dW return y0 + df + dg elif diff_eqs.return_type == 'x,x': def int_func(y0, t, *args): val = __f(y0, t, *args) df = val[0] * __dt dW = normal_like(y0) dg = __dt_sqrt * val[1] * dW return y0 + df + dg else: raise IntegratorError # ODE else: if diff_eqs.is_multi_return: if diff_eqs.return_type in ['(x,),', '(x,x),']: def int_func(y0, t, *args): val = __f(y0, t, *args) y = y0 + __dt * val[0][0] return (y,) + tuple(val[1:]) else: raise IntegratorError(f'Unrecognized differential return type: ' f'{diff_eqs.return_type}') else: if diff_eqs.return_type == 'x': def int_func(y0, t, *args): return y0 + __dt * __f(y0, t, *args) elif diff_eqs.return_type == 'x,x': def int_func(y0, t, *args): return y0 + __dt * __f(y0, t, *args)[0] elif diff_eqs.return_type in ['(x,),', '(x,x),']: def int_func(y0, t, *args): return y0 + __dt * __f(y0, t, *args)[0][0] else: raise IntegratorError(f'Unrecognized differential return type: ' f'{diff_eqs.return_type}') return int_func def rk2(diff_eqs, __beta=2 / 3): __f = diff_eqs.func __dt = profile.get_dt() if diff_eqs.is_stochastic: raise NotImplementedError else: if diff_eqs.is_multi_return: if diff_eqs.return_type in ['(x,),', '(x,x),']: def int_func(y0, t, *args): val = __f(y0, t, *args) k1 = val[0][0] k2 = __f(y0 + __beta * __dt * k1, t + __beta * __dt, *args)[0][0] y = y0 + __dt * ((1 - 1 / (2 * __beta)) * k1 + 1 / (2 * __beta) * k2) return (y,) + tuple(val[1:]) else: raise IntegratorError(f'Unrecognized differential return type: ' f'{diff_eqs.return_type}') else: if diff_eqs.return_type == 'x': def int_func(y0, t, *args): k1 = __f(y0, t, *args) k2 = __f(y0 + __beta * __dt * k1, t + __beta * __dt, *args) y = y0 + __dt * ((1 - 1 / (2 * __beta)) * k1 + 1 / (2 * __beta) * k2) return y elif diff_eqs.return_type == 'x,x': def int_func(y0, t, *args): k1 = __f(y0, t, *args)[0] k2 = __f(y0 + __beta * __dt * k1, t + __beta * __dt, *args)[0] y = y0 + __dt * ((1 - 1 / (2 * __beta)) * k1 + 1 / (2 * __beta) * k2) return y elif diff_eqs.return_type in ['(x,),', '(x,x),']: def int_func(y0, t, *args): k1 = __f(y0, t, *args)[0][0] k2 = __f(y0 + __beta * __dt * k1, t + __beta * __dt, *args)[0][0] y = y0 + __dt * ((1 - 1 / (2 * __beta)) * k1 + 1 / (2 * __beta) * k2) return y else: raise IntegratorError(f'Unrecognized differential return type: ' f'{diff_eqs.return_type}') return int_func def heun(diff_eqs): __f = diff_eqs.func __dt = profile.get_dt() if diff_eqs.is_stochastic: __dt_sqrt = np.sqrt(profile.get_dt()) if diff_eqs.is_functional_noise: if diff_eqs.is_multi_return: if diff_eqs.return_type == '(x,x),': def int_func(y0, t, *args): val = __f(y0, t, *args) dfdg = val[0] dg = dfdg[1] df = dfdg[0] * __dt dW = normal_like(y0) y_bar = y0 + dg * dW * __dt_sqrt dg_bar = __f(y_bar, t, *args)[0][1] dg = 0.5 * (dg + dg_bar) * dW * __dt_sqrt y = y0 + df + dg return (y,) + tuple(val[1:]) else: raise ValueError else: if diff_eqs.return_type == '(x,x),': def int_func(y0, t, *args): val = __f(y0, t, *args)[0] df = val[0] * __dt dg = val[1] dW = normal_like(y0) y_bar = y0 + dg * dW * __dt_sqrt dg_bar = __f(y_bar, t, *args)[0][1] dg = 0.5 * (dg + dg_bar) * dW * __dt_sqrt y = y0 + df + dg return y elif diff_eqs.return_type == 'x,x': def int_func(y0, t, *args): val = __f(y0, t, *args) df = val[0] * __dt dg = val[1] dW = normal_like(y0) y_bar = y0 + dg * dW * __dt_sqrt dg_bar = __f(y_bar, t, *args)[1] dg = 0.5 * (dg + dg_bar) * dW * __dt_sqrt y = y0 + df + dg return y else: raise IntegratorError return int_func else: return euler(diff_eqs) else: return rk2(diff_eqs, __beta=1.) def rk3(diff_eqs): __f = diff_eqs.func __dt = profile.get_dt() if diff_eqs.is_stochastic: raise NotImplementedError else: if diff_eqs.is_multi_return: if diff_eqs.return_type in ['(x,),', '(x,x),']: def int_func(y0, t, *args): val = __f(y0, t, *args) k1 = val[0][0] k2 = __f(y0 + __dt / 2 * k1, t + __dt / 2, *args)[0][0] k3 = __f(y0 - __dt * k1 + 2 * __dt * k2, t + __dt, *args)[0][0] y = y0 + __dt / 6 * (k1 + 4 * k2 + k3) return (y,) + tuple(val[1:]) else: raise IntegratorError(f'Unrecognized differential return type: ' f'{diff_eqs.return_type}') else: if diff_eqs.return_type == 'x': def int_func(y0, t, *args): k1 = __f(y0, t, *args) k2 = __f(y0 + __dt / 2 * k1, t + __dt / 2, *args) k3 = __f(y0 - __dt * k1 + 2 * __dt * k2, t + __dt, *args) return y0 + __dt / 6 * (k1 + 4 * k2 + k3) elif diff_eqs.return_type == 'x,x': def int_func(y0, t, *args): k1 = __f(y0, t, *args)[0] k2 = __f(y0 + __dt / 2 * k1, t + __dt / 2, *args)[0] k3 = __f(y0 - __dt * k1 + 2 * __dt * k2, t + __dt, *args)[0] return y0 + __dt / 6 * (k1 + 4 * k2 + k3) elif diff_eqs.return_type in ['(x,),', '(x,x),']: def int_func(y0, t, *args): k1 = __f(y0, t, *args)[0][0] k2 = __f(y0 + __dt / 2 * k1, t + __dt / 2, *args)[0][0] k3 = __f(y0 - __dt * k1 + 2 * __dt * k2, t + __dt, *args)[0][0] return y0 + __dt / 6 * (k1 + 4 * k2 + k3) else: raise IntegratorError(f'Unrecognized differential return type: ' f'{diff_eqs.return_type}') return int_func def rk4(diff_eqs): __f = diff_eqs.func __dt = profile.get_dt() if diff_eqs.is_stochastic: raise NotImplementedError else: if diff_eqs.is_multi_return: if diff_eqs.return_type in ['(x,),', '(x,x),']: def int_func(y0, t, *args): val = __f(y0, t, *args) k1 = val[0][0] k2 = __f(y0 + __dt / 2 * k1, t + __dt / 2, *args)[0][0] k3 = __f(y0 + __dt / 2 * k2, t + __dt / 2, *args)[0][0] k4 = __f(y0 + __dt * k3, t + __dt, *args)[0][0] y = y0 + __dt / 6 * (k1 + 2 * k2 + 2 * k3 + k4) return (y,) + tuple(val[1:]) else: raise IntegratorError(f'Unrecognized differential return type: ' f'{diff_eqs.return_type}') else: if diff_eqs.return_type == 'x': def int_func(y0, t, *args): k1 = __f(y0, t, *args) k2 = __f(y0 + __dt / 2 * k1, t + __dt / 2, *args) k3 = __f(y0 + __dt / 2 * k2, t + __dt / 2, *args) k4 = __f(y0 + __dt * k3, t + __dt, *args) return y0 + __dt / 6 * (k1 + 2 * k2 + 2 * k3 + k4) elif diff_eqs.return_type == 'x,x': def int_func(y0, t, *args): k1 = __f(y0, t, *args)[0] k2 = __f(y0 + __dt / 2 * k1, t + __dt / 2, *args)[0] k3 = __f(y0 + __dt / 2 * k2, t + __dt / 2, *args)[0] k4 = __f(y0 + __dt * k3, t + __dt, *args)[0] return y0 + __dt / 6 * (k1 + 2 * k2 + 2 * k3 + k4) elif diff_eqs.return_type in ['(x,),', '(x,x),']: def int_func(y0, t, *args): k1 = __f(y0, t, *args)[0][0] k2 = __f(y0 + __dt / 2 * k1, t + __dt / 2, *args)[0][0] k3 = __f(y0 + __dt / 2 * k2, t + __dt / 2, *args)[0][0] k4 = __f(y0 + __dt * k3, t + __dt, *args)[0][0] return y0 + __dt / 6 * (k1 + 2 * k2 + 2 * k3 + k4) else: raise IntegratorError(f'Unrecognized differential return type: ' f'{diff_eqs.return_type}') return int_func def rk4_alternative(diff_eqs): __f = diff_eqs.func __dt = profile.get_dt() if diff_eqs.is_stochastic: raise IntegratorError('"RK4_alternative" method doesn\'t support stochastic differential equation.') else: if diff_eqs.is_multi_return: if diff_eqs.return_type in ['(x,),', '(x,x),']: def int_func(y0, t, *args): val = __f(y0, t, *args) k1 = val[0][0] k2 = __f(y0 + __dt / 3 * k1, t + __dt / 3, *args)[0][0] k3 = __f(y0 - __dt / 3 * k1 + __dt * k2, t + 2 * __dt / 3, *args)[0][0] k4 = __f(y0 + __dt * k1 - __dt * k2 + __dt * k3, t + __dt, *args)[0][0] y = y0 + __dt / 8 * (k1 + 3 * k2 + 3 * k3 + k4) return (y,) + tuple(val[1:]) else: raise IntegratorError(f'Unrecognized differential return type: ' f'{diff_eqs.return_type}') else: if diff_eqs.return_type == 'x': def int_func(y0, t, *args): k1 = __f(y0, t, *args) k2 = __f(y0 + __dt / 3 * k1, t + __dt / 3, *args) k3 = __f(y0 - __dt / 3 * k1 + __dt * k2, t + 2 * __dt / 3, *args) k4 = __f(y0 + __dt * k1 - __dt * k2 + __dt * k3, t + __dt, *args) return y0 + __dt / 8 * (k1 + 3 * k2 + 3 * k3 + k4) elif diff_eqs.return_type == 'x,x': def int_func(y0, t, *args): k1 = __f(y0, t, *args)[0] k2 = __f(y0 + __dt / 3 * k1, t + __dt / 3, *args)[0] k3 = __f(y0 - __dt / 3 * k1 + __dt * k2, t + 2 * __dt / 3, *args)[0] k4 = __f(y0 + __dt * k1 - __dt * k2 + __dt * k3, t + __dt, *args)[0] return y0 + __dt / 8 * (k1 + 3 * k2 + 3 * k3 + k4) elif diff_eqs.return_type in ['(x,),', '(x,x),']: def int_func(y0, t, *args): k1 = __f(y0, t, *args)[0][0] k2 = __f(y0 + __dt / 3 * k1, t + __dt / 3, *args)[0][0] k3 = __f(y0 - __dt / 3 * k1 + __dt * k2, t + 2 * __dt / 3, *args)[0][0] k4 = __f(y0 + __dt * k1 - __dt * k2 + __dt * k3, t + __dt, *args)[0][0] return y0 + __dt / 8 * (k1 + 3 * k2 + 3 * k3 + k4) else: raise IntegratorError(f'Unrecognized differential return type: ' f'{diff_eqs.return_type}') return int_func def exponential_euler(diff_eq): assert isinstance(diff_eq, DiffEquation) f = diff_eq.f dt = profile.get_dt() if diff_eq.is_stochastic: dt_sqrt = np.sqrt(dt) g = diff_eq.g if callable(g): if diff_eq.is_multi_return: def int_f(y0, t, *args): val = f(y0, t, *args) dydt, linear_part = val[0], val[1] dW = normal_like(y0) dg = dt_sqrt * g(y0, t, *args) * dW exp = np.exp(linear_part * dt) y1 = y0 + (exp - 1) / linear_part * dydt + exp * dg return (y1,) + tuple(val[2:]) else: def int_f(y0, t, *args): dydt, linear_part = f(y0, t, *args) dW = normal_like(y0) dg = dt_sqrt * g(y0, t, *args) * dW exp = np.exp(linear_part * dt) y1 = y0 + (exp - 1) / linear_part * dydt + exp * dg return y1 else: assert isinstance(g, (int, float, np.ndarray)) if diff_eq.is_multi_return: def int_f(y0, t, *args): val = f(y0, t, *args) dydt, linear_part = val[0], val[1] dW = normal_like(y0) dg = dt_sqrt * g * dW exp = np.exp(linear_part * dt) y1 = y0 + (exp - 1) / linear_part * dydt + exp * dg return (y1,) + tuple(val[1:]) else: def int_f(y0, t, *args): dydt, linear_part = f(y0, t, *args) dW = normal_like(y0) dg = dt_sqrt * g * dW exp = np.exp(linear_part * dt) y1 = y0 + (exp - 1) / linear_part * dydt + exp * dg return y1 else: if diff_eq.is_multi_return: def int_f(y0, t, *args): val = f(y0, t, *args) df, linear_part = val[0], val[1] y = y0 + (np.exp(linear_part * dt) - 1) / linear_part * df return (y,) + tuple(val[2:]) else: def int_f(y0, t, *args): df, linear_part = f(y0, t, *args) y = y0 + (np.exp(linear_part * dt) - 1) / linear_part * df return y return int_f def milstein_Ito(diff_eq): __f = diff_eq.func __dt = profile.get_dt() __dt_sqrt = np.sqrt(profile.get_dt()) if diff_eq.is_stochastic: if diff_eq.is_functional_noise: if diff_eq.return_type == '(x,x),': if diff_eq.is_multi_return: def int_func(y0, t, *args): dW = normal_like(y0) val = __f(y0, t, *args) dfdg = val[0][0] df = dfdg[0] * __dt g_n = dfdg[1] dg = dfdg[1] * dW * __dt_sqrt y_n_bar = y0 + df + g_n * __dt_sqrt g_n_bar = __f(y_n_bar, t, *args)[0][1] y1 = y0 + df + dg + 0.5 * (g_n_bar - g_n) * (dW * dW * __dt_sqrt - __dt_sqrt) return (y1,) + tuple(val[1:]) else: def int_func(y0, t, *args): dW = normal_like(y0) val = __f(y0, t, *args) dfdg = val[0][0] df = dfdg[0] * __dt g_n = dfdg[1] dg = dfdg[1] * dW * __dt_sqrt y_n_bar = y0 + df + g_n * __dt_sqrt g_n_bar = __f(y_n_bar, t, *args)[0][1] y1 = y0 + df + dg + 0.5 * (g_n_bar - g_n) * (dW * dW * __dt_sqrt - __dt_sqrt) return y1 elif diff_eq.return_type == 'x,x': def int_func(y0, t, *args): dW = normal_like(y0) val = __f(y0, t, *args) df = val[0] * __dt g_n = val[1] dg = g_n * dW * __dt_sqrt y_n_bar = y0 + df + g_n * __dt_sqrt g_n_bar = __f(y_n_bar, t, *args)[1] y1 = y0 + df + dg + 0.5 * (g_n_bar - g_n) * (dW * dW * __dt_sqrt - __dt_sqrt) return y1 else: raise ValueError return int_func return euler(diff_eq) def milstein_Stra(diff_eq): __f = diff_eq.func __dt = profile.get_dt() __dt_sqrt = np.sqrt(profile.get_dt()) if diff_eq.is_stochastic: if diff_eq.is_functional_noise: if diff_eq.return_type == '(x,x),': if diff_eq.is_multi_return: def int_func(y0, t, *args): dW = normal_like(y0) val = __f(y0, t, *args) dfdg = val[0] df = dfdg[0] * __dt g_n = dfdg[1] dg = dfdg[1] * dW * __dt_sqrt y_n_bar = y0 + df + g_n * __dt_sqrt g_n_bar = __f(y_n_bar, t, *args)[0][1] extra_term = 0.5 * (g_n_bar - g_n) * (dW * dW * __dt_sqrt) y1 = y0 + df + dg + extra_term return (y1,) + tuple(val[1:]) else: def int_func(y0, t, *args): dW = normal_like(y0) val = __f(y0, t, *args) dfdg = val[0] df = dfdg[0] * __dt g_n = dfdg[1] dg = dfdg[1] * dW * __dt_sqrt y_n_bar = y0 + df + g_n * __dt_sqrt g_n_bar = __f(y_n_bar, t, *args)[0][1] extra_term = 0.5 * (g_n_bar - g_n) * (dW * dW * __dt_sqrt) y1 = y0 + df + dg + extra_term return y1 elif diff_eq.return_type == 'x,x': def int_func(y0, t, *args): dW = normal_like(y0) dfdg = __f(y0, t, *args) df = dfdg[0] * __dt g_n = dfdg[1] dg = dfdg[1] * dW * __dt_sqrt y_n_bar = y0 + df + g_n * __dt_sqrt g_n_bar = __f(y_n_bar, t, *args)[0][1] extra_term = 0.5 * (g_n_bar - g_n) * (dW * dW * __dt_sqrt) y1 = y0 + df + dg + extra_term return y1 else: raise ValueError return int_func return euler(diff_eq)
/scikit-brain-0.3.3.tar.gz/scikit-brain-0.3.3/brainpy/integration/methods.py
0.505859
0.224034
methods.py
pypi
from . import diff_equation from . import integrator from . import methods from . import sympy_tools from .diff_equation import * from .integrator import * from .sympy_tools import * from .. import profile _SUPPORT_METHODS = [ 'euler', 'midpoint', 'heun', 'rk2', 'rk3', 'rk4', 'rk4_alternative', 'exponential', 'milstein', 'milstein_ito', 'milstein_stra', ] def integrate(func=None, method=None): """Generate the one-step integrator function for differential equations. Using this method, the users only need to define the right side of the equation. For example, for the `m` channel in the Hodgkin–Huxley neuron model .. math:: \\alpha = {0.1 * (V + 40 \\over 1 - \\exp(-(V + 40) / 10)} \\beta = 4.0 * \\exp(-(V + 65) / 18) {dm \\over dt} = \\alpha * (1 - m) - \\beta * m Using ``BrainPy``, this ODE function can be written as >>> import numpy as np >>> from brainpy import integrate >>> >>> @integrate(method='rk4') >>> def int_m(m, t, V): >>> alpha = 0.1 * (V + 40) / (1 - np.exp(-(V + 40) / 10)) >>> beta = 4.0 * np.exp(-(V + 65) / 18) >>> return alpha * (1 - m) - beta * m Parameters ---------- func : callable The function at the right hand of the differential equation. If a stochastic equation (SDE) is defined, then `func` is the drift coefficient (the deterministic part) of the SDE. method : None, str, callable The method of numerical integrator. Returns ------- integrator : Integrator If `f` is provided, then the one-step numerical integrator will be returned. if not, the wrapper will be provided. """ method = method if method is not None else profile.get_numerical_method() _integrator_ = get_integrator(method) if func is None: return lambda f: _integrator_(DiffEquation(func=f)) else: return _integrator_(DiffEquation(func=func))
/scikit-brain-0.3.3.tar.gz/scikit-brain-0.3.3/brainpy/integration/__init__.py
0.847432
0.392249
__init__.py
pypi
import math import numba import numpy from numba.extending import overload from .. import profile # Get functions in math _functions_in_math = [] for key in dir(math): if not key.startswith('__'): _functions_in_math.append(getattr(math, key)) # Get functions in NumPy _functions_in_numpy = [] for key in dir(numpy): if not key.startswith('__'): _functions_in_numpy.append(getattr(numpy, key)) for key in dir(numpy.random): if not key.startswith('__'): _functions_in_numpy.append(getattr(numpy.random, key)) for key in dir(numpy.linalg): if not key.startswith('__'): _functions_in_numpy.append(getattr(numpy.linalg, key)) def func_in_numpy_or_math(func): return func in _functions_in_math or func in _functions_in_numpy @overload(numpy.cbrt) def cbrt_func(x): def cbrt(x): return numpy.power(x, 1. / 3) return cbrt @overload(numpy.squeeze) def squeeze_func(a, axis=None): if isinstance(axis, numba.types.NoneType): def squeeze(a, axis=None): shape = [] for s in a.shape: if s != 1: shape.append(s) return numpy.reshape(a, shape) return squeeze elif isinstance(axis, numba.types.Integer): def squeeze(a, axis=None): shape = [] for i, s in enumerate(a.shape): if s != 1 or i != axis: shape.append(s) return numpy.reshape(a, shape) return squeeze else: def squeeze(a, axis=None): shape = [] for i, s in enumerate(a.shape): if s != 1 or i not in axis: shape.append(s) return numpy.reshape(a, shape) return squeeze @overload(numpy.float_power) def float_power_func(x1, x2): def float_power(x1, x2): return numpy.power(numpy.float(x1), x2) return float_power @overload(numpy.heaviside) def heaviside_func(x1, x2): def heaviside(x1, x2): return numpy.where(x1 == 0, x2, numpy.where(x1 > 0, 1, 0)) return heaviside @overload(numpy.moveaxis) def moveaxis_func(x, source, destination): def moveaxis(x, source, destination): shape = list(x.shape) s = shape.pop(source) shape.insert(destination, s) return numpy.transpose(x, tuple(shape)) return moveaxis @overload(numpy.swapaxes) def swapaxes_func(x, axis1, axis2): def swapaxes(x, axis1, axis2): shape = list(x.shape) s1 = shape[axis1] s2 = shape[axis2] shape[axis1] = s2 shape[axis2] = s1 return numpy.transpose(x, tuple(shape)) return swapaxes @overload(numpy.logspace) def logspace_func(start, stop, num=50, endpoint=True, base=10.0, dtype=None): def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None): return numpy.power(base, numpy.linspace(start, stop, num=num, endpoint=endpoint)).astype(dtype) return logspace @overload(numpy.inner) def inner_func(a, b): def inner(a, b): return numpy.sum(a * b) return inner @overload(numpy.fix) def fix_func(x): def fix(x): return numpy.where(x >= 0, x, -numpy.floor(-x)) return fix @overload(numpy.clip) def clip_func(x, x_min, x_max): def clip(x, x_min, x_max): x = numpy.maximum(x, x_min) x = numpy.minimum(x, x_max) return x return clip @overload(numpy.allclose) def allclose_func(a, b, rtol=1e-05, atol=1e-08): def allclose(a, b, rtol=1e-05, atol=1e-08): return numpy.all(numpy.absolute(a - b) <= (atol + rtol * numpy.absolute(b))) return allclose @overload(numpy.isclose) def isclose_func(a, b, rtol=1e-05, atol=1e-08): def isclose(a, b, rtol=1e-05, atol=1e-08): return numpy.absolute(a - b) <= (atol + rtol * numpy.absolute(b)) return isclose @overload(numpy.average) def average(a, axis=None, weights=None): if isinstance(weights, numba.types.NoneType): def func(a, axis=None, weights=None): return numpy.mean(a, axis) return func else: def func(a, axis=None, weights=None): return numpy.sum(a * weights, axis=axis) / sum(weights) return func @numba.generated_jit(**profile.get_numba_profile()) def normal_like(x): if isinstance(x, (numba.types.Integer, numba.types.Float)): return lambda x: numpy.random.normal() else: return lambda x: numpy.random.normal(0., 1.0, x.shape)
/scikit-brain-0.3.3.tar.gz/scikit-brain-0.3.3/brainpy/backend/__init__.py
0.613352
0.330944
__init__.py
pypi
import math from collections import OrderedDict import numba as nb from numba import cuda import numpy as np from .. import profile from ..errors import TypeMismatchError __all__ = [ 'TypeChecker', 'ObjState', 'NeuState', 'SynState', 'gpu_set_vector_val', 'ListConn', 'MatConn', 'Array', 'Int', 'Float', 'List', 'Dict', ] class TypeChecker(object): def __init__(self, help): self.help = help def check(self, cls): raise NotImplementedError @classmethod def make_copy(cls, *args, **kwargs): raise NotImplementedError def gpu_set_scalar_val(data, val, idx): i = cuda.grid(1) if i < data.shape[1]: data[idx, i] = val def gpu_set_vector_val(data, val, idx): i = cuda.grid(1) if i < data.shape[1]: data[idx, i] = val[i] if cuda.is_available(): gpu_set_scalar_val = cuda.jit('(float64[:, :], float64, int64)')(gpu_set_scalar_val) gpu_set_vector_val = cuda.jit('(float64[:, :], float64[:], int64)')(gpu_set_vector_val) class ObjState(dict, TypeChecker): def __init__(self, *args, help='', **kwargs): # 1. initialize TypeChecker TypeChecker.__init__(self, help=help) # 2. get variables variables = OrderedDict() for a in args: if isinstance(a, str): variables[a] = 0. elif isinstance(a, (tuple, list)): for v in a: variables[v] = 0. elif isinstance(a, dict): for key, val in a.items(): if not isinstance(val, (int, float)): raise ValueError(f'The default value setting in a dict must be int/float.') variables[key] = val else: raise ValueError(f'Only support str/tuple/list/dict, not {type(variables)}.') for key, val in kwargs.items(): if not isinstance(val, (int, float)): raise ValueError(f'The default value setting must be int/float.') variables[key] = val # 3. others self._keys = list(variables.keys()) self._values = list(variables.values()) self._vars = variables def check(self, cls): if not isinstance(cls, type(self)): raise TypeMismatchError(f'Must be an instance of "{type(self)}", but got "{type(cls)}".') for k in self._keys: if k not in cls: raise TypeMismatchError(f'Key "{k}" is not found in "cls".') def get_cuda_data(self): _data_cuda = self.__getitem__('_data_cuda') if _data_cuda is None: _data = self.__getitem__('_data') _data_cuda = cuda.to_device(_data) super(ObjState, self).__setitem__('_data_cuda', _data_cuda) return _data_cuda def __setitem__(self, key, val): if key in self._vars: # get data data = self.__getitem__('_data') _var2idx = self.__getitem__('_var2idx') idx = _var2idx[key] # gpu setattr if profile.run_on_gpu(): gpu_data = self.get_cuda_data() if data.shape[1] <= profile._num_thread_gpu: num_thread = data.shape[1] num_block = 1 else: num_thread = profile._num_thread_gpu num_block = math.ceil(data.shape[1] / profile._num_thread_gpu) if np.isscalar(val): gpu_set_scalar_val[num_block, num_thread](gpu_data, val, idx) else: if val.shape[0] != data.shape[1]: raise ValueError(f'Wrong value dimension {val.shape[0]} != {data.shape[1]}') gpu_set_vector_val[num_block, num_thread](gpu_data, val, idx) cuda.synchronize() # cpu setattr else: data[idx] = val elif key in ['_data', '_var2idx', '_idx2var']: raise KeyError(f'"{key}" cannot be modified.') else: raise KeyError(f'"{key}" is not defined in {type(self).__name__}, ' f'only finds "{str(self._keys)}".') def __str__(self): return f'{self.__class__.__name__} ({str(self._keys)})' def __repr__(self): return self.__str__() class NeuState(ObjState): """Neuron State Management. """ def __call__(self, size): if isinstance(size, int): size = (size,) elif isinstance(size, (tuple, list)): size = tuple(size) else: raise ValueError(f'Unknown size type: {type(size)}.') data = np.zeros((len(self._vars),) + size, dtype=np.float_) var2idx = dict() idx2var = dict() state = dict() for i, (k, v) in enumerate(self._vars.items()): state[k] = data[i] data[i] = v var2idx[k] = i idx2var[i] = k state['_data'] = data state['_data_cuda'] = None state['_var2idx'] = var2idx state['_idx2var'] = idx2var dict.__init__(self, state) return self def make_copy(self, size): obj = NeuState(self._vars) return obj(size=size) @nb.njit([nb.types.UniTuple(nb.int64[:], 2)(nb.int64[:], nb.int64[:], nb.int64[:]), nb.types.UniTuple(nb.int64, 2)(nb.int64, nb.int64, nb.int64)]) def update_delay_indices(delay_in, delay_out, delay_len): _delay_in = (delay_in + 1) % delay_len _delay_out = (delay_out + 1) % delay_len return _delay_in, _delay_out class SynState(ObjState): """Synapse State Management. """ def __init__(self, *args, help='', **kwargs): super(SynState, self).__init__(*args, help=help, **kwargs) self._delay_len = 1 self._delay_in = 0 self._delay_out = 0 def __call__(self, size, delay=None, delay_vars=()): # check size if isinstance(size, int): size = (size,) elif isinstance(size, (tuple, list)): size = tuple(size) else: raise ValueError(f'Unknown size type: {type(size)}.') # check delay delay = 0 if (delay is None) or (delay < 1) else delay assert isinstance(delay, int), '"delay" must be a int to specify the delay length.' self._delay_len = delay self._delay_in = delay - 1 # check delay_vars if isinstance(delay_vars, str): delay_vars = (delay_vars,) elif isinstance(delay_vars, (tuple, list)): delay_vars = tuple(delay_vars) else: raise ValueError(f'Unknown delay_vars type: {type(delay_vars)}.') # initialize data length = len(self._vars) + delay * len(delay_vars) data = np.zeros((length,) + size, dtype=np.float_) var2idx = dict() idx2var = dict() state = dict() for i, (k, v) in enumerate(self._vars.items()): data[i] = v state[k] = data[i] var2idx[k] = i idx2var[i] = k index_offset = len(self._vars) for i, v in enumerate(delay_vars): var2idx[f'_{v}_offset'] = i * delay + index_offset state[f'_{v}_delay'] = data[i * delay + index_offset: (i + 1) * delay + index_offset] state['_data'] = data state['_data_cuda'] = None state['_var2idx'] = var2idx state['_idx2var'] = idx2var dict.__init__(self, state) return self def make_copy(self, size, delay=None, delay_vars=()): obj = SynState(self._vars) return obj(size=size, delay=delay, delay_vars=delay_vars) def delay_push(self, g, var): if self._delay_len > 0: data = self.__getitem__('_data') offset = self.__getitem__('_var2idx')[f'_{var}_offset'] data[self._delay_in + offset] = g def delay_pull(self, var): if self._delay_len > 0: data = self.__getitem__('_data') offset = self.__getitem__('_var2idx')[f'_{var}_offset'] return data[self._delay_out + offset] else: data = self.__getitem__('_data') var2idx = self.__getitem__('_var2idx') return data[var2idx[var]] def _update_delay_indices(self): din, dout = update_delay_indices(self._delay_in, self._delay_out, self._delay_len) self._delay_in = din self._delay_out = dout class ListConn(TypeChecker): """Synaptic connection with list type.""" def __init__(self, help=''): super(ListConn, self).__init__(help=help) def check(self, cls): if profile.is_jit(): if not isinstance(cls, nb.typed.List): raise TypeMismatchError(f'In numba mode, "cls" must be an instance of {type(nb.typed.List)}, ' f'but got {type(cls)}. Hint: you can use "ListConn.create()" method.') if not isinstance(cls[0], (nb.typed.List, np.ndarray)): raise TypeMismatchError(f'In numba mode, elements in "cls" must be an instance of ' f'{type(nb.typed.List)} or ndarray, but got {type(cls[0])}. ' f'Hint: you can use "ListConn.create()" method.') else: if not isinstance(cls, list): raise TypeMismatchError(f'ListConn requires a list, but got {type(cls)}.') if not isinstance(cls[0], (list, np.ndarray)): raise TypeMismatchError(f'ListConn requires the elements of the list must be list or ' f'ndarray, but got {type(cls)}.') @classmethod def make_copy(cls, conn): assert isinstance(conn, (list, tuple)), '"conn" must be a tuple/list.' assert isinstance(conn[0], (list, tuple)), 'Elements of "conn" must be tuple/list.' if profile.is_jit(): a_list = nb.typed.List() for l in conn: a_list.append(np.uint64(l)) else: a_list = conn return a_list def __str__(self): return 'ListConn' class MatConn(TypeChecker): """Synaptic connection with matrix (2d array) type.""" def __init__(self, help=''): super(MatConn, self).__init__(help=help) def check(self, cls): if not (isinstance(cls, np.ndarray) and np.ndim(cls) == 2): raise TypeMismatchError(f'MatConn requires a two-dimensional ndarray.') def __str__(self): return 'MatConn' class SliceConn(TypeChecker): def __init__(self, help=''): super(SliceConn, self).__init__(help=help) def check(self, cls): if not (isinstance(cls, np.ndarray) and np.shape[1] == 2): raise TypeMismatchError(f'') def __str__(self): return 'SliceConn' class Array(TypeChecker): """NumPy ndarray.""" def __init__(self, dim, help=''): self.dim = dim super(Array, self).__init__(help=help) def __call__(self, size): if isinstance(size, int): assert self.dim == 1 else: assert len(size) == self.dim return np.zeros(size, dtype=np.float_) def check(self, cls): if not (isinstance(cls, np.ndarray) and np.ndim(cls) == self.dim): raise TypeMismatchError(f'MatConn requires a {self.dim}-D ndarray.') def __str__(self): return type(self).__name__ + f' (dim={self.dim})' class String(TypeChecker): def __init__(self, help=''): super(String, self).__init__(help=help) def check(self, cls): if not isinstance(cls, str): raise TypeMismatchError(f'Require a string, got {type(cls)}.') def __str__(self): return 'StringType' class Int(TypeChecker): def __init__(self, help=''): super(Int, self).__init__(help=help) def check(self, cls): if not isinstance(cls, int): raise TypeMismatchError(f'Require an int, got {type(cls)}.') def __str__(self): return 'IntType' class Float(TypeChecker): def __init__(self, help=''): super(Float, self).__init__(help=help) def check(self, cls): if not isinstance(cls, float): raise TypeMismatchError(f'Require a float, got {type(cls)}.') def __str__(self): return 'Floatype' class List(TypeChecker): def __init__(self, item_type=None, help=''): if item_type is None: self.item_type = None else: assert isinstance(item_type, TypeChecker), 'Must be a TypeChecker.' self.item_type = item_type super(List, self).__init__(help=help) def check(self, cls): if profile.is_jit(): if not isinstance(cls, nb.typed.List): raise TypeMismatchError(f'In numba, "List" requires an instance of {type(nb.typed.List)}, ' f'but got {type(cls)}.') else: if not isinstance(cls, list): raise TypeMismatchError(f'"List" requires an instance of list, ' f'but got {type(cls)}.') if self.item_type is not None: self.item_type.check(cls[0]) def __str__(self): return type(self).__name__ + f'(item_type={str(self.item_type)})' class Dict(TypeChecker): def __init__(self, key_type=String, item_type=None, help=''): if key_type is not None: assert isinstance(key_type, TypeChecker), 'Must be a TypeChecker.' self.key_type = key_type if item_type is not None: assert isinstance(item_type, TypeChecker), 'Must be a TypeChecker.' self.item_type = item_type super(Dict, self).__init__(help=help) def check(self, cls): if profile.is_jit(): if not isinstance(cls, nb.typed.Dict): raise TypeMismatchError(f'In numba, "Dict" requires an instance of {type(nb.typed.Dict)}, ' f'but got {type(cls)}.') else: if not isinstance(cls, dict): raise TypeMismatchError(f'"Dict" requires an instance of dict, ' f'but got {type(cls)}.') if self.key_type is not None: for key in cls.keys(): self.key_type.check(key) if self.item_type is not None: for item in cls.items(): self.item_type.check(item) def __str__(self): return type(self).__name__ + f'(key_type={str(self.key_type)}, item_type={str(self.item_type)})'
/scikit-brain-0.3.3.tar.gz/scikit-brain-0.3.3/brainpy/core/types.py
0.518302
0.196614
types.py
pypi
import time import numpy as np from numba import cuda from .base import Ensemble from .constants import INPUT_OPERATIONS from .constants import SCALAR_MODE from .neurons import NeuGroup from .synapses import SynConn from .. import profile from .. import tools from ..errors import ModelUseError __all__ = [ 'Network', ] class Network(object): """The main simulation controller in ``BrainPy``. ``Network`` handles the running of a simulation. It contains a set of objects that are added with `add()`. The `run()` method actually runs the simulation. The main loop runs according to user add orders. The objects in the `Network` are accessible via their names, e.g. `net.name` would return the `object` (including neurons and synapses). """ def __init__(self, *args, mode='once', **kwargs): # store and neurons and synapses self._all_neu_groups = [] self._all_syn_conns = [] self._all_objects = [] # store all objects self._objsets = dict() # record the current step self.t_start = 0. self.t_end = 0. self.t_duration = 0. # add objects self.add(*args, **kwargs) # check assert mode in ['once', 'repeat'] self.mode = mode self._step_func = None def _add_obj(self, obj, name=None): # check object type self._all_objects.append(obj) if isinstance(obj, NeuGroup): self._all_neu_groups.append(obj) elif isinstance(obj, SynConn): self._all_syn_conns.append(obj) else: raise ValueError(f'Unknown object type "{type(obj)}". Network only support NeuGroup and SynConn.') # check object name name = obj.name if name is None else name if name in self._objsets: raise KeyError(f'Name "{name}" has been used in the network, please change another name.') # add object in the network self._objsets[name] = obj setattr(self, name, obj) if obj.name != name: setattr(self, obj.name, obj) def add(self, *args, **kwargs): """Add object (neurons or synapses or monitor) to the network. Parameters ---------- args The nameless objects. kwargs The named objects, which can be accessed by `net.xxx` (xxx is the name of the object). """ for obj in args: self._add_obj(obj) for name, obj in kwargs.items(): self._add_obj(obj, name) def _format_inputs(self, inputs, run_length): # check try: assert isinstance(inputs, (tuple, list)) except AssertionError: raise ModelUseError('"inputs" must be a tuple/list.') if len(inputs) > 0 and not isinstance(inputs[0], (list, tuple)): if isinstance(inputs[0], Ensemble): inputs = [inputs] else: raise ModelUseError('Unknown input structure.') for inp in inputs: if not 3 <= len(inp) <= 4: raise ModelUseError('For each target, you must specify "(target, key, value, [operation])".') if len(inp) == 4: if inp[3] not in INPUT_OPERATIONS: raise ModelUseError(f'Input operation only support ' f'"{list(INPUT_OPERATIONS.keys())}", not "{inp[3]}".') # format input formatted_inputs = {} for inp in inputs: # target if isinstance(inp[0], str): target = getattr(self, inp[0]).name elif isinstance(inp[0], Ensemble): target = inp[0].name else: raise KeyError(f'Unknown input target: {str(inp[0])}') # key if not isinstance(inp[1], str): raise ModelUseError('For each input, input[1] must be a string ' 'to specify variable of the target.') key = inp[1] # value and data type if isinstance(inp[2], (int, float)): val = inp[2] data_type = 'fix' elif isinstance(inp[2], np.ndarray): val = inp[2] if val.shape[0] == run_length: data_type = 'iter' else: data_type = 'fix' else: raise ModelUseError(f'For each input, input[2] must be a numerical value to ' f'specify input values, but we get a {type(inp)}') # operation if len(inp) == 4: ops = inp[3] else: ops = '+' # append if target not in formatted_inputs: formatted_inputs[target] = [] format_inp = (key, val, ops, data_type) formatted_inputs[target].append(format_inp) return formatted_inputs def build(self, run_length, inputs=()): assert isinstance(run_length, int) code_scopes = {} code_lines = ['# network step function\n' 'def step_func(_t, _i, _dt):'] # inputs format_inputs = self._format_inputs(inputs, run_length) for obj in self._all_objects: if profile.run_on_gpu(): if obj.model.mode != SCALAR_MODE: raise ModelUseError('GPU mode only support scalar-based mode.') code_scopes[obj.name] = obj code_scopes[f'{obj.name}_runner'] = obj.runner lines_of_call = obj._build(inputs=format_inputs.get(obj.name, None), mon_length=run_length) code_lines.extend(lines_of_call) if profile.run_on_gpu(): code_scopes['cuda'] = cuda func_code = '\n '.join(code_lines) exec(compile(func_code, '', 'exec'), code_scopes) step_func = code_scopes['step_func'] if profile.show_format_code(): tools.show_code_str(func_code.replace('def ', f'def network_')) if profile.show_code_scope(): tools.show_code_scope(code_scopes, ['__builtins__', 'step_func']) return step_func def run(self, duration, inputs=(), report=False, report_percent=0.1): """Run the simulation for the given duration. This function provides the most convenient way to run the network. For example: Parameters ---------- duration : int, float, tuple, list The amount of simulation time to run for. inputs : list, tuple The receivers, external inputs and durations. report : bool Report the progress of the simulation. report_percent : float The speed to report simulation progress. """ # check the duration # ------------------ if isinstance(duration, (int, float)): start, end = 0, duration elif isinstance(duration, (tuple, list)): if len(duration) != 2: raise ModelUseError('Only support duration with the format of "(start, end)".') start, end = duration else: raise ValueError(f'Unknown duration type: {type(duration)}') self.t_start, self.t_end = start, end dt = profile.get_dt() ts = np.asarray(np.arange(start, end, dt), dtype=np.float_) run_length = ts.shape[0] if self.mode != 'repeat' or self._step_func is None: # initialize the function # ----------------------- self._step_func = self.build(run_length, inputs) self.t_duration = end - start else: # check running duration # ---------------------- if self.t_duration != (end - start): raise ModelUseError(f'Each run in "repeat" mode must be done ' f'with the same duration, but got ' f'{self.t_duration} != {end - start}.') # check and reset inputs # ---------------------- formatted_inputs = self._format_inputs(inputs, run_length) for obj_name, inps in formatted_inputs.items(): obj = getattr(self, obj_name) obj_inputs = obj.runner._inputs all_keys = list(obj_inputs.keys()) for key, val, ops, data_type in inps: if np.shape(obj_inputs[key][0]) != np.shape(val): raise ModelUseError(f'The input shape for "{key}" should keep the same. ' f'However, we got the last input shape ' f'= {np.shape(obj_inputs[key][0])}, ' f'and the current input shape = {np.shape(val)}') if obj_inputs[key][1] != ops: raise ModelUseError(f'The input operation for "{key}" should keep the same. ' f'However, we got the last operation is ' f'"{obj_inputs[key][1]}", and the current operation ' f'is "{ops}"') obj.runner.set_data(f'{key.replace(".", "_")}_inp', val) all_keys.remove(key) if len(all_keys): raise ModelUseError(f'The inputs of {all_keys} are not provided.') dt = self.dt if report: # Run the model with progress report # ---------------------------------- t0 = time.time() self._step_func(_t=ts[0], _i=0, _dt=dt) print('Compilation used {:.4f} s.'.format(time.time() - t0)) print("Start running ...") report_gap = int(run_length * report_percent) t0 = time.time() for run_idx in range(1, run_length): self._step_func(_t=ts[run_idx], _i=run_idx, _dt=dt) if (run_idx + 1) % report_gap == 0: percent = (run_idx + 1) / run_length * 100 print('Run {:.1f}% used {:.3f} s.'.format(percent, time.time() - t0)) print('Simulation is done in {:.3f} s.'.format(time.time() - t0)) else: # Run the model # ------------- for run_idx in range(run_length): self._step_func(_t=ts[run_idx], _i=run_idx, _dt=dt) # format monitor # -------------- for obj in self._all_objects: if profile.run_on_gpu(): obj.runner.gpu_data_to_cpu() obj.mon['ts'] = self.ts @property def ts(self): """Get the time points of the network. """ return np.array(np.arange(self.t_start, self.t_end, self.dt), dtype=np.float_) @property def dt(self): return profile.get_dt()
/scikit-brain-0.3.3.tar.gz/scikit-brain-0.3.3/brainpy/core/network.py
0.781747
0.375993
network.py
pypi
import re import typing import numpy as np from . import constants from .base import Ensemble from .base import ObjType from .neurons import NeuGroup from .neurons import NeuSubGroup from .types import SynState from .. import profile from .. import tools from ..connectivity import Connector from ..errors import ModelDefError from ..errors import ModelUseError __all__ = [ 'SynType', 'SynConn', 'delayed', ] _SYN_CONN_NO = 0 class SynType(ObjType): """Abstract Synapse Type. It can be defined based on a collection of synapses or a single synapse model. """ def __init__( self, name: str, ST: SynState, steps: typing.Union[callable, list, tuple], mode: str = 'vector', requires: dict = None, hand_overs: typing.Dict = None, heter_params_replace: dict = None, ): if mode not in [constants.SCALAR_MODE, constants.VECTOR_MODE, constants.MATRIX_MODE]: raise ModelDefError('SynType only support "scalar", "vector" or "matrix".') super(SynType, self).__init__( ST=ST, requires=requires, steps=steps, name=name, mode=mode, heter_params_replace=heter_params_replace, hand_overs=hand_overs) # inspect delay keys # ------------------ # delay function delay_funcs = [] for func in self.steps: if func.__name__.startswith('_brainpy_delayed_'): delay_funcs.append(func) if len(delay_funcs): delay_func_code = '\n'.join([tools.deindent(tools.get_main_code(func)) for func in delay_funcs]) delay_func_code_left = '\n'.join(tools.format_code(delay_func_code).lefts) # get delayed variables _delay_keys = set() delay_keys_in_left = set(re.findall(r'ST\[[\'"](\w+)[\'"]\]', delay_func_code_left)) if len(delay_keys_in_left) > 0: raise ModelDefError(f'Delayed function cannot assign value to "ST".') delay_keys = set(re.findall(r'ST\[[\'"](\w+)[\'"]\]', delay_func_code)) if len(delay_keys) > 0: _delay_keys.update(delay_keys) self._delay_keys = list(_delay_keys) class SynConn(Ensemble): """Synaptic connections. Parameters ---------- model : SynType The instantiated neuron type model. pars_update : dict, None Parameters to update. pre_group : NeuGroup, None Pre-synaptic neuron group. post_group : NeuGroup, None Post-synaptic neuron group. conn : Connector, None Connection method to create synaptic connectivity. num : int The number of the synapses. delay : float The time of the synaptic delay. monitors : list, tuple, None Variables to monitor. name : str, None The name of the neuron group. """ def __init__( self, model: SynType, pre_group: typing.Union[NeuGroup, NeuSubGroup] = None, post_group: typing.Union[NeuGroup, NeuSubGroup] = None, conn: typing.Union[Connector, np.ndarray, typing.Dict] = None, delay: float = 0., name: str = None, monitors: typing.Union[typing.Tuple, typing.List] = None, satisfies: typing.Dict = None, pars_update: typing.Dict = None, ): # name # ---- if name is None: global _SYN_CONN_NO name = f'SynConn{_SYN_CONN_NO}' _SYN_CONN_NO += 1 else: name = name # model # ------ if not isinstance(model, SynType): raise ModelUseError(f'{type(self).__name__} receives an instance of {SynType.__name__}, ' f'not {type(model).__name__}.') if model.mode == 'scalar': if pre_group is None or post_group is None: raise ModelUseError('Using scalar-based synapse model must ' 'provide "pre_group" and "post_group".') # pre or post neuron group # ------------------------ self.pre_group = pre_group self.post_group = post_group self.conn = None if pre_group is not None and post_group is not None: # check # ------ if not isinstance(pre_group, (NeuGroup, NeuSubGroup)): raise ModelUseError('"pre_group" must be an instance of NeuGroup/NeuSubGroup.') if not isinstance(post_group, (NeuGroup, NeuSubGroup)): raise ModelUseError('"post_group" must be an instance of NeuGroup/NeuSubGroup.') if conn is None: raise ModelUseError('"conn" must be provided when "pre_group" and "post_group" are not None.') # pre and post synaptic state self.pre = pre_group.ST self.post = post_group.ST # connections # ------------ if isinstance(conn, Connector): self.conn = conn self.conn(pre_group.indices, post_group.indices) else: if isinstance(conn, np.ndarray): # check matrix dimension if np.ndim(conn) != 2: raise ModelUseError(f'"conn" must be a 2D array, not {np.ndim(conn)}D.') # check matrix shape conn_shape = np.shape(conn) if not (conn_shape[0] == pre_group.num and conn_shape[1] == post_group.num): raise ModelUseError(f'The shape of "conn" must be ({pre_group.num}, {post_group.num})') # get pre_ids and post_ids pre_ids, post_ids = np.where(conn > 0) else: # check conn type if not isinstance(conn, dict): raise ModelUseError(f'"conn" only support "dict", 2D ndarray, ' f'or instance of bp.connect.Connector.') # check conn content if not ('i' in conn and 'j' in conn): raise ModelUseError('When provided "conn" is a dict, "i" and "j" must in "conn".') # get pre_ids and post_ids pre_ids = np.asarray(conn['i'], dtype=np.int_) post_ids = np.asarray(conn['j'], dtype=np.int_) self.conn = Connector() self.conn.pre_ids = pre_group.indices.flatten()[pre_ids] self.conn.post_ids = post_group.indices.flatten()[post_ids] # get synaptic structures self.conn.set_size(num_post=post_group.size, num_pre=pre_group.size) if model.mode == constants.SCALAR_MODE: self.conn.set_requires(model.step_args + ['post2syn', 'pre2syn']) else: self.conn.set_requires(model.step_args) for k in self.conn.requires: setattr(self, k, getattr(self.conn, k)) self.pre_ids = self.conn.pre_ids self.post_ids = self.conn.post_ids num = len(self.pre_ids) else: if 'num' not in satisfies: raise ModelUseError('"num" must be provided in "satisfies" when ' '"pre_group" and "post_group" are none.') num = satisfies['num'] try: assert 0 < num < 2 ** 64 except AssertionError: raise ModelUseError('Total synapse number "num" must be a valid number in "uint64".') # initialize # ---------- super(SynConn, self).__init__(model=model, pars_update=pars_update, name=name, num=num, monitors=monitors, cls_type=constants.SYN_CONN_TYPE, satisfies=satisfies) # delay # ------- if delay is None: delay_len = 1 elif isinstance(delay, (int, float)): dt = profile.get_dt() delay_len = int(np.ceil(delay / dt)) if delay_len == 0: delay_len = 1 else: raise ValueError("BrainPy currently doesn't support other kinds of delay.") self.delay_len = delay_len # delay length # ST # -- if self.model.mode == constants.MATRIX_MODE: if pre_group is None: if 'pre_size' not in satisfies: raise ModelUseError('"pre_size" must be provided in "satisfies" when "pre_group" is none.') pre_size = satisfies['pre_size'] else: pre_size = pre_group.size if post_group is None: if 'post_size' not in satisfies: raise ModelUseError('"post_size" must be provided in "satisfies" when "post_group" is none.') post_size = satisfies['post_size'] else: post_size = post_group.size size = (pre_size, post_size) else: size = (self.num,) self.ST = self.model.ST.make_copy(size=size, delay=delay_len, delay_vars=self.model._delay_keys) def delayed(func): """Decorator for synapse delay. Parameters ---------- func : callable The step function which use delayed synapse state. Returns ------- func : callable The modified step function. """ func.__name__ = f'_brainpy_delayed_{func.__name__}' return func
/scikit-brain-0.3.3.tar.gz/scikit-brain-0.3.3/brainpy/core/synapses.py
0.662796
0.210665
synapses.py
pypi
import typing import numpy as np from . import constants from .base import Ensemble from .base import ObjType from .types import NeuState from ..errors import ModelDefError from ..errors import ModelUseError __all__ = [ 'NeuType', 'NeuGroup', 'NeuSubGroup', ] _NEU_GROUP_NO = 0 class NeuType(ObjType): """Abstract Neuron Type. It can be defined based on a group of neurons or a single neuron. """ def __init__( self, name: str, ST: NeuState, steps: typing.Union[typing.Callable, typing.List, typing.Tuple], mode: str = 'vector', requires: dict = None, hand_overs: typing.Dict = None, heter_params_replace: typing.Dict = None, ): if mode not in [constants.SCALAR_MODE, constants.VECTOR_MODE]: raise ModelDefError('NeuType only support "scalar" or "vector".') super(NeuType, self).__init__( ST=ST, requires=requires, steps=steps, name=name, mode=mode, heter_params_replace=heter_params_replace, hand_overs=hand_overs) class NeuGroup(Ensemble): """Neuron Group. Parameters ---------- model : NeuType The instantiated neuron type model. geometry : int, tuple The neuron group geometry. pars_update : dict, None Parameters to update. monitors : list, tuple, None Variables to monitor. name : str, None The name of the neuron group. """ def __init__( self, model: NeuType, geometry: typing.Union[typing.Tuple, typing.List, int], monitors: typing.Union[typing.List, typing.Tuple] = None, name: str = None, satisfies: typing.Dict = None, pars_update: typing.Dict = None, ): # name # ----- if name is None: global _NEU_GROUP_NO name = f'NeuGroup{_NEU_GROUP_NO}' _NEU_GROUP_NO += 1 else: name = name # num and geometry # ----------------- if isinstance(geometry, (int, float)): geometry = num = int(geometry) self.indices = np.asarray(np.arange(int(geometry)), dtype=np.int_) elif isinstance(geometry, (tuple, list)): if len(geometry) == 1: geometry = num = geometry[0] indices = np.arange(num) elif len(geometry) == 2: height, width = geometry[0], geometry[1] num = height * width indices = np.arange(num).reshape((height, width)) else: raise ModelUseError('Do not support 3+ dimensional networks.') self.indices = np.asarray(indices, dtype=np.int_) else: raise ValueError() self.geometry = geometry self.size = np.size(self.indices) # model # ------ try: assert isinstance(model, NeuType) except AssertionError: raise ModelUseError(f'{NeuGroup.__name__} receives an ' f'instance of {NeuType.__name__}, ' f'not {type(model).__name__}.') # initialize # ---------- super(NeuGroup, self).__init__(model=model, pars_update=pars_update, name=name, num=num, monitors=monitors, cls_type=constants.NEU_GROUP_TYPE, satisfies=satisfies) # ST # -- self.ST = self.model.ST.make_copy(num) def __getitem__(self, item): """Return a subset of neuron group. Parameters ---------- item : slice, int, tuple of slice Returns ------- sub_group : NeuSubGroup The subset of the neuron group. """ if isinstance(item, int): try: assert item < self.num except AssertionError: raise ModelUseError(f'Index error, because the maximum number of neurons' f'is {self.num}, but got "item={item}".') d1_start, d1_end, d1_step = item, item + 1, 1 check_slice(d1_start, d1_end, self.num) indices = self.indices[d1_start:d1_end:d1_step] elif isinstance(item, slice): d1_start, d1_end, d1_step = item.indices(self.num) check_slice(d1_start, d1_end, self.num) indices = self.indices[d1_start:d1_end:d1_step] elif isinstance(item, tuple): if not isinstance(self.geometry, (tuple, list)): raise ModelUseError(f'{self.name} has a 1D geometry, cannot use a tuple of slice.') if len(item) != 2: raise ModelUseError(f'Only support 2D network, cannot make {len(item)}D slice.') if isinstance(item[0], slice): d1_start, d1_end, d1_step = item[0].indices(self.geometry[0]) elif isinstance(item[0], int): d1_start, d1_end, d1_step = item[0], item[0] + 1, 1 else: raise ModelUseError("Only support slicing syntax or a single index.") check_slice(d1_start, d1_end, self.geometry[0]) if isinstance(item[1], slice): d2_start, d2_end, d2_step = item[1].indices(self.geometry[1]) elif isinstance(item[1], int): d2_start, d2_end, d2_step = item[1], item[1] + 1, 1 else: raise ModelUseError("Only support slicing syntax or a single index.") check_slice(d1_start, d1_end, self.geometry[1]) indices = self.indices[d1_start:d1_end:d1_step, d2_start:d2_end:d2_step] else: raise ModelUseError('Subgroups can only be constructed using slicing syntax, ' 'a single index, or an array of contiguous indices.') return NeuSubGroup(source=self, indices=indices) def check_slice(start, end, length): if start >= end: raise ModelUseError(f'Illegal start/end values for subgroup, {start}>={end}') if start >= length: raise ModelUseError(f'Illegal start value for subgroup, {start}>={length}') if end > length: raise ModelUseError(f'Illegal stop value for subgroup, {end}>{length}') if start < 0: raise ModelUseError('Indices have to be positive.') class NeuSubGroup(object): """Subset of a `NeuGroup`. """ def __init__(self, source: NeuGroup, indices: np.ndarray): try: assert isinstance(source, NeuGroup) except AssertionError: raise ModelUseError('NeuSubGroup only support an instance of NeuGroup.') self.source = source self.indices = indices self.num = np.size(indices) def __getattr__(self, item): if item in ['source', 'indices', 'num']: return getattr(self, item) else: return getattr(self.source, item)
/scikit-brain-0.3.3.tar.gz/scikit-brain-0.3.3/brainpy/core/neurons.py
0.739611
0.410343
neurons.py
pypi
import numba as nb import numpy as np from .. import profile from ..errors import ModelUseError __all__ = [ 'Connector', 'ij2mat', 'mat2ij', 'pre2post', 'post2pre', 'pre2syn', 'post2syn', 'pre_slice_syn', 'post_slice_syn', ] def ij2mat(i, j, num_pre=None, num_post=None): """Convert i-j connection to matrix connection. Parameters ---------- i : list, np.ndarray Pre-synaptic neuron index. j : list, np.ndarray Post-synaptic neuron index. num_pre : int The number of the pre-synaptic neurons. num_post : int The number of the post-synaptic neurons. Returns ------- conn_mat : np.ndarray A 2D ndarray connectivity matrix. """ if len(i) != len(j): raise ModelUseError('"i" and "j" must be the equal length.') if num_pre is None: print('WARNING: "num_pre" is not provided, the result may not be accurate.') num_pre = np.max(i) if num_post is None: print('WARNING: "num_post" is not provided, the result may not be accurate.') num_post = np.max(j) i = np.asarray(i, dtype=np.int64) j = np.asarray(j, dtype=np.int64) conn_mat = np.zeros((num_pre, num_post), dtype=np.float_) conn_mat[i, j] = 1. return conn_mat def mat2ij(conn_mat): """Get the i-j connections from connectivity matrix. Parameters ---------- conn_mat : np.ndarray Connectivity matrix with `(num_pre, num_post)` shape. Returns ------- conn_tuple : tuple (Pre-synaptic neuron indexes, post-synaptic neuron indexes). """ conn_mat = np.asarray(conn_mat) if np.ndim(conn_mat) != 2: raise ModelUseError('Connectivity matrix must be in the shape of (num_pre, num_post).') pre_ids, post_ids = np.where(conn_mat > 0) pre_ids = np.ascontiguousarray(pre_ids, dtype=np.int_) post_ids = np.ascontiguousarray(post_ids, dtype=np.int_) return pre_ids, post_ids def pre2post(i, j, num_pre=None): """Get pre2post connections from `i` and `j` indexes. Parameters ---------- i : list, np.ndarray The pre-synaptic neuron indexes. j : list, np.ndarray The post-synaptic neuron indexes. num_pre : int, None The number of the pre-synaptic neurons. Returns ------- conn : list The conn list of pre2post. """ if len(i) != len(j): raise ModelUseError('The length of "i" and "j" must be the same.') if num_pre is None: print('WARNING: "num_pre" is not provided, the result may not be accurate.') num_pre = np.max(i) pre2post_list = [[] for _ in range(num_pre)] for pre_id, post_id in zip(i, j): pre2post_list[pre_id].append(post_id) pre2post_list = [np.array(l) for l in pre2post_list] if profile.is_jit(): pre2post_list_nb = nb.typed.List() for pre_id in range(num_pre): pre2post_list_nb.append(np.int64(pre2post_list[pre_id])) pre2post_list = pre2post_list_nb return pre2post_list def post2pre(i, j, num_post=None): """Get post2pre connections from `i` and `j` indexes. Parameters ---------- i : list, np.ndarray The pre-synaptic neuron indexes. j : list, np.ndarray The post-synaptic neuron indexes. num_post : int, None The number of the post-synaptic neurons. Returns ------- conn : list The conn list of post2pre. """ if len(i) != len(j): raise ModelUseError('The length of "i" and "j" must be the same.') if num_post is None: print('WARNING: "num_post" is not provided, the result may not be accurate.') num_post = np.max(j) post2pre_list = [[] for _ in range(num_post)] for pre_id, post_id in zip(i, j): post2pre_list[post_id].append(pre_id) post2pre_list = [np.array(l) for l in post2pre_list] if profile.is_jit(): post2pre_list_nb = nb.typed.List() for post_id in range(num_post): post2pre_list_nb.append(np.int64(post2pre_list[post_id])) post2pre_list = post2pre_list_nb return post2pre_list def pre2syn(i, num_pre=None): """Get pre2syn connections from `i` and `j` indexes. Parameters ---------- i : list, np.ndarray The pre-synaptic neuron indexes. num_pre : int The number of the pre-synaptic neurons. Returns ------- conn : list The conn list of pre2syn. """ if num_pre is None: print('WARNING: "num_pre" is not provided, the result may not be accurate.') num_pre = np.max(i) pre2syn_list = [[] for _ in range(num_pre)] for syn_id, pre_id in enumerate(i): pre2syn_list[pre_id].append(syn_id) pre2syn_list = [np.array(l) for l in pre2syn_list] if profile.is_jit(): pre2syn_list_nb = nb.typed.List() for pre_ids in pre2syn_list: pre2syn_list_nb.append(np.int64(pre_ids)) pre2syn_list = pre2syn_list_nb return pre2syn_list def post2syn(j, num_post=None): """Get post2syn connections from `i` and `j` indexes. Parameters ---------- j : list, np.ndarray The post-synaptic neuron indexes. num_post : int The number of the post-synaptic neurons. Returns ------- conn : list The conn list of post2syn. """ if num_post is None: print('WARNING: "num_post" is not provided, the result may not be accurate.') num_post = np.max(j) post2syn_list = [[] for _ in range(num_post)] for syn_id, post_id in enumerate(j): post2syn_list[post_id].append(syn_id) post2syn_list = [np.array(l) for l in post2syn_list] if profile.is_jit(): post2syn_list_nb = nb.typed.List() for pre_ids in post2syn_list: post2syn_list_nb.append(np.int64(pre_ids)) post2syn_list = post2syn_list_nb return post2syn_list def pre_slice_syn(i, j, num_pre=None): """Get post slicing connections by pre-synaptic ids. Parameters ---------- i : list, np.ndarray The pre-synaptic neuron indexes. j : list, np.ndarray The post-synaptic neuron indexes. num_pre : int The number of the pre-synaptic neurons. Returns ------- conn : list The conn list of post2syn. """ # check if len(i) != len(j): raise ModelUseError('The length of "i" and "j" must be the same.') if num_pre is None: print('WARNING: "num_pre" is not provided, the result may not be accurate.') num_pre = np.max(i) # pre2post connection pre2post_list = [[] for _ in range(num_pre)] for pre_id, post_id in zip(i, j): pre2post_list[pre_id].append(post_id) post_ids = np.asarray(np.concatenate(pre2post_list), dtype=np.int_) # pre2post slicing slicing = [] start = 0 for posts in pre2post_list: end = start + len(posts) slicing.append([start, end]) start = end slicing = np.asarray(slicing, dtype=np.int_) # pre_ids pre_ids = np.repeat(np.arange(num_pre), slicing[:, 1] - slicing[:, 0]) return pre_ids, post_ids, slicing def post_slice_syn(i, j, num_post=None): """Get pre slicing connections by post-synaptic ids. Parameters ---------- i : list, np.ndarray The pre-synaptic neuron indexes. j : list, np.ndarray The post-synaptic neuron indexes. num_post : int The number of the post-synaptic neurons. Returns ------- conn : list The conn list of post2syn. """ if len(i) != len(j): raise ModelUseError('The length of "i" and "j" must be the same.') if num_post is None: print('WARNING: "num_post" is not provided, the result may not be accurate.') num_post = np.max(j) # post2pre connection post2pre_list = [[] for _ in range(num_post)] for pre_id, post_id in zip(i, j): post2pre_list[post_id].append(pre_id) pre_ids = np.asarray(np.concatenate(post2pre_list), dtype=np.int_) # post2pre slicing slicing = [] start = 0 for pres in post2pre_list: end = start + len(pres) slicing.append([start, end]) start = end slicing = np.asarray(slicing, dtype=np.int_) # post_ids post_ids = np.repeat(np.arange(num_post), slicing[:, 1] - slicing[:, 0]) return pre_ids, post_ids, slicing class Connector(object): """Abstract connector class.""" def __init__(self): # total size of the pre/post-synaptic neurons # useful for the construction of pre2post/pre2syn/etc. self.num_pre = None self.num_post = None # synaptic structures self.pre_ids = None self.post_ids = None self.conn_mat = None self.pre2post = None self.post2pre = None self.pre2syn = None self.post2syn = None self.pre_slice_syn = None self.post_slice_syn = None # synaptic weights self.weights = None # the required synaptic structures self.requires = () def set_size(self, num_pre, num_post): try: assert isinstance(num_pre, int) assert 0 < num_pre except AssertionError: raise ModelUseError('"num_pre" must be integrator bigger than 0.') try: assert isinstance(num_post, int) assert 0 < num_post except AssertionError: raise ModelUseError('"num_post" must be integrator bigger than 0.') self.num_pre = num_pre self.num_post = num_post def set_requires(self, syn_requires): # get synaptic requires requires = set() for n in syn_requires: if n in ['pre_ids', 'post_ids', 'conn_mat', 'pre2post', 'post2pre', 'pre2syn', 'post2syn', 'pre_slice_syn', 'post_slice_syn']: requires.add(n) self.requires = list(requires) # synaptic structure to handle needs = [] if 'pre_slice_syn' in self.requires and 'post_slice_syn' in self.requires: raise ModelUseError('Cannot use "pre_slice_syn" and "post_slice_syn" simultaneously. \n' 'We recommend you use "pre_slice_syn + post2syn" ' 'or "post_slice_syn + pre2syn".') elif 'pre_slice_syn' in self.requires: needs.append('pre_slice_syn') elif 'post_slice_syn' in self.requires: needs.append('post_slice_syn') for n in self.requires: if n in ['pre_slice_syn', 'post_slice_syn', 'pre_ids', 'post_ids']: continue needs.append(n) # make synaptic data structure for n in needs: getattr(self, f'make_{n}')() def __call__(self, pre_indices, post_indices): raise NotImplementedError def make_conn_mat(self): if self.conn_mat is None: self.conn_mat = ij2mat(self.pre_ids, self.post_ids, self.num_pre, self.num_post) def make_mat2ij(self): if self.pre_ids is None or self.post_ids is None: self.pre_ids, self.post_ids = mat2ij(self.conn_mat) def make_pre2post(self): self.pre2post = pre2post(self.pre_ids, self.post_ids, self.num_pre) def make_post2pre(self): self.post2pre = post2pre(self.pre_ids, self.post_ids, self.num_post) def make_pre2syn(self): self.pre2syn = pre2syn(self.pre_ids, self.num_pre) def make_post2syn(self): self.post2syn = post2syn(self.post_ids, self.num_post) def make_pre_slice_syn(self): self.pre_ids, self.post_ids, self.pre_slice_syn = \ pre_slice_syn(self.pre_ids, self.post_ids, self.num_pre) def make_post_slice_syn(self): self.pre_ids, self.post_ids, self.post_slice_syn = \ post_slice_syn(self.pre_ids, self.post_ids, self.num_post)
/scikit-brain-0.3.3.tar.gz/scikit-brain-0.3.3/brainpy/connectivity/base.py
0.706798
0.505127
base.py
pypi
import numba as nb import numpy as np from .base import Connector from ..errors import ModelUseError if hasattr(nb.core, 'dispatcher'): from numba.core.dispatcher import Dispatcher else: from numba.core import Dispatcher __all__ = ['One2One', 'one2one', 'All2All', 'all2all', 'GridFour', 'grid_four', 'GridEight', 'grid_eight', 'GridN', 'FixedPostNum', 'FixedPreNum', 'FixedProb', 'GaussianProb', 'GaussianWeight', 'DOG', 'SmallWorld', 'ScaleFree'] class One2One(Connector): """ Connect two neuron groups one by one. This means The two neuron groups should have the same size. """ def __init__(self): super(One2One, self).__init__() def __call__(self, pre_indices, post_indices): pre_indices = np.asarray(pre_indices) post_indices = np.asarray(post_indices) self.pre_ids = np.ascontiguousarray(pre_indices.flatten(), dtype=np.int_) self.post_ids = np.ascontiguousarray(post_indices.flatten(), dtype=np.int_) try: assert np.size(self.pre_ids) == np.size(self.post_ids) except AssertionError: raise ModelUseError(f'One2One connection must be defined in two groups with the same size, ' f'but we got {np.size(self.pre_ids)} != {np.size(self.post_ids)}.') if self.num_pre is None: self.num_pre = pre_indices.max() if self.num_post is None: self.num_post = post_indices.max() one2one = One2One() class All2All(Connector): """Connect each neuron in first group to all neurons in the post-synaptic neuron groups. It means this kind of conn will create (num_pre x num_post) synapses. """ def __init__(self, include_self=True): self.include_self = include_self super(All2All, self).__init__() def __call__(self, pre_indices, post_indices): pre_indices = pre_indices.flatten() post_indices = post_indices.flatten() num_pre, num_post = len(pre_indices), len(post_indices) mat = np.ones((num_pre, num_post)) if not self.include_self: for i in range(min([num_post, num_pre])): mat[i, i] = 0 pre_ids, post_ids = np.where(mat > 0) self.pre_ids = np.ascontiguousarray(pre_ids, dtype=np.int_) self.post_ids = np.ascontiguousarray(post_ids, dtype=np.int_) if self.num_pre is None: self.num_pre = pre_indices.max() if self.num_post is None: self.num_post = post_indices.max() all2all = All2All(include_self=True) @nb.njit def _grid_four(height, width, row, include_self): conn_i = [] conn_j = [] for col in range(width): i_index = (row * width) + col if 0 <= row - 1 < height: j_index = ((row - 1) * width) + col conn_i.append(i_index) conn_j.append(j_index) if 0 <= row + 1 < height: j_index = ((row + 1) * width) + col conn_i.append(i_index) conn_j.append(j_index) if 0 <= col - 1 < width: j_index = (row * width) + col - 1 conn_i.append(i_index) conn_j.append(j_index) if 0 <= col + 1 < width: j_index = (row * width) + col + 1 conn_i.append(i_index) conn_j.append(j_index) if include_self: conn_i.append(i_index) conn_j.append(i_index) return conn_i, conn_j class GridFour(Connector): """The nearest four neighbors conn method.""" def __init__(self, include_self=False): super(GridFour, self).__init__() self.include_self = include_self def __call__(self, pre_indices, post_indices=None): if post_indices is not None: try: assert np.shape(pre_indices) == np.shape(post_indices) except AssertionError: raise ModelUseError(f'The shape of pre-synaptic group should be the same with the post group. ' f'But we got {np.shape(pre_indices)} != {np.shape(post_indices)}.') if len(pre_indices.shape) == 1: height, width = pre_indices.shape[0], 1 elif len(pre_indices.shape) == 2: height, width = pre_indices.shape else: raise ModelUseError('Currently only support two-dimensional geometry.') conn_i = [] conn_j = [] for row in range(height): a = _grid_four(height, width, row, include_self=self.include_self) conn_i.extend(a[0]) conn_j.extend(a[1]) conn_i = np.asarray(conn_i) conn_j = np.asarray(conn_j) pre_indices = pre_indices.flatten() self.pre_ids = pre_indices[conn_i] if self.num_pre is None: self.num_pre = pre_indices.max() if post_indices is None: self.post_ids = pre_indices[conn_j] else: post_indices = post_indices.flatten() self.post_ids = post_indices[conn_j] if self.num_post is None: self.num_post = post_indices.max() grid_four = GridFour() @nb.njit def _grid_n(height, width, row, n, include_self): conn_i = [] conn_j = [] for col in range(width): i_index = (row * width) + col for row_diff in range(-n, n + 1): for col_diff in range(-n, n + 1): if (not include_self) and (row_diff == col_diff == 0): continue if 0 <= row + row_diff < height and 0 <= col + col_diff < width: j_index = ((row + row_diff) * width) + col + col_diff conn_i.append(i_index) conn_j.append(j_index) return conn_i, conn_j class GridN(Connector): """The nearest (2*N+1) * (2*N+1) neighbors conn method. Parameters ---------- N : int Extend of the conn scope. For example: When N=1, [x x x] [x I x] [x x x] When N=2, [x x x x x] [x x x x x] [x x I x x] [x x x x x] [x x x x x] include_self : bool Whether create (i, i) conn ? """ def __init__(self, n=1, include_self=False): super(GridN, self).__init__() self.n = n self.include_self = include_self def __call__(self, pre_indices, post_indices=None): if post_indices is not None: try: assert np.shape(pre_indices) == np.shape(post_indices) except AssertionError: raise ModelUseError(f'The shape of pre-synaptic group should be the same with the post group. ' f'But we got {np.shape(pre_indices)} != {np.shape(post_indices)}.') if len(pre_indices.shape) == 1: height, width = pre_indices.shape[0], 1 elif len(pre_indices.shape) == 2: height, width = pre_indices.shape else: raise ModelUseError('Currently only support two-dimensional geometry.') conn_i = [] conn_j = [] for row in range(height): res = _grid_n(height=height, width=width, row=row, n=self.n, include_self=self.include_self) conn_i.extend(res[0]) conn_j.extend(res[1]) conn_i = np.asarray(conn_i, dtype=np.int_) conn_j = np.asarray(conn_j, dtype=np.int_) pre_indices = pre_indices.flatten() if self.num_pre is None: self.num_pre = pre_indices.max() self.pre_ids = pre_indices[conn_i] if post_indices is None: self.post_ids = pre_indices[conn_j] else: post_indices = post_indices.flatten() self.post_ids = post_indices[conn_j] if self.num_post is None: self.num_post = post_indices.max() class GridEight(GridN): """The nearest eight neighbors conn method.""" def __init__(self, include_self=False): super(GridEight, self).__init__(n=1, include_self=include_self) grid_eight = GridEight() class FixedProb(Connector): """Connect the post-synaptic neurons with fixed probability. Parameters ---------- prob : float The conn probability. include_self : bool Whether create (i, i) conn ? seed : None, int Seed the random generator. """ def __init__(self, prob, include_self=True, seed=None): super(FixedProb, self).__init__() self.prob = prob self.include_self = include_self self.seed = seed def __call__(self, pre_indices, post_indices): pre_indices = pre_indices.flatten() post_indices = post_indices.flatten() num_pre, num_post = len(pre_indices), len(post_indices) prob_mat = np.random.random(size=(num_pre, num_post)) if not self.include_self: diag_index = np.arange(min([num_pre, num_post])) prob_mat[diag_index, diag_index] = 1. conn_mat = prob_mat < self.prob pre_ids, post_ids = np.where(conn_mat) self.conn_mat = np.float_(conn_mat) self.pre_ids = pre_indices[pre_ids] self.post_ids = post_indices[post_ids] if self.num_pre is None: self.num_pre = pre_indices.max() if self.num_post is None: self.num_post = post_indices.max() class FixedPreNum(Connector): """Connect the pre-synaptic neurons with fixed number for each post-synaptic neuron. Parameters ---------- num : float, int The conn probability (if "num" is float) or the fixed number of connectivity (if "num" is int). include_self : bool Whether create (i, i) conn ? seed : None, int Seed the random generator. """ def __init__(self, num, include_self=True, seed=None): super(FixedPreNum, self).__init__() if isinstance(num, int): assert num >= 0, '"num" must be bigger than 0.' elif isinstance(num, float): assert 0. <= num <= 1., '"num" must be in [0., 1.].' else: raise ValueError(f'Unknown type: {type(num)}') self.num = num self.include_self = include_self self.seed = seed def __call__(self, pre_indices, post_indices): pre_indices = pre_indices.flatten() post_indices = post_indices.flatten() num_pre, num_post = len(pre_indices), len(post_indices) num = self.num if isinstance(self.num, int) else int(self.num * num_pre) assert num <= num_pre, f'"num" must be less than "num_pre", but got {num} > {num_pre}' prob_mat = np.random.random(size=(num_pre, num_post)) if not self.include_self: diag_index = np.arange(min([num_pre, num_post])) prob_mat[diag_index, diag_index] = 1.1 arg_sort = np.argsort(prob_mat, axis=0)[:num] self.pre_ids = np.asarray(np.concatenate(arg_sort), dtype=np.int64) self.post_ids = np.asarray(np.repeat(np.arange(num_post), num_pre), dtype=np.int64) if self.num_pre is None: self.num_pre = pre_indices.max() if self.num_post is None: self.num_post = post_indices.max() class FixedPostNum(Connector): """Connect the post-synaptic neurons with fixed number for each pre-synaptic neuron. Parameters ---------- num : float, int The conn probability (if "num" is float) or the fixed number of connectivity (if "num" is int). include_self : bool Whether create (i, i) conn ? seed : None, int Seed the random generator. """ def __init__(self, num, include_self=True, seed=None): if isinstance(num, int): assert num >= 0, '"num" must be bigger than 0.' elif isinstance(num, float): assert 0. <= num <= 1., '"num" must be in [0., 1.].' else: raise ValueError(f'Unknown type: {type(num)}') self.num = num self.include_self = include_self self.seed = seed super(FixedPostNum, self).__init__() def __call__(self, pre_indices, post_indices): pre_indices = pre_indices.flatten() post_indices = post_indices.flatten() num_pre = len(pre_indices) num_post = len(post_indices) num = self.num if isinstance(self.num, int) else int(self.num * num_post) assert num <= num_post, f'"num" must be less than "num_post", but got {num} > {num_post}' prob_mat = np.random.random(size=(num_pre, num_post)) if not self.include_self: diag_index = np.arange(min([num_pre, num_post])) prob_mat[diag_index, diag_index] = 1.1 arg_sort = np.argsort(prob_mat, axis=1)[:, num] self.post_ids = np.asarray(np.concatenate(arg_sort), dtype=np.int64) self.pre_ids = np.asarray(np.repeat(np.arange(num_pre), num_post), dtype=np.int64) if self.num_pre is None: self.num_pre = pre_indices.max() if self.num_post is None: self.num_post = post_indices.max() @nb.njit def _gaussian_weight(pre_i, pre_width, pre_height, num_post, post_width, post_height, w_max, w_min, sigma, normalize, include_self): conn_i = [] conn_j = [] conn_w = [] # get normalized coordination pre_coords = (pre_i // pre_width, pre_i % pre_width) if normalize: pre_coords = (pre_coords[0] / (pre_height - 1) if pre_height > 1 else 1., pre_coords[1] / (pre_width - 1) if pre_width > 1 else 1.) for post_i in range(num_post): if (pre_i == post_i) and (not include_self): continue # get normalized coordination post_coords = (post_i // post_width, post_i % post_width) if normalize: post_coords = (post_coords[0] / (post_height - 1) if post_height > 1 else 1., post_coords[1] / (post_width - 1) if post_width > 1 else 1.) # Compute Euclidean distance between two coordinates distance = (pre_coords[0] - post_coords[0]) ** 2 distance += (pre_coords[1] - post_coords[1]) ** 2 # get weight and conn value = w_max * np.exp(-distance / (2.0 * sigma ** 2)) if value > w_min: conn_i.append(pre_i) conn_j.append(post_i) conn_w.append(value) return conn_i, conn_j, conn_w class GaussianWeight(Connector): """Builds a Gaussian conn pattern between the two populations, where the weights decay with gaussian function. Specifically, .. math:: w(x, y) = w_{max} \\cdot \\exp(-\\frac{(x-x_c)^2+(y-y_c)^2}{2\\sigma^2}) where :math:`(x, y)` is the position of the pre-synaptic neuron (normalized to [0,1]) and :math:`(x_c,y_c)` is the position of the post-synaptic neuron (normalized to [0,1]), :math:`w_{max}` is the maximum weight. In order to void creating useless synapses, :math:`w_{min}` can be set to restrict the creation of synapses to the cases where the value of the weight would be superior to :math:`w_{min}`. Default is :math:`0.01 w_{max}`. Parameters ---------- sigma : float Width of the Gaussian function. w_max : float The weight amplitude of the Gaussian function. w_min : float, None The minimum weight value below which synapses are not created (default: 0.01 * `w_max`). normalize : bool Whether normalize the coordination. include_self : bool Whether create the conn at the same position. """ def __init__(self, sigma, w_max, w_min=None, normalize=True, include_self=True): super(GaussianWeight, self).__init__() self.sigma = sigma self.w_max = w_max self.w_min = w_max * 0.01 if w_min is None else w_min self.normalize = normalize self.include_self = include_self def __call__(self, pre_indices, post_indices): num_pre = np.size(pre_indices) num_post = np.size(post_indices) assert np.ndim(pre_indices) == 2 assert np.ndim(post_indices) == 2 pre_height, pre_width = pre_indices.shape post_height, post_width = post_indices.shape # get the connections and weights i, j, w = [], [], [] for pre_i in range(num_pre): a = _gaussian_weight(pre_i=pre_i, pre_width=pre_width, pre_height=pre_height, num_post=num_post, post_width=post_width, post_height=post_height, w_max=self.w_max, w_min=self.w_min, sigma=self.sigma, normalize=self.normalize, include_self=self.include_self) i.extend(a[0]) j.extend(a[1]) w.extend(a[2]) pre_ids = np.asarray(i, dtype=np.int_) post_ids = np.asarray(j, dtype=np.int_) w = np.asarray(w, dtype=np.float_) pre_indices = pre_indices.flatten() post_indices = post_indices.flatten() self.pre_ids = pre_indices[pre_ids] self.post_ids = post_indices[post_ids] self.weights = w if self.num_pre is None: self.num_pre = pre_indices.max() if self.num_post is None: self.num_post = post_indices.max() @nb.njit def _gaussian_prob(pre_i, pre_width, pre_height, num_post, post_width, post_height, p_min, sigma, normalize, include_self): conn_i = [] conn_j = [] conn_p = [] # get normalized coordination pre_coords = (pre_i // pre_width, pre_i % pre_width) if normalize: pre_coords = (pre_coords[0] / (pre_height - 1) if pre_height > 1 else 1., pre_coords[1] / (pre_width - 1) if pre_width > 1 else 1.) for post_i in range(num_post): if (pre_i == post_i) and (not include_self): continue # get normalized coordination post_coords = (post_i // post_width, post_i % post_width) if normalize: post_coords = (post_coords[0] / (post_height - 1) if post_height > 1 else 1., post_coords[1] / (post_width - 1) if post_width > 1 else 1.) # Compute Euclidean distance between two coordinates distance = (pre_coords[0] - post_coords[0]) ** 2 distance += (pre_coords[1] - post_coords[1]) ** 2 # get weight and conn value = np.exp(-distance / (2.0 * sigma ** 2)) if value > p_min: conn_i.append(pre_i) conn_j.append(post_i) conn_p.append(value) return conn_i, conn_j, conn_p class GaussianProb(Connector): """Builds a Gaussian conn pattern between the two populations, where the conn probability decay according to the gaussian function. Specifically, .. math:: p=\\exp(-\\frac{(x-x_c)^2+(y-y_c)^2}{2\\sigma^2}) where :math:`(x, y)` is the position of the pre-synaptic neuron and :math:`(x_c,y_c)` is the position of the post-synaptic neuron. Parameters ---------- sigma : float Width of the Gaussian function. normalize : bool Whether normalize the coordination. include_self : bool Whether create the conn at the same position. seed : bool The random seed. """ def __init__(self, sigma, p_min=0., normalize=True, include_self=True, seed=None): super(GaussianProb, self).__init__() self.sigma = sigma self.p_min = p_min self.normalize = normalize self.include_self = include_self def __call__(self, pre_indices, post_indices): num_pre = np.size(pre_indices) num_post = np.size(post_indices) assert np.ndim(pre_indices) == 2 assert np.ndim(post_indices) == 2 pre_height, pre_width = pre_indices.shape post_height, post_width = post_indices.shape # get the connections i, j, p = [], [], [] # conn_i, conn_j, probabilities for pre_i in range(num_pre): a = _gaussian_prob(pre_i=pre_i, pre_width=pre_width, pre_height=pre_height, num_post=num_post, post_width=post_width, post_height=post_height, p_min=self.p_min, sigma=self.sigma, normalize=self.normalize, include_self=self.include_self) i.extend(a[0]) j.extend(a[1]) p.extend(a[2]) p = np.asarray(p, dtype=np.float_) selected_idxs = np.where(np.random.random(len(p)) < p)[0] i = np.asarray(i, dtype=np.int_)[selected_idxs] j = np.asarray(j, dtype=np.int_)[selected_idxs] pre_indices = pre_indices.flatten() post_indices = post_indices.flatten() self.pre_ids = pre_indices[i] self.post_ids = post_indices[j] if self.num_pre is None: self.num_pre = pre_indices.max() if self.num_post is None: self.num_post = post_indices.max() @nb.njit def _dog(pre_i, pre_width, pre_height, num_post, post_width, post_height, w_max_p, w_max_n, w_min, sigma_p, sigma_n, normalize, include_self): conn_i = [] conn_j = [] conn_w = [] # get normalized coordination pre_coords = (pre_i // pre_width, pre_i % pre_width) if normalize: pre_coords = (pre_coords[0] / (pre_height - 1) if pre_height > 1 else 1., pre_coords[1] / (pre_width - 1) if pre_width > 1 else 1.) for post_i in range(num_post): if (pre_i == post_i) and (not include_self): continue # get normalized coordination post_coords = (post_i // post_width, post_i % post_width) if normalize: post_coords = (post_coords[0] / (post_height - 1) if post_height > 1 else 1., post_coords[1] / (post_width - 1) if post_width > 1 else 1.) # Compute Euclidean distance between two coordinates distance = (pre_coords[0] - post_coords[0]) ** 2 distance += (pre_coords[1] - post_coords[1]) ** 2 # get weight and conn value = w_max_p * np.exp(-distance / (2.0 * sigma_p ** 2)) - \ w_max_n * np.exp(-distance / (2.0 * sigma_n ** 2)) if np.abs(value) > w_min: conn_i.append(pre_i) conn_j.append(post_i) conn_w.append(value) return conn_i, conn_j, conn_w class DOG(Connector): """Builds a Difference-Of-Gaussian (dog) conn pattern between the two populations. Mathematically, .. math:: w(x, y) = w_{max}^+ \\cdot \\exp(-\\frac{(x-x_c)^2+(y-y_c)^2}{2\\sigma_+^2}) - w_{max}^- \\cdot \\exp(-\\frac{(x-x_c)^2+(y-y_c)^2}{2\\sigma_-^2}) where weights smaller than :math:`0.01 * abs(w_{max} - w_{min})` are not created and self-connections are avoided by default (parameter allow_self_connections). Parameters ---------- sigmas : tuple Widths of the positive and negative Gaussian functions. ws_max : tuple The weight amplitudes of the positive and negative Gaussian functions. w_min : float, None The minimum weight value below which synapses are not created (default: :math:`0.01 * w_{max}^+ - w_{min}^-`). normalize : bool Whether normalize the coordination. include_self : bool Whether create the conn at the same position. """ def __init__(self, sigmas, ws_max, w_min=None, normalize=True, include_self=True): super(DOG, self).__init__() self.sigma_p, self.sigma_n = sigmas self.w_max_p, self.w_max_n = ws_max self.w_min = np.abs(ws_max[0] - ws_max[1]) * 0.01 if w_min is None else w_min self.normalize = normalize self.include_self = include_self def __call__(self, pre_indices, post_indices): num_pre = np.size(pre_indices) num_post = np.size(post_indices) assert np.ndim(pre_indices) == 2 assert np.ndim(post_indices) == 2 pre_height, pre_width = pre_indices.shape post_height, post_width = post_indices.shape # get the connections and weights i, j, w = [], [], [] # conn_i, conn_j, weights for pre_i in range(num_pre): a = _dog(pre_i=pre_i, pre_width=pre_width, pre_height=pre_height, num_post=num_post, post_width=post_width, post_height=post_height, w_max_p=self.w_max_p, w_max_n=self.w_max_n, w_min=self.w_min, sigma_p=self.sigma_p, sigma_n=self.sigma_n, normalize=self.normalize, include_self=self.include_self) i.extend(a[0]) j.extend(a[1]) w.extend(a[2]) # format connections and weights i = np.asarray(i, dtype=np.int_) j = np.asarray(j, dtype=np.int_) w = np.asarray(w, dtype=np.float_) pre_indices = pre_indices.flatten() post_indices = post_indices.flatten() self.pre_ids = pre_indices[i] self.post_ids = post_indices[j] self.weights = w if self.num_pre is None: self.num_pre = pre_indices.max() if self.num_post is None: self.num_post = post_indices.max() class ScaleFree(Connector): def __init__(self): raise NotImplementedError class SmallWorld(Connector): def __init__(self): raise NotImplementedError
/scikit-brain-0.3.3.tar.gz/scikit-brain-0.3.3/brainpy/connectivity/methods.py
0.601477
0.402216
methods.py
pypi
import matplotlib.pyplot as plt import numpy as np from matplotlib import animation from matplotlib.gridspec import GridSpec from .. import profile from ..errors import ModelUseError __all__ = [ 'line_plot', 'raster_plot', 'animate_2D', 'animate_1D', ] def line_plot(ts, val_matrix, plot_ids=None, ax=None, xlim=None, ylim=None, xlabel='Time (ms)', ylabel='value', legend=None, title=None, show=False): """Show the specified value in the given object (Neurons or Synapses.) Parameters ---------- ts : np.ndarray The time steps. val_matrix : np.ndarray The value matrix which record the history trajectory. It can be easily accessed by specifying the ``monitors`` of NeuGroup/SynConn by: ``neu/syn = NeuGroup/SynConn(..., monitors=[k1, k2])`` plot_ids : None, int, tuple, a_list The index of the value to plot. ax : None, Axes The figure to plot. xlim : list, tuple The xlim. ylim : list, tuple The ylim. xlabel : str The xlabel. ylabel : str The ylabel. legend : str The prefix of legend for plot. show : bool Whether show the figure. """ # get plot_ids if plot_ids is None: plot_ids = [0] elif isinstance(plot_ids, int): plot_ids = [plot_ids] try: assert isinstance(plot_ids, (list, tuple)) except AssertionError: raise ModelUseError('"plot_ids" specifies the value index to plot, ' 'it must be a list/tuple.') # get ax if ax is None: ax = plt # plot val_matrix = val_matrix.reshape((val_matrix.shape[0], -1)) if legend: for idx in plot_ids: ax.plot(ts, val_matrix[:, idx], label=f'{legend}-{idx}') else: for idx in plot_ids: ax.plot(ts, val_matrix[:, idx]) # legend if legend: ax.legend() # xlim if xlim is not None: plt.xlim(xlim[0], xlim[1]) # ylim if ylim is not None: plt.ylim(ylim[0], ylim[1]) # xlable if xlabel: plt.xlabel(xlabel) # ylabel if ylabel: plt.ylabel(ylabel) # title if title: plt.title(title) # show if show: plt.show() def raster_plot(ts, sp_matrix, ax=None, marker='.', markersize=2, color='k', xlabel='Time (ms)', ylabel='Neuron index', xlim=None, ylim=None, title=None, show=False): """Show the rater plot of the spikes. Parameters ---------- ts : np.ndarray The run times. sp_matrix : np.ndarray The spike matrix which records the spike information. It can be easily accessed by specifying the ``monitors`` of NeuGroup by: ``neu = NeuGroup(..., monitors=['spike'])`` ax : Axes The figure. markersize : int The size of the marker. color : str The color of the marker. xlim : list, tuple The xlim. ylim : list, tuple The ylim. xlabel : str The xlabel. ylabel : str The ylabel. show : bool Show the figure. """ # get index and time elements = np.where(sp_matrix > 0.) index = elements[1] time = ts[elements[0]] # plot rater if ax is None: ax = plt ax.plot(time, index, marker + color, markersize=markersize) # xlable if xlabel: plt.xlabel(xlabel) # ylabel if ylabel: plt.ylabel(ylabel) if xlim: plt.xlim(xlim[0], xlim[1]) if ylim: plt.ylim(ylim[0], ylim[1]) if title: plt.title(title) if show: plt.show() def animate_2D(values, net_size, dt=None, val_min=None, val_max=None, cmap=None, frame_delay=1., frame_step=1, title_size=10, figsize=None, gif_dpi=None, video_fps=None, save_path=None, show=True): """Animate the potentials of the neuron group. Parameters ---------- values : np.ndarray The membrane potentials of the neuron group. net_size : tuple The size of the neuron group. dt : float The time duration of each step. val_min : float, int The minimum of the potential. val_max : float, int The maximum of the potential. cmap : str The colormap. frame_delay : int, float The delay to show each frame. frame_step : int The step to show the potential. If `frame_step=3`, then each frame shows one of the every three steps. title_size : int The size of the title. figsize : None, tuple The size of the figure. gif_dpi : int Controls the dots per inch for the movie frames. This combined with the figure's size in inches controls the size of the movie. If ``None``, use defaults in matplotlib. video_fps : int Frames per second in the movie. Defaults to ``None``, which will use the animation's specified interval to set the frames per second. save_path : None, str The save path of the animation. show : bool Whether show the animation. Returns ------- figure : plt.figure The created figure instance. """ dt = profile.get_dt() if dt is None else dt num_step, num_neuron = values.shape height, width = net_size val_min = values.min() if val_min is None else val_min val_max = values.max() if val_max is None else val_max figsize = figsize or (6, 6) fig = plt.figure(figsize=(figsize[0], figsize[1]), constrained_layout=True) gs = GridSpec(1, 1, figure=fig) fig.add_subplot(gs[0, 0]) def frame(t): img = values[t] fig.clf() plt.pcolor(img, cmap=cmap, vmin=val_min, vmax=val_max) plt.colorbar() plt.axis('off') fig.suptitle("Time: {:.2f} ms".format((t + 1) * dt), fontsize=title_size, fontweight='bold') return [fig.gca()] values = values.reshape((num_step, height, width)) anim_result = animation.FuncAnimation( fig, frame, frames=list(range(1, num_step, frame_step)), init_func=None, interval=frame_delay, repeat_delay=3000) if save_path is None: if show: plt.show() else: if save_path[-3:] == 'gif': anim_result.save(save_path, dpi=gif_dpi, writer='imagemagick') elif save_path[-3:] == 'mp4': anim_result.save(save_path, writer='ffmpeg', fps=video_fps, bitrate=3000) else: anim_result.save(save_path + '.mp4', writer='ffmpeg', fps=video_fps, bitrate=3000) return fig def animate_1D(dynamical_vars, static_vars=(), dt=None, xlim=None, ylim=None, xlabel=None, ylabel=None, frame_delay=50., frame_step=1, title_size=10, figsize=None, gif_dpi=None, video_fps=None, save_path=None, show=True): """Animation of one-dimensional data. Parameters ---------- dynamical_vars : dict, np.ndarray, list of np.ndarray, list of dict The dynamical variables which will be animated. static_vars : dict, np.ndarray, list of np.ndarray, list of dict The static variables. xticks : list, np.ndarray The xticks. dt : float The numerical integration step. xlim : tuple The xlim. ylim : tuple The ylim. xlabel : str The xlabel. ylabel : str The ylabel. frame_delay : int, float The delay to show each frame. frame_step : int The step to show the potential. If `frame_step=3`, then each frame shows one of the every three steps. title_size : int The size of the title. figsize : None, tuple The size of the figure. gif_dpi : int Controls the dots per inch for the movie frames. This combined with the figure's size in inches controls the size of the movie. If ``None``, use defaults in matplotlib. video_fps : int Frames per second in the movie. Defaults to ``None``, which will use the animation's specified interval to set the frames per second. save_path : None, str The save path of the animation. show : bool Whether show the animation. Returns ------- figure : plt.figure The created figure instance. """ # check dt dt = profile.get_dt() if dt is None else dt # check figure fig = plt.figure(figsize=(figsize or (6, 6)), constrained_layout=True) gs = GridSpec(1, 1, figure=fig) fig.add_subplot(gs[0, 0]) # check dynamical variables final_dynamic_vars = [] lengths = [] has_legend = False if isinstance(dynamical_vars, (tuple, list)): for var in dynamical_vars: if isinstance(var, dict): assert 'ys' in var, 'Must provide "ys" item.' if 'legend' not in var: var['legend'] = None else: has_legend = True if 'xs' not in var: var['xs'] = np.arange(var['ys'].shape[1]) elif isinstance(var, np.ndarray): var = {'ys': var, 'xs': np.arange(var.shape[1]), 'legend': None} else: raise ValueError(f'Unknown data type: {type(var)}') assert np.ndim(var['ys']) == 2, "Dynamic variable must be 2D data." lengths.append(var['ys'].shape[0]) final_dynamic_vars.append(var) elif isinstance(dynamical_vars, np.ndarray): assert np.ndim(dynamical_vars) == 2, "Dynamic variable must be 2D data." lengths.append(dynamical_vars.shape[0]) final_dynamic_vars.append({'ys': dynamical_vars, 'xs': np.arange(dynamical_vars.shape[1]), 'legend': None}) elif isinstance(dynamical_vars, dict): assert 'ys' in dynamical_vars, 'Must provide "ys" item.' if 'legend' not in dynamical_vars: dynamical_vars['legend'] = None else: has_legend = True if 'xs' not in dynamical_vars: dynamical_vars['xs'] = np.arange(dynamical_vars['ys'].shape[1]) lengths.append(dynamical_vars['ys'].shape[0]) final_dynamic_vars.append(dynamical_vars) else: raise ValueError(f'Unknown dynamical data type: {type(dynamical_vars)}') lengths = np.array(lengths) assert np.all(lengths == lengths[0]), 'Dynamic variables must have equal length.' # check static variables final_static_vars = [] if isinstance(static_vars, (tuple, list)): for var in static_vars: if isinstance(var, dict): assert 'data' in var, 'Must provide "ys" item.' if 'legend' not in var: var['legend'] = None else: has_legend = True elif isinstance(var, np.ndarray): var = {'data': var, 'legend': None} else: raise ValueError(f'Unknown data type: {type(var)}') assert np.ndim(var['data']) == 1, "Static variable must be 1D data." final_static_vars.append(var) elif isinstance(static_vars, np.ndarray): final_static_vars.append({'data': static_vars, 'xs': np.arange(static_vars.shape[0]), 'legend': None}) elif isinstance(static_vars, dict): assert 'ys' in static_vars, 'Must provide "ys" item.' if 'legend' not in static_vars: static_vars['legend'] = None else: has_legend = True if 'xs' not in static_vars: static_vars['xs'] = np.arange(static_vars['ys'].shape[0]) final_static_vars.append(static_vars) else: raise ValueError(f'Unknown static data type: {type(static_vars)}') # ylim if ylim is None: ylim_min = np.inf ylim_max = -np.inf for var in final_dynamic_vars + final_static_vars: if var['ys'].max() > ylim_max: ylim_max = var['ys'].max() if var['ys'].min() < ylim_min: ylim_min = var['ys'].min() if ylim_min > 0: ylim_min = ylim_min * 0.98 else: ylim_min = ylim_min * 1.02 if ylim_max > 0: ylim_max = ylim_max * 1.02 else: ylim_max = ylim_max * 0.98 ylim = (ylim_min, ylim_max) def frame(t): fig.clf() for dvar in final_dynamic_vars: plt.plot(dvar['xs'], dvar['ys'][t], label=dvar['legend']) for svar in final_static_vars: plt.plot(svar['xs'], svar['ys'], label=svar['legend']) if xlim is not None: plt.xlim(xlim[0], xlim[1]) if has_legend: plt.legend() if xlabel: plt.xlabel(xlabel) if ylabel: plt.ylabel(ylabel) plt.ylim(ylim[0], ylim[1]) fig.suptitle(t="Time: {:.2f} ms".format((t + 1) * dt), fontsize=title_size, fontweight='bold') return [fig.gca()] anim_result = animation.FuncAnimation(fig=fig, func=frame, frames=range(1, lengths[0], frame_step), init_func=None, interval=frame_delay, repeat_delay=3000) # save or show if save_path is None: if show: plt.show() else: if save_path[-3:] == 'gif': anim_result.save(save_path, dpi=gif_dpi, writer='imagemagick') elif save_path[-3:] == 'mp4': anim_result.save(save_path, writer='ffmpeg', fps=video_fps, bitrate=3000) else: anim_result.save(save_path + '.mp4', writer='ffmpeg', fps=video_fps, bitrate=3000) return fig
/scikit-brain-0.3.3.tar.gz/scikit-brain-0.3.3/brainpy/visualization/plots.py
0.887302
0.682984
plots.py
pypi
import dataclasses from pathlib import Path from typing import List, Optional from .common import APIVersion, Paths __all__ = [ "Archive", "Artifact", "CodeModel", "CommandFragment", "Configuration", "Dependency", "Destination", "Directory", "Install", "Link", "Prefix", "Project", "Source", "StringCMakeVersion", "Sysroot", "Target", ] def __dir__() -> List[str]: return __all__ @dataclasses.dataclass(frozen=True) class StringCMakeVersion: string: str @dataclasses.dataclass(frozen=True) class Directory: source: Path build: Path projectIndex: int jsonFile: Optional[Path] = None parentIndex: Optional[int] = None childIndexes: List[int] = dataclasses.field(default_factory=list) targetIndexes: List[int] = dataclasses.field(default_factory=list) minimumCMakeVersion: Optional[StringCMakeVersion] = None hasInstallRule: bool = False # Directory is currently not resolved automatically. @dataclasses.dataclass(frozen=True) class Project: name: str directoryIndexes: List[int] parentIndex: Optional[int] = None childIndexes: List[int] = dataclasses.field(default_factory=list) targetIndexes: List[int] = dataclasses.field(default_factory=list) @dataclasses.dataclass(frozen=True) class Artifact: path: Path @dataclasses.dataclass(frozen=True) class Prefix: path: Path @dataclasses.dataclass(frozen=True) class Destination: path: Path backtrace: Optional[int] = None @dataclasses.dataclass(frozen=True) class Install: prefix: Prefix destinations: List[Destination] @dataclasses.dataclass(frozen=True) class CommandFragment: fragment: str role: str @dataclasses.dataclass(frozen=True) class Sysroot: path: Path @dataclasses.dataclass(frozen=True) class Link: language: str commandFragments: List[CommandFragment] lto: Optional[bool] = None sysroot: Optional[Sysroot] = None @dataclasses.dataclass(frozen=True) class Archive: commandFragments: List[CommandFragment] = dataclasses.field(default_factory=list) lto: Optional[bool] = None @dataclasses.dataclass(frozen=True) class Dependency: id: str backtrace: Optional[int] = None @dataclasses.dataclass(frozen=True) class Source: path: Path compileGroupIndex: Optional[int] = None sourceGroupIndex: Optional[int] = None isGenerated: Optional[bool] = None backtrace: Optional[int] = None @dataclasses.dataclass(frozen=True) class Target: name: str id: str type: str paths: Paths sources = List[Source] nameOnDisk: Optional[Path] = None artifacts: List[Artifact] = dataclasses.field(default_factory=list) isGeneratorProvided: Optional[bool] = None install: Optional[Install] = None link: Optional[Link] = None archive: Optional[Archive] = None dependencies: List[Dependency] = dataclasses.field(default_factory=list) @dataclasses.dataclass(frozen=True) class Configuration: name: str projects: List[Project] targets: List[Target] directories: List[Directory] @dataclasses.dataclass(frozen=True) class CodeModel: kind: str version: APIVersion paths: Paths configurations: List[Configuration]
/scikit_build_core-0.5.0-py3-none-any.whl/scikit_build_core/file_api/model/codemodel.py
0.839405
0.300131
codemodel.py
pypi
from __future__ import annotations import ast import dataclasses import inspect import sys import textwrap from collections.abc import Generator from pathlib import Path from packaging.version import Version from .._compat.typing import get_args, get_origin __all__ = ["pull_docs"] def __dir__() -> list[str]: return __all__ def _get_value(value: ast.expr) -> str: if sys.version_info < (3, 8): assert isinstance(value, ast.Str) return value.s assert isinstance(value, ast.Constant) return value.value def pull_docs(dc: type[object]) -> dict[str, str]: """ Pulls documentation from a dataclass. """ t = ast.parse(inspect.getsource(dc)) (obody,) = t.body assert isinstance(obody, ast.ClassDef) body = obody.body return { assign.target.id: textwrap.dedent(_get_value(expr.value)).strip().replace("\n", " ") # type: ignore[union-attr] for assign, expr in zip(body[:-1], body[1:]) if isinstance(assign, ast.AnnAssign) and isinstance(expr, ast.Expr) } @dataclasses.dataclass class DCDoc: name: str default: str docs: str def __str__(self) -> str: docs = "\n".join(f"# {s}" for s in textwrap.wrap(self.docs, width=78)) return f"{docs}\n{self.name} = {self.default}\n" def mk_docs(dc: type[object], prefix: str = "") -> Generator[DCDoc, None, None]: """ Makes documentation for a dataclass. """ assert dataclasses.is_dataclass(dc) docs = pull_docs(dc) for field in dataclasses.fields(dc): if dataclasses.is_dataclass(field.type): yield from mk_docs(field.type, prefix=f"{prefix}{field.name}.") continue if get_origin(field.type) is list: field_type = get_args(field.type)[0] if dataclasses.is_dataclass(field_type): yield from mk_docs(field_type, prefix=f"{prefix}{field.name}[].") continue if field.default is not dataclasses.MISSING and field.default is not None: default = repr( str(field.default) if isinstance(field.default, (Path, Version)) else field.default ) elif field.default_factory is not dataclasses.MISSING: default = repr(field.default_factory()) else: default = '""' yield DCDoc( f"{prefix}{field.name}".replace("_", "-"), default.replace("'", '"').replace("True", "true").replace("False", "false"), docs[field.name], )
/scikit_build_core-0.5.0-py3-none-any.whl/scikit_build_core/settings/documentation.py
0.557604
0.253896
documentation.py
pypi
from __future__ import annotations import dataclasses import sys from pathlib import Path from typing import Any, Union from packaging.version import Version from .._compat.builtins import ExceptionGroup from .._compat.typing import Literal, get_args, get_origin from .documentation import pull_docs __all__ = ["to_json_schema", "convert_type", "FailedConversion"] def __dir__() -> list[str]: return __all__ class FailedConversion(TypeError): pass def to_json_schema(dclass: type[Any], *, normalize_keys: bool) -> dict[str, Any]: assert dataclasses.is_dataclass(dclass) props = {} errs = [] required = [] for field in dataclasses.fields(dclass): if dataclasses.is_dataclass(field.type): props[field.name] = to_json_schema( field.type, normalize_keys=normalize_keys ) continue try: props[field.name] = convert_type(field.type, normalize_keys=normalize_keys) except FailedConversion as err: if sys.version_info < (3, 11): notes = "__notes__" # set so linter's won't try to be clever setattr(err, notes, [*getattr(err, notes, []), f"Field: {field.name}"]) else: # pylint: disable-next=no-member err.add_note(f"Field: {field.name}") errs.append(err) continue if field.default is not dataclasses.MISSING and field.default is not None: props[field.name]["default"] = ( str(field.default) if isinstance(field.default, (Version, Path)) else field.default ) if ( field.default_factory is dataclasses.MISSING and field.default is dataclasses.MISSING ): required.append(field.name) if errs: msg = f"Failed Conversion to JSON Schema on {dclass.__name__}" raise ExceptionGroup(msg, errs) docs = pull_docs(dclass) for k, v in docs.items(): props[k]["description"] = v if normalize_keys: props = {k.replace("_", "-"): v for k, v in props.items()} if required: return { "type": "object", "additionalProperties": False, "required": required, "properties": props, } return {"type": "object", "additionalProperties": False, "properties": props} def convert_type(t: Any, *, normalize_keys: bool) -> dict[str, Any]: if dataclasses.is_dataclass(t): return to_json_schema(t, normalize_keys=normalize_keys) if t is str or t is Path or t is Version: return {"type": "string"} if t is bool: return {"type": "boolean"} origin = get_origin(t) args = get_args(t) if origin is list: assert len(args) == 1 return { "type": "array", "items": convert_type(args[0], normalize_keys=normalize_keys), } if origin is dict: assert len(args) == 2 assert args[0] is str if args[1] is Any: return {"type": "object"} return { "type": "object", "patternProperties": { ".+": convert_type(args[1], normalize_keys=normalize_keys) }, } if origin is Union: # Ignore optional if len(args) == 2 and any(a is type(None) for a in args): return convert_type( next(iter(a for a in args if a is not type(None))), normalize_keys=normalize_keys, ) return {"oneOf": [convert_type(a, normalize_keys=normalize_keys) for a in args]} if origin is Literal: return {"enum": list(args)} msg = f"Cannot convert type {t} to JSON Schema" raise FailedConversion(msg)
/scikit_build_core-0.5.0-py3-none-any.whl/scikit_build_core/settings/json_schema.py
0.52975
0.263973
json_schema.py
pypi
from __future__ import annotations import dataclasses import os import typing from collections.abc import Generator, Iterator, Mapping, Sequence from typing import Any, TypeVar, Union from .._compat.builtins import ExceptionGroup from .._compat.typing import Literal, Protocol, get_args, get_origin T = TypeVar("T") __all__ = ["Source", "SourceChain", "ConfSource", "EnvSource", "TOMLSource"] def __dir__() -> list[str]: return __all__ def _dig_strict(__dict: Mapping[str, Any], *names: str) -> Any: for name in names: __dict = __dict[name] return __dict def _dig_not_strict(__dict: Mapping[str, Any], *names: str) -> Any: for name in names: __dict = __dict.get(name, {}) return __dict def _dig_fields(__opt: Any, *names: str) -> Any: for name in names: fields = dataclasses.fields(__opt) types = [x.type for x in fields if x.name == name] if len(types) != 1: msg = f"Could not access {'.'.join(names)}" raise KeyError(msg) (__opt,) = types return __opt def _process_union(target: type[Any]) -> Any: """ Filters None out of Unions. If a Union only has one item, return that item. """ origin = get_origin(target) if origin is Union: non_none_args = [a for a in get_args(target) if a is not type(None)] if len(non_none_args) == 1: return non_none_args[0] return Union[tuple(non_none_args)] return target def _get_target_raw_type(target: type[Any]) -> Any: """ Takes a type like ``Optional[str]`` and returns str, or ``Optional[Dict[str, int]]`` and returns dict. Returns Union for a Union with more than one non-none type. Literal is also a valid return. """ target = _process_union(target) origin = get_origin(target) return origin or target def _get_inner_type(__target: type[Any]) -> type[Any]: """ Takes a types like ``List[str]`` and returns str, or ``Dict[str, int]`` and returns int. """ raw_target = _get_target_raw_type(__target) target = _process_union(__target) if raw_target == list: return get_args(target)[0] # type: ignore[no-any-return] if raw_target == dict: return get_args(target)[1] # type: ignore[no-any-return] msg = f"Expected a list or dict, got {target!r}" raise AssertionError(msg) def _nested_dataclass_to_names(__target: type[Any], *inner: str) -> Iterator[list[str]]: """ Yields each entry, like ``("a", "b", "c")`` for ``a.b.c``. """ if dataclasses.is_dataclass(__target): for field in dataclasses.fields(__target): yield from _nested_dataclass_to_names(field.type, *inner, field.name) else: yield list(inner) class Source(Protocol): def has_item(self, *fields: str, is_dict: bool) -> bool: """ Check if the source contains a chain of fields. For example, ``fields = [Field(name="a"), Field(name="b")]`` will check if the source contains the key "a.b". ``is_dict`` should be set if it can be nested. """ ... def get_item(self, *fields: str, is_dict: bool) -> Any: """ Select an item from a chain of fields. Raises KeyError if the there is no item. ``is_dict`` should be set if it can be nested. """ ... @classmethod def convert(cls, item: Any, target: type[Any]) -> object: """ Convert an ``item`` from the base representation of the source's source into a ``target`` type. Raises TypeError if the conversion fails. """ ... def unrecognized_options(self, options: object) -> Generator[str, None, None]: """ Given a model, produce an iterator of all unrecognized option names. Empty iterator if this can't be computed for the source (like for environment variables). """ ... def all_option_names(self, target: type[Any]) -> Iterator[str]: """ Given a model, produce a list of all possible names (used for producing suggestions). """ ... class EnvSource: """ This is a source using environment variables. """ def __init__(self, prefix: str, *, env: Mapping[str, str] | None = None) -> None: self.env = env or os.environ self.prefix = prefix def _get_name(self, *fields: str) -> str: names = [field.upper() for field in fields] return "_".join([self.prefix, *names] if self.prefix else names) def has_item(self, *fields: str, is_dict: bool) -> bool: # noqa: ARG002 name = self._get_name(*fields) return bool(self.env.get(name, "")) def get_item( self, *fields: str, is_dict: bool # noqa: ARG002 ) -> str | dict[str, str]: name = self._get_name(*fields) if name in self.env: return self.env[name] msg = f"{name!r} not found in environment" raise KeyError(msg) @classmethod def convert(cls, item: str, target: type[Any]) -> object: raw_target = _get_target_raw_type(target) if dataclasses.is_dataclass(raw_target): msg = f"Array of dataclasses are not supported in configuration settings ({raw_target})" raise TypeError(msg) if raw_target == list: return [ cls.convert(i.strip(), _get_inner_type(target)) for i in item.split(";") ] if raw_target == dict: items = (i.strip().split("=") for i in item.split(";")) return {k: cls.convert(v, _get_inner_type(target)) for k, v in items} if raw_target is bool: return item.strip().lower() not in {"0", "false", "off", "no", ""} if raw_target is Union and str in get_args(target): return item if raw_target is Literal: if item not in get_args(_process_union(target)): msg = f"{item!r} not in {get_args(_process_union(target))!r}" raise TypeError(msg) return item if callable(raw_target): return raw_target(item) msg = f"Can't convert target {target}" raise TypeError(msg) def unrecognized_options( self, options: object # noqa: ARG002 ) -> Generator[str, None, None]: yield from () def all_option_names(self, target: type[Any]) -> Iterator[str]: prefix = [self.prefix] if self.prefix else [] for names in _nested_dataclass_to_names(target): yield "_".join(prefix + names).upper() def _unrecognized_dict( settings: Mapping[str, Any], options: Any, above: Sequence[str] ) -> Generator[str, None, None]: for keystr in settings: # We don't have DataclassInstance exposed in typing yet matches = [ x for x in dataclasses.fields(options) if x.name.replace("_", "-") == keystr ] if not matches: yield ".".join((*above, keystr)) continue (inner_option_field,) = matches inner_option = inner_option_field.type if dataclasses.is_dataclass(inner_option): yield from _unrecognized_dict( settings[keystr], inner_option, (*above, keystr) ) class ConfSource: """ This is a source for the PEP 517 configuration settings. You should initialize it with a dict from PEP 517. a.b will be treated as nested dicts. "verify" is a boolean that determines whether unrecognized options should be checked for. Only set this to false if this might be sharing config options at the same level. """ def __init__( self, *prefixes: str, settings: Mapping[str, str | list[str]], verify: bool = True, ): self.prefixes = prefixes self.settings = settings self.verify = verify def _get_name(self, *fields: str) -> list[str]: names = [field.replace("_", "-") for field in fields] return [*self.prefixes, *names] def has_item(self, *fields: str, is_dict: bool) -> bool: names = self._get_name(*fields) name = ".".join(names) if is_dict: return any(k.startswith(f"{name}.") for k in self.settings) return name in self.settings def get_item(self, *fields: str, is_dict: bool) -> str | list[str] | dict[str, str]: names = self._get_name(*fields) name = ".".join(names) if is_dict: d = { k[len(name) + 1 :]: str(v) for k, v in self.settings.items() if k.startswith(f"{name}.") } if d: return d msg = f"Dict items {name}.* not found in settings" raise KeyError(msg) if name in self.settings: return self.settings[name] msg = f"{name!r} not found in configuration settings" raise KeyError(msg) @classmethod def convert( cls, item: str | list[str] | dict[str, str], target: type[Any] ) -> object: raw_target = _get_target_raw_type(target) if dataclasses.is_dataclass(raw_target): msg = f"Array of dataclasses are not supported in configuration settings ({raw_target})" raise TypeError(msg) if raw_target == list: if isinstance(item, list): return [cls.convert(i, _get_inner_type(target)) for i in item] if isinstance(item, dict): msg = f"Expected {target}, got {type(item).__name__}" raise TypeError(msg) return [ cls.convert(i.strip(), _get_inner_type(target)) for i in item.split(";") ] if raw_target == dict: assert not isinstance(item, (str, list)) return {k: cls.convert(v, _get_inner_type(target)) for k, v in item.items()} if isinstance(item, (list, dict)): msg = f"Expected {target}, got {type(item).__name__}" raise TypeError(msg) if raw_target is bool: return item.strip().lower() not in {"0", "false", "off", "no", ""} if raw_target is Union and str in get_args(target): return item if raw_target is Literal: if item not in get_args(_process_union(target)): msg = f"{item!r} not in {get_args(_process_union(target))!r}" raise TypeError(msg) return item if callable(raw_target): return raw_target(item) msg = f"Can't convert target {target}" raise TypeError(msg) def unrecognized_options(self, options: object) -> Generator[str, None, None]: if not self.verify: return for keystr in self.settings: keys = keystr.replace("-", "_").split(".")[len(self.prefixes) :] try: outer_option = _dig_fields(options, *keys[:-1]) except KeyError: yield ".".join(keystr.split(".")[:-1]) continue if dataclasses.is_dataclass(outer_option): try: _dig_fields(outer_option, keys[-1]) except KeyError: yield keystr continue if _get_target_raw_type(outer_option) == dict: continue def all_option_names(self, target: type[Any]) -> Iterator[str]: for names in _nested_dataclass_to_names(target): dash_names = [name.replace("_", "-") for name in names] yield ".".join((*self.prefixes, *dash_names)) class TOMLSource: def __init__(self, *prefixes: str, settings: Mapping[str, Any]): self.prefixes = prefixes self.settings = _dig_not_strict(settings, *prefixes) def _get_name(self, *fields: str) -> list[str]: return [field.replace("_", "-") for field in fields] def has_item(self, *fields: str, is_dict: bool) -> bool: # noqa: ARG002 names = self._get_name(*fields) try: _dig_strict(self.settings, *names) return True except KeyError: return False def get_item(self, *fields: str, is_dict: bool) -> Any: # noqa: ARG002 names = self._get_name(*fields) try: return _dig_strict(self.settings, *names) except KeyError: msg = f"{names!r} not found in configuration settings" raise KeyError(msg) from None @classmethod def convert(cls, item: Any, target: type[Any]) -> object: raw_target = _get_target_raw_type(target) if dataclasses.is_dataclass(raw_target): fields = dataclasses.fields(raw_target) values = ((k.replace("-", "_"), v) for k, v in item.items()) return raw_target( **{ k: cls.convert(v, *[f.type for f in fields if f.name == k]) for k, v in values } ) if raw_target is list: if not isinstance(item, list): msg = f"Expected {target}, got {type(item).__name__}" raise TypeError(msg) return [cls.convert(it, _get_inner_type(target)) for it in item] if raw_target is dict: if not isinstance(item, dict): msg = f"Expected {target}, got {type(item).__name__}" raise TypeError(msg) return {k: cls.convert(v, _get_inner_type(target)) for k, v in item.items()} if raw_target is Any: return item if raw_target is Union and type(item) in get_args(target): return item if raw_target is Literal: if item not in get_args(_process_union(target)): msg = f"{item!r} not in {get_args(_process_union(target))!r}" raise TypeError(msg) return item if callable(raw_target): return raw_target(item) msg = f"Can't convert target {target}" raise TypeError(msg) def unrecognized_options(self, options: object) -> Generator[str, None, None]: yield from _unrecognized_dict(self.settings, options, self.prefixes) def all_option_names(self, target: type[Any]) -> Iterator[str]: for names in _nested_dataclass_to_names(target): dash_names = [name.replace("_", "-") for name in names] yield ".".join((*self.prefixes, *dash_names)) class SourceChain: def __init__(self, *sources: Source, prefixes: Sequence[str] = ()) -> None: """ Combine a collection of sources into a single object that can run ``convert_target(dataclass)``. An optional list of prefixes can be given that will be prepended (dot separated) to error messages. """ self.sources = sources self.prefixes = prefixes def __getitem__(self, index: int) -> Source: return self.sources[index] def has_item(self, *fields: str, is_dict: bool) -> bool: return any(source.has_item(*fields, is_dict=is_dict) for source in self.sources) def get_item(self, *fields: str, is_dict: bool) -> Any: for source in self.sources: if source.has_item(*fields, is_dict=is_dict): return source.get_item(*fields, is_dict=is_dict) msg = f"{fields!r} not found in any source" raise KeyError(msg) def convert_target(self, target: type[T], *prefixes: str) -> T: """ Given a dataclass type, create an object of that dataclass filled with the values in the sources. """ errors = [] prep: dict[str, Any] = {} for field in dataclasses.fields(target): # type: ignore[arg-type] if dataclasses.is_dataclass(field.type): try: prep[field.name] = self.convert_target( field.type, *prefixes, field.name ) except Exception as e: name = ".".join([*self.prefixes, *prefixes, field.name]) e.__notes__ = [*getattr(e, "__notes__", []), f"Field: {name}"] # type: ignore[attr-defined] errors.append(e) continue is_dict = _get_target_raw_type(field.type) == dict for source in self.sources: if source.has_item(*prefixes, field.name, is_dict=is_dict): simple = source.get_item(*prefixes, field.name, is_dict=is_dict) try: tmp = source.convert(simple, field.type) except Exception as e: name = ".".join([*self.prefixes, *prefixes, field.name]) e.__notes__ = [*getattr(e, "__notes__", []), f"Field {name}"] # type: ignore[attr-defined] errors.append(e) prep[field.name] = None break if is_dict: assert isinstance(tmp, dict), f"{field.name} must be a dict" prep[field.name] = {**tmp, **prep.get(field.name, {})} continue prep[field.name] = tmp break if field.name in prep: continue if field.default is not dataclasses.MISSING: prep[field.name] = field.default continue if field.default_factory is not dataclasses.MISSING: prep[field.name] = field.default_factory() continue errors.append(ValueError(f"Missing value for {field.name!r}")) if errors: prefix_str = ".".join([*self.prefixes, *prefixes]) msg = f"Failed converting {prefix_str}" raise ExceptionGroup(msg, errors) return target(**prep) def unrecognized_options(self, options: object) -> Generator[str, None, None]: for source in self.sources: yield from source.unrecognized_options(options) if typing.TYPE_CHECKING: _: Source = typing.cast(EnvSource, None) _ = typing.cast(ConfSource, None) _ = typing.cast(TOMLSource, None)
/scikit_build_core-0.5.0-py3-none-any.whl/scikit_build_core/settings/sources.py
0.863852
0.189109
sources.py
pypi
from __future__ import annotations import copy import json from typing import Any from ..resources import resources __all__ = ["get_skbuild_schema", "generate_skbuild_schema"] def __dir__() -> list[str]: return __all__ def generate_skbuild_schema(tool_name: str = "scikit-build") -> dict[str, Any]: "Generate the complete schema for scikit-build settings." assert tool_name == "scikit-build", "Only scikit-build is supported." from .json_schema import to_json_schema from .skbuild_model import ScikitBuildSettings schema = { "$schema": "http://json-schema.org/draft-07/schema", "$id": "https://github.com/scikit-build/scikit-build-core/blob/main/src/scikit_build_core/resources/scikit-build.schema.json", "description": "Scikit-build-core's settings.", **to_json_schema(ScikitBuildSettings, normalize_keys=True), } # Manipulate a bit to get better validation # This is making the generate's template or template-path required generate = schema["properties"]["generate"]["items"] for prop in generate["properties"].values(): if prop.get("type", "") == "string": prop["minLength"] = 1 generate_tmpl = copy.deepcopy(generate) generate_path = copy.deepcopy(generate) generate_tmpl["required"] = ["path", "template"] del generate_tmpl["properties"]["template-path"] del generate_tmpl["properties"]["template"]["default"] generate_path["required"] = ["path", "template-path"] del generate_path["properties"]["template"] schema["properties"]["generate"]["items"] = { "oneOf": [generate_tmpl, generate_path] } return schema def get_skbuild_schema(tool_name: str = "scikit-build") -> dict[str, Any]: "Get the stored complete schema for scikit-build settings." assert tool_name == "scikit-build", "Only scikit-build is supported." with resources.joinpath("scikit-build.schema.json").open(encoding="utf-8") as f: return json.load(f) # type: ignore[no-any-return] if __name__ == "__main__": d = generate_skbuild_schema() print(json.dumps(d, indent=2)) # noqa: T201
/scikit_build_core-0.5.0-py3-none-any.whl/scikit_build_core/settings/skbuild_schema.py
0.788217
0.220636
skbuild_schema.py
pypi
import dataclasses from pathlib import Path from typing import Any, Dict, List, Optional, Union from packaging.version import Version from .._compat.typing import Literal __all__ = [ "BackportSettings", "CMakeSettings", "EditableSettings", "InstallSettings", "LoggingSettings", "NinjaSettings", "SDistSettings", "ScikitBuildSettings", "GenerateSettings", "WheelSettings", ] def __dir__() -> List[str]: return __all__ @dataclasses.dataclass class CMakeSettings: minimum_version: Version = Version("3.15") """ The minimum version of CMake to use. If CMake is not present on the system or is older than this, it will be downloaded via PyPI if possible. An empty string will disable this check. """ args: List[str] = dataclasses.field(default_factory=list) """ A list of args to pass to CMake when configuring the project. Setting this in config or envvar will override toml. See also ``cmake.define``. """ define: Dict[str, Union[str, bool]] = dataclasses.field(default_factory=dict) """ A table of defines to pass to CMake when configuring the project. Additive. """ verbose: bool = False """ Verbose printout when building. """ build_type: str = "Release" """ The build type to use when building the project. Valid options are: "Debug", "Release", "RelWithDebInfo", "MinSizeRel", "", etc. """ source_dir: Path = Path() """ The source directory to use when building the project. Currently only affects the native builder (not the setuptools plugin). """ targets: List[str] = dataclasses.field(default_factory=list) """ The build targets to use when building the project. Empty builds the default target. """ @dataclasses.dataclass class NinjaSettings: minimum_version: Version = Version("1.5") """ The minimum version of Ninja to use. If Ninja is not present on the system or is older than this, it will be downloaded via PyPI if possible. An empty string will disable this check. """ make_fallback: bool = True """ If CMake is not present on the system or is older required, it will be downloaded via PyPI if possible. An empty string will disable this check. """ @dataclasses.dataclass class LoggingSettings: level: Literal[ "NOTSET", "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL" ] = "WARNING" """ The logging level to display, "DEBUG", "INFO", "WARNING", and "ERROR" are possible options. """ @dataclasses.dataclass class SDistSettings: include: List[str] = dataclasses.field(default_factory=list) """ Files to include in the SDist even if they are skipped by default. Supports gitignore syntax. """ exclude: List[str] = dataclasses.field(default_factory=list) """ Files to exclude from the SDist even if they are included by default. Supports gitignore syntax. """ reproducible: bool = True """ If set to True, try to build a reproducible distribution (Unix and Python 3.9+ recommended). ``SOURCE_DATE_EPOCH`` will be used for timestamps, or a fixed value if not set. """ cmake: bool = False """ If set to True, CMake will be run before building the SDist. """ @dataclasses.dataclass class WheelSettings: packages: Optional[List[str]] = None """ A list of packages to auto-copy into the wheel. If this is not set, it will default to the first of ``src/<package>`` or ``<package>`` if they exist. The prefix(s) will be stripped from the package name inside the wheel. """ py_api: str = "" """ The Python tags. The default (empty string) will use the default Python version. You can also set this to "cp37" to enable the CPython 3.7+ Stable ABI / Limited API (only on CPython and if the version is sufficient, otherwise this has no effect). Or you can set it to "py3" or "py2.py3" to ignore Python ABI compatibility. The ABI tag is inferred from this tag. """ expand_macos_universal_tags: bool = False """ Fill out extra tags that are not required. This adds "x86_64" and "arm64" to the list of platforms when "universal2" is used, which helps older Pip's (before 21.0.1) find the correct wheel. """ install_dir: str = "" """ The install directory for the wheel. This is relative to the platlib root. You might set this to the package name. The original dir is still at SKBUILD_PLATLIB_DIR (also SKBUILD_DATA_DIR, etc. are available). EXPERIMENTAL: An absolute path will be one level higher than the platlib root, giving access to "/platlib", "/data", "/headers", and "/scripts". """ license_files: List[str] = dataclasses.field( default_factory=lambda: ["LICEN[CS]E*", "COPYING*", "NOTICE*", "AUTHORS*"] ) """ A list of license files to include in the wheel. Supports glob patterns. """ @dataclasses.dataclass class BackportSettings: find_python: Version = Version("3.26.1") """ If CMake is less than this value, backport a copy of FindPython. Set to 0 disable this, or the empty string. """ @dataclasses.dataclass class EditableSettings: mode: Literal["redirect"] = "redirect" """ Select the editable mode to use. Currently only "redirect" is supported. """ verbose: bool = True """ Turn on verbose output for the editable mode rebuilds. """ rebuild: bool = False """ Rebuild the project when the package is imported. The build-directory must be set. """ @dataclasses.dataclass class InstallSettings: components: List[str] = dataclasses.field(default_factory=list) """ The components to install. If empty, all default components are installed. """ strip: Optional[bool] = None """ Whether to strip the binaries. True for scikit-build-core 0.5+. """ @dataclasses.dataclass class GenerateSettings: path: Path """ The path (relative to platlib) for the file to generate. """ template: str = "" """ The template to use for the file. This includes string.Template style placeholders for all the metadata. If empty, a template-path must be set. """ template_path: Optional[Path] = None """ The path to the template file. If empty, a template must be set. """ location: Literal["install", "build", "source"] = "install" """ The place to put the generated file. The "build" directory is useful for CMake files, and the "install" directory is useful for Python files, usually. You can also write directly to the "source" directory, will overwrite existing files & remember to gitignore the file. """ @dataclasses.dataclass class ScikitBuildSettings: cmake: CMakeSettings = dataclasses.field(default_factory=CMakeSettings) ninja: NinjaSettings = dataclasses.field(default_factory=NinjaSettings) logging: LoggingSettings = dataclasses.field(default_factory=LoggingSettings) sdist: SDistSettings = dataclasses.field(default_factory=SDistSettings) wheel: WheelSettings = dataclasses.field(default_factory=WheelSettings) backport: BackportSettings = dataclasses.field(default_factory=BackportSettings) editable: EditableSettings = dataclasses.field(default_factory=EditableSettings) install: InstallSettings = dataclasses.field(default_factory=InstallSettings) generate: List[GenerateSettings] = dataclasses.field(default_factory=list) metadata: Dict[str, Dict[str, Any]] = dataclasses.field(default_factory=dict) """ List dynamic metadata fields and hook locations in this table. """ strict_config: bool = True """ Strictly check all config options. If False, warnings will be printed for unknown options. If True, an error will be raised. """ experimental: bool = False """ Enable early previews of features not finalized yet. """ minimum_version: Optional[Version] = None """ If set, this will provide a method for backward compatibility. """ build_dir: str = "" """ The build directory. Defaults to a temporary directory, but can be set. """
/scikit_build_core-0.5.0-py3-none-any.whl/scikit_build_core/settings/skbuild_model.py
0.908638
0.347316
skbuild_model.py
pypi
from __future__ import annotations import base64 import copy import csv import dataclasses import hashlib import io import os import stat import time import zipfile from collections.abc import Mapping, Set from email.message import Message from email.policy import EmailPolicy from pathlib import Path from zipfile import ZipInfo import packaging.utils from packaging.tags import Tag from packaging.utils import BuildTag from pyproject_metadata import StandardMetadata from .. import __version__ from .._compat.typing import Self EMAIL_POLICY = EmailPolicy(max_line_length=0, mangle_from_=False, utf8=True) MIN_TIMESTAMP = 315532800 # 1980-01-01 00:00:00 UTC def _b64encode(data: bytes) -> bytes: return base64.urlsafe_b64encode(data).rstrip(b"=") __all__ = ["WheelWriter", "WheelMetadata"] def __dir__() -> list[str]: return __all__ @dataclasses.dataclass class WheelMetadata: root_is_purelib: bool = False metadata_version: str = "1.0" generator: str = f"scikit-build-core {__version__}" build_tag: BuildTag = () tags: Set[Tag] = dataclasses.field(default_factory=frozenset) def as_bytes(self) -> bytes: msg = Message(policy=EMAIL_POLICY) msg["Wheel-Version"] = self.metadata_version msg["Generator"] = self.generator msg["Root-Is-Purelib"] = str(self.root_is_purelib).lower() if self.build_tag: msg["Build"] = str(self.build_tag[0]) + self.build_tag[1] for tag in sorted(self.tags, key=lambda t: (t.interpreter, t.abi, t.platform)): msg["Tag"] = f"{tag.interpreter}-{tag.abi}-{tag.platform}" return msg.as_bytes() @dataclasses.dataclass class WheelWriter: """A general tool for writing wheels. Designed to look a little like ZipFile.""" metadata: StandardMetadata folder: Path tags: Set[Tag] wheel_metadata = WheelMetadata(root_is_purelib=False) buildver: str = "" license_files: Mapping[Path, bytes] = dataclasses.field(default_factory=dict) _zipfile: zipfile.ZipFile | None = None @property def name_ver(self) -> str: name = packaging.utils.canonicalize_name(self.metadata.name).replace("-", "_") # replace - with _ as a local version separator version = str(self.metadata.version).replace("-", "_") return f"{name}-{version}" @property def basename(self) -> str: pyver = ".".join(sorted({t.interpreter for t in self.tags})) abi = ".".join(sorted({t.abi for t in self.tags})) arch = ".".join(sorted({t.platform for t in self.tags})) optbuildver = [self.buildver] if self.buildver else [] return "-".join([self.name_ver, *optbuildver, pyver, abi, arch]) @property def wheelpath(self) -> Path: return self.folder / f"{self.basename}.whl" @property def dist_info(self) -> str: return f"{self.name_ver}.dist-info" @staticmethod def timestamp(mtime: float | None = None) -> tuple[int, int, int, int, int, int]: timestamp = int(os.environ.get("SOURCE_DATE_EPOCH", mtime or time.time())) # The ZIP file format does not support timestamps before 1980. timestamp = max(timestamp, MIN_TIMESTAMP) return time.gmtime(timestamp)[0:6] def dist_info_contents(self) -> dict[str, bytes]: entry_points = io.StringIO() ep = self.metadata.entrypoints.copy() ep["console_scripts"] = self.metadata.scripts ep["gui_scripts"] = self.metadata.gui_scripts for group, entries in ep.items(): if entries: entry_points.write(f"[{group}]\n") for name, target in entries.items(): entry_points.write(f"{name} = {target}\n") entry_points.write("\n") self.wheel_metadata.tags = self.tags # Using deepcopy here because of a bug in pyproject-metadata # https://github.com/FFY00/python-pyproject-metadata/pull/49 rfc822 = copy.deepcopy(self.metadata).as_rfc822() for fp in self.license_files: rfc822["License-File"] = f"{fp}" license_entries = { f"licenses/{fp}": data for fp, data in self.license_files.items() } return { "METADATA": bytes(rfc822), "WHEEL": self.wheel_metadata.as_bytes(), "entry_points.txt": entry_points.getvalue().encode("utf-8"), **license_entries, } def build(self, wheel_dirs: dict[str, Path]) -> None: assert "platlib" in wheel_dirs assert "purelib" not in wheel_dirs assert {"platlib", "data", "headers", "scripts", "null"} >= wheel_dirs.keys() # The "main" directory (platlib for us) will be handled specially below plans = {"": wheel_dirs["platlib"]} data_dir = f"{self.name_ver}.data" for key in sorted({"data", "headers", "scripts"} & wheel_dirs.keys()): plans[key] = wheel_dirs[key] for key, path in plans.items(): for filename in sorted(path.glob("**/*")): is_in_dist_info = any(x.endswith(".dist-info") for x in filename.parts) is_python_cache = filename.suffix in {".pyc", ".pyo"} if filename.is_file() and not is_in_dist_info and not is_python_cache: relpath = filename.relative_to(path) target = Path(data_dir) / key / relpath if key else relpath self.write(str(filename), str(target)) dist_info_contents = self.dist_info_contents() for key, data in dist_info_contents.items(): self.writestr(f"{self.dist_info}/{key}", data) def write(self, filename: str, arcname: str | None = None) -> None: """Write a file to the archive. Paths are normalized to Posix paths.""" with Path(filename).open("rb") as f: st = os.fstat(f.fileno()) data = f.read() # Zipfiles require Posix paths for the arcname zinfo = ZipInfo( (arcname or filename).replace("\\", "/"), date_time=self.timestamp(st.st_mtime), ) zinfo.compress_type = zipfile.ZIP_DEFLATED zinfo.external_attr = (stat.S_IMODE(st.st_mode) | stat.S_IFMT(st.st_mode)) << 16 self.writestr(zinfo, data) def writestr(self, zinfo_or_arcname: str | ZipInfo, data: bytes) -> None: """Write bytes (not strings) to the archive.""" assert isinstance(data, bytes) assert self._zipfile is not None if isinstance(zinfo_or_arcname, zipfile.ZipInfo): zinfo = zinfo_or_arcname else: zinfo = zipfile.ZipInfo( zinfo_or_arcname.replace("\\", "/"), date_time=self.timestamp(), ) zinfo.compress_type = zipfile.ZIP_DEFLATED zinfo.external_attr = (0o664 | stat.S_IFREG) << 16 assert ( "\\" not in zinfo.filename ), f"\\ not supported in zip; got {zinfo.filename!r}" self._zipfile.writestr(zinfo, data) def __enter__(self) -> Self: if not self.wheelpath.parent.exists(): self.wheelpath.parent.mkdir(parents=True) self._zipfile = zipfile.ZipFile( self.wheelpath, "w", compression=zipfile.ZIP_DEFLATED ) return self def __exit__(self, *args: object) -> None: assert self._zipfile is not None record = f"{self.dist_info}/RECORD" data = io.StringIO() writer = csv.writer(data, delimiter=",", quotechar='"', lineterminator="\n") for member in self._zipfile.infolist(): assert ( "\\" not in member.filename ), f"Invalid zip contents: {member.filename}" with self._zipfile.open(member) as f: member_data = f.read() sha = _b64encode(hashlib.sha256(member_data).digest()).decode("ascii") writer.writerow((member.filename, f"sha256={sha}", member.file_size)) writer.writerow((record, "", "")) self.writestr(record, data.getvalue().encode("utf-8")) self._zipfile.close() self._zipfile = None
/scikit_build_core-0.5.0-py3-none-any.whl/scikit_build_core/build/_wheelfile.py
0.711631
0.188175
_wheelfile.py
pypi
from __future__ import annotations import contextlib import copy import gzip import io import os import tarfile from pathlib import Path from packaging.utils import canonicalize_name from packaging.version import Version from .. import __version__ from .._compat import tomllib from .._logging import rich_print from ..settings.metadata import get_standard_metadata from ..settings.skbuild_read_settings import SettingsReader from ._file_processor import each_unignored_file from ._init import setup_logging from .generate import generate_file_contents from .wheel import _build_wheel_impl __all__ = ["build_sdist"] def __dir__() -> list[str]: return __all__ def get_reproducible_epoch() -> int: """ Return an integer representing the integer number of seconds since the Unix epoch. If the `SOURCE_DATE_EPOCH` environment variable is set, use that value. Otherwise, always return `1667997441`. """ return int(os.environ.get("SOURCE_DATE_EPOCH", "1667997441")) def normalize_file_permissions(st_mode: int) -> int: """ Normalize the permission bits in the st_mode field from stat to 644/755 Popular VCSs only track whether a file is executable or not. The exact permissions can vary on systems with different umasks. Normalising to 644 (non executable) or 755 (executable) makes builds more reproducible. Taken from https://github.com/pypa/flit/blob/6a2a8c6462e49f584941c667b70a6f48a7b3f9ab/flit_core/flit_core/common.py#L257 """ # Set 644 permissions, leaving higher bits of st_mode unchanged new_mode = (st_mode | 0o644) & ~0o133 if st_mode & 0o100: new_mode |= 0o111 # Executable: 644 -> 755 return new_mode def normalize_tar_info(tar_info: tarfile.TarInfo) -> tarfile.TarInfo: """ Normalize the TarInfo associated with a file to improve reproducibility. Inspired by Hatch https://github.com/pypa/hatch/blob/573192f88022bb781c698dae2c0b84ef3fb9a7ad/backend/src/hatchling/builders/sdist.py#L51 """ tar_info = copy.copy(tar_info) tar_info.uname = "" tar_info.gname = "" tar_info.uid = 0 tar_info.gid = 0 tar_info.mode = normalize_file_permissions(tar_info.mode) tar_info.mtime = get_reproducible_epoch() return tar_info def add_bytes_to_tar( tar: tarfile.TarFile, data: bytes, name: str, normalize: bool ) -> None: """ Write ``data`` bytes to ``name`` in a tarfile ``tar``. Normalize the info if ``normalize`` is true. """ tarinfo = tarfile.TarInfo(name) if normalize: tarinfo = normalize_tar_info(tarinfo) with io.BytesIO(data) as bio: tarinfo.size = bio.getbuffer().nbytes tar.addfile(tarinfo, bio) def build_sdist( sdist_directory: str, config_settings: dict[str, list[str] | str] | None = None, ) -> str: rich_print( f"[green]***[/green] [bold][green]scikit-build-core {__version__}[/green]", "[red](sdist)[/red]", ) with Path("pyproject.toml").open("rb") as f: pyproject = tomllib.load(f) settings_reader = SettingsReader(pyproject, config_settings or {}) settings = settings_reader.settings setup_logging(settings.logging.level) settings_reader.validate_may_exit() sdist_dir = Path(sdist_directory) reproducible = settings.sdist.reproducible timestamp = get_reproducible_epoch() if reproducible else None metadata = get_standard_metadata(pyproject, settings) # Using deepcopy here because of a bug in pyproject-metadata # https://github.com/FFY00/python-pyproject-metadata/pull/49 pkg_info = bytes(copy.deepcopy(metadata).as_rfc822()) # Only normalize SDist name if 0.5+ is requested for backwards compat should_normalize_name = ( settings.minimum_version is None or settings.minimum_version >= Version("0.5") ) sdist_name = ( canonicalize_name(metadata.name).replace("-", "_") if should_normalize_name else metadata.name ) srcdirname = f"{sdist_name}-{metadata.version}" filename = f"{srcdirname}.tar.gz" if settings.sdist.cmake: _build_wheel_impl( None, config_settings, None, exit_after_config=True, editable=False ) for gen in settings.generate: if gen.location == "source": contents = generate_file_contents(gen, metadata) gen.path.write_text(contents) settings.sdist.include.append(str(gen.path)) sdist_dir.mkdir(parents=True, exist_ok=True) with contextlib.ExitStack() as stack: gzip_container = stack.enter_context( gzip.GzipFile(sdist_dir / filename, mode="wb", mtime=timestamp) ) tar = stack.enter_context( tarfile.TarFile(fileobj=gzip_container, mode="w", format=tarfile.PAX_FORMAT) ) paths = sorted( each_unignored_file( Path(), include=settings.sdist.include, exclude=settings.sdist.exclude, ) ) for filepath in paths: tar.add( filepath, arcname=srcdirname / filepath, filter=normalize_tar_info if reproducible else lambda x: x, ) add_bytes_to_tar(tar, pkg_info, f"{srcdirname}/PKG-INFO", reproducible) return filename
/scikit_build_core-0.5.0-py3-none-any.whl/scikit_build_core/build/sdist.py
0.68342
0.159381
sdist.py
pypi
from __future__ import annotations import os import platform import re import subprocess import sys import textwrap from typing import Iterable from setuptools import monkey from .._compat.typing import TypedDict from . import abstract from .abstract import CMakeGenerator VS_YEAR_TO_VERSION = { "2017": 15, "2019": 16, "2022": 17, } """Describes the version of `Visual Studio` supported by :class:`CMakeVisualStudioIDEGenerator` and :class:`CMakeVisualStudioCommandLineGenerator`. The different version are identified by their year. """ VS_YEAR_TO_MSC_VER = { "2017": "1910", # VS 2017 - can be +9 "2019": "1920", # VS 2019 - can be +9 "2022": "1930", # VS 2022 - can be +9 } ARCH_TO_MSVC_ARCH = { "Win32": "x86", "ARM64": "x86_arm64", "x64": "x86_amd64", } class CachedEnv(TypedDict): PATH: str INCLUDE: str LIB: str class WindowsPlatform(abstract.CMakePlatform): """Windows implementation of :class:`.abstract.CMakePlatform`.""" def __init__(self) -> None: super().__init__() self._vs_help = "" vs_help_template = ( textwrap.dedent( """ Building windows wheels for Python {pyver} requires Microsoft Visual Studio %s. Get it with "%s": %s """ ) .strip() .format(pyver=".".join(str(v) for v in sys.version_info[:2])) ) # For Python 3.7 and above: VS2022, VS2019, VS2017 supported_vs_years = [("2022", "v143"), ("2019", "v142"), ("2017", "v141")] self._vs_help = vs_help_template % ( supported_vs_years[0][0], "Visual Studio 2017", "https://visualstudio.microsoft.com/vs/", ) self._vs_help += ( "\n\n" + textwrap.dedent( """ Or with "Visual Studio 2019": https://visualstudio.microsoft.com/vs/ Or with "Visual Studio 2022": https://visualstudio.microsoft.com/vs/ """ ).strip() ) try: import ninja # pylint: disable=import-outside-toplevel ninja_executable_path = os.path.join(ninja.BIN_DIR, "ninja") ninja_args = ["-DCMAKE_MAKE_PROGRAM:FILEPATH=" + ninja_executable_path] except ImportError: ninja_args = [] extra = [] for vs_year, vs_toolset in supported_vs_years: vs_version = VS_YEAR_TO_MSC_VER[vs_year] args = [f"-D_SKBUILD_FORCE_MSVC={vs_version}"] self.default_generators.extend( [ CMakeVisualStudioCommandLineGenerator("Ninja", vs_year, vs_toolset, args=ninja_args + args), CMakeVisualStudioIDEGenerator(vs_year, vs_toolset), ] ) extra.append(CMakeVisualStudioCommandLineGenerator("NMake Makefiles", vs_year, vs_toolset, args=args)) self.default_generators.extend(extra) @property def generator_installation_help(self) -> str: """Return message guiding the user for installing a valid toolchain.""" return self._vs_help def _compute_arch() -> str: """Currently only supports Intel -> ARM cross-compilation.""" if platform.machine() == "ARM64" or "arm64" in os.environ.get("SETUPTOOLS_EXT_SUFFIX", "").lower(): return "ARM64" if platform.architecture()[0] == "64bit": return "x64" return "Win32" class CMakeVisualStudioIDEGenerator(CMakeGenerator): """ Represents a Visual Studio CMake generator. .. automethod:: __init__ """ def __init__(self, year: str, toolset: str | None = None) -> None: """Instantiate a generator object with its name set to the `Visual Studio` generator associated with the given ``year`` (see :data:`VS_YEAR_TO_VERSION`), the current platform (32-bit or 64-bit) and the selected ``toolset`` (if applicable). """ vs_version = VS_YEAR_TO_VERSION[year] vs_base = f"Visual Studio {vs_version} {year}" vs_arch = _compute_arch() super().__init__(vs_base, toolset=toolset, arch=vs_arch) def _find_visual_studio_2017_or_newer(vs_version: int) -> str: """Adapted from https://github.com/python/cpython/blob/3.7/Lib/distutils/_msvccompiler.py The ``vs_version`` corresponds to the `Visual Studio` version to lookup. See :data:`VS_YEAR_TO_VERSION`. Returns `path` based on the result of invoking ``vswhere.exe``. If no install is found, returns an empty string. ..note: If ``vswhere.exe`` is not available, by definition, VS 2017 or newer is not installed. """ root = os.environ.get("PROGRAMFILES(X86)") or os.environ.get("PROGRAMFILES") if not root: return "" try: path = subprocess.run( [ os.path.join(root, "Microsoft Visual Studio", "Installer", "vswhere.exe"), "-version", f"[{vs_version:.1f}, {vs_version + 1:.1f})", "-prerelease", "-requires", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property", "installationPath", "-products", "*", ], encoding="utf-8" if sys.platform.startswith("cygwin") else "mbcs", check=True, stdout=subprocess.PIPE, errors="strict", ).stdout.strip() except (subprocess.CalledProcessError, OSError, UnicodeDecodeError): return "" path = os.path.join(path, "VC", "Auxiliary", "Build") if os.path.isdir(path): return path return "" def find_visual_studio(vs_version: int) -> str: """Return Visual Studio installation path associated with ``vs_version`` or an empty string if any. The ``vs_version`` corresponds to the `Visual Studio` version to lookup. See :data:`VS_YEAR_TO_VERSION`. .. note:: - Returns `path` based on the result of invoking ``vswhere.exe``. """ return _find_visual_studio_2017_or_newer(vs_version) # To avoid multiple slow calls to ``subprocess.run()`` (either directly or # indirectly through ``query_vcvarsall``), results of previous calls are cached. __get_msvc_compiler_env_cache: dict[str, CachedEnv] = {} def _get_msvc_compiler_env(vs_version: int, vs_toolset: str | None = None) -> CachedEnv | dict[str, str]: """ Return a dictionary of environment variables corresponding to ``vs_version`` that can be used with :class:`CMakeVisualStudioCommandLineGenerator`. The ``vs_toolset`` is used only for Visual Studio 2017 or newer (``vs_version >= 15``). If specified, ``vs_toolset`` is used to set the `-vcvars_ver=XX.Y` argument passed to ``vcvarsall.bat`` script. """ # Set architecture vc_arch = ARCH_TO_MSVC_ARCH[_compute_arch()] # If any, return cached version cache_key = ",".join([str(vs_version), vc_arch, str(vs_toolset)]) if cache_key in __get_msvc_compiler_env_cache: return __get_msvc_compiler_env_cache[cache_key] monkey.patch_for_msvc_specialized_compiler() # type: ignore[no-untyped-call] vc_dir = find_visual_studio(vs_version) vcvarsall = os.path.join(vc_dir, "vcvarsall.bat") if not os.path.exists(vcvarsall): return {} # Set vcvars_ver argument based on toolset vcvars_ver = "" if vs_toolset is not None: match = re.findall(r"^v(\d\d)(\d+)$", vs_toolset)[0] if match: match_str = ".".join(match) vcvars_ver = f"-vcvars_ver={match_str}" try: out_bytes = subprocess.run( f'cmd /u /c "{vcvarsall}" {vc_arch} {vcvars_ver} && set', stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=sys.platform.startswith("cygwin"), check=True, ).stdout out = out_bytes.decode("utf-16le", errors="replace") vc_env = { key.lower(): value for key, _, value in (line.partition("=") for line in out.splitlines()) if key and value } cached_env: CachedEnv = { "PATH": vc_env.get("path", ""), "INCLUDE": vc_env.get("include", ""), "LIB": vc_env.get("lib", ""), } __get_msvc_compiler_env_cache[cache_key] = cached_env return cached_env except subprocess.CalledProcessError as exc: print(exc.output.decode("utf-16le", errors="replace"), file=sys.stderr, flush=True) return {} class CMakeVisualStudioCommandLineGenerator(CMakeGenerator): """ Represents a command-line CMake generator initialized with a specific `Visual Studio` environment. .. automethod:: __init__ """ def __init__(self, name: str, year: str, toolset: str | None = None, args: Iterable[str] | None = None): """Instantiate CMake command-line generator. The generator ``name`` can be values like `Ninja`, `NMake Makefiles` or `NMake Makefiles JOM`. The ``year`` defines the `Visual Studio` environment associated with the generator. See :data:`VS_YEAR_TO_VERSION`. If set, the ``toolset`` defines the `Visual Studio Toolset` to select. The platform (32-bit or 64-bit or ARM) is automatically selected. """ arch = _compute_arch() vc_env = _get_msvc_compiler_env(VS_YEAR_TO_VERSION[year], toolset) env = {str(key.upper()): str(value) for key, value in vc_env.items()} super().__init__(name, env, arch=arch, args=args) self._description = f"{self.name} ({CMakeVisualStudioIDEGenerator(year, toolset).description})"
/scikit_build-0.17.6-py3-none-any.whl/skbuild/platform_specifics/windows.py
0.759939
0.166913
windows.py
pypi
from __future__ import annotations import os from setuptools.command.build_py import build_py as _build_py from ..constants import CMAKE_INSTALL_DIR from ..utils import distribution_hide_listing, logger from . import set_build_base_mixin class build_py(set_build_base_mixin, _build_py): """Custom implementation of ``build_py`` setuptools command.""" def initialize_options(self) -> None: """Handle --hide-listing option. Initializes ``outfiles_count``. """ super().initialize_options() self.outfiles_count = 0 def build_module(self, module: str | list[str] | tuple[str, ...], module_file: str, package: str) -> None: """Handle --hide-listing option. Increments ``outfiles_count``. """ super().build_module(module, module_file, package) # type: ignore[no-untyped-call] self.outfiles_count += 1 def run(self, *args: object, **kwargs: object) -> None: """Handle --hide-listing option. Display number of copied files. It corresponds to the value of ``outfiles_count``. """ with distribution_hide_listing(self.distribution): super().run(*args, **kwargs) logger.info("copied %d files", self.outfiles_count) def find_modules(self) -> list[tuple[str, str, str]]: """Finds individually-specified Python modules, ie. those listed by module name in 'self.py_modules'. Returns a list of tuples (package, module_base, filename): 'package' is a tuple of the path through package-space to the module; 'module_base' is the bare (no packages, no dots) module name, and 'filename' is the path to the ".py" file (relative to the distribution root) that implements the module. """ # Map package names to tuples of useful info about the package: # (package_dir, checked) # package_dir - the directory where we'll find source files for # this package # checked - true if we have checked that the package directory # is valid (exists, contains __init__.py, ... ?) packages: dict[str, tuple[str, bool]] = {} # List of (package, module, filename) tuples to return modules: list[tuple[str, str, str]] = [] # We treat modules-in-packages almost the same as toplevel modules, # just the "package" for a toplevel is empty (either an empty # string or empty list, depending on context). Differences: # - don't check for __init__.py in directory for empty package for module in self.py_modules: path = module.split(".") package = ".".join(path[0:-1]) module_base = path[-1] try: (package_dir, checked) = packages[package] except KeyError: package_dir = self.get_package_dir(package) # type: ignore[no-untyped-call] checked = False if not checked: init_py = self.check_package(package, package_dir) # type: ignore[no-untyped-call] packages[package] = (package_dir, True) if init_py: modules.append((package, "__init__", init_py)) # XXX perhaps we should also check for just .pyc files # (so greedy closed-source bastards can distribute Python # modules too) module_file = os.path.join(package_dir, module_base + ".py") # skbuild: prepend CMAKE_INSTALL_DIR if file exists in the # CMake install tree. if os.path.exists(os.path.join(CMAKE_INSTALL_DIR(), module_file)): module_file = os.path.join(CMAKE_INSTALL_DIR(), module_file) if not self.check_module(module, module_file): # type: ignore[no-untyped-call] continue modules.append((package, module_base, module_file)) return modules
/scikit_build-0.17.6-py3-none-any.whl/skbuild/command/build_py.py
0.719088
0.165054
build_py.py
pypi
import logging from contextlib import contextmanager from typing import Any from ..resources import ( CacheKey, ObjCacheMeta, ) from ..utils import ( format_bytes_to_str, hash_for_iterable, ) estimator_logger = logging.getLogger('scikit_cache.estimator') class EstimatorsMixin: """Mixin for cache controller to work with SKLearn estimators.""" @contextmanager def make_cached_estimator(self, estimator: Any) -> Any: """Make estimator instance with cachable methods. This is context manager, works like this: with cache.make_cached_estimator(estimator) as cached_estimator: cached_estimator.fit() This function modifies existing estimator instance. Returned instance has same class but it containes modified ``.fit()`` method. This "cached estimator" can be used anywhere just as usual SKLearn estimator, but every time ``.fit()`` method is called it will go to cache to check if estimator was already calculated and cached. To enable caching for cached estimator - you need to enable cache using ``cache.enable()`` function. By default, all cached estimator work as normal estimators. """ estimator_class = estimator.__class__ if not hasattr(estimator_class, '__original_fit__'): estimator_class.__original_fit__ = estimator_class.fit estimator_class.fit = self._estimator_fit_with_cache estimator_class.__cache_ctrl__ = self try: yield estimator finally: if hasattr(estimator_class, '__original_fit__'): estimator_class.fit = estimator_class.__original_fit__ delattr(estimator_class, '__original_fit__') delattr(estimator_class, '__cache_ctrl__') @staticmethod def _estimator_fit_with_cache(instance: Any, *args: Any, **kwargs: Any) -> Any: """Function that implements ``BaseEstimator.fit()`` with cache mechanisms.""" from sklearn.utils.validation import check_is_fitted cache = instance.__cache_ctrl__ # If caching is disabled then use original ``.fit()`` function if not cache.is_enabled_for_estimators: return instance.__original_fit__(*args, **kwargs) # Get hash of all fit params including class and original parameters estimator_hash = hash_for_iterable(( instance.__class__, instance.get_params(), args, kwargs, )) # Make cache key raw_key = f'estimators__{estimator_hash}' cache_key = CacheKey(raw_key) # Check if cached result exists (if read mode enabled) if 'r' in cache.__mode__: found, cached_result = cache._get(cache_key) if found: instance.__dict__ = cached_result.__dict__ check_is_fitted(instance) cache._log( 'estimator cache hit', level='info', logger=estimator_logger, ) return instance else: cache._log( 'estimator cache miss', level='warning', logger=estimator_logger, ) # Call original ``.fit()`` function fit_result = instance.__original_fit__(*args, **kwargs) check_is_fitted(fit_result) # Save fit result to cache if 'w' in cache.__mode__: cache_meta = ObjCacheMeta( raw_key=raw_key, ttl=cache.default_ttl, **cache._base_meta.dict(), ) cache._set(cache_key, fit_result, cache_meta) size = format_bytes_to_str(cache_meta.object_size) cache._log( f'estimator cache write - {size}', level='info', logger=estimator_logger, ) return fit_result
/scikit-cache-0.1.2.tar.gz/scikit-cache-0.1.2/scikit_cache/components/estimators.py
0.894588
0.156008
estimators.py
pypi
from datetime import ( datetime, timedelta, ) from functools import wraps from typing import ( Any, Callable, List, TypeVar, Union, cast, ) from scikit_cache.utils import ( format_str_to_bytes, get_file_access_time, ) from ..resources import CacheKey F = TypeVar('F', bound=Callable[..., Any]) class CleanUpMixin: """Mixin for ``CacheController`` class with cleanup private methods.""" def _get_clean_objects_by_expired_tl(self) -> List[CacheKey]: """Get list of cache keys with expired TTL.""" current_time = datetime.now() expired_keys = [] for cache_key, meta_cache in self._get_all_cache_meta().items(): if meta_cache.ttl >= 0: creation_time = datetime.fromisoformat(meta_cache.creation_time) expire_time = creation_time + timedelta(seconds=meta_cache.ttl) if current_time > expire_time: expired_keys.append(cache_key) return expired_keys def _get_clean_objects_by_max_number(self, max_number: int) -> List[CacheKey]: """Get list of cache keys to delete that exceed max number of objects.""" meta_dict = self._get_all_cache_meta() delete_number = len(meta_dict) - max_number if delete_number < 1: return [] return sorted(meta_dict, key=self._clean_sorting_func)[:delete_number] def _get_clean_objects_by_max_size(self, max_size: Union[int, str]) -> List[CacheKey]: """Get list of cache keys to delete that exceed max cache dir size.""" if not isinstance(max_size, int): max_size = format_str_to_bytes(max_size) total_size, result_keys = 0, [] meta_dict = self._get_all_cache_meta() for cache_key in sorted(meta_dict, key=self._clean_sorting_func, reverse=True): total_size += meta_dict[cache_key].object_size if total_size > max_size: result_keys.append(cache_key) return result_keys @property def _clean_sorting_func(self) -> Callable: """Get function that will be used for cache keys sorting. Result function depends on ``autoclean_mode`` parameter: - if it's "last_used", then result function will return file access time - if it's "last_created", then result function will return file creation time """ if self.autoclean_mode == 'last_used': return self._get_access_time_by_cache_key elif self.autoclean_mode == 'last_created': return self._get_creation_time_by_cache_key else: raise ValueError(f'Unknown ``autoclean_mode`` value: {self.autoclean_mode}') def _get_access_time_by_cache_key(self, cache_key: CacheKey) -> float: """Get file access time using cache key.""" pickle_path = self._handler.get_cache_pickle_path(cache_key) return get_file_access_time(filename=str(pickle_path)) def _get_creation_time_by_cache_key(self, cache_key: CacheKey) -> float: """Get file creation time using cache key.""" return self.__meta_cache__[cache_key].creation_timestamp # type: ignore def cache_autoclean(func: F) -> F: """Decorator to automatically call ``self.clean`` after each function call. Decorator can be applied only to ``CacheController`` class methods. """ if not func.__qualname__.startswith('CacheController.'): raise ValueError( 'Decorator ``cache_autoclean`` can only be applied to ``CacheController`` methods', ) @wraps(func) def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any: result = func(self, *args, **kwargs) if self.autoclean: self.clean() return result return cast(F, wrapper)
/scikit-cache-0.1.2.tar.gz/scikit-cache-0.1.2/scikit_cache/components/cleanup.py
0.894444
0.154153
cleanup.py
pypi
import inspect import logging from types import CodeType from typing import ( Any, Callable, ) import joblib from .base import get_func_name from .estimators import ( get_estimator_params, is_estimator, ) logger = logging.getLogger('scikit_cache.hashing') def hash_for_simple_object(obj: Any) -> str: """Get hash for any object.""" return str(joblib.hash(obj)) def hash_for_none() -> str: """Get simple hash for None objects.""" return '0' * 32 def hash_for_code(code: CodeType) -> str: """Get hash for ``code`` object.""" if not isinstance(code, CodeType): raise TypeError(f'Parameter ``code`` must be ``CodeType``, not {type(code)}') try: co_consts_hash = hash_for_iterable(code.co_consts) except Exception as e: logger.warning(f'Error on hashing code consts {code}\n{e!r}') co_consts_hash = hash_for_simple_object(code.co_consts) return hash_for_simple_object(co_consts_hash.encode() + code.co_code) def hash_for_iterable(iterable: Any) -> str: """Get hash for iterable objects.""" return hash_for_simple_object(''.join(hash_by_type(value) for value in iterable)) def hash_for_dict(_dict: dict) -> str: """Get hash for dict objects.""" if not isinstance(_dict, dict): raise TypeError(f'Parameter ``_dict`` must be dict, not {type(_dict)}') return hash_for_simple_object({k: hash_by_type(v) for k, v in _dict.items()}) def hash_for_callable(func: Callable, include_name: bool = True) -> str: """Hash for callable objects.""" if not callable(func): raise TypeError(f'Parameter ``func`` must be callable, not {type(func)}') try: result = hash_for_code(func.__code__) except Exception as e: logger.warning(f'Error on hashing func code {func}\n{e!r}') result = hash_for_simple_object(func) if include_name: result = hash_for_simple_object(f'{result}.{get_func_name(func)}') return result def hash_for_class(_class: type) -> str: """Get hash for ``class`` object. NOTE: It's poor hash implementation but works for some cases. """ try: return hash_for_simple_object(inspect.getsource(_class)) except Exception as e: logger.warning(f'Error on hashing class {_class}\n{e!r}') return hash_for_simple_object(_class) def hash_for_estimator(obj: Any) -> str: """Get hash for ``sklearn.BaseEstimator`` instance.""" estimator_class = obj.__class__ estimator_params = get_estimator_params(obj, all_params=True) return hash_for_class(estimator_class) + hash_for_dict(estimator_params) def hash_by_type(obj: Any) -> str: """Hash for any object depending on it's type.""" if obj is None: return hash_for_none() elif isinstance(obj, (list, tuple, set)): return hash_for_iterable(obj) elif isinstance(obj, dict): return hash_for_dict(obj) elif is_estimator(obj): return hash_for_estimator(obj) elif isinstance(obj, (str, int, float, bytes, frozenset)): pass elif inspect.isclass(obj): return hash_for_class(obj) elif callable(obj): return hash_for_callable(obj) elif isinstance(obj, CodeType): return hash_for_code(obj) return hash_for_simple_object(obj)
/scikit-cache-0.1.2.tar.gz/scikit-cache-0.1.2/scikit_cache/utils/hashing.py
0.833799
0.177775
hashing.py
pypi
import os import pwd import random from datetime import datetime from typing import ( Any, Callable, Tuple, ) SIZE_UNITS = (' bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB') CACHE_HIT_ATTR = '__scikit_cache_hit__' def is_scikit_cache_hit(func: Callable) -> Any: """Get saved attribute if where is cache hit or not. This CACHE_HIT_ATTR automatically added in ``DecoratorMixin`` to function dictionary and allows to detect cache hit/miss after function call. """ if hasattr(func, '__wrapped__'): func = func.__wrapped__ # Extract original func from decorated return getattr(func, CACHE_HIT_ATTR, None) def get_datetime_str() -> str: """Get datetime as string is ISO format.""" return datetime.now().isoformat() def get_random_hex(bits: int = 128) -> str: """Get random HEX string.""" return '{0:x}'.format(random.getrandbits(bits)) def get_func_name(func: Callable) -> str: """Get full function name (with module path).""" try: return f'{func.__module__}.{func.__name__}'.replace('__', '') except AttributeError: raise ValueError(f'``get_func_name`` accepts callable objects, not {type(func)}') def yaml_repr(value: Any) -> Any: """Represent value for YAML format.""" # Pandas ``DataFrame`` or ``Series`` if hasattr(value, 'shape'): return f'<{value.__class__.__name__}: {value.shape}>' # List/tuple if isinstance(value, (list, tuple)): return [yaml_repr(v) for v in value] # Dict if isinstance(value, dict): return {yaml_repr(k): yaml_repr(v) for k, v in value.items()} # YAML supported native types if isinstance(value, (int, float, bool, str)) or value is None: return value # All other objects return repr(value) def get_username() -> str: """Get current username.""" try: return pwd.getpwuid(os.getuid())[0] except Exception: return os.path.expanduser('~').split('/')[-1] def format_bytes_to_str( size: int, units: Tuple[str, ...] = SIZE_UNITS, ) -> str: """Get human readable string representation of size in bytes.""" return str(size) + units[0] if size < 1024 else format_bytes_to_str(size >> 10, units[1:]) def format_str_to_bytes(size: str) -> int: """Convert human readable strinb representaion of file size to integer. For example: >>> format_str_to_bytes(size='1 MB') 1048576 """ size_multiplier = 1 for i, unit in enumerate(SIZE_UNITS): if unit in size: size_part, _ = size.split(unit) size_multiplier = pow(1024, i) or 1 return int(float(size_part.strip()) * size_multiplier) raise ValueError(f'No units found in string. Available units: {SIZE_UNITS}')
/scikit-cache-0.1.2.tar.gz/scikit-cache-0.1.2/scikit_cache/utils/base.py
0.782704
0.25118
base.py
pypi
__author__ = 'du' from abc import ABCMeta, abstractmethod from six import add_metaclass import numpy as np from chainer import Chain, Variable, optimizers from chainer import functions as F from sklearn import base @add_metaclass(ABCMeta) class BaseChainerEstimator(base.BaseEstimator): def __init__(self, optimizer=optimizers.SGD(), batch_size=10, n_iter=100, report=10, network_params=None): if network_params is None: network_params = dict() self.network_params = network_params self.network = self._setup_network(**network_params) self.optimizer = optimizer self.optimizer.setup(self.network) self.n_iter = n_iter self.report = report self.batch_size = batch_size @abstractmethod def _setup_network(self, **params): return Chain(l1=F.Linear(1, 1)) @abstractmethod def _forward(self, x, train=False): y = self.network.l1(x) return y @abstractmethod def _loss_func(self, y, t): return F.mean_squared_error(y, t) def fit(self, x_data, y_data=None): score = 1e100 if y_data is None: y_data = x_data all_x = Variable(x_data) all_y = Variable(y_data) data_size = len(x_data) for epoch in range(self.n_iter): indexes = np.random.permutation(data_size) for i in range(0, data_size, self.batch_size): xx = Variable(x_data[indexes[i: i + self.batch_size]]) yy = Variable(y_data[indexes[i: i + self.batch_size]]) self.optimizer.zero_grads() loss = self._loss_func(self._forward(xx, train=True), yy) loss.backward() self.optimizer.update() if self.report > 0 and epoch % self.report == 0: loss = self._loss_func(self._forward(all_x), all_y) d_score = score - loss.data score = loss.data print(epoch, loss.data, d_score) return self class ChainerRegresser(BaseChainerEstimator, base.RegressorMixin): def predict(self, x_data): x = Variable(x_data) y = self._forward(x, train=False) return y.data class ChainerClassifier(BaseChainerEstimator, base.ClassifierMixin): def predict(self, x_data): x = Variable(x_data) y = self._forward(x, train=False) return F.softmax(y).data.argmax(1) class ChainerTransformer(BaseChainerEstimator, base.TransformerMixin): @abstractmethod def _transform(self, x, train=False): raise NotImplementedError def transform(self, x_data): x = Variable(x_data) z = self._transform(x) return z.data def fit(self, x_data, y_data=None): return BaseChainerEstimator.fit(self, x_data, None)
/scikit-chainer-0.4.2.tar.gz/scikit-chainer-0.4.2/skchainer/__init__.py
0.885155
0.249584
__init__.py
pypi
import subprocess from abc import ABCMeta, abstractmethod from tempfile import NamedTemporaryFile import time import logging import pandas as pd from .utils import NamedProgressBar from . import core from .utils import iterable_to_series, optional_second_method, nanarray, squeeze from . import io LOGGER = logging.getLogger(__name__) class BaseTransformer(object): """ Transformer Base Class. Specific Base Transformer classes inherit from this class and implement `transform` and `axis_names`. """ __metaclass__ = ABCMeta # To share some functionality betweeen Transformer and AtomTransformer def __init__(self, verbose=True): self.verbose = verbose def optional_bar(self, **kwargs): if self.verbose: bar = NamedProgressBar(name=self.__class__.__name__, **kwargs) else: def bar(x): return x return bar @property @abstractmethod def axes_names(self): """ tuple: The names of the axes. """ pass @abstractmethod def transform(self, mols): """ Transform objects according to the objects transform protocol. Args: mols (skchem.Mol or pd.Series or iterable): The mol objects to transform. Returns: pd.Series or pd.DataFrame """ pass class Transformer(BaseTransformer): """ Molecular based Transformer Base class. Concrete Transformers inherit from this class and must implement `_transform_mol` and `_columns`. See Also: AtomTransformer.""" @property @abstractmethod def columns(self): """ pd.Index: The column index to use. """ return pd.Index(None) @abstractmethod def _transform_mol(self, mol): """ Transform a molecule. """ pass def _transform_series(self, ser): """ Transform a series of molecules to an np.ndarray. """ bar = self.optional_bar() return [self._transform_mol(mol) for mol in bar(ser)] @optional_second_method def transform(self, mols, **kwargs): """ Transform objects according to the objects transform protocol. Args: mols (skchem.Mol or pd.Series or iterable): The mol objects to transform. Returns: pd.Series or pd.DataFrame """ if isinstance(mols, core.Mol): # just squeeze works on series return pd.Series(self._transform_mol(mols), index=self.columns, name=self.__class__.__name__).squeeze() elif not isinstance(mols, pd.Series): mols = iterable_to_series(mols) res = pd.DataFrame(self._transform_series(mols), index=mols.index, columns=self.columns) return squeeze(res, axis=1) @property def axes_names(self): """ tuple: The names of the axes. """ return 'batch', self.columns.name class BatchTransformer(BaseTransformer): """ Transformer Mixin in which transforms on multiple molecules save overhead. Implement `_transform_series` with the transformation rather than `_transform_mol`. Must occur before `Transformer` or `AtomTransformer` in method resolution order. See Also: Transformer, AtomTransformer. """ def _transform_mol(self, mol): """ Transform a molecule. """ v = self.verbose self.verbose = False res = self.transform([mol]).iloc[0] self.verbose = v return res @abstractmethod def _transform_series(self, ser): """ Transform a series of molecules to an np.ndarray. """ pass class AtomTransformer(BaseTransformer): """ Transformer that will produce a Panel. Concrete classes inheriting from this should implement `_transform_atom`, `_transform_mol` and `minor_axis`. See Also: Transformer """ def __init__(self, max_atoms=100, **kwargs): self.max_atoms = max_atoms self.major_axis = pd.RangeIndex(self.max_atoms, name='atom_idx') super(AtomTransformer, self).__init__(**kwargs) @property @abstractmethod def minor_axis(self): """ pd.Index: Minor axis of transformed values. """ return pd.Index(None) # expects a length @property def axes_names(self): """ tuple: The names of the axes. """ return 'batch', 'atom_idx', self.minor_axis.name @optional_second_method def transform(self, mols): """ Transform objects according to the objects transform protocol. Args: mols (skchem.Mol or pd.Series or iterable): The mol objects to transform. Returns: pd.Series or pd.DataFrame """ if isinstance(mols, core.Atom): # just squeeze works on series return pd.Series(self._transform_atom(mols), index=self.minor_axis).squeeze() elif isinstance(mols, core.Mol): res = pd.DataFrame(self._transform_mol(mols), index=self.major_axis[:len(mols.atoms)], columns=self.minor_axis) return squeeze(res, axis=1) elif not isinstance(mols, pd.Series): mols = iterable_to_series(mols) res = pd.Panel(self._transform_series(mols), items=mols.index, major_axis=self.major_axis, minor_axis=self.minor_axis) return squeeze(res, axis=(1, 2)) @abstractmethod def _transform_atom(self, atom): """ Transform an atom to a 1D array of length `len(self.columns)`. """ pass def _transform_mol(self, mol): """ Transform a Mol to a 2D array. """ res = nanarray((len(mol.atoms), len(self.minor_axis))) for i, atom in enumerate(mol.atoms): res[i] = self._transform_atom(atom) return res def _transform_series(self, ser): """ Transform a Series<Mol> to a 3D array. """ if self.verbose: bar = NamedProgressBar(name=self.__class__.__name__) else: # use identity. def bar(obj): return obj res = nanarray((len(ser), self.max_atoms, len(self.minor_axis))) for i, mol in enumerate(bar(ser)): res[i, :len(mol.atoms), :len(self.minor_axis)] = self._transform_mol(mol) return res class External(object): """ Mixin for wrappers of external CLI tools. Concrete classes must implement `validate_install`.""" __metaclass__ = ABCMeta install_hint = "" # give an explanation of how to install external tool here. def __init__(self, **kwargs): assert self.validated, 'External tool not installed. ' + self.install_hint super(External, self).__init__(**kwargs) @property def validated(self): """ bool: whether the external tool is installed and active. """ if not hasattr(self.__class__, '_validated'): self.__class__._validated = self.validate_install() return self.__class__._validated @staticmethod @abstractmethod def validate_install(): """ Determine if the external tool is available. """ pass class CLIWrapper(External, BaseTransformer): """ CLI wrapper. Concrete classes inheriting from this must implement `_cli_args`, `monitor_progress`, `_parse_outfile`, `_parse_errors`.""" def __init__(self, error_on_fail=False, warn_on_fail=True, **kwargs): super(CLIWrapper, self).__init__(**kwargs) self.error_on_fail = error_on_fail self.warn_on_fail = warn_on_fail def _transform_series(self, ser): """ Transform a series. """ with NamedTemporaryFile(suffix='.sdf') as infile, NamedTemporaryFile() as outfile: io.write_sdf(ser, infile.name) args = self._cli_args(infile.name, outfile.name) p = subprocess.Popen(args, stderr=subprocess.PIPE) if self.verbose: bar = self.optional_bar(max_value=len(ser)) while p.poll() is None: time.sleep(0.5) bar.update(self.monitor_progress(outfile.name)) bar.finish() p.wait() res = self._parse_outfile(outfile.name) errs = p.stderr.read().decode() errs = self._parse_errors(errs) # set the index of results to that of the input, with the failed indices removed if isinstance(res, (pd.Series, pd.DataFrame)): res.index = ser.index.delete(errs) elif isinstance(res, pd.Panel): res.items = ser.index.delete(errs) else: raise ValueError('Parsed datatype ({}) not supported.'.format(type(res))) # go through the errors and put them back in (transform doesn't lose instances) if len(errs): for err in errs: err = ser.index[err] if self.error_on_fail: raise ValueError('Failed to transform {}.'.format(err)) if self.warn_on_fail: LOGGER.warn('Failed to transform %s', err) res.ix[err] = None return res.loc[ser.index].values @abstractmethod def _cli_args(self, infile, outfile): """ list: The cli arguments. """ return [] @abstractmethod def monitor_progress(self, filename): """ Report the progress. """ pass @abstractmethod def _parse_outfile(self, outfile): """ Parse the file written and return a series. """ pass @abstractmethod def _parse_errors(self, errs): """ Parse stderr and return error indices. """ pass class Featurizer(object): """ Base class for m -> data transforms, such as Fingerprinting etc. Concrete subclasses should implement `name`, returning a string uniquely identifying the featurizer. """ __metaclass__ = ABCMeta
/scikit-chem-0.0.6.tar.gz/scikit-chem-0.0.6/skchem/base.py
0.837387
0.4231
base.py
pypi
import warnings from abc import ABCMeta, abstractmethod import pandas as pd from rdkit.Chem.rdDistGeom import EmbedMolecule from .. import core from ..utils import Suppressor from ..base import Transformer from ..filters.base import TransformFilter class ForceField(Transformer, TransformFilter): # TODO: Multiple conformer generation handling. """ Base forcefield class. Filter drops those that fail to be optimized. """ def __init__(self, embed=True, warn_on_fail=True, error_on_fail=False, drop_failed=True, add_hs=True, **kwargs): self.add_hs = add_hs self.drop_failed = drop_failed self.warn_on_fail = warn_on_fail self.error_on_fail = error_on_fail self.preembed = embed super(ForceField, self).__init__(**kwargs) @property def columns(self): return pd.Index(['structure']) def embed(self, mol): success = EmbedMolecule(mol) if success == -1: msg = 'Failed to Embed Molecule {}'.format(mol.name) if self.error_on_fail: raise RuntimeError(msg) elif self.warn_on_fail: warnings.warn(msg) return None if self.add_hs: return mol.add_hs(add_coords=True) else: return mol def _transform_mol(self, mol): with Suppressor(): if self.preembed: mol = self.embed(mol) if mol is None: # embedding failed return None res = self._optimize(mol) if res == -1: msg = 'Failed to optimize molecule \'{}\' using {}'.format(mol.name, self.__class__) if self.error_on_fail: raise RuntimeError(msg) elif self.warn_on_fail: warnings.warn(msg) return None return mol @abstractmethod def _optimize(self, mol): pass class RoughEmbedding(ForceField): def _optimize(self, mol): return mol
/scikit-chem-0.0.6.tar.gz/scikit-chem-0.0.6/skchem/forcefields/base.py
0.438304
0.175927
base.py
pypi
from sklearn.manifold import TSNE, MDS from sklearn.decomposition import PCA from matplotlib import pyplot as plt import pandas as pd from pandas.core.base import NoNewAttributesMixin, AccessorProperty from pandas.core.series import Series from pandas.core.index import Index from .. import core from .. import descriptors DIM_RED = { 'tsne': TSNE, 'pca': PCA, 'mds': MDS } class StructureMethods(NoNewAttributesMixin): """ Accessor for calling chemical methods on series of molecules. """ def __init__(self, data): self._data = data def add_hs(self, **kwargs): return self._data.apply(lambda m: m.add_hs(**kwargs)) def remove_hs(self, **kwargs): return self._data.apply(lambda m: m.remove_hs(**kwargs)) def visualize(self, fper='morgan', dim_red='tsne', dim_red_kw={}, **kwargs): if isinstance(dim_red, str): dim_red = DIM_RED.get(dim_red.lower())(**dim_red_kw) fper = descriptors.get(fper) fper.verbose = False feats = fper.transform(self._data) feats = feats.fillna(feats.mean()) twod = pd.DataFrame(dim_red.fit_transform(feats)) return twod.plot.scatter(x=0, y=1, **kwargs) @property def atoms(self): return self._data.apply(lambda m: m.atoms) def only_contains_mols(ser): return ser.apply(lambda s: isinstance(s, core.Mol)).all() class StructureAccessorMixin(object): """ Mixin to bind chemical methods to objects. """ def _make_structure_accessor(self): if isinstance(self, Index): raise AttributeError('Can only use .mol accessor with molecules,' 'which use np.object_ in scikit-chem.') if not only_contains_mols(self): raise AttributeError('Can only use .mol accessor with ' 'Series that only contain mols.') return StructureMethods(self) mol = AccessorProperty(StructureMethods, _make_structure_accessor) Series.__bases__ += StructureAccessorMixin,
/scikit-chem-0.0.6.tar.gz/scikit-chem-0.0.6/skchem/pandas_ext/structure_methods.py
0.853806
0.390331
structure_methods.py
pypi
import functools from abc import ABCMeta import pandas as pd import numpy as np from rdkit import Chem from rdkit.Chem import Crippen from rdkit.Chem import Lipinski from rdkit.Chem import rdMolDescriptors, rdPartialCharges from rdkit.Chem.rdchem import HybridizationType from ..core import Mol from ..resource import PERIODIC_TABLE, ORGANIC from ..base import AtomTransformer, Featurizer from ..utils import nanarray def element(a): """ Return the element """ return a.GetSymbol() def is_element(a, symbol='C'): """ Is the atom of a given element """ return element(a) == symbol element_features = {'is_{}'.format(e): functools.partial(is_element, symbol=e) for e in ORGANIC} def is_h_acceptor(a): """ Is an H acceptor? """ m = a.GetOwningMol() idx = a.GetIdx() return idx in [i[0] for i in Lipinski._HAcceptors(m)] def is_h_donor(a): """ Is an H donor? """ m = a.GetOwningMol() idx = a.GetIdx() return idx in [i[0] for i in Lipinski._HDonors(m)] def is_hetero(a): """ Is a heteroatom? """ m = a.GetOwningMol() idx = a.GetIdx() return idx in [i[0] for i in Lipinski._Heteroatoms(m)] def atomic_number(a): """ Atomic number of atom """ return a.GetAtomicNum() def atomic_mass(a): """ Atomic mass of atom """ return a.mass def explicit_valence(a): """ Explicit valence of atom """ return a.GetExplicitValence() def implicit_valence(a): """ Implicit valence of atom """ return a.GetImplicitValence() def valence(a): """ returns the valence of the atom """ return explicit_valence(a) + implicit_valence(a) def formal_charge(a): """ Formal charge of atom """ return a.GetFormalCharge() def is_aromatic(a): """ Boolean if atom is aromatic""" return a.GetIsAromatic() def num_implicit_hydrogens(a): """ Number of implicit hydrogens """ return a.GetNumImplicitHs() def num_explicit_hydrogens(a): """ Number of explicit hydrodgens """ return a.GetNumExplicitHs() def num_hydrogens(a): """ Number of hydrogens """ return num_implicit_hydrogens(a) + num_explicit_hydrogens(a) def is_in_ring(a): """ Whether the atom is in a ring """ return a.IsInRing() def crippen_log_p_contrib(a): """ Hacky way of getting logP contribution. """ idx = a.GetIdx() m = a.GetOwningMol() return Crippen._GetAtomContribs(m)[idx][0] def crippen_molar_refractivity_contrib(a): """ Hacky way of getting molar refractivity contribution. """ idx = a.GetIdx() m = a.GetOwningMol() return Crippen._GetAtomContribs(m)[idx][1] def tpsa_contrib(a): """ Hacky way of getting total polar surface area contribution. """ idx = a.GetIdx() m = a.GetOwningMol() return rdMolDescriptors._CalcTPSAContribs(m)[idx] def labute_asa_contrib(a): """ Hacky way of getting accessible surface area contribution. """ idx = a.GetIdx() m = a.GetOwningMol() return rdMolDescriptors._CalcLabuteASAContribs(m)[0][idx] def gasteiger_charge(a, force_calc=False): """ Hacky way of getting gasteiger charge """ res = a.props.get('_GasteigerCharge', None) if res and not force_calc: return float(res) else: idx = a.GetIdx() m = a.GetOwningMol() rdPartialCharges.ComputeGasteigerCharges(m) return float(a.props['_GasteigerCharge']) def electronegativity(a): return PERIODIC_TABLE.loc[a.atomic_number, 'pauling_electronegativity'] def first_ionization(a): return PERIODIC_TABLE.loc[a.atomic_number, 'first_ionisation_energy'] def group(a): return PERIODIC_TABLE.loc[a.atomic_number, 'group'] def period(a): return PERIODIC_TABLE.loc[a.atomic_number, 'period'] def is_hybridized(a, hybrid_type=HybridizationType.SP3): """ Hybridized as type hybrid_type, default SP3 """ return str(a.GetHybridization()) is hybrid_type hybridization_features = {'is_' + n + '_hybridized': functools.partial(is_hybridized, hybrid_type=n) for n in HybridizationType.names} ATOM_FEATURES = { 'atomic_number': atomic_number, 'atomic_mass': atomic_mass, 'formal_charge': formal_charge, 'gasteiger_charge': gasteiger_charge, 'electronegativity': electronegativity, 'first_ionisation': first_ionization, 'group': group, 'period': period, 'valence': valence, 'is_aromatic': is_aromatic, 'num_hydrogens': num_hydrogens, 'is_in_ring': is_in_ring, 'log_p_contrib': crippen_log_p_contrib, 'molar_refractivity_contrib': crippen_molar_refractivity_contrib, 'is_h_acceptor': is_h_acceptor, 'is_h_donor': is_h_donor, 'is_heteroatom': is_hetero, 'total_polar_surface_area_contrib': tpsa_contrib, 'total_labute_accessible_surface_area': labute_asa_contrib, } ATOM_FEATURES.update(element_features) ATOM_FEATURES.update(hybridization_features) class AtomFeaturizer(AtomTransformer, Featurizer): def __init__(self, features='all', **kwargs): self.features = features super(AtomFeaturizer, self).__init__(**kwargs) @property def name(self): return 'atom_feat' @property def features(self): return self._features @features.setter def features(self, features): if features == 'all': features = ATOM_FEATURES elif isinstance(features, str): features = {features: ATOM_FEATURES[features]} elif isinstance(features, list): features = {feature: ATOM_FEATURES[feature] for feature in features} elif isinstance(features, (dict, pd.Series)): features = features else: raise NotImplementedError('Cannot use features {}'.format(features)) self._features = pd.Series(features) self._features.index.name = 'atom_features' @property def minor_axis(self): return self.features.index def _transform_atom(self, atom): return self.features.apply(lambda f: f(atom)).values def _transform_mol(self, mol): return np.array([self.transform(a) for a in mol.atoms]) class DistanceTransformer(AtomTransformer, Featurizer): """ Base class implementing Distance Matrix transformers. Concrete classes inheriting from this should implement `_transform_mol`. """ __metaclass__ = ABCMeta @property def minor_axis(self): return pd.RangeIndex(self.max_atoms, name='atom_idx') def _transform_atom(self, atom): return NotImplemented def transform(self, mols): res = super(DistanceTransformer, self).transform(mols) if isinstance(mols, Mol): res = res.iloc[:len(mols.atoms), :len(mols.atoms)] return res class SpacialDistanceTransformer(DistanceTransformer): """ Transformer class for generating 3D distance matrices. """ # TODO: handle multiple conformers def name(self): return 'spacial_dist' def _transform_mol(self, mol): res = nanarray((len(mol.atoms), self.max_atoms)) res[:, :len(mol.atoms)] = Chem.Get3DDistanceMatrix(mol) return res class GraphDistanceTransformer(DistanceTransformer): """ Transformer class for generating Graph distance matrices. """ # TODO: handle multiple conformers def name(self): return 'graph_dist' def _transform_mol(self, mol): res = nanarray((len(mol.atoms), self.max_atoms)) res[:len(mol.atoms), :len(mol.atoms)] = Chem.GetDistanceMatrix(mol) return res
/scikit-chem-0.0.6.tar.gz/scikit-chem-0.0.6/skchem/descriptors/atom.py
0.745769
0.51562
atom.py
pypi