Reference¶
3D Animation¶
-
class
salabim.
Animate3dBase
(visible=True, keep=True, arg=None, layer=0, parent=None, env=None, **kwargs)¶ Base class for a 3D animation object
When a class inherits from this base class, it will be added to the animation objects list to be shownParameters: - visible (bool) – visible
if False, animation object is not shown, shown otherwise (default True) - layer (int) – layer value
lower layer values are displayed later in the frame (default 0) - arg (any) – this is used when a parameter is a function with two parameters, as the first argument or
if a parameter is a method as the instance
default: self (instance itself) - parent (Component) – component where this animation object belongs to (default None)
if given, the animation object will be removed automatically when the parent component is no longer accessible - env (Environment) – environment where the component is defined
if omitted, default_env will be used
-
remove
()¶ removes the 3d animation oject
-
setup
()¶ called immediately after initialization of a the Animate3dBase object.
by default this is a dummy method, but it can be overridden.
only keyword arguments will be passed
Example
- class AnimateVehicle(sim.Animate3dBase):
- def setup(self, length):
- self.length = length self.register_dynamic_attributes(“length”)
…
-
show
(unremove)¶ It is possible to use this method if already shown
- visible (bool) – visible
-
class
salabim.
Animate3dBox
(x_len=1, y_len=1, z_len=1, x=0, y=0, z=0, z_angle=0, x_ref=0, y_ref=0, z_ref=0, color='white', edge_color='', shaded=False, visible=True, arg=None, layer=0, parent=None, env=None, **kwargs)¶ Creates a 3D box
Parameters: - x_len (float) – length of the box in x direction (deffult 1)
- y_len (float) – length of the box in y direction (default 1)
- z_len (float) – length of the box in z direction (default 1)
- x (float) – x position of the box (default 0)
- y (float) – y position of the box (default 0)
- z (float) – z position of the box (default 0)
- z_angle (float) – angle around the z-axis (default 0)
- x_ref (int) – if -1, the x parameter refers to the ‘end’ of the box
if 0, the x parameter refers to the center of the box (default)
if 1, the x parameter refers to the ‘start’ of the box - y_ref (int) – if -1, the y parameter refers to the ‘end’ of the box
if 0, the y parameter refers to the center of the box (default)
if 1, the y parameter refers to the ‘start’ of the box - z_ref (int) – if -1, the z parameter refers to the ‘end’ of the box
if 0, the z parameter refers to the center of the box (default)
if 1, the z parameter refers to the ‘start’ of the box - color (colorspec) – color of the box (default “white”)
if the color is “” (or the alpha is 0), the sides will not be colored at all - edge_color (colorspec) – color of the edges of the (default “”)
if the color is “” (or the alpha is 0), the edges will not be drawn at all - shaded (bool) – if False (default), all sides will be colored with color if True, the various sides will have a sligtly different darkness, thus resulting in a pseudo shaded object
- visible (bool) – visible
if False, animation object is not shown, shown otherwise (default True) - layer (int) – layer value
lower layer values are displayed later in the frame (default 0) - arg (any) – this is used when a parameter is a function with two parameters, as the first argument or
if a parameter is a method as the instance
default: self (instance itself) - parent (Component) – component where this animation object belongs to (default None)
if given, the animation object will be removed automatically when the parent component is no longer accessible - env (Environment) – environment where the component is defined
if omitted, default_env will be used
Note
All parameters, apart from parent, arg and env can be specified as:
- a scalar, like 10
- a function with zero arguments, like lambda: my_x
- a function with one argument, being the time t, like lambda t: t + 10
- a function with two parameters, being arg (as given) and the time, like lambda comp, t: comp.state
- a method instance arg for time t, like self.state, actually leading to arg.state(t) to be called
-
class
salabim.
Animate3dCylinder
(x0=0, y0=0, z0=0, x1=1, y1=1, z1=1, color='white', radius=1, number_of_sides=8, rotation_angle=0, show_lids=True, visible=True, arg=None, layer=0, parent=None, env=None, **kwargs)¶ Creates a 3D cylinder between two given points
Parameters: - x0 (float) – x coordinate of start point (default 0)
- y0 (float) – y coordinate of start point (default 0)
- z0 (float) – z coordinate of start point (default 0)
- x1 (float) – x coordinate of end point (default 0)
- y1 (float) – y coordinate of end point (default 0)
- z1 (float) – z coordinate of end point (default 0)
- color (colorspec) – color of the cylinder (default “white”)
- number_of_sides (int) – number of sides of the cylinder (default 8)
must be >= 3 - rotation_angle (float) – rotation of the bar in degrees (default 0)
- show_lids (bool) – if True (default), the lids will be drawn if False, tyhe cylinder will be open at both sides
- visible (bool) – visible
if False, animation object is not shown, shown otherwise (default True) - layer (int) – layer value
lower layer values are displayed later in the frame (default 0) - arg (any) – this is used when a parameter is a function with two parameters, as the first argument or
if a parameter is a method as the instance
default: self (instance itself) - parent (Component) – component where this animation object belongs to (default None)
if given, the animation object will be removed automatically when the parent component is no longer accessible - env (Environment) – environment where the component is defined
if omitted, default_env will be used
Note
All parameters, apart from parent, arg and env can be specified as:
- a scalar, like 10
- a function with zero arguments, like lambda: my_x
- a function with one argument, being the time t, like lambda t: t + 10
- a function with two parameters, being arg (as given) and the time, like lambda comp, t: comp.state
- a method instance arg for time t, like self.state, actually leading to arg.state(t) to be called
-
class
salabim.
Animate3dGrid
(x_range=[0], y_range=[0], z_range=[0], color='white', visible=True, arg=None, layer=0, parent=None, env=None, **kwargs)¶ Creates a 3D grid
Parameters: - x_range (iterable) – x coordinates of grid lines (default [0])
- y_range (iterable) – y coordinates of grid lines (default [0])
- z_range (iterable) – z coordinates of grid lines (default [0])
- color (colorspec) – color of the line (default “white”)
- visible (bool) – visible
if False, animation object is not shown, shown otherwise (default True) - layer (int) – layer value
lower layer values are displayed later in the frame (default 0) - arg (any) – this is used when a parameter is a function with two parameters, as the first argument or
if a parameter is a method as the instance
default: self (instance itself) - parent (Component) – component where this animation object belongs to (default None)
if given, the animation object will be removed automatically when the parent component is no longer accessible - env (Environment) – environment where the component is defined
if omitted, default_env will be used
Note
All parameters, apart from parent, arg and env can be specified as:
- a scalar, like 10
- a function with zero arguments, like lambda: my_x
- a function with one argument, being the time t, like lambda t: t + 10
- a function with two parameters, being arg (as given) and the time, like lambda comp, t: comp.state
- a method instance arg for time t, like self.state, actually leading to arg.state(t) to be called
-
class
salabim.
Animate3dLine
(x0=0, y0=0, z0=0, x1=1, y1=1, z1=0, color='white', visible=True, arg=None, layer=0, parent=None, env=None, **kwargs)¶ Creates a 3D line
Parameters: - x0 (float) – x coordinate of start point (default 0)
- y0 (float) – y coordinate of start point (default 0)
- z0 (float) – z coordinate of start point (default 0)
- x1 (float) – x coordinate of end point (default 0)
- y1 (float) – y coordinate of end point (default 0)
- z1 (float) – z coordinate of end point (default 0)
- color (colorspec) – color of the line (default “white”)
- visible (bool) – visible
if False, animation object is not shown, shown otherwise (default True) - layer (int) – layer value
lower layer values are displayed later in the frame (default 0) - arg (any) – this is used when a parameter is a function with two parameters, as the first argument or
if a parameter is a method as the instance
default: self (instance itself) - parent (Component) – component where this animation object belongs to (default None)
if given, the animation object will be removed automatically when the parent component is no longer accessible - env (Environment) – environment where the component is defined
if omitted, default_env will be used
Note
All parameters, apart from parent, arg and env can be specified as:
- a scalar, like 10
- a function with zero arguments, like lambda: my_x
- a function with one argument, being the time t, like lambda t: t + 10
- a function with two parameters, being arg (as given) and the time, like lambda comp, t: comp.state
- a method instance arg for time t, like self.state, actually leading to arg.state(t) to be called
-
class
salabim.
Animate3dObj
(filename, x=0, y=0, z=0, x_angle=0, y_angle=0, z_angle=0, x_translate=0, y_translate=0, z_translate=0, x_scale=1, y_scale=1, z_scale=1, show_warnings=False, visible=True, arg=None, layer=0, parent=None, env=None, **kwargs)¶ Creates a 3D animation object from an .obj file
Parameters: - filename (str or Path) – obj file to be read (default extension .obj)
if there are .mtl or .jpg required by this file, they should be available - x (float) – x position (default 0)
- y (float) – y position (default 0)
- z (float) – z position (default 0)
- x_angle (float) – angle along x axis (default: 0)
- y_angle (float) – angle along y axis (default: 0)
- z_angle (float) – angle along z axis (default: 0)
- x_translate (float) – translation in x direction (default: 0)
- y_translate (float) – translation in y direction (default: 0)
- z_translate (float) – translation in z direction (default: 0)
- x_scale (float) – scaling in x direction (default: 1)
- y_translate – translation in y direction (default: 1)
- z_translate – translation in z direction (default: 1)
- show_warnings (bool) – as pywavefront does not support all obj commands, reading the file sometimes leads
to (many) warning log messages
with this flag, they can be turned off (the deafult) - visible (bool) – visible
if False, animation object is not shown, shown otherwise (default True) - layer (int) – layer value
lower layer values are displayed later in the frame (default 0) - arg (any) – this is used when a parameter is a function with two parameters, as the first argument or
if a parameter is a method as the instance
default: self (instance itself) - parent (Component) – component where this animation object belongs to (default None)
if given, the animation object will be removed automatically when the parent component is no longer accessible - env (Environment) – environment where the component is defined
if omitted, default_env will be used
Note
All parameters, apart from parent, arg and env can be specified as:
- a scalar, like 10
- a function with zero arguments, like lambda: my_x
- a function with one argument, being the time t, like lambda t: t + 10
- a function with two parameters, being arg (as given) and the time, like lambda comp, t: comp.state
- a method instance arg for time t, like self.state, actually leading to arg.state(t) to be calledNote
This method requires the pywavefront and pyglet module to be installed
- filename (str or Path) – obj file to be read (default extension .obj)
-
class
salabim.
Animate3dQueue
(queue, x=0, y=0, z=0, direction='x+', max_length=None, reverse=False, layer=0, id=None, arg=None, parent=None, visible=True, keep=True)¶ Animates the component in a queue.
Parameters: - queue (Queue) –
- x (float) – x-position of the first component in the queue
default: 0 - y (float) – y-position of the first component in the queue
default: 0 - z (float) – z-position of the first component in the queue
default: 0 - direction (str) – if “x+”, waiting line runs in positive x direction (default)
if “x-“, waiting line runs in negative x direction
if “y+”, waiting line runs in positive y direction
if “y-“, waiting line runs in negative y direction
if “z+”, waiting line runs in positive z direction
if “z-“, waiting line runs in negative z direction - reverse (bool) – if False (default), display in normal order. If True, reversed.
- max_length (int) – maximum number of components to be displayed
- layer (int) – layer (default 0)
- id (any) – the animation works by calling the animation_objects method of each component, optionally with id. By default, this is self, but can be overriden, particularly with the queue
- arg (any) – this is used when a parameter is a function with two parameters, as the first argument or
if a parameter is a method as the instance
default: self (instance itself) - visible (bool) – if False, nothing will be shown
(default True) - keep (bool) – if False, animation object will be taken from the animation objects. With show(), the animation can be reshown. (default True)
- parent (Component) – component where this animation object belongs to (default None)
if given, the animation object will be removed automatically when the parent component is no longer accessible
Note
All parameters, apart from queue, id, arg and parent can be specified as:
- a scalar, like 10
- a function with zero arguments, like lambda: title
- a function with one argument, being the time t, like lambda t: t + 10
- a function with two parameters, being arg (as given) and the time, like lambda comp, t: comp.state
- a method instance arg for time t, like self.state, actually leading to arg.state(t) to be called-
queue
()¶ Returns: the queue this object refers to. Can be useful in Component.animation3d_objects Return type: queue
-
show
(unremove)¶ It is possible to use this method if already shown
-
class
salabim.
Animate3dRectangle
(x0=0, y0=0, x1=1, y1=1, z=0, color='white', visible=True, arg=None, layer=0, parent=None, env=None, **kwargs)¶ Creates a 3D rectangle
Parameters: - x0 (float) – lower left x position (default 0)
- y0 (float) – lower left y position (default 0)
- x1 (float) – upper right x position (default 1)
- y1 (float) – upper right y position (default 1)
- z (float) – z position of rectangle (default 0)
- color (colorspec) – color of the rectangle (default “white”)
- visible (bool) – visible
if False, animation object is not shown, shown otherwise (default True) - layer (int) – layer value
lower layer values are displayed later in the frame (default 0) - arg (any) – this is used when a parameter is a function with two parameters, as the first argument or
if a parameter is a method as the instance
default: self (instance itself) - parent (Component) – component where this animation object belongs to (default None)
if given, the animation object will be removed automatically when the parent component is no longer accessible - env (Environment) – environment where the component is defined
if omitted, default_env will be used
Note
All parameters, apart from parent, arg and env can be specified as:
- a scalar, like 10
- a function with zero arguments, like lambda: my_x
- a function with one argument, being the time t, like lambda t: t + 10
- a function with two parameters, being arg (as given) and the time, like lambda comp, t: comp.state
- a method instance arg for time t, like self.state, actually leading to arg.state(t) to be called
Animation¶
-
class
salabim.
Animate
(parent=None, layer=0, keep=True, visible=True, screen_coordinates=None, t0=None, x0=0, y0=0, offsetx0=0, offsety0=0, circle0=None, line0=None, polygon0=None, rectangle0=None, points0=None, image=None, text=None, font='', anchor='c', as_points=False, max_lines=0, text_anchor=None, linewidth0=None, fillcolor0=None, linecolor0='fg', textcolor0='fg', angle0=0, alpha0=255, fontsize0=20, width0=None, t1=None, x1=None, y1=None, offsetx1=None, offsety1=None, circle1=None, line1=None, polygon1=None, rectangle1=None, points1=None, linewidth1=None, fillcolor1=None, linecolor1=None, textcolor1=None, angle1=None, alpha1=None, fontsize1=None, width1=None, xy_anchor='', over3d=None, env=None)¶ defines an animation object
Parameters: - parent (Component) – component where this animation object belongs to (default None)
if given, the animation object will be removed automatically when the parent component is no longer accessible - layer (int) – layer value
lower layer values are on top of higher layer values (default 0) - keep (bool) – keep
if False, animation object is hidden after t1, shown otherwise (default True) - visible (bool) – visible
if False, animation object is not shown, shown otherwise (default True) - screen_coordinates (bool) – use screen_coordinates
normally, the scale parameters are use for positioning and scaling objects.
if True, screen_coordinates will be used instead. - xy_anchor (str) – specifies where x and y (i.e. x0, y0, x1 and y1) are relative to
possible values are (default: sw) :
nw n ne
w c e
sw s se
If null string, the given coordimates are used untranslated - t0 (float) – time of start of the animation (default: now)
- x0 (float) – x-coordinate of the origin at time t0 (default 0)
- y0 (float) – y-coordinate of the origin at time t0 (default 0)
- offsetx0 (float) – offsets the x-coordinate of the object at time t0 (default 0)
- offsety0 (float) – offsets the y-coordinate of the object at time t0 (default 0)
- circle0 (float or tuple/list) – the circle spec of the circle at time t0
- radius
- one item tuple/list containing the radius
- five items tuple/list cntaining radius, radius1, arc_angle0, arc_angle1 and draw_arc (see class AnimateCircle for details) - line0 (tuple) – the line(s) (xa,ya,xb,yb,xc,yc, …) at time t0
- polygon0 (tuple) – the polygon (xa,ya,xb,yb,xc,yc, …) at time t0
the last point will be auto connected to the start - rectangle0 (tuple) – the rectangle (xlowerleft,ylowerleft,xupperright,yupperright) at time t0
- image (str, pathlib.Path or PIL image) – the image to be displayed
This may be either a filename or a PIL image - text (str, tuple or list) – the text to be displayed
if text is str, the text may contain linefeeds, which are shown as individual lines - max_lines (int) – the maximum of lines of text to be displayed
if positive, it refers to the first max_lines lines
if negative, it refers to the first -max_lines lines
if zero (default), all lines will be displayed - font (str or list/tuple) – font to be used for texts
Either a string or a list/tuple of fontnames. If not found, uses calibri or arial - anchor (str) – anchor position
specifies where to put images or texts relative to the anchor point
possible values are (default: c):
nw n ne
w c e
sw s se
- as_points (bool) – if False (default), lines in line, rectangle and polygon are drawn
if True, only the end points are shown in line, rectangle and polygon - linewidth0 (float) – linewidth of the contour at time t0 (default 0 for polygon, rectangle and circle, 1 for line)
if as_point is True, the default size is 3 - fillcolor0 (colorspec) – color of interior at time t0 (default foreground_color)
if as_points is True, fillcolor0 defaults to transparent - linecolor0 (colorspec) – color of the contour at time t0 (default foreground_color)
- textcolor0 (colorspec) – color of the text at time 0 (default foreground_color)
- angle0 (float) – angle of the polygon at time t0 (in degrees) (default 0)
- alpha0 (float) – alpha of the image at time t0 (0-255) (default 255)
- fontsize0 (float) – fontsize of text at time t0 (default 20)
- width0 (float) – width of the image to be displayed at time t0
if omitted or None, no scaling - t1 (float) – time of end of the animation (default inf)
if keep=True, the animation will continue (frozen) after t1 - x1 (float) – x-coordinate of the origin at time t1(default x0)
- y1 (float) – y-coordinate of the origin at time t1 (default y0)
- offsetx1 (float) – offsets the x-coordinate of the object at time t1 (default offsetx0)
- offsety1 (float) – offsets the y-coordinate of the object at time t1 (default offsety0)
- circle1 (float or tuple/list) – the circle spec of the circle at time t1 (default: circle0)
- radius
- one item tuple/list containing the radius
- five items tuple/list cntaining radius, radius1, arc_angle0, arc_angle1 and draw_arc (see class AnimateCircle for details) - line1 (tuple) – the line(s) at time t1 (xa,ya,xb,yb,xc,yc, …) (default: line0)
should have the same number of elements as line0 - polygon1 (tuple) – the polygon at time t1 (xa,ya,xb,yb,xc,yc, …) (default: polygon0)
should have the same number of elements as polygon0 - rectangle1 (tuple) – the rectangle (xlowerleft,ylowerleft,xupperright,yupperright) at time t1 (default: rectangle0)
- linewidth1 (float) – linewidth of the contour at time t1 (default linewidth0)
- fillcolor1 (colorspec) – color of interior at time t1 (default fillcolor0)
- linecolor1 (colorspec) – color of the contour at time t1 (default linecolor0)
- textcolor1 (colorspec) – color of text at time t1 (default textcolor0)
- angle1 (float) – angle of the polygon at time t1 (in degrees) (default angle0)
- alpha1 (float) – alpha of the image at time t1 (0-255) (default alpha0)
- fontsize1 (float) – fontsize of text at time t1 (default: fontsize0)
- width1 (float) – width of the image to be displayed at time t1 (default: width0)
- over3d (bool) – if True, this object will be rendered to the OpenGL window
if False (default), the normal 2D plane will be used.
Note
- one (and only one) of the following parameters is required:
- circle0
- image
- line0
- polygon0
- rectangle0
- text
- colors may be specified as a
- valid colorname
- hexname
- tuple (R,G,B) or (R,G,B,A)
- “fg” or “bg”
colornames may contain an additional alpha, like
red#7f
hexnames may be either 3 of 4 bytes long (#rrggbb
or#rrggbbaa
)
both colornames and hexnames may be given as a tuple with an additional alpha between 0 and 255, e.g.(255,0,255,128)
, (“red”,127)`` or("#ff00ff",128)
fg is the foreground color
bg is the background colorPermitted parameters
parameter circle image line polygon rectangle text parent layer keep screen_coordinates xy_anchor t0,t1 x0,x1 y0,y1 offsetx0,offsetx1 offsety0,offsety1 circle0,circle1 image line0,line1 polygon0,polygon1 rectangle0,rectangle1 text anchor linewidth0,linewidth1 fillcolor0,fillcolor1 linecolor0,linecolor1 textcolor0,textcolor1 angle0,angle1 alpha0,alpha1 as_points font fontsize0,fontsize1 width0,width1 -
alpha
(t=None)¶ alpha of an animate object. May be overridden.
Parameters: t (float) – current time Returns: alpha – default behaviour: linear interpolation between self.alpha0 and self.alpha1 Return type: float
-
anchor
(t=None)¶ anchor of an animate object. May be overridden.
Parameters: t (float) – current time Returns: anchor – default behaviour: self.anchor0 (anchor given at creation or update) Return type: str
-
angle
(t=None)¶ angle of an animate object. May be overridden.
Parameters: t (float) – current time Returns: angle – default behaviour: linear interpolation between self.angle0 and self.angle1 Return type: float
-
as_points
(t=None)¶ as_points of an animate object. May be overridden.
Parameters: t (float) – current time Returns: as_points – default behaviour: self.as_points (text given at creation or update) Return type: bool
-
circle
(t=None)¶ circle of an animate object. May be overridden.
Parameters: t (float) – current time Returns: circle – either
- radius
- one item tuple/list containing the radius
- five items tuple/list cntaining radius, radius1, arc_angle0, arc_angle1 and draw_arc
(see class AnimateCircle for details)
default behaviour: linear interpolation between self.circle0 and self.circle1Return type: float or tuple/list
-
fillcolor
(t=None)¶ fillcolor of an animate object. May be overridden.
Parameters: t (float) – current time Returns: fillcolor – default behaviour: linear interpolation between self.fillcolor0 and self.fillcolor1 Return type: colorspec
-
font
(t=None)¶ font of an animate object. May be overridden.
Parameters: t (float) – current time Returns: font – default behaviour: self.font0 (font given at creation or update) Return type: str
-
fontsize
(t=None)¶ fontsize of an animate object. May be overridden.
Parameters: t (float) – current time Returns: fontsize – default behaviour: linear interpolation between self.fontsize0 and self.fontsize1 Return type: float
-
image
(t=None)¶ image of an animate object. May be overridden.
Parameters: t (float) – current time Returns: image – use function spec_to_image to load a file default behaviour: self.image0 (image given at creation or update) Return type: PIL.Image.Image
-
keep
(t)¶ keep attribute of an animate object. May be overridden.
Parameters: t (float) – current time Returns: keep – default behaviour: self.keep0 or t <= self.t1 (visible given at creation or update) Return type: bool
-
layer
(t=None)¶ layer of an animate object. May be overridden.
Parameters: t (float) – current time Returns: layer – default behaviour: self.layer0 (layer given at creation or update) Return type: int or float
-
line
(t=None)¶ line of an animate object. May be overridden.
Parameters: t (float) – current time Returns: line – series of x- and y-coordinates (xa,ya,xb,yb,xc,yc, …)
default behaviour: linear interpolation between self.line0 and self.line1Return type: tuple
-
linecolor
(t=None)¶ linecolor of an animate object. May be overridden.
Parameters: t (float) – current time Returns: linecolor – default behaviour: linear interpolation between self.linecolor0 and self.linecolor1 Return type: colorspec
-
linewidth
(t=None)¶ linewidth of an animate object. May be overridden.
Parameters: t (float) – current time Returns: linewidth – default behaviour: linear interpolation between self.linewidth0 and self.linewidth1 Return type: float
-
max_lines
(t=None)¶ maximum number of lines to be displayed of text. May be overridden.
Parameters: t (float) – current time Returns: max_lines – default behaviour: self.max_lines0 (max_lines given at creation or update) Return type: int
-
offsetx
(t=None)¶ offsetx of an animate object. May be overridden.
Parameters: t (float) – current time Returns: offsetx – default behaviour: linear interpolation between self.offsetx0 and self.offsetx1 Return type: float
-
offsety
(t=None)¶ offsety of an animate object. May be overridden.
Parameters: t (float) – current time Returns: offsety – default behaviour: linear interpolation between self.offsety0 and self.offsety1 Return type: float
-
points
(t=None)¶ points of an animate object. May be overridden.
Parameters: t (float) – current time Returns: points – series of x- and y-coordinates (xa,ya,xb,yb,xc,yc, …)
default behaviour: linear interpolation between self.points0 and self.points1Return type: tuple
-
polygon
(t=None)¶ polygon of an animate object. May be overridden.
Parameters: t (float) – current time Returns: polygon – series of x- and y-coordinates describing the polygon (xa,ya,xb,yb,xc,yc, …)
default behaviour: linear interpolation between self.polygon0 and self.polygon1Return type: tuple
-
rectangle
(t=None)¶ rectangle of an animate object. May be overridden.
Parameters: t (float) – current time Returns: rectangle – (xlowerleft,ylowerlef,xupperright,yupperright)
default behaviour: linear interpolation between self.rectangle0 and self.rectangle1Return type: tuple
-
remove
()¶ removes the animation object from the animation queue, so effectively ending this animation.
Note
The animation object might be still updated, if required
-
text
(t=None)¶ text of an animate object. May be overridden.
Parameters: t (float) – current time Returns: text – default behaviour: self.text0 (text given at creation or update) Return type: str
-
text_anchor
(t=None)¶ text_anchor of an animate object. May be overridden.
Parameters: t (float) – current time Returns: text_anchor – default behaviour: self.text_anchor0 (text_anchor given at creation or update) Return type: str
-
textcolor
(t=None)¶ textcolor of an animate object. May be overridden.
Parameters: t (float) – current time Returns: textcolor – default behaviour: linear interpolation between self.textcolor0 and self.textcolor1 Return type: colorspec
-
update
(layer=None, keep=None, visible=None, t0=None, x0=None, y0=None, offsetx0=None, offsety0=None, circle0=None, line0=None, polygon0=None, rectangle0=None, points0=None, image=None, text=None, font=None, anchor=None, xy_anchor0=None, max_lines=None, text_anchor=None, linewidth0=None, fillcolor0=None, linecolor0=None, textcolor0=None, angle0=None, alpha0=None, fontsize0=None, width0=None, xy_anchor1=None, as_points=None, t1=None, x1=None, y1=None, offsetx1=None, offsety1=None, circle1=None, line1=None, polygon1=None, rectangle1=None, points1=None, linewidth1=None, fillcolor1=None, linecolor1=None, textcolor1=None, angle1=None, alpha1=None, fontsize1=None, width1=None)¶ updates an animation object
Parameters: - layer (int) – layer value
lower layer values are on top of higher layer values (default see below) - keep (bool) – keep
if False, animation object is hidden after t1, shown otherwise (default see below) - visible (bool) – visible
if False, animation object is not shown, shown otherwise (default see below) - xy_anchor (str) – specifies where x and y (i.e. x0, y0, x1 and y1) are relative to
possible values are:
nw n ne
w c e
sw s se
If null string, the given coordimates are used untranslated
default see below - t0 (float) – time of start of the animation (default: now)
- x0 (float) – x-coordinate of the origin at time t0 (default see below)
- y0 (float) – y-coordinate of the origin at time t0 (default see below)
- offsetx0 (float) – offsets the x-coordinate of the object at time t0 (default see below)
- offsety0 (float) – offsets the y-coordinate of the object at time t0 (default see below)
- circle0 (float or tuple/list) – the circle spec of the circle at time t0
- radius
- one item tuple/list containing the radius
- five items tuple/list cntaining radius, radius1, arc_angle0, arc_angle1 and draw_arc (see class AnimateCircle for details) - line0 (tuple) – the line(s) at time t0 (xa,ya,xb,yb,xc,yc, …) (default see below)
- polygon0 (tuple) – the polygon at time t0 (xa,ya,xb,yb,xc,yc, …)
the last point will be auto connected to the start (default see below) - rectangle0 (tuple) – the rectangle at time t0
(xlowerleft,ylowerlef,xupperright,yupperright) (default see below) - points0 (tuple) – the points(s) at time t0 (xa,ya,xb,yb,xc,yc, …) (default see below)
- image (str or PIL image) – the image to be displayed
This may be either a filename or a PIL image (default see below) - text (str) – the text to be displayed (default see below)
- font (str or list/tuple) – font to be used for texts
Either a string or a list/tuple of fontnames. (default see below) If not found, uses calibri or arial - max_lines (int) – the maximum of lines of text to be displayed
if positive, it refers to the first max_lines lines
if negative, it refers to the first -max_lines lines
if zero (default), all lines will be displayed - anchor (str) – anchor position
specifies where to put images or texts relative to the anchor point (default see below)
possible values are (default: c):
nw n ne
w c e
sw s se
- linewidth0 (float) – linewidth of the contour at time t0 (default see below)
- fillcolor0 (colorspec) – color of interior/text at time t0 (default see below)
- linecolor0 (colorspec) – color of the contour at time t0 (default see below)
- angle0 (float) – angle of the polygon at time t0 (in degrees) (default see below)
- fontsize0 (float) – fontsize of text at time t0 (default see below)
- width0 (float) – width of the image to be displayed at time t0 (default see below)
if None, the original width of the image will be used - t1 (float) – time of end of the animation (default: inf)
if keep=True, the animation will continue (frozen) after t1 - x1 (float) – x-coordinate of the origin at time t1 (default x0)
- y1 (float) – y-coordinate of the origin at time t1 (default y0)
- offsetx1 (float) – offsets the x-coordinate of the object at time t1 (default offsetx0)
- offsety1 (float) – offsets the y-coordinate of the object at time t1 (default offset0)
- circle1 (float or tuple/ist) – the circle spec of the circle at time t1
- radius
- one item tuple/list containing the radius
- five items tuple/list cntaining radius, radius1, arc_angle0, arc_angle1 and draw_arc (see class AnimateCircle for details) - line1 (tuple) – the line(s) at time t1 (xa,ya,xb,yb,xc,yc, …) (default: line0)
should have the same number of elements as line0 - polygon1 (tuple) – the polygon at time t1 (xa,ya,xb,yb,xc,yc, …) (default: polygon0)
should have the same number of elements as polygon0 - rectangle1 (tuple) – the rectangle at time t (xlowerleft,ylowerleft,xupperright,yupperright)
(default: rectangle0)
- points1 (tuple) – the points(s) at time t1 (xa,ya,xb,yb,xc,yc, …) (default: points0)
should have the same number of elements as points1 - linewidth1 (float) – linewidth of the contour at time t1 (default linewidth0)
- fillcolor1 (colorspec) – color of interior/text at time t1 (default fillcolor0)
- linecolor1 (colorspec) – color of the contour at time t1 (default linecolor0)
- angle1 (float) – angle of the polygon at time t1 (in degrees) (default angle0)
- fontsize1 (float) – fontsize of text at time t1 (default: fontsize0)
- width1 (float) – width of the image to be displayed at time t1 (default: width0)
Note
The type of the animation cannot be changed with this method.
The default value of most of the parameters is the current value (at time now)- layer (int) – layer value
-
visible
(t=None)¶ visible attribute of an animate object. May be overridden.
Parameters: t (float) – current time Returns: visible – default behaviour: self.visible0 and t >= self.t0 (visible given at creation or update) Return type: bool
-
width
(t=None)¶ width position of an animated image object. May be overridden.
Parameters: t (float) – current time Returns: width – default behaviour: linear interpolation between self.width0 and self.width1
if None, the original width of the image will be usedReturn type: float
-
x
(t=None)¶ x-position of an animate object. May be overridden.
Parameters: t (float) – current time Returns: x – default behaviour: linear interpolation between self.x0 and self.x1 Return type: float
-
xy_anchor
(t=None)¶ xy_anchor attribute of an animate object. May be overridden.
Parameters: t (float) – current time Returns: xy_anchor – default behaviour: self.xy_anchor0 (xy_anchor given at creation or update) Return type: str
-
y
(t=None)¶ y-position of an animate object. May be overridden.
Parameters: t (float) – current time Returns: y – default behaviour: linear interpolation between self.y0 and self.y1 Return type: float
- parent (Component) – component where this animation object belongs to (default None)
-
class
salabim.
AnimateButton
(x=0, y=0, width=80, fillcolor='fg', color='bg', text='', font='', fontsize=15, action=None, env=None, xy_anchor='sw')¶ defines a button
Parameters: - x (int) – x-coordinate of centre of the button in screen coordinates (default 0)
- y (int) – y-coordinate of centre of the button in screen coordinates (default 0)
- width (int) – width of button in screen coordinates (default 80)
- height (int) – height of button in screen coordinates (default 30)
- linewidth (int) – width of contour in screen coordinates (default 0=no contour)
- fillcolor (colorspec) – color of the interior (foreground_color)
- linecolor (colorspec) – color of contour (default foreground_color)
- color (colorspec) – color of the text (default background_color)
- text (str or function) – text of the button (default null string)
if text is an argumentless function, this will be called each time; the button is shown/updated - font (str) – font of the text (default Helvetica)
- fontsize (int) – fontsize of the text (default 15)
- action (function) – action to take when button is pressed
executed when the button is pressed (default None) the function should have no arguments - xy_anchor (str) – specifies where x and y are relative to
possible values are (default: sw):
nw n ne
w c e
sw s se
- env (Environment) – environment where the component is defined
if omitted, default_env will be used
Note
All measures are in screen coordinates
On Pythonista, this functionality is emulated by salabim On other platforms, the tkinter functionality is used.-
remove
()¶ removes the button object.
the ui object is removed from the ui queue, so effectively ending this ui
-
class
salabim.
AnimateCircle
(radius=None, radius1=None, arc_angle0=None, arc_angle1=None, draw_arc=None, x=None, y=None, fillcolor=None, linecolor=None, linewidth=None, text=None, fontsize=None, textcolor=None, font=None, angle=None, xy_anchor=None, layer=None, max_lines=None, offsetx=None, offsety=None, text_anchor=None, text_offsetx=None, text_offsety=None, arg=None, parent=None, visible=None, keep=None, env=None, screen_coordinates=False, over3d=None)¶ Displays a (partial) circle or (partial) ellipse , optionally with a text
Parameters: - radius (float) – radius of the circle
- radius1 (float) – the ‘height’ of the ellipse. If None (default), a circle will be drawn
- arc_angle0 (float) – start angle of the circle (default 0)
- arc_angle1 (float) – end angle of the circle (default 360)
when arc_angle1 > arc_angle0 + 360, only 360 degrees will be shown - draw_arc (bool) – if False (default), no arcs will be drawn if True, the arcs from and to the center will be drawn
- x (float) – position of anchor point (default 0)
- y (float) – position of anchor point (default 0)
- xy_anchor (str) – specifies where x and y are relative to
possible values are (default: sw) :
nw n ne
w c e
sw s se
If null string, the given coordimates are used untranslated
The positions corresponds to a full circle even if arc_angle0 and/or arc_angle1 are specified. - offsetx (float) – offsets the x-coordinate of the circle (default 0)
- offsety (float) – offsets the y-coordinate of the circle (default 0)
- linewidth (float) – linewidth of the contour
default 1 - fillcolor (colorspec) – color of interior (default foreground_color)
default transparent - linecolor (colorspec) – color of the contour (default transparent)
- angle (float) – angle of the circle/ellipse and/or text (in degrees)
default: 0 - text (str, tuple or list) – the text to be displayed
if text is str, the text may contain linefeeds, which are shown as individual lines - max_lines (int) – the maximum of lines of text to be displayed
if positive, it refers to the first max_lines lines
if negative, it refers to the last -max_lines lines
if zero (default), all lines will be displayed - font (str or list/tuple) – font to be used for texts
Either a string or a list/tuple of fontnames. If not found, uses calibri or arial - text_anchor (str) – anchor position of text|n|
specifies where to texts relative to the polygon
point
possible values are (default: c):
nw n ne
w c e
sw s se
- textcolor (colorspec) – color of the text (default foreground_color)
- text_offsetx (float) – extra x offset to the text_anchor point
- text_offsety (float) – extra y offset to the text_anchor point
- fontsize (float) – fontsize of text (default 15)
- arg (any) – this is used when a parameter is a function with two parameters, as the first argument or
if a parameter is a method as the instance
default: self (instance itself) - parent (Component) – component where this animation object belongs to (default None)
if given, the animation object will be removed automatically when the parent component is no longer accessible - screen_coordinates (bool) – use screen_coordinates
normally, the scale parameters are use for positioning and scaling objects.
if True, screen_coordinates will be used instead. - over3d (bool) – if True, this object will be rendered to the OpenGL window
if False (default), the normal 2D plane will be used.
Note
All measures are in screen coordinates
All parameters, apart from parent, arg and env can be specified as:
- a scalar, like 10
- a function with zero arguments, like lambda: title
- a function with one argument, being the time t, like lambda t: t + 10
- a function with two parameters, being arg (as given) and the time, like lambda comp, t: comp.state
- a method instance arg for time t, like self.state, actually leading to arg.state(t) to be called
-
class
salabim.
AnimateCombined
(animation_objects, **kwargs)¶ Combines several Animate? objects
Parameters: - animation_objects (iterable) – iterable of Animate2dBase, Animate3dBase or AnimateCombined objects
- **kwargs (dict) – attributes to be set for objects in animation_objects
Notes
When an attribute of an AnimateCombined is assigned, it will propagate to all members, provided it has already that attribute.
When an attribute of an AnimateCombined is queried, the value of the attribute of the first animation_object of the list that has such an attribute will be returned.
If the attribute does not exist in any animation_object of the list, an AttributeError will be raised.
It is possible to use animation_objects withan = sim.AnimationCombined(car.animation_objects[2:]) an = sim.AnimationCombined(car.animation3d_objects[3:])
-
append
(item)¶ Add Animate2dBase, Animate3dBase or AnimateCombined object
Parameters: item (Animate2dBase, Animate3dBase or AnimateCombined) – to be added
-
remove
()¶ remove all members from the animation
-
show
()¶ show all members in the animation
-
update
(**kwargs)¶ Updated one or more attributes
Parameters: **kwargs (dict) – attributes to be set
-
class
salabim.
AnimateEntry
(x=0, y=0, number_of_chars=20, value='', fillcolor='fg', color='bg', text='', action=None, env=None, xy_anchor='sw')¶ defines a button
Parameters: - x (int) – x-coordinate of centre of the button in screen coordinates (default 0)
- y (int) – y-coordinate of centre of the button in screen coordinates (default 0)
- number_of_chars (int) – number of characters displayed in the entry field (default 20)
- fillcolor (colorspec) – color of the entry background (default foreground_color)
- color (colorspec) – color of the text (default background_color)
- value (str) – initial value of the text of the entry (default null string)
- action (function) – action to take when the Enter-key is pressed
the function should have no arguments - xy_anchor (str) – specifies where x and y are relative to
possible values are (default: sw):
nw n ne
w c e
sw s se
- env (Environment) – environment where the component is defined
if omitted, default_env will be used
Note
All measures are in screen coordinates
This class is not available under Pythonista.-
get
()¶ get the current value of the entry
Returns: Current value of the entry Return type: str
-
remove
()¶ removes the entry object.
the ui object is removed from the ui queue, so effectively ending this ui
-
class
salabim.
AnimateImage
(image=None, x=None, y=None, width=None, text=None, fontsize=None, textcolor=None, font=None, angle=None, alpha=None, xy_anchor=None, layer=None, max_lines=None, offsetx=None, offsety=None, text_anchor=None, text_offsetx=None, text_offsety=None, anchor=None, visible=None, keep=None, env=None, arg=None, screen_coordinates=False, over3d=None, parent=None)¶ Displays an image, optionally with a text
Parameters: - image (str, pathlib.Path or PIL Image) – image to be displayed
if used as function or method or in direct assigmnent, the image should be a file containing an image or a PIL image - x (float) – position of anchor point (default 0)
- y (float) – position of anchor point (default 0)
- xy_anchor (str) – specifies where x and y are relative to
possible values are (default: sw) :
nw n ne
w c e
sw s se
If null string, the given coordimates are used untranslated - anchor (str) – specifies where the x and refer to
possible values are (default: sw) :
nw n ne
w c e
sw s se
- offsetx (float) – offsets the x-coordinate of the circle (default 0)
- offsety (float) – offsets the y-coordinate of the circle (default 0)
- angle (float) – angle of the image (in degrees) (default 0)
- alpha (float) – alpha of the image (0-255) (default 255)
- width (float) – width of the image (default: None = no scaling)
- text (str, tuple or list) – the text to be displayed
if text is str, the text may contain linefeeds, which are shown as individual lines - max_lines (int) – the maximum of lines of text to be displayed
if positive, it refers to the first max_lines lines
if negative, it refers to the last -max_lines lines
if zero (default), all lines will be displayed - font (str or list/tuple) – font to be used for texts
Either a string or a list/tuple of fontnames. If not found, uses calibri or arial - text_anchor (str) – anchor position of text|n|
specifies where to texts relative to the polygon
point
possible values are (default: c):
nw n ne
w c e
sw s se
- textcolor (colorspec) – color of the text (default foreground_color)
- text_offsetx (float) – extra x offset to the text_anchor point
- text_offsety (float) – extra y offset to the text_anchor point
- fontsize (float) – fontsize of text (default 15)
- arg (any) – this is used when a parameter is a function with two parameters, as the first argument or
if a parameter is a method as the instance
default: self (instance itself) - parent (Component) – component where this animation object belongs to (default None)
if given, the animation object will be removed automatically when the parent component is no longer accessible - screen_coordinates (bool) – use screen_coordinates
normally, the scale parameters are used for positioning and scaling objects.
if True, screen_coordinates will be used instead. - over3d (bool) – if True, this object will be rendered to the OpenGL window
if False (default), the normal 2D plane will be used.
Note
All measures are in screen coordinates
All parameters, apart from parent, arg and env can be specified as:
- a scalar, like 10
- a function with zero arguments, like lambda: title
- a function with one argument, being the time t, like lambda t: t + 10
- a function with two parameters, being arg (as given) and the time, like lambda comp, t: comp.state
- a method instance arg for time t, like self.state, actually leading to arg.state(t) to be called- image (str, pathlib.Path or PIL Image) – image to be displayed
-
class
salabim.
AnimateLine
(spec=None, x=None, y=None, linecolor=None, linewidth=None, text=None, fontsize=None, textcolor=None, font=None, angle=None, xy_anchor=None, layer=None, max_lines=None, offsetx=None, offsety=None, as_points=None, text_anchor=None, text_offsetx=None, text_offsety=None, arg=None, parent=None, visible=None, keep=None, env=None, screen_coordinates=False, over3d=None)¶ Displays a line, optionally with a text
Parameters: - spec (tuple or list) – should specify x0, y0, x1, y1, …
- x (float) – position of anchor point (default 0)
- y (float) – position of anchor point (default 0)
- xy_anchor (str) – specifies where x and y are relative to
possible values are (default: sw) :
nw n ne
w c e
sw s se
If null string, the given coordimates are used untranslated - offsetx (float) – offsets the x-coordinate of the line (default 0)
- offsety (float) – offsets the y-coordinate of the line (default 0)
- linewidth (float) – linewidth of the contour
default 1 - linecolor (colorspec) – color of the contour (default foreground_color)
- angle (float) – angle of the line (in degrees)
default: 0 - as_points (bool) – if False (default), the contour lines are drawn
if True, only the corner points are shown - text (str, tuple or list) – the text to be displayed
if text is str, the text may contain linefeeds, which are shown as individual lines - max_lines (int) – the maximum of lines of text to be displayed
if positive, it refers to the first max_lines lines
if negative, it refers to the last -max_lines lines
if zero (default), all lines will be displayed - font (str or list/tuple) – font to be used for texts
Either a string or a list/tuple of fontnames. If not found, uses calibri or arial - text_anchor (str) – anchor position of text|n|
specifies where to texts relative to the polygon
point
possible values are (default: c):
nw n ne
w c e
sw s se
- textcolor (colorspec) – color of the text (default foreground_color)
- text_offsetx (float) – extra x offset to the text_anchor point
- text_offsety (float) – extra y offset to the text_anchor point
- fontsize (float) – fontsize of text (default 15)
- arg (any) – this is used when a parameter is a function with two parameters, as the first argument or
if a parameter is a method as the instance
default: self (instance itself) - parent (Component) – component where this animation object belongs to (default None)
if given, the animation object will be removed automatically when the parent component is no longer accessible - screen_coordinates (bool) – use screen_coordinates
normally, the scale parameters are use for positioning and scaling objects.
if True, screen_coordinates will be used instead. - over3d (bool) – if True, this object will be rendered to the OpenGL window
if False (default), the normal 2D plane will be used.
Note
All measures are in screen coordinates
All parameters, apart from parent, arg and env can be specified as:
- a scalar, like 10
- a function with zero arguments, like lambda: title
- a function with one argument, being the time t, like lambda t: t + 10
- a function with two parameters, being arg (as given) and the time, like lambda comp, t: comp.state
- a method instance arg for time t, like self.state, actually leading to arg.state(t) to be called
-
class
salabim.
AnimateMonitor
(monitor, linecolor='fg', linewidth=None, fillcolor='', bordercolor='fg', borderlinewidth=1, titlecolor='fg', nowcolor='red', titlefont='', titlefontsize=15, title=None, x=0, y=0, offsetx=0, offsety=0, angle=0, vertical_offset=0, parent=None, vertical_scale=5, horizontal_scale=1, width=200, height=75, xy_anchor='sw', vertical_map=<class 'float'>, labels=(), label_color='fg', label_font='', label_fontsize=15, label_anchor='e', label_offsetx=0, label_offsety=0, label_linewidth=1, label_linecolor='fg', as_points=None, over3d=None, layer=0, visible=True, keep=True, screen_coordinates=True, arg=None)¶ animates a monitor in a panel
Parameters: - monitor (Monitor) – monitor to be animated
- linecolor (colorspec) – color of the line or points (default foreground color)
- linewidth (int) – width of the line or points (default 1 for level, 3 for non level monitors)
- fillcolor (colorspec) – color of the panel (default transparent)
- bordercolor (colorspec) – color of the border (default foreground color)
- borderlinewidth (int) – width of the line around the panel (default 1)
- nowcolor (colorspec) – color of the line indicating now (default red)
- titlecolor (colorspec) – color of the title (default foreground color)
- titlefont (font) – font of the title (default null string)
- titlefontsize (int) – size of the font of the title (default 15)
- title (str) – title to be shown above panel
default: name of the monitor - x (int) – x-coordinate of panel, relative to xy_anchor, default 0
- y (int) – y-coordinate of panel, relative to xy_anchor. default 0
- offsetx (float) – offsets the x-coordinate of the panel (default 0)
- offsety (float) – offsets the y-coordinate of the panel (default 0)
- angle (float) – rotation angle in degrees, default 0
- xy_anchor (str) – specifies where x and y are relative to
possible values are (default: sw):
nw n ne
w c e
sw s se
- vertical_offset (float) –
- the vertical position of x within the panel is
- vertical_offset + x * vertical_scale (default 0)
- vertical_scale (float) – the vertical position of x within the panel is vertical_offset + x * vertical_scale (default 5)
- horizontal_scale (float) – the relative horizontal position of time t within the panel is on t * horizontal_scale, possibly shifted (default 1)|n|
- width (int) – width of the panel (default 200)
- height (int) – height of the panel (default 75)
- vertical_map (function) – when a y-value has to be plotted it will be translated by this function
default: float
when the function results in a TypeError or ValueError, the value 0 is assumed
when y-values are non numeric, it is advised to provide an approriate map function, like:
vertical_map = “unknown red green blue yellow”.split().index - labels (iterable) – labels to be shown on the vertical axis (default: empty tuple)
the placement of the labels is controlled by the vertical_map method - label_color (colorspec) – color of labels (default: foreground color)
- label_font (font) – font of the labels (default null string)
- label_fontsize (int) – size of the font of the labels (default 15)
- label_anchor (str) – specifies where the label coordinates (as returned by map_value) are relative to
possible values are (default: e):
nw n ne
w c e
sw s se
- label_offsetx (float) – offsets the x-coordinate of the label (default 0)
- label_offsety (float) – offsets the y-coordinate of the label (default 0)
- label_linewidth (int) – width of the label line (default 1)
- label_linecolor (colorspec) – color of the label lines (default foreground color)
- layer (int) – layer (default 0)
- as_points (bool) – allows to override the line/point setting, which is by default False for level monitors and True for non level monitors
- parent (Component) – component where this animation object belongs to (default None)
if given, the animation object will be removed automatically when the parent component is no longer accessible - over3d (bool) – if True, this object will be rendered to the OpenGL window
if False (default), the normal 2D plane will be used. - visible (bool) – visible
if False, animation monitor is not shown, shown otherwise (default True) - screen_coordinates (bool) – use screen_coordinates
if False, the scale parameters are use for positioning and scaling objects.
if True (default), screen_coordinates will be used.
Note
All measures are in screen coordinates
-
remove
()¶ removes the animate object and thus closes this animation
-
show
(unremove)¶ It is possible to use this method if already shown
-
class
salabim.
AnimatePoints
(spec=None, x=None, y=None, linecolor=None, linewidth=None, text=None, fontsize=None, textcolor=None, font=None, angle=None, xy_anchor=None, layer=None, max_lines=None, offsetx=None, offsety=None, as_points=None, text_anchor=None, text_offsetx=None, text_offsety=None, arg=None, parent=None, visible=None, keep=None, env=None, screen_coordinates=False, over3d=None)¶ Displays a series of points, optionally with a text
Parameters: - spec (tuple or list) – should specify x0, y0, x1, y1, …
- x (float) – position of anchor point (default 0)
- y (float) – position of anchor point (default 0)
- xy_anchor (str) – specifies where x and y are relative to
possible values are (default: sw) :
nw n ne
w c e
sw s se
If null string, the given coordimates are used untranslated - offsetx (float) – offsets the x-coordinate of the points (default 0)
- offsety (float) – offsets the y-coordinate of the points (default 0)
- linewidth (float) – width of the points
default 1 - linecolor (colorspec) – color of the points (default foreground_color)
- angle (float) – angle of the points (in degrees)
default: 0 - as_points (bool) – if False (default), the contour lines are drawn
if True, only the corner points are shown - text (str, tuple or list) – the text to be displayed
if text is str, the text may contain linefeeds, which are shown as individual lines - max_lines (int) – the maximum of lines of text to be displayed
if positive, it refers to the first max_lines lines
if negative, it refers to the last -max_lines lines
if zero (default), all lines will be displayed - font (str or list/tuple) – font to be used for texts
Either a string or a list/tuple of fontnames. If not found, uses calibri or arial - text_anchor (str) – anchor position of text|n|
specifies where to texts relative to the polygon
point
possible values are (default: c):
nw n ne
w c e
sw s se
- textcolor (colorspec) – color of the text (default foreground_color)
- text_offsetx (float) – extra x offset to the text_anchor point
- text_offsety (float) – extra y offset to the text_anchor point
- fontsize (float) – fontsize of text (default 15)
- arg (any) – this is used when a parameter is a function with two parameters, as the first argument or
if a parameter is a method as the instance
default: self (instance itself) - parent (Component) – component where this animation object belongs to (default None)
if given, the animation object will be removed automatically when the parent component is no longer accessible - screen_coordinates (bool) – use screen_coordinates
normally, the scale parameters are use for positioning and scaling objects.
if True, screen_coordinates will be used instead. - over3d (bool) – if True, this object will be rendered to the OpenGL window
if False (default), the normal 2D plane will be used.
Note
All measures are in screen coordinates
All parameters, apart from parent, arg and env can be specified as:
- a scalar, like 10
- a function with zero arguments, like lambda: title
- a function with one argument, being the time t, like lambda t: t + 10
- a function with two parameters, being arg (as given) and the time, like lambda comp, t: comp.state
- a method instance arg for time t, like self.state, actually leading to arg.state(t) to be called
-
class
salabim.
AnimatePolygon
(spec=None, x=None, y=None, fillcolor=None, linecolor=None, linewidth=None, text=None, fontsize=None, textcolor=None, font=None, angle=None, xy_anchor=None, layer=None, max_lines=None, offsetx=None, offsety=None, as_points=None, text_anchor=None, text_offsetx=None, text_offsety=None, arg=None, parent=None, visible=None, keep=None, env=None, screen_coordinates=False, over3d=None)¶ Displays a polygon, optionally with a text
Parameters: - spec (tuple or list) – should specify x0, y0, x1, y1, …
- x (float) – position of anchor point (default 0)
- y (float) – position of anchor point (default 0)
- xy_anchor (str) – specifies where x and y are relative to
possible values are (default: sw) :
nw n ne
w c e
sw s se
If null string, the given coordimates are used untranslated - offsetx (float) – offsets the x-coordinate of the polygon (default 0)
- offsety (float) – offsets the y-coordinate of the polygon (default 0)
- linewidth (float) – linewidth of the contour
default 1 - fillcolor (colorspec) – color of interior (default foreground_color)
default transparent - linecolor (colorspec) – color of the contour (default transparent)
- angle (float) – angle of the polygon (in degrees)
default: 0 - as_points (bool) – if False (default), the contour lines are drawn
if True, only the corner points are shown - text (str, tuple or list) – the text to be displayed
if text is str, the text may contain linefeeds, which are shown as individual lines - max_lines (int) – the maximum of lines of text to be displayed
if positive, it refers to the first max_lines lines
if negative, it refers to the last -max_lines lines
if zero (default), all lines will be displayed - font (str or list/tuple) – font to be used for texts
Either a string or a list/tuple of fontnames. If not found, uses calibri or arial - text_anchor (str) – anchor position of text|n|
specifies where to texts relative to the polygon
point
possible values are (default: c):
nw n ne
w c e
sw s se
- textcolor (colorspec) – color of the text (default foreground_color)
- text_offsetx (float) – extra x offset to the text_anchor point
- text_offsety (float) – extra y offset to the text_anchor point
- fontsize (float) – fontsize of text (default 15)
- arg (any) – this is used when a parameter is a function with two parameters, as the first argument or
if a parameter is a method as the instance
default: self (instance itself) - parent (Component) – component where this animation object belongs to (default None)
if given, the animation object will be removed automatically when the parent component is no longer accessible - screen_coordinates (bool) – use screen_coordinates
normally, the scale parameters are use for positioning and scaling objects.
if True, screen_coordinates will be used instead. - over3d (bool) – if True, this object will be rendered to the OpenGL window
if False (default), the normal 2D plane will be used.
Note
All measures are in screen coordinates
All parameters, apart from parent, arg and env can be specified as:
- a scalar, like 10
- a function with zero arguments, like lambda: title
- a function with one argument, being the time t, like lambda t: t + 10
- a function with two parameters, being arg (as given) and the time, like lambda comp, t: comp.state
- a method instance arg for time t, like self.state, actually leading to arg.state(t) to be called
-
class
salabim.
AnimateQueue
(queue, x=50, y=50, direction='w', trajectory=None, max_length=None, xy_anchor='sw', reverse=False, title=None, titlecolor='fg', titlefontsize=15, titlefont='', titleoffsetx=None, titleoffsety=None, layer=0, id=None, arg=None, parent=None, over3d=None, keep=True, visible=True)¶ Animates the component in a queue.
queue : Queue
- x : float
- x-position of the first component in the queue
default: 50 - y : float
- y-position of the first component in the queue
default: 50 - direction : str
- if “w”, waiting line runs westwards (i.e. from right to left)
if “n”, waiting line runs northeards (i.e. from bottom to top)
if “e”, waiting line runs eastwards (i.e. from left to right) (default)
if “s”, waiting line runs southwards (i.e. from top to bottom)
:
- trajectory : Trajectory
- trajectory to be followed. Overrides any given directory
- reverse : bool
- if False (default), display in normal order. If True, reversed.
- max_length : int
- maximum number of components to be displayed
- xy_anchor : str
- specifies where x and y are relative to
possible values are (default: sw):
nw n ne
w c e
sw s se
- titlecolor : colorspec
- color of the title (default foreground color)
- titlefont : font
- font of the title (default null string)
- titlefontsize : int
- size of the font of the title (default 15)
- title : str
- title to be shown above queue
default: name of the queue - titleoffsetx : float
- x-offset of the title relative to the start of the queue
default: 25 if direction is w, -25 otherwise - titleoffsety : float
- y-offset of the title relative to the start of the queue
default: -25 if direction is s, -25 otherwise - id : any
- the animation works by calling the animation_objects method of each component, optionally with id. By default, this is self, but can be overriden, particularly with the queue
- arg : any
- this is used when a parameter is a function with two parameters, as the first argument or
if a parameter is a method as the instance
default: self (instance itself) - visible : bool
- if False, nothing will be shown
(default True) - keep : bool
- if False, animation object will be taken from the animation objects. With show(), the animation can be reshown. (default True)
- parent : Component
- component where this animation object belongs to (default None)
if given, the animation object will be removed automatically when the parent component is no longer accessible
All measures are in screen coordinates
All parameters, apart from queue, id, arg and parent can be specified as:
- a scalar, like 10
- a function with zero arguments, like lambda: title
- a function with one argument, being the time t, like lambda t: t + 10
- a function with two parameters, being arg (as given) and the time, like lambda comp, t: comp.state
- a method instance arg for time t, like self.state, actually leading to arg.state(t) to be called-
show
(unremove)¶ It is possible to use this method if already shown
-
class
salabim.
AnimateRectangle
(spec=None, x=None, y=None, fillcolor=None, linecolor=None, linewidth=None, text=None, fontsize=None, textcolor=None, font=None, angle=None, xy_anchor=None, layer=None, max_lines=None, offsetx=None, offsety=None, as_points=None, text_anchor=None, text_offsetx=None, text_offsety=None, arg=None, parent=None, visible=None, keep=None, env=None, screen_coordinates=False, over3d=None)¶ Displays a rectangle, optionally with a text
Parameters: - spec (four item tuple or list) – should specify xlowerleft, ylowerleft, xupperright, yupperright
- x (float) – position of anchor point (default 0)
- y (float) – position of anchor point (default 0)
- xy_anchor (str) – specifies where x and y are relative to
possible values are (default: sw) :
nw n ne
w c e
sw s se
If null string, the given coordimates are used untranslated - offsetx (float) – offsets the x-coordinate of the rectangle (default 0)
- offsety (float) – offsets the y-coordinate of the rectangle (default 0)
- linewidth (float) – linewidth of the contour
default 1 - fillcolor (colorspec) – color of interior (default foreground_color)
default transparent - linecolor (colorspec) – color of the contour (default transparent)
- angle (float) – angle of the rectangle (in degrees)
default: 0 - as_points (bool) – if False (default), the contour lines are drawn
if True, only the corner points are shown - text (str, tuple or list) – the text to be displayed
if text is str, the text may contain linefeeds, which are shown as individual lines - max_lines (int) – the maximum of lines of text to be displayed
if positive, it refers to the first max_lines lines
if negative, it refers to the last -max_lines lines
if zero (default), all lines will be displayed - font (str or list/tuple) – font to be used for texts
Either a string or a list/tuple of fontnames. If not found, uses calibri or arial - text_anchor (str) – anchor position of text|n|
specifies where to texts relative to the rectangle
point
possible values are (default: c):
nw n ne
w c e
sw s se
- textcolor (colorspec) – color of the text (default foreground_color)
- text_offsetx (float) – extra x offset to the text_anchor point
- text_offsety (float) – extra y offset to the text_anchor point
- fontsize (float) – fontsize of text (default 15)
- arg (any) – this is used when a parameter is a function with two parameters, as the first argument or
if a parameter is a method as the instance
default: self (instance itself) - parent (Component) – component where this animation object belongs to (default None)
if given, the animation object will be removed automatically when the parent component is no longer accessible
Note
All measures are in screen coordinates
All parameters, apart from parent, arg and env can be specified as:
- a scalar, like 10
- a function with zero arguments, like lambda: title
- a function with one argument, being the time t, like lambda t: t + 10
- a function with two parameters, being arg (as given) and the time, like lambda comp, t: comp.state
- a method instance arg for time t, like self.state, actually leading to arg.state(t) to be called
-
class
salabim.
AnimateSlider
(x=0, y=0, width=100, height=20, vmin=0, vmax=10, v=None, resolution=1, background_color='bg', foreground_color='fg', trough_color='lightgray', show_value=True, label='', font='', fontsize=12, action=None, xy_anchor='sw', env=None, linecolor=None, labelcolor=None, layer=None)¶ defines a slider
Parameters: - x (int) – x-coordinate of centre of the slider in screen coordinates (default 0)
- y (int) – y-coordinate of centre of the slider in screen coordinates (default 0)
- vmin (float) – minimum value of the slider (default 0)
- vmax (float) – maximum value of the slider (default 0)
- v (float) – initial value of the slider (default 0)
should be between vmin and vmax - resolution (float) – step size of value (default 1)
- width (float) – width of slider in screen coordinates (default 100)
- height (float) – height of slider in screen coordinates (default 20)
- foreground_color (colorspec) – color of the foreground (default “fg”)
- background_color (colorspec) – color of the backgroundground (default “bg”)
- trough_color (colorspec) – color of the trough (default “lightgrey”)
- show_value (boolean) – if True (default), show values; if False don’t show values
- label (str) – label if the slider (default null string)
- font (str) – font of the text (default Helvetica)
- fontsize (int) – fontsize of the text (default 12)
- action (function) – function executed when the slider value is changed (default None)
the function should have one argument, being the new value
if None (default), no action - xy_anchor (str) – specifies where x and y are relative to
possible values are (default: sw):
nw n ne
w c e
sw s se
- env (Environment) – environment where the component is defined
if omitted, default_env will be used
Note
The current value of the slider is the v attibute of the slider.
All measures are in screen coordinates
On Pythonista, this functionality is emulated by salabim On other platforms, the tkinter functionality is used.-
remove
()¶ removes the slider object
The ui object is removed from the ui queue, so effectively ending this ui
-
v
(value=None)¶ value
Parameters: value (float) – new value
if omitted, no changeReturns: Current value of the slider Return type: float
-
class
salabim.
AnimateText
(text=None, x=None, y=None, font=None, fontsize=None, textcolor=None, text_anchor=None, angle=None, xy_anchor=None, layer=None, max_lines=None, offsetx=None, offsety=None, arg=None, visible=None, keep=None, parent=None, env=None, screen_coordinates=False, over3d=None)¶ Displays a text
Parameters: - text (str, tuple or list) – the text to be displayed
if text is str, the text may contain linefeeds, which are shown as individual lines if text is tple or list, each item is displayed on a separate line - x (float) – position of anchor point (default 0)
- y (float) – position of anchor point (default 0)
- xy_anchor (str) – specifies where x and y are relative to
possible values are (default: sw) :
nw n ne
w c e
sw s se
If null string, the given coordimates are used untranslated - offsetx (float) – offsets the x-coordinate of the rectangle (default 0)
- offsety (float) – offsets the y-coordinate of the rectangle (default 0)
- angle (float) – angle of the text (in degrees)
default: 0 - max_lines (int) – the maximum of lines of text to be displayed
if positive, it refers to the first max_lines lines
if negative, it refers to the last -max_lines lines
if zero (default), all lines will be displayed - font (str or list/tuple) – font to be used for texts
Either a string or a list/tuple of fontnames. If not found, uses calibri or arial - text_anchor (str) – anchor position of text|n|
specifies where to texts relative to the rectangle
point
possible values are (default: c):
nw n ne
w c e
sw s se
- textcolor (colorspec) – color of the text (default foreground_color)
- fontsize (float) – fontsize of text (default 15)
- arg (any) – this is used when a parameter is a function with two parameters, as the first argument or
if a parameter is a method as the instance
default: self (instance itself) - parent (Component) – component where this animation object belongs to (default None)
if given, the animation object will be removed automatically when the parent component is no longer accessible - screen_coordinates (bool) – use screen_coordinates
normally, the scale parameters are use for positioning and scaling objects.
if True, screen_coordinates will be used instead. - over3d (bool) – if True, this object will be rendered to the OpenGL window
if False (default), the normal 2D plane will be used.
Note
All measures are in screen coordinates
All parameters, apart from parent, arg and env can be specified as:
- a scalar, like 10
- a function with zero arguments, like lambda: title
- a function with one argument, being the time t, like lambda t: t + 10
- a function with two parameters, being arg (as given) and the time, like lambda comp, t: comp.state
- a method instance arg for time t, like self.state, actually leading to arg.state(t) to be called- text (str, tuple or list) – the text to be displayed
Component¶
-
class
salabim.
Component
(name=None, at=None, delay=None, priority=None, urgent=None, process=None, suppress_trace=False, suppress_pause_at_step=False, skip_standby=False, mode='', cap_now=None, env=None, **kwargs)¶ Component object
A salabim component is used as component (primarily for queueing) or as a component with a process
Usually, a component will be defined as a subclass of Component.Parameters: - name (str) – name of the component.
if the name ends with a period (.), auto serializing will be applied
if the name end with a comma, auto serializing starting at 1 will be applied
if omitted, the name will be derived from the class it is defined in (lowercased) - at (float or distribution) – schedule time
if omitted, now is used
if distribution, the distribution is sampled - delay (float or distributiom) – schedule with a delay
if omitted, no delay
if distribution, the distribution is sampled - priority (float) – priority
default: 0
if a component has the same time on the event list, this component is sorted accoring to the priority. - urgent (bool) – urgency indicator
if False (default), the component will be scheduled behind all other components scheduled for the same time and priority
if True, the component will be scheduled in front of all components scheduled for the same time and priority - process (str) – name of process to be started.
if None (default), it will try to start self.process()
if null string, no process will be started even if self.process() exists, i.e. become a data component. - suppress_trace (bool) – suppress_trace indicator
if True, this component will be excluded from the trace
If False (default), the component will be traced
Can be queried or set later with the suppress_trace method. - suppress_pause_at_step (bool) – suppress_pause_at_step indicator
if True, if this component becomes current, do not pause when stepping
If False (default), the component will be paused when stepping
Can be queried or set later with the suppress_pause_at_step method. - skip_standby (bool) – skip_standby indicator
if True, after this component became current, do not activate standby components
If False (default), after the component became current activate standby components
Can be queried or set later with the skip_standby method. - mode (str preferred) – mode
will be used in trace and can be used in animations
if omitted, the mode will be “”.
also mode_time will be set to now. - cap_now (bool) – indicator whether times (at, delay) in the past are allowed. If, so now() will be used. default: sys.default_cap_now(), usualy False
- env (Environment) – environment where the component is defined
if omitted, default_env will be used
-
activate
(at=None, delay=0, priority=0, urgent=False, process=None, keep_request=False, keep_wait=False, mode=None, cap_now=None, **kwargs)¶ activate component
Parameters: - at (float or distribution) – schedule time
if omitted, now is used
inf is allowed
if distribution, the distribution is sampled - delay (float or distribution) – schedule with a delay
if omitted, no delay
if distribution, the distribution is sampled - priority (float) – priority
default: 0
if a component has the same time on the event list, this component is sorted accoring to the priority. - urgent (bool) – urgency indicator
if False (default), the component will be scheduled behind all other components scheduled for the same time and priority
if True, the component will be scheduled in front of all components scheduled for the same time and priority - process (str) – name of process to be started.
if None (default), process will not be changed
if the component is a data component, the generator function process will be used as the default process.
note that the function must be a generator, i.e. contains at least one yield. - keep_request (bool) – this affects only components that are requesting.
if True, the requests will be kept and thus the status will remain requesting
if False (the default), the request(s) will be canceled and the status will become scheduled - keep_wait (bool) – this affects only components that are waiting.
if True, the waits will be kept and thus the status will remain waiting
if False (the default), the wait(s) will be canceled and the status will become scheduled - cap_now (bool) – indicator whether times (at, delay) in the past are allowed. If, so now() will be used. default: sys.default_cap_now(), usualy False
- mode (str preferred) – mode
will be used in the trace and can be used in animations
if nothing specified, the mode will be unchanged.
also mode_time will be set to now, if mode is set.
Note
if to be applied to the current component, use
yield self.activate()
.
if both at and delay are specified, the component becomes current at the sum of the two values.- at (float or distribution) – schedule time
-
animation3d_objects
(id)¶ defines how to display a component in Animate3dQueue
Parameters: id (any) – id as given by Animate3dQueue. Note that by default this the reference to the Animate3dQueue object. Returns: size_x : how much to displace the next component in x-direction, if applicable
size_y : how much to displace the next component in y-direction, if applicable
size_z : how much to displace the next component in z-direction, if applicable
animation objects : instances of Animate3dBase class
default behaviour:
white 3dbox of size 8, placed on the z=0 plane (displacements 10).Return type: List or tuple containg Note
If you override this method, be sure to use the same header, either with or without the id parameter.
Note
The animation object should support the x_offset, y_offset and z_offset attributes, in order to be able to position the object correctly. All native salabim Animate3d classes are offset aware.
-
animation_objects
(id)¶ defines how to display a component in AnimateQueue
Parameters: id (any) – id as given by AnimateQueue. Note that by default this the reference to the AnimateQueue object. Returns: size_x : how much to displace the next component in x-direction, if applicable
size_y : how much to displace the next component in y-direction, if applicable
animation objects : instances of Animate class
default behaviour:
square of size 40 (displacements 50), with the sequence number centered.Return type: List or tuple containg Note
If you override this method, be sure to use the same header, either with or without the id parameter.
-
base_name
()¶ Returns: base name of the component (the name used at initialization) Return type: str
-
cancel
(mode=None)¶ cancel component (makes the component data)
Parameters: mode (str preferred) – mode
will be used in trace and can be used in animations
if nothing specified, the mode will be unchanged.
also mode_time will be set to now, if mode is set.Note
if to be used for the current component, use
yield self.cancel()
.
-
claimed_quantity
(resource)¶ Parameters: resource (Resoure) – resource to be queried Returns: the claimed quantity from a resource – if the resource is not claimed, 0 will be returned Return type: float or int
-
claimed_resources
()¶ Returns: list of claimed resources Return type: list
-
count
(q=None)¶ queue count
Parameters: q (Queue) – queue to check or
if omitted, the number of queues where the component is inReturns: 1 if component is in q, 0 otherwise –
if q is omitted, the number of queues where the component is inReturn type: int
-
creation_time
()¶ Returns: time the component was created Return type: float
-
deregister
(registry)¶ deregisters the component in the registry
Parameters: registry (list) – list of registered components Returns: component (self) Return type: Component
-
enter
(q)¶ enters a queue at the tail
Parameters: q (Queue) – queue to enter Note
the priority will be set to the priority of the tail component of the queue, if any or 0 if queue is empty
-
enter_at_head
(q)¶ enters a queue at the head
Parameters: q (Queue) – queue to enter Note
the priority will be set to the priority of the head component of the queue, if any or 0 if queue is empty
-
enter_behind
(q, poscomponent)¶ enters a queue behind a component
Parameters: Note
the priority will be set to the priority of poscomponent
-
enter_in_front_of
(q, poscomponent)¶ enters a queue in front of a component
Parameters: Note
the priority will be set to the priority of poscomponent
-
enter_sorted
(q, priority)¶ enters a queue, according to the priority
Parameters: - q (Queue) – queue to enter
- priority (type that can be compared with other priorities in the queue) – priority in the queue
Note
The component is placed just before the first component with a priority > given priority
-
enter_time
(q)¶ Parameters: q (Queue) – queue where component belongs to Returns: time the component entered the queue Return type: float
-
failed
()¶ Returns: - True, if the latest request/wait has failed (either by timeout or external) (bool)
- False, otherwise
-
get
(*args, **kwargs)¶ equivalent to request
-
hold
(duration=None, till=None, priority=0, urgent=False, mode=None, cap_now=None)¶ hold the component
Parameters: - duration (float or distribution) – specifies the duration
if omitted, 0 is used
inf is allowed
if distribution, the distribution is sampled - till (float or distribution) – specifies at what time the component will become current
if omitted, now is used
inf is allowed
if distribution, the distribution is sampled - priority (float) – priority
default: 0
if a component has the same time on the event list, this component is sorted accoring to the priority. - urgent (bool) – urgency indicator
if False (default), the component will be scheduled behind all other components scheduled for the same time and priority
if True, the component will be scheduled in front of all components scheduled for the same time and priority - mode (str preferred) – mode
will be used in trace and can be used in animations
if nothing specified, the mode will be unchanged.
also mode_time will be set to now, if mode is set. - cap_now (bool) – indicator whether times (duration, till) in the past are allowed. If, so now() will be used. default: sys.default_cap_now(), usualy False
Note
if to be used for the current component, use
yield self.hold(...)
.if both duration and till are specified, the component will become current at the sum of these two.
- duration (float or distribution) – specifies the duration
-
index
(q)¶ Parameters: q (Queue) – queue to be queried Returns: index of component in q – if component belongs to q
-1 if component does not belong to qReturn type: int
-
interrupt
(mode=None)¶ interrupt the component
Parameters: mode (str preferred) – mode
will be used in trace and can be used in animations
if nothing is specified, the mode will be unchanged.
also mode_time will be set to now, if mode is set.Note
Cannot be applied on the current component.
Use resume() to resume
-
interrupt_level
()¶ returns interrupt level of an interrupted component
non interrupted components return 0
-
interrupted_status
()¶ returns the original status of an interrupted component
- possible values are
- passive
- scheduled
- requesting
- waiting
- standby
-
isbumped
(resource=None)¶ check whether component is bumped from resource
Parameters: resource (Resource) – resource to be checked if omitted, checks whether component belongs to any resource claimers Returns: True if this component is not in the resource claimers – False otherwise Return type: bool
-
isclaiming
(resource=None)¶ check whether component is claiming from resource
Parameters: resource (Resource) – resource to be checked if omitted, checks whether component is in any resource claimers Returns: True if this component is in the resource claimers – False otherwise Return type: bool
-
iscurrent
()¶ Returns: True if status is current, False otherwise Return type: bool Note
Be sure to always include the parentheses, otherwise the result will be always True!
-
isdata
()¶ Returns: True if status is data, False otherwise Return type: bool Note
Be sure to always include the parentheses, otherwise the result will be always True!
-
isinterrupted
()¶ Returns: True if status is interrupted, False otherwise Return type: bool Note
Be sure to always include the parentheses, otherwise the result will be always True
-
ispassive
()¶ Returns: True if status is passive, False otherwise Return type: bool Note
Be sure to always include the parentheses, otherwise the result will be always True!
-
isrequesting
()¶ Returns: True if status is requesting, False otherwise Return type: bool Note
Be sure to always include the parentheses, otherwise the result will be always True!
-
isscheduled
()¶ Returns: True if status is scheduled, False otherwise Return type: bool Note
Be sure to always include the parentheses, otherwise the result will be always True!
-
isstandby
()¶ Returns: True if status is standby, False otherwise Return type: bool Note
Be sure to always include the parentheses, otherwise the result will be always True
-
iswaiting
()¶ Returns: True if status is waiting, False otherwise Return type: bool Note
Be sure to always include the parentheses, otherwise the result will be always True!
-
leave
(q=None)¶ leave queue
Parameters: q (Queue) – queue to leave Note
statistics are updated accordingly
-
line_number
()¶ current line number of the process
Returns: Current line number – for data components, “” will be returned Return type: str
-
mode_time
()¶ Returns: time the component got it’s latest mode – For a new component this is the time the component was created.
this function is particularly useful for animations.Return type: float
-
name
(value=None)¶ Parameters: value (str) – new name of the component if omitted, no change Returns: Name of the component Return type: str Note
base_name and sequence_number are not affected if the name is changed
-
passivate
(mode=None)¶ passivate the component
Parameters: mode (str preferred) – mode
will be used in trace and can be used in animations
if nothing is specified, the mode will be unchanged.
also mode_time will be set to now, if mode is set.Note
if to be used for the current component (nearly always the case), use
yield self.passivate()
.
-
predecessor
(q)¶ Parameters:
-
print_info
(as_str=False, file=None)¶ prints information about the component
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
priority
(q, priority=None)¶ gets/sets the priority of a component in a queue
Parameters: - q (Queue) – queue where the component belongs to
- priority (type that can be compared with other priorities in the queue) – priority in queue
if omitted, no change
Returns: the priority of the component in the queue
Return type: float
Note
if you change the priority, the order of the queue may change
-
put
(*args, **kwargs)¶ equivalent to request, but anonymous quantities are negated
-
queues
()¶ Returns: set of queues where the component belongs to Return type: set
-
register
(registry)¶ registers the component in the registry
Parameters: registry (list) – list of (to be) registered objects Returns: component (self) Return type: Component Note
Use Component.deregister if component does not longer need to be registered.
-
release
(*args)¶ release a quantity from a resource or resources
Parameters: args (sequence of items, where each items can be) – - a resources, where quantity=current claimed quantity
- a tuple/list containing a resource and the quantity to be released
Note
It is not possible to release from an anonymous resource, this way. Use Resource.release() in that case.
Example
yield self.request(r1,(r2,2),(r3,3,100))
–> requests 1 from r1, 2 from r2 and 3 from r3 with priority 100c1.release
–> releases 1 from r1, 2 from r2 and 3 from r3yield self.request(r1,(r2,2),(r3,3,100))
c1.release((r2,1))
–> releases 1 from r2yield self.request(r1,(r2,2),(r3,3,100))
c1.release((r2,1),r3)
–> releases 2 from r2,and 3 from r3
-
remaining_duration
(value=None, priority=0, urgent=False)¶ Parameters: - value (float) – set the remaining_duration
The action depends on the status where the component is in:
- passive: the remaining duration is update according to the given value
- standby and current: not allowed
- scheduled: the component is rescheduled according to the given value
- waiting or requesting: the fail_at is set according to the given value
- interrupted: the remaining_duration is updated according to the given value - priority (float) – priority
default: 0
if a component has the same time on the event list, this component is sorted accoring to the priority. - urgent (bool) – urgency indicator
if False (default), the component will be scheduled behind all other components scheduled for the same time and priority
if True, the component will be scheduled in front of all components scheduled for the same time and priority
Returns: remaining duration – if passive, remaining time at time of passivate
if scheduled, remaing time till scheduled time
if requesting or waiting, time till fail_at time
else: 0Return type: float
Note
This method is useful for interrupting a process and then resuming it, after some (breakdown) time
- value (float) – set the remaining_duration
-
remove_animation_children
()¶ removes animation children
Note
Normally, the animation_children are removed automatically upon termination of a component (when it terminates)
-
request
(*args, **kwargs)¶ request from a resource or resources
Parameters: - args (sequence of items where each item can be:) –
- resource, where quantity=1, priority=tail of requesters queue
- tuples/list containing a resource, a quantity and optionally a priority.
- if the priority is not specified, the request
for the resource be added to the tail of
the requesters queue
- priority (float) – priority of the fail event|n|
default: 0
if a component has the same time on the event list, this component is sorted accoring to the priority. - urgent (bool) – urgency indicator
if False (default), the component will be scheduled behind all other components scheduled for the same time and priority
if True, the component will be scheduled in front of all components scheduled for the same time and priority - fail_at (float or distribution) – time out
if the request is not honored before fail_at, the request will be cancelled and the parameter failed will be set.
if not specified, the request will not time out.
if distribution, the distribution is sampled - fail_delay (float or distribution) – time out
if the request is not honored before now+fail_delay, the request will be cancelled and the parameter failed will be set.
if not specified, the request will not time out.
if distribution, the distribution is sampled - oneof (bool) – if oneof is True, just one of the requests has to be met (or condition),
where honoring follows the order given.
if oneof is False (default), all requests have to be met to be honored - mode (str preferred) – mode
will be used in trace and can be used in animations
if nothing specified, the mode will be unchanged.
also mode_time will be set to now, if mode is set. - cap_now (bool) – indicator whether times (fail_at, fail_delay) in the past are allowed. If, so now() will be used. default: sys.default_cap_now(), usualy False
Note
Not allowed for data components or main.
If to be used for the current component (which will be nearly always the case), use
yield self.request(...)
.If the same resource is specified more that once, the quantities are summed
The requested quantity may exceed the current capacity of a resource
The parameter failed will be reset by a calling request or wait
Example
yield self.request(r1)
–> requests 1 from r1
yield self.request(r1,r2)
–> requests 1 from r1 and 1 from r2
yield self.request(r1,(r2,2),(r3,3,100))
–> requests 1 from r1, 2 from r2 and 3 from r3 with priority 100
yield self.request((r1,1),(r2,2))
–> requests 1 from r1, 2 from r2
yield self.request(r1, r2, r3, oneoff=True)
–> requests 1 from r1, r2 or r3- args (sequence of items where each item can be:) –
-
requested_quantity
(resource)¶ Parameters: resource (Resoure) – resource to be queried Returns: the requested (not yet honored) quantity from a resource – if there is no request for the resource, 0 will be returned Return type: float or int
-
requested_resources
()¶ Returns: list of requested resources Return type: list
-
resume
(all=False, mode=None, priority=0, urgent=False)¶ resumes an interrupted component
Parameters: - all (bool) – if True, the component returns to the original status, regardless of the number of interrupt levels
if False (default), the interrupt level will be decremented and if the level reaches 0, the component will return to the original status. - mode (str preferred) – mode
will be used in trace and can be used in animations
if nothing is specified, the mode will be unchanged.
also mode_time will be set to now, if mode is set. - priority (float) – priority
default: 0
if a component has the same time on the event list, this component is sorted accoring to the priority.
- urgent : bool
- urgency indicator
if False (default), the component will be scheduled behind all other components scheduled for the same time and priority
if True, the component will be scheduled in front of all components scheduled for the same time and priority
Note
Can be only applied to interrupted components.
- all (bool) – if True, the component returns to the original status, regardless of the number of interrupt levels
-
running_process
()¶ Returns: name of the running process – if data component, None Return type: str
-
scheduled_priority
()¶ Returns: priority the component is scheduled with – returns None otherwise Return type: float Note
The method has to traverse the event list, so performance may be an issue.
-
scheduled_time
()¶ Returns: time the component scheduled for, if it is scheduled – returns inf otherwise Return type: float
-
sequence_number
()¶ Returns: sequence_number of the component – (the sequence number at initialization)
normally this will be the integer value of a serialized name, but also non serialized names (without a dotcomma at the end) will be numbered)Return type: int
-
set_mode
(value=None)¶ Parameters: value (any, str recommended) – new mode
mode_time will be set to now if omitted, no change
-
setup
()¶ called immediately after initialization of a component.
by default this is a dummy method, but it can be overridden.
only keyword arguments will be passed
Example
- class Car(sim.Component):
- def setup(self, color):
- self.color = color
- def process(self):
- …
redcar=Car(color=”red”)
bluecar=Car(color=”blue”)
-
skip_standby
(value=None)¶ Parameters: value (bool) – new skip_standby value
if omitted, no changeReturns: skip_standby indicator – components with the skip_standby indicator of True, will not activate standby components after the component became current. Return type: bool
-
standby
(mode=None)¶ puts the component in standby mode
Parameters: mode (str preferred) – mode
will be used in trace and can be used in animations
if nothing specified, the mode will be unchanged.
also mode_time will be set to now, if mode is set.Note
Not allowed for data components or main.
if to be used for the current component (which will be nearly always the case), use
yield self.standby()
.
-
status
()¶ returns the status of a component
- possible values are
- data
- passive
- scheduled
- requesting
- waiting
- current
- standby
- interrupted
-
successor
(q)¶ Parameters: q (Queue) – queue where the component belongs to Returns: the successor of the component in the queue – if component is not at the tail.
returns None if component is at the tail.Return type: Component
-
suppress_pause_at_step
(value=None)¶ Parameters: value (bool) – new suppress_trace value
if omitted, no changeReturns: suppress_pause_at_step – components with the suppress_pause_at_step of True, will be ignored in a step Return type: bool
-
suppress_trace
(value=None)¶ Parameters: value (bool) – new suppress_trace value
if omitted, no changeReturns: suppress_trace – components with the suppress_status of True, will be ignored in the trace Return type: bool
-
wait
(*args, **kwargs)¶ wait for any or all of the given state values are met
Parameters: - args (sequence of items, where each item can be) –
- a state, where value=True, priority=tail of waiters queue)
- a tuple/list containing
- state, a value and optionally a priority.
if the priority is not specified, this component will be added to the tail of the waiters queue
- a tuple/list containing
- priority (float) – priority of the fail event|n|
default: 0
if a component has the same time on the event list, this component is sorted accoring to the priority. - urgent (bool) – urgency indicator
if False (default), the component will be scheduled behind all other components scheduled for the same time and priority
if True, the component will be scheduled in front of all components scheduled for the same time and priority - fail_at (float or distribution) – time out
if the wait is not honored before fail_at, the wait will be cancelled and the parameter failed will be set.
if not specified, the wait will not time out.
if distribution, the distribution is sampled - fail_delay (float or distribution) – time out
if the wait is not honored before now+fail_delay, the request will be cancelled and the parameter failed will be set.
if not specified, the wait will not time out.
if distribution, the distribution is sampled - all (bool) – if False (default), continue, if any of the given state/values is met
if True, continue if all of the given state/values are met - mode (str preferred) – mode
will be used in trace and can be used in animations
if nothing specified, the mode will be unchanged.
also mode_time will be set to now, if mode is set. - cap_now (bool) – indicator whether times (fail_at, fail_duration) in the past are allowed. If, so now() will be used. default: sys.default_cap_now(), usualy False
Note
Not allowed for data components or main.
If to be used for the current component (which will be nearly always the case), use
yield self.wait(...)
.It is allowed to wait for more than one value of a state
the parameter failed will be reset by a calling waitIf you want to check for all components to meet a value (and clause), use Component.wait(…, all=True)
The value may be specified in three different ways:
- constant, that value is just compared to state.value()
yield self.wait((light,”red”)) - an expression, containg one or more $-signs
the $ is replaced by state.value(), each time the condition is tested.
self refers to the component under test, state refers to the state under test.
yield self.wait((light,’$ in (“red”,”yellow”)’))
yield self.wait((level,”$<30”)) - a function. In that case the parameter should function that
should accept three arguments: the value, the component under test and the
state under test.
usually the function will be a lambda function, but that’s not a requirement.
yield self.wait((light,lambda t, comp, state: t in (“red”,”yellow”)))
yield self.wait((level,lambda t, comp, state: t < 30))
Example
yield self.wait(s1)
–> waits for s1.value()==True
yield self.wait(s1,s2)
–> waits for s1.value()==True or s2.value==True
yield self.wait((s1,False,100),(s2,"on"),s3)
–> waits for s1.value()==False or s2.value==”on” or s3.value()==True
s1 is at the tail of waiters, because of the set priority
yield self.wait(s1,s2,all=True)
–> waits for s1.value()==True and s2.value==True- args (sequence of items, where each item can be) –
- name (str) – name of the component.
ComponentGenerator¶
-
class
salabim.
ComponentGenerator
(component_class, generator_name=None, at=None, delay=None, till=None, duration=None, number=None, iat=None, force_at=False, force_till=False, suppress_trace=False, suppress_pause_at_step=False, disturbance=None, env=None, **kwargs)¶ Component generator object
A component generator can be used to genetate components
There are two ways of generating components:
- according to a given inter arrival time (iat) value or distribution - random spread over a given time intervalParameters: - component_class (callable, usually a subclass of Component or Pdf or Cdf distribution) – the type of components to be generated
in case of a distribution, the Pdf or Cdf should return a callable - generator_name (str) – name of the component generator.
if the name ends with a period (.), auto serializing will be applied
if the name end with a comma, auto serializing starting at 1 will be applied
if omitted, the name will be derived from the name of the component_class, padded with ‘.generator’ - at (float or distribution) – time where the generator starts time
if omitted, now is used
if distribution, the distribution is sampled - delay (float or distribution) – delay where the generator starts (at = now + delay)
if omitted, no delay
if distribution, the distribution is sampled - till (float or distribution) – time up to which components should be generated
if omitted, no end
if distribution, the distribution is sampled - duration (float or distribution) – duration to which components should be generated (till = now + duration)
if omitted, no end
if distribution, the distribution is sampled - number (int or distribution) – (maximum) number of components to be generated
if distribution, the distribution is sampled - iat (float or distribution) – inter arrival time (distribution).
if None (default), a random spread over the interval (at, till) will be used - force_at (bool) –
- for iat generation:
- if False (default), the first component will be generated at time = at + sample from the iat
if True, the first component will be generated at time = at - for random spread generation:
- if False (default), no force for time = at
if True, force the first generation at time = at
- for iat generation:
- force_till (bool) – only possible for random spread generation:
if False (default), no force for time = till
if True, force the last generated component at time = till - disturbance (callable (usually a distribution)) – for each component to be generated, the disturbance call (sampling) is added
to the actual generation time.
disturbance may only be used together with iat. The force_at parameter is not allowed in that case. - suppress_trace (bool) – suppress_trace indicator
if True, the component generator events will be excluded from the trace
If False (default), the component generator will be traced
Can be queried or set later with the suppress_trace method. - suppress_pause_at_step (bool) – suppress_pause_at_step indicator
if True, if this component generator becomes current, do not pause when stepping
If False (default), the component generator will be paused when stepping
Can be queried or set later with the suppress_pause_at_step method. - cap_now (bool) – indicator whether times (activation) in the past are allowed. If, so now() will be used. default: sys.default_cap_now(), usualy False
- env (Environment) – environment where the component is defined
if omitted, default_env will be used
Note
For iat distributions: if till/duration and number are specified, the generation stops whichever condition comes first.
-
print_info
(as_str=False, file=None)¶ prints information about the component generator
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
- component_class (callable, usually a subclass of Component or Pdf or Cdf distribution) – the type of components to be generated
Distributions¶
-
class
salabim.
_Expression
(dis0, dis1, op)¶ expression distribution
This class is only created when using an expression with one ore more distributions.
Note
The randomstream of the distribution(s) in the expression are used.
-
mean
()¶ Returns: Mean of the expression of distribution(s) – returns nan if mean can’t be calculated Return type: float
-
print_info
(as_str=False, file=None)¶ prints information about the expression of distribution(s)
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
sample
()¶ Returns: Sample of the expression of distribution(s) Return type: float
-
-
class
salabim.
Beta
(alpha, beta, randomstream=None)¶ beta distribution
Parameters: - alpha (float) – alpha shape of the distribution
should be >0 - beta (float) – beta shape of the distribution
should be >0 - randomstream (randomstream) – randomstream to be used
if omitted, random will be used
if used as random.Random(12299) it assigns a new stream with the specified seed
-
mean
()¶ Returns: Mean of the distribution Return type: float
-
print_info
(as_str=False, file=None)¶ prints information about the distribution
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
sample
()¶ Returns: Sample of the distribution Return type: float
- alpha (float) – alpha shape of the distribution
-
class
salabim.
Bounded
(dis, lowerbound=None, upperbound=None, fail_value=None, number_of_retries=None, include_lowerbound=None, include_upperbound=None, time_unit=None, env=None)¶ Parameters: - dis (distribution) – distribution to be bounded
- lowerbound (float) – sample values < lowerbound will be rejected (at most 100 retries)
if omitted, no lowerbound check - upperbound (float) – sample values > upperbound will be rejected (at most 100 retries)
if omitted, no upperbound check - fail_value (float) – value to be used if. after number_of_tries retries, sample is still not within bounds
default: lowerbound, if specified, otherwise upperbound - number_of_tries (int) – number of tries before fail_value is returned
default: 100 - include_lowerbound (bool) – if True (default), the lowerbound may be included. if False, the lowerbound will be excluded.
- include_upperbound (bool) – if True (default), the upperbound may be included. if False, the upperbound will be excluded.
- time_unit (str) – specifies the time unit of the lowerbound or upperbound|n|
must be one of “years”, “weeks”, “days”, “hours”, “minutes”, “seconds”, “milliseconds”, “microseconds”
default : no conversion
Note
If, after number_of_tries retries, the sampled value is still not within the given bounds, fail_value will be returned
Samples that cannot be converted to float (only possible with Pdf and CumPdf) are assumed to be within the bounds.-
mean
()¶ Returns: Mean of the expression of bounded distribution – unless no bounds are specified, returns nan Return type: float
-
print_info
(as_str=False, file=None)¶ prints information about the expression of distribution(s)
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
class
salabim.
Cdf
(spec, time_unit=None, randomstream=None, env=None)¶ Cumulative distribution function
Parameters: - spec (list or tuple) –
list with x-values and corresponding cumulative density (x1,c1,x2,c2, …xn,cn)
Requirements:x1<=x2<= …<=xn
c1<=c2<=cn
c1=0
cn>0
all cumulative densities are auto scaled according to cn, so no need to set cn to 1 or 100. - time_unit (str) – specifies the time unit
must be one of “years”, “weeks”, “days”, “hours”, “minutes”, “seconds”, “milliseconds”, “microseconds”
default : no conversion - randomstream (randomstream) – if omitted, random will be used
if used as random.Random(12299) it defines a new stream with the specified seed - env (Environment) – environment where the distribution is defined
if omitted, default_env will be used
-
mean
()¶ Returns: Mean of the distribution Return type: float
-
print_info
(as_str=False, file=None)¶ prints information about the distribution
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
sample
()¶ Returns: Sample of the distribution Return type: float
- spec (list or tuple) –
-
class
salabim.
Constant
(value, time_unit=None, randomstream=None, env=None)¶ constant distribution
Parameters: - value (float) – value to be returned in sample
- time_unit (str) – specifies the time unit
must be one of “years”, “weeks”, “days”, “hours”, “minutes”, “seconds”, “milliseconds”, “microseconds”
default : no conversion - randomstream (randomstream) – randomstream to be used
if omitted, random will be used
if used as random.Random(12299) it assigns a new stream with the specified seed
Note that this is only for compatibility with other distributions - env (Environment) – environment where the distribution is defined
if omitted, default_env will be used
-
mean
()¶ Returns: mean of the distribution (= the specified constant) Return type: float
-
print_info
(as_str=False, file=None)¶ prints information about the distribution
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
sample
()¶ Returns: sample of the distribution (= the specified constant) Return type: float
-
class
salabim.
Distribution
(spec, randomstream=None, time_unit=None)¶ Generate a distribution from a string
Parameters: - spec (str) –
- string containing a valid salabim distribution, where only the first letters are relevant and casing is not important. Note that Erlang, Cdf, CumPdf and Poisson require at least two letters (Er, Cd, Cu and Po)
- string containing one float (c1), resulting in Constant(c1)
- string containing two floats seperated by a comma (c1,c2), resulting in a Uniform(c1,c2)
- string containing three floats, separated by commas (c1,c2,c3), resulting in a Triangular(c1,c2,c3)
- time_unit (str) – Supported time_units:
“years”, “weeks”, “days”, “hours”, “minutes”, “seconds”, “milliseconds”, “microseconds”
if spec has a time_unit as well, this parameter is ignored - randomstream (randomstream) – if omitted, random will be used
if used as random.Random(12299) it assigns a new stream with the specified seed
Note
The randomstream in the specifying string is ignored.
It is possible to use expressions in the specification, as long these are valid within the context of the salabim module, which usually implies a global variable of the salabim package.Examples
Uniform(13) ==> Uniform(13)
Uni(12,15) ==> Uniform(12,15)
UNIF(12,15) ==> Uniform(12,15)
N(12,3) ==> Normal(12,3)
Tri(10,20). ==> Triangular(10,20,15)
10. ==> Constant(10)
12,15 ==> Uniform(12,15)
(12,15) ==> Uniform(12,15)
Exp(a) ==> Exponential(100), provided sim.a=100
E(2) ==> Exponential(2) Er(2,3) ==> Erlang(2,3)-
mean
()¶ Returns: Mean of the distribution Return type: float
-
print_info
(as_str=False, file=None)¶ prints information about the distribution
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
sample
()¶ Returns: Sample of the distribution Return type: any (usually float)
- spec (str) –
-
class
salabim.
Erlang
(shape, rate=None, time_unit=None, scale=None, randomstream=None, env=None)¶ erlang distribution
Parameters: - shape (int) – shape of the distribution (k)
should be >0 - rate (float) – rate parameter (lambda)
if omitted, the scale is used
should be >0 - time_unit (str) – specifies the time unit
must be one of “years”, “weeks”, “days”, “hours”, “minutes”, “seconds”, “milliseconds”, “microseconds”
default : no conversion - scale (float) – scale of the distribution (mu)
if omitted, the rate is used
should be >0 - randomstream (randomstream) – randomstream to be used
if omitted, random will be used
if used as random.Random(12299) it assigns a new stream with the specified seed - env (Environment) – environment where the distribution is defined
if omitted, default_env will be used
Note
Either rate or scale has to be specified, not both.
-
mean
()¶ Returns: Mean of the distribution Return type: float
-
print_info
(as_str=False, file=None)¶ prints information about the distribution
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
sample
()¶ Returns: Sample of the distribution Return type: float
- shape (int) – shape of the distribution (k)
-
class
salabim.
Exponential
(mean=None, time_unit=None, rate=None, randomstream=None, env=None)¶ exponential distribution
Parameters: - mean (float) – mean of the distribtion (beta)|n|
if omitted, the rate is used
must be >0 - time_unit (str) – specifies the time unit
must be one of “years”, “weeks”, “days”, “hours”, “minutes”, “seconds”, “milliseconds”, “microseconds”
default : no conversion - rate (float) – rate of the distribution (lambda)|n|
if omitted, the mean is used
must be >0 - randomstream (randomstream) – randomstream to be used
if omitted, random will be used
if used as random.Random(12299) it assigns a new stream with the specified seed - env (Environment) – environment where the distribution is defined
if omitted, default_env will be used
Note
Either mean or rate has to be specified, not both
-
mean
()¶ Returns: Mean of the distribution Return type: float
-
print_info
(as_str=False, file=None)¶ prints information about the distribution
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
sample
()¶ Returns: Sample of the distribution Return type: float
- mean (float) – mean of the distribtion (beta)|n|
if omitted, the rate is used
-
class
salabim.
External
(dis, *args, **kwargs)¶ External distribution function
This distribution allows distributions from other modules, notably random, numpy.random and scipy.stats to be used as were they salabim distributions.
Parameters: - dis (external distribution) –
either
- random.xxx
- numpy.random.xxx
- scipy.stats.xxx
- random.xxx
- *args (any) – positional arguments to be passed to the dis distribution
- **kwargs (any) – keyword arguments to be passed to the dis distribution
- time_unit (str) – specifies the time unit
must be one of “years”, “weeks”, “days”, “hours”, “minutes”, “seconds”, “milliseconds”, “microseconds”
default : no conversion - env (Environment) – environment where the distribution is defined
if omitted, default_env will be used
-
mean
()¶ Returns: mean of the distribution – only available for scipy.stats distribution. Otherwise nan will be returned. Return type: float
-
print_info
(as_str=False, file=None)¶ prints information about the distribution
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
sample
()¶ Returns: Sample of the distribution via external distribution method Return type: any (usually float)
- dis (external distribution) –
-
class
salabim.
Gamma
(shape, scale=None, time_unit=None, rate=None, randomstream=None, env=None)¶ gamma distribution
Parameters: - shape (float) – shape of the distribution (k)
should be >0 - scale (float) – scale of the distribution (teta)
should be >0 - time_unit (str) – specifies the time unit
must be one of “years”, “weeks”, “days”, “hours”, “minutes”, “seconds”, “milliseconds”, “microseconds”
default : no conversion - rate (float) – rate of the distribution (beta)
should be >0 - randomstream (randomstream) – randomstream to be used
if omitted, random will be used
if used as random.Random(12299) it assigns a new stream with the specified seed
- env : Environment
- environment where the distribution is defined
if omitted, default_env will be used
Note
Either scale or rate has to be specified, not both.
-
mean
()¶ Returns: Mean of the distribution Return type: float
-
print_info
(as_str=False, file=None)¶ prints information about the distribution
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
sample
()¶ Returns: Sample of the distribution Return type: float
- shape (float) – shape of the distribution (k)
-
class
salabim.
Normal
(mean, standard_deviation=None, time_unit=None, coefficient_of_variation=None, use_gauss=False, randomstream=None, env=None)¶ normal distribution
Parameters: - mean (float) – mean of the distribution
- standard_deviation (float) – standard deviation of the distribution
if omitted, coefficient_of_variation, is used to specify the variation if neither standard_devation nor coefficient_of_variation is given, 0 is used, thus effectively a contant distribution
must be >=0 - coefficient_of_variation (float) – coefficient of variation of the distribution
if omitted, standard_deviation is used to specify variation
the resulting standard_deviation must be >=0 - use_gauss (bool) – if False (default), use the random.normalvariate method
if True, use the random.gauss method
the documentation for random states that the gauss method should be slightly faster, although that statement is doubtful. - time_unit (str) – specifies the time unit
must be one of “years”, “weeks”, “days”, “hours”, “minutes”, “seconds”, “milliseconds”, “microseconds”
default : no conversion - randomstream (randomstream) – randomstream to be used
if omitted, random will be used
if used as random.Random(12299) it assigns a new stream with the specified seed - env (Environment) – environment where the distribution is defined
if omitted, default_env will be used
-
mean
()¶ Returns: Mean of the distribution Return type: float
-
print_info
(as_str=False, file=None)¶ prints information about the distribution
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
sample
()¶ Returns: Sample of the distribution Return type: float
-
class
salabim.
Pdf
(spec, probabilities=None, time_unit=None, randomstream=None, env=None)¶ Probability distribution function
Parameters: - spec (list, tuple or dict) –
either
- if no probabilities specified:
list/tuple with x-values and corresponding probability dict where the keys are re x-values and the values are probabilities (x0, p0, x1, p1, …xn,pn) - if probabilities is specified:
list with x-values
- if no probabilities specified:
- probabilities (iterable or float) – if omitted, spec contains the probabilities
the iterable (p0, p1, …pn) contains the probabilities of the corresponding x-values from spec.
alternatively, if a float is given (e.g. 1), all x-values have equal probability. The value is not important. - time_unit (str) – specifies the time unit
must be one of “years”, “weeks”, “days”, “hours”, “minutes”, “seconds”, “milliseconds”, “microseconds”
default : no conversion - randomstream (randomstream) – if omitted, random will be used
if used as random.Random(12299) it assigns a new stream with the specified seed - env (Environment) – environment where the distribution is defined
if omitted, default_env will be used
Note
p0+p1=…+pn>0
all densities are auto scaled according to the sum of p0 to pn, so no need to have p0 to pn add up to 1 or 100.
The x-values can be any type.
If it is a salabim distribution, not the distribution, but a sample will be returned when calling sample.-
mean
()¶ Returns: mean of the distribution – if the mean can’t be calculated (if not all x-values are scalars or distributions), nan will be returned. Return type: float
-
print_info
(as_str=False, file=None)¶ prints information about the distribution
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
sample
(n=None)¶ Parameters: n (number of samples : int) – if not specified, specifies just return one sample, as usual
if specified, return a list of n sampled values from the distribution without replacement. This requires that all probabilities are equal.
If n > number of values in the Pdf distribution, n is assumed to be the number of values in the distribution.
If a sampled value is a distribution, a sample from that distribution will be returned.Returns: Sample of the distribution – In case n is specified, returns a list of n values Return type: any (usually float) or list
- spec (list, tuple or dict) –
-
class
salabim.
Poisson
(mean, randomstream=None)¶ Poisson distribution
Parameters: - mean (float) – mean (lambda) of the distribution
- randomstream (randomstream) – randomstream to be used
if omitted, random will be used
if used as random.Random(12299) it assigns a new stream with the specified seed
Note
The run time of this function increases when mean (lambda) increases.
It is not recommended to use mean (lambda) > 100-
mean
()¶ Returns: Mean of the distribution Return type: float
-
print_info
(as_str=False, file=None)¶ prints information about the distribution
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
sample
()¶ Returns: Sample of the distribution Return type: int
-
class
salabim.
Triangular
(low, high=None, mode=None, time_unit=None, randomstream=None, env=None)¶ triangular distribution
Parameters: - low (float) – lowerbound of the distribution
- high (float) – upperbound of the distribution
if omitted, low will be used, thus effectively a constant distribution
high must be >= low - mode (float) – mode of the distribution
if omitted, the average of low and high will be used, thus a symmetric triangular distribution
mode must be between low and high - time_unit (str) – specifies the time unit
must be one of “years”, “weeks”, “days”, “hours”, “minutes”, “seconds”, “milliseconds”, “microseconds”
default : no conversion - randomstream (randomstream) – randomstream to be used
if omitted, random will be used
if used as random.Random(12299) it assigns a new stream with the specified seed - env (Environment) – environment where the distribution is defined
if omitted, default_env will be used
-
mean
()¶ Returns: Mean of the distribution Return type: float
-
print_info
(as_str=False, file=None)¶ prints information about the distribution
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
sample
()¶ Returns: Sample of the distribtion Return type: float
-
class
salabim.
Uniform
(lowerbound, upperbound=None, time_unit=None, randomstream=None, env=None)¶ uniform distribution
Parameters: - lowerbound (float) – lowerbound of the distribution
- upperbound (float) – upperbound of the distribution
if omitted, lowerbound will be used
must be >= lowerbound - time_unit (str) – specifies the time unit
must be one of “years”, “weeks”, “days”, “hours”, “minutes”, “seconds”, “milliseconds”, “microseconds”
default : no conversion - randomstream (randomstream) – randomstream to be used
if omitted, random will be used
if used as random.Random(12299) it assigns a new stream with the specified seed - env (Environment) – environment where the distribution is defined
if omitted, default_env will be used
-
mean
()¶ Returns: Mean of the distribution Return type: float
-
print_info
(as_str=False, file=None)¶ prints information about the distribution
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
sample
()¶ Returns: Sample of the distribution Return type: float
-
class
salabim.
Weibull
(scale, shape, time_unit=None, randomstream=None, env=None)¶ weibull distribution
Parameters: - scale (float) – scale of the distribution (alpha or k)
- shape (float) – shape of the distribution (beta or lambda)|n| should be >0
- time_unit (str) – specifies the time unit
must be one of “years”, “weeks”, “days”, “hours”, “minutes”, “seconds”, “milliseconds”, “microseconds”
default : no conversion - randomstream (randomstream) – randomstream to be used
if omitted, random will be used
if used as random.Random(12299) it assigns a new stream with the specified seed - env (Environment) – environment where the distribution is defined
if omitted, default_env will be used
-
mean
()¶ Returns: Mean of the distribution Return type: float
-
print_info
(as_str=False, file=None)¶ prints information about the distribution
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
sample
()¶ Returns: Sample of the distribution Return type: float
Environment¶
-
class
salabim.
Environment
(trace=False, random_seed=None, set_numpy_random_seed=True, time_unit='n/a', datetime0=False, name=None, print_trace_header=True, isdefault_env=True, retina=False, do_reset=None, blind_animation=False, *args, **kwargs)¶ environment object
Parameters: - trace (bool or file handle) – defines whether to trace or not
if this a file handle (open for write), the trace output will be sent to this file.
if omitted, False - random_seed (hashable object, usually int) – the seed for random, equivalent to random.seed()
if “*”, a purely random value (based on the current time) will be used (not reproducable)
if the null string, no action on random is taken
if None (the default), 1234567 will be used. - time_unit (str) – Supported time_units:
“years”, “weeks”, “days”, “hours”, “minutes”, “seconds”, “milliseconds”, “microseconds”, “n/a”
default: “n/a” - datetime0 (bool or datetime.datetime) – display time and durations as datetime.datetime/datetime.timedelta
if falsy (default), disabled
if True, the t=0 will correspond to 1 January 1970
if no time_unit is specified, but datetime0 is not falsy, time_unit will be set to seconds - name (str) – name of the environment
if the name ends with a period (.), auto serializing will be applied
if the name end with a comma, auto serializing starting at 1 will be applied
if omitted, the name will be derived from the class (lowercased) or “default environment” if isdefault_env is True. - print_trace_header (bool) – if True (default) print a (two line) header line as a legend
if False, do not print a header
note that the header is only printed if trace=True - isdefault_env (bool) – if True (default), this environment becomes the default environment
if False, this environment will not be the default environment
if omitted, this environment becomes the default environment - set_numpy_random_seed (bool) – if True (default), numpy.random.seed() will be called with the given seed.
This is particularly useful when using External distributions.
If numpy is not installed, this parameter is ignored
if False, numpy.random.seed is not called. - do_reset (bool) – if True, reset the simulation environment
if False, do not reset the simulation environment
if None (default), reset the simulation environment when run under Pythonista, otherwise no reset - blind_animation (bool) – if False (default), animation will be performed as expected
if True, animations will run silently. This is useful to make videos when tkinter is not installed (installable). This is particularly useful when running a simulation on a server. Note that this will show a slight performance increase, when creating videos.
Note
The trace may be switched on/off later with trace
The seed may be later set with random_seed()
Initially, the random stream will be seeded with the value 1234567. If required to be purely, not reproducable, values, use random_seed=”*”.-
an_clocktext
()¶ function to initialize the system clocktext
called by run(), if animation is True.
may be overridden to change the standard behaviour.
function to initialize the menu buttons
may be overridden to change the standard behaviour.
-
an_modelname
()¶ function to show the modelname
may be overridden to change the standard behaviour.
function to initialize the synced buttons
may be overridden to change the standard behaviour.
function to initialize the unsynced buttons
may be overridden to change the standard behaviour.
-
animate
(value=None)¶ animate indicator
Parameters: value (bool) – new animate indicator
if ‘?’, animation will be set, if possible if not specified, no changeReturns: animate status Return type: bool Note
When the run is not issued, no action will be taken.
-
animate3d
(value=None)¶ animate3d indicator
Parameters: value (bool) – new animate3d indicator
if ‘?’, 3D-animation will be set, if possible if not specified, no changeReturns: animate3d status Return type: bool Note
When the animate is not issued, no action will be taken.
-
animate_debug
(value=None)¶ Animate debug
Parameters: value (bool) – animate_debug
default: no change
initially: FalseReturns: animate_debug Return type: bool
-
animation_parameters
(animate=None, synced=None, speed=None, width=None, height=None, title=None, show_menu_buttons=None, x0=None, y0=None, x1=None, background_color=None, foreground_color=None, background3d_color=None, fps=None, modelname=None, use_toplevel=None, show_fps=None, show_time=None, maximum_number_of_bitmaps=None, video=None, video_repeat=None, video_pingpong=None, audio=None, audio_speed=None, animate_debug=None, animate3d=None, width3d=None, height3d=None, video_width=None, video_height=None, video_mode=None, position=None, position3d=None, visible=None)¶ set animation parameters
Parameters: - animate (bool) – animate indicator
new animate indicator
if ‘?’, animation will be set, possible
if not specified, no change - animate3d (bool) – animate3d indicator
new animate3d indicator
if ‘?’, 3D-animation will be set, possible
if not specified, no change - synced (bool) – specifies whether animation is synced
if omitted, no change. At init of the environment synced will be set to True - speed (float) – speed
specifies how much faster or slower than real time the animation will run. e.g. if 2, 2 simulation time units will be displayed per second. - width (int) – width of the animation in screen coordinates
if omitted, no change. At init of the environment, the width will be set to 1024 for non Pythonista and the current screen width for Pythonista. - height (int) – height of the animation in screen coordinates
if omitted, no change. At init of the environment, the height will be set to 768 for non Pythonista and the current screen height for Pythonista. - position (tuple(x,y)) – position of the animation window
if omitted, no change. At init of the environment, the position will be set to (0, 0)
no effect for Pythonista - width3d (int) – width of the 3d animation in screen coordinates
if omitted, no change. At init of the environment, the 3d width will be set to 1024. - height3d (int) – height of the 3d animation in screen coordinates
if omitted, no change. At init of the environment, the 3d height will be set to 768. - position3d (tuple(x,y)) – position of the 3d animation window
At init of the environment, the position will be set to (0, 0)
This has to be set before the 3d animation starts as the window can only be postioned at initialization - title (str) – title of the canvas window
if omitted, no change. At init of the environment, the title will be set to salabim.
if “”, the title will be suppressed. - x0 (float) – user x-coordinate of the lower left corner
if omitted, no change. At init of the environment, x0 will be set to 0. - y0 (float) – user y_coordinate of the lower left corner
if omitted, no change. At init of the environment, y0 will be set to 0. - x1 (float) – user x-coordinate of the lower right corner
if omitted, no change. At init of the environment, x1 will be set to 1024 for non Pythonista and the current screen width for Pythonista. - background_color (colorspec) – color of the background
if omitted, no change. At init of the environment, this will be set to white. - foreground_color (colorspec) – color of foreground (texts)
if omitted and background_color is specified, either white of black will be used, in order to get a good contrast with the background color.
if omitted and background_color is also omitted, no change. At init of the environment, this will be set to black. - background3d_color (colorspec) – color of the 3d background
if omitted, no change. At init of the environment, this will be set to black. - fps (float) – number of frames per second
- modelname (str) – name of model to be shown in upper left corner,
along with text “a salabim model”
if omitted, no change. At init of the environment, this will be set to the null string, which implies suppression of this feature. - use_toplevel (bool) – if salabim animation is used in parallel with
other modules using tkinter, it might be necessary to
initialize the root with tkinter.TopLevel().
In that case, set this parameter to True.
if False (default), the root will be initialized with tkinter.Tk() - show_fps (bool) – if True, show the number of frames per second
if False, do not show the number of frames per second (default) - show_time (bool) – if True, show the time (default)
if False, do not show the time - show_menu_buttons (bool) – if True, show the menu buttons (default)
if False, do not show the menu buttons - maximum_number_of_bitmaps (int) – maximum number of tkinter bitmaps (default 4000)
- video (str) – if video is not omitted, a video with the name video
will be created.
Normally, use .mp4 as extension.
If the extension is .gif or .png an animated gif / png file will be written, unless there is a * in the filename
If the extension is .gif, .jpg, .png, .bmp, .ico or .tiff and one * appears in the filename, individual frames will be written with a six digit sequence at the place of the asteriks in the file name. If the video extension is not .gif, .jpg, .png, .bmp, .ico or .tiff, a codec may be added by appending a plus sign and the four letter code name, like “myvideo.avi+DIVX”.
If no codec is given, MJPG will be used for .avi files, otherwise .mp4v
Under PyDroid only .avi files are supported. - video_repeat (int) – number of times animated gif or png should be repeated
0 means inifinite
at init of the environment video_repeat is 1
this only applies to gif and png files production. - video_pingpong (bool) – if True, all frames will be added reversed at the end of the video (useful for smooth loops)
at init of the environment video_pingpong is False
this only applies to gif and png files production. - audio (str) – name of file to be played (mp3 or wav files)
if the none string, the audio will be stopped
default: no change
for more information, see Environment.audio() - visible (bool) – if True (start condition), the animation window will be visible
if False, the animation window will be hidden (‘withdrawn’)
Note
The y-coordinate of the upper right corner is determined automatically in such a way that the x and y scaling are the same.
- animate (bool) – animate indicator
-
animation_post_tick
(t)¶ called just after the animation object loop.
Default behaviour: just returnParameters: t (float) – Current (animation) time.
-
animation_pre_tick
(t)¶ called just before the animation object loop.
Default behaviour: just returnParameters: t (float) – Current (animation) time.
-
audio
(filename)¶ Play audio during animation
Parameters: filename (str) – name of file to be played (mp3 or wav files)
if “”, the audio will be stopped
optionaly, a start time in seconds may be given by appending the filename a > followed by the start time, like ‘mytune.mp3>12.5’ if not specified (None), no changeReturns: filename being played (“” if nothing is being played) Return type: str Note
Only supported on Windows and Pythonista platforms. On other platforms, no effect.
Variable bit rate mp3 files may be played incorrectly on Windows platforms. Try and use fixed bit rates (e.g. 128 or 320 kbps)
-
audio_speed
(value=None)¶ Play audio during animation
Parameters: value (float) – animation speed at which the audio should be played
default: no change
initially: 1Returns: speed being played Return type: int
-
background3d_color
(value=None)¶ background3d_color of the animation
Parameters: value (colorspec) – new background_color
if not specified, no changeReturns: background3d_color of animation Return type: colorspec
-
background_color
(value=None)¶ background_color of the animation
Parameters: value (colorspec) – new background_color
if not specified, no changeReturns: background_color of animation Return type: colorspec
-
base_name
()¶ returns the base name of the environment (the name used at initialization)
-
beep
()¶ Beeps
Works only on Windows and iOS (Pythonista). For other platforms this is just a dummy method.
-
camera_auto_print
(value=None)¶ queries or set camera_auto_print
Parameters: value (boolean) – if None (default), no action
if True, camera_print will be called on each camera control keypress
if False, no automatic camera_printReturns: Current status Return type: bool Note
The camera_auto_print functionality is useful to get the spec for camera_move()
-
camera_move
(spec='', lag=1, offset=0, enabled=True)¶ Moves the camera according to the given spec, which is normally a collection of camera_print outputs.
Parameters: - spec (str) – output normally obtained from camera_auto_print lines
- lag (float) – lag time (for smooth camera movements) (default: 1))
- offset (float) – the duration (can be negative) given is added to the times given in spec. Default: 0
- enabled (bool) – if True (default), move camera according to spec/lag
if False, freeze camera movement
-
color_interp
(x, xp, fp)¶ linear interpolation of a color
Parameters: - x (float) – target x-value
- xp (list of float, tuples or lists) – values on the x-axis
- fp (list of colorspecs) – values on the y-axis
should be same length as xp
Returns: interpolated color value
Return type: tuple
Notes
If x < xp[0], fp[0] will be returned
If x > xp[-1], fp[-1] will be returned
-
colorinterpolate
(t, t0, t1, v0, v1)¶ does linear interpolation of colorspecs
Parameters: - t (float) – value to be interpolated from
- t0 (float) – f(t0)=v0
- t1 (float) – f(t1)=v1
- v0 (colorspec) – f(t0)=v0
- v1 (colorspec) – f(t1)=v1
Returns: linear interpolation between v0 and v1 based on t between t0 and t
Return type: colorspec
Note
Note that no extrapolation is done, so if t<t0 ==> v0 and t>t1 ==> v1
This function is heavily used during animation
-
colorspec_to_tuple
(colorspec)¶ translates a colorspec to a tuple
Parameters: colorspec (tuple, list or str) – #rrggbb
==> alpha = 255 (rr, gg, bb in hex)
#rrggbbaa
==> alpha = aa (rr, gg, bb, aa in hex)
colorname
==> alpha = 255
(colorname, alpha)
(r, g, b)
==> alpha = 255
(r, g, b, alpha)
"fg"
==> foreground_color
"bg"
==> background_colorReturns: Return type: (r, g, b, a)
-
datetime0
(datetime0=None)¶ Gets and/or sets datetime0
Parameters: datetime0 (bool or datetime.datetime) – if omitted, nothing will be set
if falsy, disabled
if True, the t=0 will correspond to 1 January 1970
if no time_unit is specified, but datetime0 is not falsy, time_unit will be set to secondsReturns: current value of datetime0 Return type: bool or datetime.datetime
-
datetime_to_t
(datetime)¶ Parameters: datetime (datetime.datetime) – Returns: datetime translated to simulation time in the current time_unit Return type: float Raises: ValueError
– if datetime0 is False
-
days
(t)¶ convert the given time in days to the current time unit
Parameters: t (float or distribution) – time in days
if distribution, the distribution is sampledReturns: time in days, converted to the current time_unit Return type: float
-
duration_to_str
(duration)¶ Parameters: duration (float) – duration to be converted to string in trace Returns: duration in required format – default: f”{duration:.3f}” if datetime0 is False or duration in the format “hh:mm:dd” or “d hh:mm:ss” Return type: str Note
May be overrridden.
-
duration_to_timedelta
(duration)¶ Parameters: duration (float) – Returns: timedelta corresponding to duration Return type: datetime.timedelta Raises: ValueError
– if time unit is not set
-
foreground_color
(value=None)¶ foreground_color of the animation
Parameters: value (colorspec) – new foreground_color
if not specified, no changeReturns: foreground_color of animation Return type: colorspec
-
fps
(value=None)¶ Parameters: value (int) – new fps
if not specified, no changeReturns: fps Return type: bool
-
get_time_unit
()¶ gets time unit
Returns: Current time unit dimension (default “n/a”) Return type: str
-
height
(value=None)¶ height of the animation in screen coordinates
Parameters: value (int) – new height
if not specified, no changeReturns: height of animation Return type: int
-
height3d
(value=None)¶ height of the 3d animation in screen coordinates
Parameters: value (int) – new 3d height
if not specified, no changeReturns: height of 3d animation Return type: int
-
hours
(t)¶ convert the given time in hours to the current time unit
Parameters: t (float or distribution) – time in hours
if distribution, the distribution is sampledReturns: time in hours, converted to the current time_unit Return type: float
-
insert_frame
(image, number_of_frames=1)¶ Insert image as frame(s) into video
Parameters: - image (Pillow image, str or Path object) – Image to be inserted
- nuumber_of_frames (int) – Number of 1/30 second long frames to be inserted
-
is_dark
(colorspec)¶ Parameters: colorspec (colorspec) – color to check Returns: True, if the colorspec is dark (rather black than white)
False, if the colorspec is light (rather white than black
if colorspec has alpha=0 (total transparent), the background_color will be testedReturn type: bool
-
is_videoing
()¶ video recording status
Returns: video recording status – True, if video is being recorded
False, otherwiseReturn type: bool
-
maximum_number_of_bitmaps
(value=None)¶ maximum number of bitmaps (applies to animation with tkinter only)
Parameters: value (int) – new maximum_number_of_bitmaps
if not specified, no changeReturns: maximum number of bitmaps Return type: int
-
microseconds
(t)¶ convert the given time in microseconds to the current time unit
Parameters: t (float or distribution) – time in microseconds
if distribution, the distribution is sampledReturns: time in microseconds, converted to the current time_unit Return type: float
-
milliseconds
(t)¶ convert the given time in milliseconds to the current time unit
Parameters: t (float or distribution) – time in milliseconds
if distribution, the distribution is sampledReturns: time in milliseconds, converted to the current time_unit Return type: float
-
minutes
(t)¶ convert the given time in minutes to the current time unit
Parameters: t (float or distribution) – time in minutes
if distribution, the distribution is sampledReturns: time in minutes, converted to the current time_unit Return type: float
-
modelname
(value=None)¶ Parameters: value (str) – new modelname
if not specified, no changeReturns: modelname Return type: str Note
If modelname is the null string, nothing will be displayed.
-
name
(value=None)¶ Parameters: value (str) – new name of the environment if omitted, no change Returns: Name of the environment Return type: str Note
base_name and sequence_number are not affected if the name is changed
-
now
()¶ Returns: the current simulation time Return type: float
-
peek
()¶ returns the time of the next component to become current
if there are no more events, peek will return inf
Only for advance use with animation / GUI event loops
-
position
(value=None)¶ position of the animation window
Parameters: value (tuple (x, y)) – new position
if not specified, no changeReturns: position of animation window Return type: tuple (x,y)
-
position3d
(value=None)¶ position of the 3d animation window
Parameters: value (tuple (x, y)) – new position
if not specified, no changeReturns: position of th 3d animation window Return type: tuple (x,y) Note
This must be given before the 3d animation is started.
-
print_info
(as_str=False, file=None)¶ prints information about the environment
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
print_trace
(s1='', s2='', s3='', s4='', s0=None, _optional=False)¶ prints a trace line
Parameters: - s1 (str) – part 1 (usually formatted now), padded to 10 characters
- s2 (str) – part 2 (usually only used for the compoent that gets current), padded to 20 characters
- s3 (str) – part 3, padded to 35 characters
- s4 (str) – part 4
- s0 (str) – part 0. if omitted, the line number from where the call was given will be used at the start of the line. Otherwise s0, left padded to 7 characters will be used at the start of the line.
- _optional (bool) – for internal use only. Do not set this flag!
Note
if self.trace is False, nothing is printed
if the current component’s suppress_trace is True, nothing is printed
-
print_trace_header
()¶ print a (two line) header line as a legend
also the legend for line numbers will be printed
not that the header is only printed if trace=True
-
reset_now
(new_now=0)¶ reset the current time
Parameters: new_now (float or distribution) – now will be set to new_now
default: 0
if distribution, the distribution is sampledNote
Internally, salabim still works with the ‘old’ time. Only in the interface from and to the user program, a correction will be applied.
The registered time in monitors will be always is the ‘old’ time. This is only relevant when using the time value in Monitor.xt() or Monitor.tx().
-
run
(duration=None, till=None, priority=inf, urgent=False, cap_now=None)¶ start execution of the simulation
Parameters: - duration (float or distribution) – schedule with a delay of duration
if 0, now is used
if distribution, the distribution is sampled - till (float or distribution) – schedule time
if omitted, inf is assumed. See also note below
if distribution, the distribution is sampled - priority (float) – priority
default: inf
if a component has the same time on the event list, main is sorted accoring to the priority. The default value of inf makes that all components will finish before the run is ended - urgent (bool) – urgency indicator
if False (default), main will be scheduled behind all other components scheduled with the same time and priority
if True, main will be scheduled in front of all components scheduled for the same time and priority - cap_now (bool) – indicator whether times (till, duration) in the past are allowed. If, so now() will be used. default: sys.default_cap_now(), usualy False
Note
if neither till nor duration is specified, the main component will be reactivated at the time there are no more events on the eventlist, i.e. possibly not at inf.
if you want to run till inf (particularly when animating), issue run(sim.inf)
only issue run() from the main level- duration (float or distribution) – schedule with a delay of duration
-
scale
()¶ scale of the animation, i.e. width / (x1 - x0)
Returns: scale Return type: float Note
It is not possible to set this value explicitely.
-
screen_to_user_coordinates_size
(screensize)¶ converts a screen size to a value to be used with user coordinates
Parameters: screensize (float) – screen size to be converted Returns: value corresponding with screensize in user coordinates Return type: float
-
screen_to_user_coordinates_x
(screenx)¶ converts a screen x coordinate to a user x coordinate
Parameters: screenx (float) – screen x coordinate to be converted Returns: user x coordinate Return type: float
-
screen_to_user_coordinates_y
(screeny)¶ converts a screen x coordinate to a user x coordinate
Parameters: screeny (float) – screen y coordinate to be converted Returns: user y coordinate Return type: float
-
seconds
(t)¶ convert the given time in seconds to the current time unit
Parameters: t (float or distribution) – time in seconds
if distribution, the distribution is sampledReturns: time in secoonds, converted to the current time_unit Return type: float
-
sequence_number
()¶ Returns: sequence_number of the environment – (the sequence number at initialization)
normally this will be the integer value of a serialized name, but also non serialized names (without a dot or a comma at the end) will be numbered)Return type: int
-
setup
()¶ called immediately after initialization of an environment.
by default this is a dummy method, but it can be overridden.
only keyword arguments are passed
-
show_camera_position
(over3d=None)¶ show camera position on the tkinter window or over3d window
The 7 camera settings will be shown in the top left corner.
Parameters: over3d (bool) – if False (default), present on 2D screen
if True, present on 3D overlay
-
show_fps
(value=None)¶ Parameters: value (bool) – new show_fps
if not specified, no changeReturns: show_fps Return type: bool
controls menu buttons
Parameters: value (bool) – if True, menu buttons are shown
if False, menu buttons are hidden
if not specified, no changeReturns: show menu button status Return type: bool
-
show_time
(value=None)¶ Parameters: value (bool) – new show_time
if not specified, no changeReturns: show_time Return type: bool
-
snapshot
(filename, video_mode='2d')¶ Takes a snapshot of the current animated frame (at time = now()) and saves it to a file
Parameters: - filename (str) – file to save the current animated frame to.
The following formats are accepted: .png, .jpg, .bmp, .ico, .gif and .tiff. Other formats are not possible. Note that, apart from .JPG files. the background may be semi transparent by setting the alpha value to something else than 255. - video_mode (str) – specifies what to save
if “2d” (default), the tkinter window will be saved
if “3d”, the OpenGL window will be saved (provided animate3d is True)
if “screen” the complete screen will be saved (no need to be in animate mode)|n| no scaling will be applied.
- filename (str) – file to save the current animated frame to.
-
speed
(value=None)¶ Parameters: value (float) – new speed
if not specified, no changeReturns: speed Return type: float
-
step
()¶ executes the next step of the future event list
for advanced use with animation / GUI loops
-
suppress_trace_linenumbers
(value=None)¶ indicates whether line numbers should be suppressed (False by default)
Parameters: value (bool) – new suppress_trace_linenumbers status
if omitted, no changeReturns: suppress_trace_linenumbers status Return type: bool Note
By default, suppress_trace_linenumbers is False, meaning that line numbers are shown in the trace. In order to improve performance, line numbers can be suppressed.
-
suppress_trace_standby
(value=None)¶ suppress_trace_standby status
Parameters: value (bool) – new suppress_trace_standby status
if omitted, no changeReturns: suppress trace status Return type: bool Note
By default, suppress_trace_standby is True, meaning that standby components are (apart from when they become non standby) suppressed from the trace.
If you set suppress_trace_standby to False, standby components are fully traced.
-
synced
(value=None)¶ Parameters: value (bool) – new synced
if not specified, no changeReturns: synced Return type: bool
-
t
()¶ Returns: the current simulation animation time Return type: float
-
t_to_datetime
(t)¶ Parameters: t (float) – time to convert Returns: t (in the current time unit) translated to the corresponding datetime Return type: float Raises: ValueError
– if datetime0 is False
-
time_to_str
(t)¶ Parameters: t (float) – time to be converted to string in trace and animation Returns: t in required format – default: f”{t:10.3f}” if datetime0 is False
or date in the format “Day YYYY-MM-DD hh:mm:dd” otherwiseReturn type: str Note
May be overrridden. Make sure that the method always returns the same length!
-
timedelta_to_duration
(timedelta)¶ Parameters: timedelta (datetime.timedelta) – Returns: timedelta translated to simulation duration in the current time_unit Return type: float Raises: ValueError
– if datetime0 is False
-
title
(value=None)¶ title of the canvas window
Parameters: value (str) – new title
if “”, the title will be suppressed
if not specified, no changeReturns: title of canvas window Return type: str Note
No effect for Pythonista
-
to_days
(t)¶ convert time t to days
Parameters: t (float or distribution) – time to be converted
if distribution, the distribution is sampledReturns: Time t converted to days Return type: float
-
to_hours
(t)¶ convert time t to hours
Parameters: t (float or distribution) – time to be converted
if distribution, the distribution is sampledReturns: Time t converted to hours Return type: float
-
to_microseconds
(t)¶ convert time t to microseconds
Parameters: t (float or distribution) – time to be converted
if distribution, the distribution is sampledReturns: Time t converted to microseconds Return type: float
-
to_milliseconds
(t)¶ convert time t to milliseconds
Parameters: t (float or distribution) – time to be converted
if distribution, the distribution is sampledReturns: Time t converted to milliseconds Return type: float
-
to_minutes
(t)¶ convert time t to minutes
Parameters: t (float or distribution) – time to be converted
if distribution, the distribution is sampledReturns: Time t converted to minutes Return type: float
-
to_seconds
(t)¶ convert time t to seconds
Parameters: t (float or distribution) – time to be converted
if distribution, the distribution is sampledReturns: Time t converted to seconds Return type: float
-
to_time_unit
(time_unit, t)¶ convert time t to the time_unit specified
Parameters: - time_unit (str) – Supported time_units:
“years”, “weeks”, “days”, “hours”, “minutes”, “seconds”, “milliseconds”, “microseconds” - t (float or distribution) – time to be converted
if distribution, the distribution is sampled
Returns: Time t converted to the time_unit specified
Return type: float
- time_unit (str) – Supported time_units:
-
to_weeks
(t)¶ convert time t to weeks
Parameters: t (float or distribution) – time to be converted
if distribution, the distribution is sampledReturns: Time t converted to weeks Return type: float
-
to_years
(t)¶ convert time t to years
Parameters: t (float or distribution) – time to be converted
if distribution, the distribution is sampledReturns: Time t converted to years Return type: float
-
trace
(value=None)¶ trace status
Parameters: value (bool of file handle) – new trace status
defines whether to trace or not
if this a file handle (open for write), the trace output will be sent to this file.
if omitted, no changeReturns: trace status Return type: bool or file handle Note
If you want to test the status, always include parentheses, like
if env.trace():
-
user_to_screen_coordinates_size
(usersize)¶ converts a user size to a value to be used with screen coordinates
Parameters: usersize (float) – user size to be converted Returns: value corresponding with usersize in screen coordinates Return type: float
-
user_to_screen_coordinates_x
(userx)¶ converts a user x coordinate to a screen x coordinate
Parameters: userx (float) – user x coordinate to be converted Returns: screen x coordinate Return type: float
-
user_to_screen_coordinates_y
(usery)¶ converts a user x coordinate to a screen x coordinate
Parameters: usery (float) – user y coordinate to be converted Returns: screen y coordinate Return type: float
-
video
(value)¶ video name
Parameters: value (str, list or tuple) – new video name
for explanation see animation_parameters()Note
If video is the null string ro None, the video (if any) will be closed.
The call can be also used as a context manager, which automatically opens and closes a file. E.g.with video("test.mp4"): env.run(100)
-
video_close
()¶ closes the current animation video recording, if any.
-
video_height
(value=None)¶ height of the video animation in screen coordinates
Parameters: value (int) – new width
if not specified, no changeReturns: height of video animation Return type: int
-
video_mode
(value=None)¶ Parameters: value (int) – new video mode (“2d”, “3d” or “screen”)
if not specified, no changeReturns: video_mode Return type: int
-
video_pingpong
(value=None)¶ video pingpong
Parameters: value (bool) – new video pingpong
if not specified, no changeReturns: video pingpong Return type: bool Note
Applies only to gif animation.
-
video_repeat
(value=None)¶ video repeat
Parameters: value (int) – new video repeat
if not specified, no changeReturns: video repeat Return type: int Note
Applies only to gif animation.
-
video_width
(value=None)¶ width of the video animation in screen coordinates
Parameters: value (int) – new width
if not specified, no changeReturns: width of video animation Return type: int
-
visible
(value=None)¶ controls visibility of the animation window
Parameters: value (bool) – if True, the animation window will be visible
if False, the animation window will be hidden (‘withdrawn’) if None (default), no changeReturns: current visibility Return type: bool
-
weeks
(t)¶ convert the given time in weeks to the current time unit
Parameters: t (float or distribution) – time in weeks
if distribution, the distribution is sampledReturns: time in weeks, converted to the current time_unit Return type: float
-
width
(value=None)¶ width of the animation in screen coordinates
Parameters: value (int) – new width
if not specified, no changeReturns: width of animation Return type: int
-
width3d
(value=None)¶ width of the 3d animation in screen coordinates
Parameters: value (int) – new 3d width
if not specified, no changeReturns: width of 3d animation Return type: int
-
x0
(value=None)¶ x coordinate of lower left corner of animation
Parameters: value (float) – new x coordinate Returns: x coordinate of lower left corner of animation Return type: float
-
x1
(value=None)¶ x coordinate of upper right corner of animation : float
Parameters: value (float) – new x coordinate
if not specified, no changeReturns: x coordinate of upper right corner of animation Return type: float
-
y0
(value=None)¶ y coordinate of lower left corner of animation
Parameters: value (float) – new y coordinate
if not specified, no changeReturns: y coordinate of lower left corner of animation Return type: float
-
y1
()¶ y coordinate of upper right corner of animation
Returns: y coordinate of upper right corner of animation Return type: float Note
It is not possible to set this value explicitely.
-
years
(t)¶ convert the given time in years to the current time unit
Parameters: t (float or distribution) – time in years
if distribution, the distribution is sampledReturns: time in years, converted to the current time_unit Return type: float
- trace (bool or file handle) – defines whether to trace or not
ItemFile¶
-
class
salabim.
ItemFile
(filename)¶ define an item file to be used with read_item, read_item_int, read_item_float and read_item_bool
Parameters: filename (str) – file to be used for subsequent read_item, read_item_int, read_item_float and read_item_bool calls
or
content to be interpreted used in subsequent read_item calls. The content should have at least one linefeed character and will be usually triple quoted.Note
It is advised to use ItemFile with a context manager, like
with sim.ItemFile("experiment0.txt") as f: run_length = f.read_item_float() |n| run_name = f.read_item() |n|
Alternatively, the file can be opened and closed explicitely, like
f = sim.ItemFile("experiment0.txt") run_length = f.read_item_float() run_name = f.read_item() f.close()
Item files consist of individual items separated by whitespace (blank or tab)|n| If a blank or tab is required in an item, use single or double quotes
All text following # on a line is ignored
All texts on a line within curly brackets {} is ignored and considered white space.
Curly braces cannot spawn multiple lines and cannot be nested.Example
Item1 "Item 2" Item3 Item4 # comment Item5 {five} Item6 {six} 'Double quote" in item' "Single quote' in item" True
-
read_item
()¶ read next item from the ItemFile
if the end of file is reached, EOFError is raised
-
read_item_bool
()¶ read next item from the ItemFile as bool
A value of False (not case sensitive) will return False
A value of 0 will return False
The null string will return False
Any other value will return Trueif the end of file is reached, EOFError is raised
-
read_item_float
()¶ read next item from the ItemFile as float
if the end of file is reached, EOFError is raised
-
read_item_int
()¶ read next field from the ItemFile as int.h
if the end of file is reached, EOFError is raised
-
Monitor¶
-
class
salabim.
Monitor
(name=None, monitor=True, level=False, initial_tally=None, type=None, weight_legend=None, fill=None, stats_only=False, env=None, *args, **kwargs)¶ Monitor object
Parameters: - name (str) – name of the monitor
if the name ends with a period (.), auto serializing will be applied
if the name end with a comma, auto serializing starting at 1 will be applied
if omitted, the name will be derived from the class it is defined in (lowercased) - monitor (bool) – if True (default), monitoring will be on.
if False, monitoring is disabled
it is possible to control monitoring later, with the monitor method - level (bool) – if False (default), individual values are tallied, optionally with weight
if True, the tallied vslues are interpreted as levels - initial_tally (any, preferably int, float or translatable into int or float) – initial value for the a level monitor
it is important to set the value correctly. default: 0
not available for non level monitors - type (str) –
- specifies how tallied values are to be stored
- ”any” (default) stores values in a list. This allows
- non numeric values. In calculations the values are forced to a numeric value (0 if not possible)
- ”bool” (True, False) Actually integer >= 0 <= 255 1 byte
- ”int8” integer >= -128 <= 127 1 byte
- ”uint8” integer >= 0 <= 255 1 byte
- ”int16” integer >= -32768 <= 32767 2 bytes
- ”uint16” integer >= 0 <= 65535 2 bytes
- ”int32” integer >= -2147483648<= 2147483647 4 bytes
- ”uint32” integer >= 0 <= 4294967295 4 bytes
- ”int64” integer >= -9223372036854775808 <= 9223372036854775807 8 bytes
- ”uint64” integer >= 0 <= 18446744073709551615 8 bytes
- ”float” float 8 bytes
- weight_legend (str) – used in print_statistics and print_histogram to indicate the dimension of weight or duration (for level monitors, e.g. minutes. Default: weight for non level monitors, duration for level monitors.
- stats_only (bool) – if True, only statistics will be collected (using less memory, but also less functionality)
if False (default), full functionality - fill (list or tuple) – can be used to fill the tallied values (all at time now).
fill is only available for non level and not stats_only monitors. - env (Environment) – environment where the monitor is defined
if omitted, default_env will be used
-
animate
(*args, **kwargs)¶ animates the monitor in a panel
Parameters: - linecolor (colorspec) – color of the line or points (default foreground color)
- linewidth (int) – width of the line or points (default 1 for level, 3 for non level monitors)
- fillcolor (colorspec) – color of the panel (default transparent)
- bordercolor (colorspec) – color of the border (default foreground color)
- borderlinewidth (int) – width of the line around the panel (default 1)
- nowcolor (colorspec) – color of the line indicating now (default red)
- titlecolor (colorspec) – color of the title (default foreground color)
- titlefont (font) – font of the title (default null string)
- titlefontsize (int) – size of the font of the title (default 15)
- title (str) – title to be shown above panel
default: name of the monitor - x (int) – x-coordinate of panel, relative to xy_anchor, default 0
- y (int) – y-coordinate of panel, relative to xy_anchor. default 0
- offsetx (float) – offsets the x-coordinate of the panel (default 0)
- offsety (float) – offsets the y-coordinate of the panel (default 0)
- angle (float) – rotation angle in degrees, default 0
- xy_anchor (str) – specifies where x and y are relative to
possible values are (default: sw):
nw n ne
w c e
sw s se
- vertical_offset (float) –
- the vertical position of x within the panel is
- vertical_offset + x * vertical_scale (default 0)
- vertical_scale (float) – the vertical position of x within the panel is vertical_offset + x * vertical_scale (default 5)
- horizontal_scale (float) – the relative horizontal position of time t within the panel is on t * horizontal_scale, possibly shifted (default 1)|n|
- width (int) – width of the panel (default 200)
- height (int) – height of the panel (default 75)
- vertical_map (function) – when a y-value has to be plotted it will be translated by this function
default: float
when the function results in a TypeError or ValueError, the value 0 is assumed
when y-values are non numeric, it is advised to provide an approriate map function, like:
vertical_map = “unknown red green blue yellow”.split().index - labels (iterable) – labels to be shown on the vertical axis (default: empty tuple)
the placement of the labels is controlled by the vertical_map method - label_color (colorspec) – color of labels (default: foreground color)
- label_font (font) – font of the labels (default null string)
- label_fontsize (int) – size of the font of the labels (default 15)
- label_anchor (str) – specifies where the label coordinates (as returned by map_value) are relative to
possible values are (default: e):
nw n ne
w c e
sw s se
- label_offsetx (float) – offsets the x-coordinate of the label (default 0)
- label_offsety (float) – offsets the y-coordinate of the label (default 0)
- label_linewidth (int) – width of the label line (default 1)
- label_linecolor (colorspec) – color of the label lines (default foreground color)
- layer (int) – layer (default 0)
- as_points (bool) – allows to override the as_points setting of tallies, which is by default False for level monitors and True for non level monitors
- parent (Component) – component where this animation object belongs to (default None)
if given, the animation object will be removed automatically when the parent component is no longer accessible - screen_coordinates (bool) – use screen_coordinates
normally, the scale parameters are use for positioning and scaling objects.
if True, screen_coordinates will be used instead. - over3d (bool) – if True, this object will be rendered to the OpenGL window
if False (default), the normal 2D plane will be used.
Returns: reference to AnimateMonitor object
Return type: Note
All measures are in screen coordinates
Note
It is recommended to use sim.AnimateMonitor instead
All measures are in screen coordinates
-
base_name
()¶ Returns: base name of the monitor (the name used at initialization) Return type: str
-
bin_duration
(lowerbound, upperbound)¶ total duration of tallied values in range (lowerbound,upperbound]
Parameters: - lowerbound (float) – non inclusive lowerbound
- upperbound (float) – inclusive upperbound
- ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes
Returns: total duration of values >lowerbound and <=upperbound
Return type: int
Note
Not available for level monitors
-
bin_number_of_entries
(lowerbound, upperbound, ex0=False)¶ count of the number of tallied values in range (lowerbound,upperbound]
Parameters: - lowerbound (float) – non inclusive lowerbound
- upperbound (float) – inclusive upperbound
- ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes
Returns: number of values >lowerbound and <=upperbound
Return type: int
Note
Not available for level monitors
-
bin_weight
(lowerbound, upperbound)¶ total weight of tallied values in range (lowerbound,upperbound]
Parameters: - lowerbound (float) – non inclusive lowerbound
- upperbound (float) – inclusive upperbound
- ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes
Returns: total weight of values >lowerbound and <=upperbound
Return type: int
Note
Not available for level monitors
-
deregister
(registry)¶ deregisters the monitor in the registry
Parameters: registry (list) – list of registered objects Returns: monitor (self) Return type: Monitor
-
duration
(ex0=False)¶ total duration
Parameters: ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes Returns: total duration Return type: float Note
Not available for non level monitors
-
duration_zero
()¶ total duratiom of zero entries
Returns: total duration of zero entries Return type: float Note
Not available for non level monitors
-
freeze
(name=None)¶ freezes this monitor (particularly useful for pickling)
Parameters: name (str) – name of the frozen monitor
default: name of this monitor + “.frozen”Returns: frozen monitor Return type: Monitor Notes
The env attribute will become a partial copy of the original environment, with the name of the original environment, padded with ‘.copy.<serial number>’
-
get
(t=None)¶ get the value of a level monitor
Parameters: t (float) – time at which the value of the level is to be returned
default: nowReturns: last tallied value – Instead of this method, the level monitor can also be called directly, like level = sim.Monitor(“level”, level=True)
…
print(level())
print(level.get()) # identicalReturn type: any, usually float Note
If the value is not available, self.off will be returned.
Only available for level monitors
-
histogram_autoscale
(ex0=False)¶ used by histogram_print to autoscale
may be overridden.Parameters: ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes Returns: bin_width, lowerbound, number_of_bins Return type: tuple
-
maximum
(ex0=False)¶ maximum of tallied values
Parameters: ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes Returns: maximum Return type: float
-
mean
(ex0=False)¶ mean of tallied values
Parameters: ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes Returns: mean Return type: float Note
If weights are applied , the weighted mean is returned
-
median
(ex0=False, interpolation='linear')¶ median of tallied values
Parameters: - ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes
- interpolation (str) – Default: ‘linear’
For non weighted monitors:
This optional parameter specifies the interpolation method to use when the 50% percentile lies between two data points i < j:
‘linear’: i + (j - i) * fraction, where fraction is the fractional part of the index surrounded by i and j. (default for monitors that are not weighted not level|n| ‘lower’: i.
‘higher’: j. (default for weighted and level monitors)
‘nearest’: i or j, whichever is nearest.
‘midpoint’: (i + j) / 2.
For weighted and level monitors:
This optional parameter specifies the interpolation method to use when the 50% percentile corresponds exactly to two data points i and j
‘linear’: (i + j) /2
‘lower’: i.
‘higher’: j
‘midpoint’: (i + j) / 2.
Returns: median (50% percentile)
Return type: float
-
merge
(*monitors, **kwargs)¶ merges this monitor with other monitor(s)
Parameters: - monitors (sequence) – zero of more monitors to be merged to this monitor
- name (str) – name of the merged monitor
default: name of this monitor + “.merged”
Returns: merged monitor
Return type: Note
Level monitors can only be merged with level monitors
Non level monitors can only be merged with non level monitors
Only monitors with the same type can be merged
If no monitors are specified, a copy is created.
For level monitors, merging means summing the available x-values|n|
-
minimum
(ex0=False)¶ minimum of tallied values
Parameters: ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes Returns: minimum Return type: float
-
monitor
(value=None)¶ enables/disables monitor
Parameters: value (bool) – if True, monitoring will be on.
if False, monitoring is disabled
if omitted, no changeReturns: True, if monitoring enabled. False, if not Return type: bool
-
multiply
(scale=1, name=None)¶ makes a monitor with all x-values multiplied with scale
Parameters: - scale (float) – scale to be applied
- name (str) – name of the multiplied monitor
default: name of this monitor
Returns: multiplied monitor
Return type: Note
Only non level monitors with type float can be multiplied
-
name
(value=None)¶ Parameters: value (str) – new name of the monitor if omitted, no change Returns: Name of the monitor Return type: str Note
base_name and sequence_number are not affected if the name is changed
-
number_of_entries
(ex0=False)¶ count of the number of entries
Parameters: ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes Returns: number of entries Return type: int Note
Not available for level monitors
-
number_of_entries_zero
()¶ count of the number of zero entries
Returns: number of zero entries Return type: int Note
Not available for level monitors
-
percentile
(q, ex0=False, interpolation='linear')¶ q-th percentile of tallied values
Parameters: - q (float) – percentage of the distribution
values <0 are treated a 0
values >100 are treated as 100 - ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes
- interpolation (str) – Default: ‘linear’
For non weighted monitors:
This optional parameter specifies the interpolation method to use when the desired percentile lies between two data points i < j:
‘linear’: i + (j - i) * fraction, where fraction is the fractional part of the index surrounded by i and j. (default for monitors that are not weighted not level|n| ‘lower’: i.
‘higher’: j. (default for weighted and level monitors)
‘nearest’: i or j, whichever is nearest.
‘midpoint’: (i + j) / 2.
For weighted and level monitors:
This optional parameter specifies the interpolation method to use when the percentile corresponds exactly to two data points i and j
‘linear’: (i + j) /2
‘lower’: i.
‘higher’: j
‘midpoint’: (i + j) / 2.
Returns: q-th percentile – 0 returns the minimum, 50 the median and 100 the maximum
Return type: float
- q (float) – percentage of the distribution
-
print_histogram
(number_of_bins=None, lowerbound=None, bin_width=None, values=False, ex0=False, as_str=False, file=None, sort_on_weight=False, sort_on_duration=False, sort_on_value=False)¶ print monitor statistics and histogram
Parameters: - number_of_bins (int) – number of bins
default: 30
if <0, also the header of the histogram will be surpressed - lowerbound (float) – first bin
default: 0 - bin_width (float) – width of the bins
default: 1 - values (bool) – if False (default), bins will be used
if True, the individual values will be shown (in alphabetical order). in that case, no cumulative values will be given - ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes
- as_str: bool
- if False (default), print the histogram if True, return a string containing the histogram
- file: file
- if None(default), all output is directed to stdout
otherwise, the output is directed to the file - sort_on_weight : bool
- if True, sort the values on weight first (largest first), then on the values itself|n|
if False, sort the values on the values itself
False is the default for non level monitors. Not permitted for level monitors. - sort_on_duration : bool
- if True, sort the values on duration first (largest first), then on the values itself|n|
if False, sort the values on the values itself
False is the default for level monitors. Not permitted for non level monitors. - sort sort_on_weight : bool
- if True, sort the values on weight first (largest first), then on the values itself|n|
if False (default), sort the values on the values itself
Not permitted for level monitors. - sort_on_duration : bool
- if True, sort the values on duration first (largest first), then on the values itself|n|
if False (default), sort the values on the values itself
Not permitted for non level monitors. - sort_on_value : bool
- if True, sort on the values.
if False (default), no sorting will take place, unless values is an iterable, in which case sorting will be done on the values anyway.
Returns: histogram (if as_str is True) Return type: str Note
If number_of_bins, lowerbound and bin_width are omitted, the histogram will be autoscaled, with a maximum of 30 classes.
- number_of_bins (int) – number of bins
-
print_histograms
(number_of_bins=None, lowerbound=None, bin_width=None, values=False, ex0=False, as_str=False, file=None)¶ print monitor statistics and histogram
Parameters: - number_of_bins (int) – number of bins
default: 30
if <0, also the header of the histogram will be surpressed - lowerbound (float) – first bin
default: 0 - bin_width (float) – width of the bins
default: 1 - values (bool) – if False (default), bins will be used
if True, the individual values will be shown (sorted on the value). in that case, no cumulative values will be given - ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes
- as_str (bool) – if False (default), print the histogram if True, return a string containing the histogram
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: histogram (if as_str is True)
Return type: str
Note
If number_of_bins, lowerbound and bin_width are omitted, the histogram will be autoscaled, with a maximum of 30 classes.
Exactly same functionality as Monitor.print_histogram()- number_of_bins (int) – number of bins
-
print_statistics
(show_header=True, show_legend=True, do_indent=False, as_str=False, file=None)¶ print monitor statistics
Parameters: - show_header (bool) – primarily for internal use
- show_legend (bool) – primarily for internal use
- do_indent (bool) – primarily for internal use
- as_str (bool) – if False (default), print the statistics if True, return a string containing the statistics
- file (file) – if None (default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: statistics (if as_str is True)
Return type: str
-
register
(registry)¶ registers the monitor in the registry
Parameters: registry (list) – list of (to be) registered objects Returns: monitor (self) Return type: Monitor Note
Use Monitor.deregister if monitor does not longer need to be registered.
-
rename
(value=None)¶ Parameters: value (str) – new name of the monitor if omitted, no change Returns: self Return type: monitor Note
in contrast to name(), this method returns itself, so can used to chain, e.g.
(m0 + m1 + m2+ m3).rename(‘m0-m3’).print_histograms()
m0[1000 : 2000].rename(‘m between t=1000 and t=2000’).print_histograms()
-
reset
(monitor=None, stats_only=None)¶ resets monitor
Parameters: - monitor (bool) – if True, monitoring will be on.
if False, monitoring is disabled if omitted, no change of monitoring state - stats_only (bool) – if True, only statistics will be collected (using less memory, but also less functionality)
if False, full functionality
if omittted, no change of stats_only
- monitor (bool) – if True, monitoring will be on.
-
reset_monitors
(monitor=None, stats_only=None)¶ resets monitor
Parameters: - monitor (bool) – if True (default), monitoring will be on.
if False, monitoring is disabled
if omitted, the monitor state remains unchanged - stats_only (bool) – if True, only statistics will be collected (using less memory, but also less functionality)
if False, full functionality
if omittted, no change of stats_only
Note
Exactly same functionality as Monitor.reset()
- monitor (bool) – if True (default), monitoring will be on.
-
sequence_number
()¶ Returns: sequence_number of the monitor – (the sequence number at initialization)
normally this will be the integer value of a serialized name, but also non serialized names (without a dot or a comma at the end) will be numbered)Return type: int
-
setup
()¶ called immediately after initialization of a monitor.
by default this is a dummy method, but it can be overridden.
only keyword arguments are passed
-
slice
(start=None, stop=None, modulo=None, name=None)¶ slices this monitor (creates a subset)
Parameters: - start (float) – if modulo is not given, the start of the slice
if modulo is given, this is indicates the slice period start (modulo modulo) - stop (float) – if modulo is not given, the end of the slice
if modulo is given, this is indicates the slice period end (modulo modulo)
note that stop is excluded from the slice (open at right hand side) - modulo (float) – specifies the distance between slice periods
if not specified, just one slice subset is used. - name (str) – name of the sliced monitor
default: name of this monitor + “.sliced”
Returns: sliced monitor
Return type: Note
It is also possible to use square bracktets to slice, like m[0:1000].
- start (float) – if modulo is not given, the start of the slice
-
start_time
()¶ Returns: Start time of the monitor – either the time of creation or latest reset Return type: float
-
std
(ex0=False)¶ standard deviation of tallied values
Parameters: ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes Returns: standard deviation Return type: float Note
If weights are applied, the weighted standard deviation is returned
-
t
()¶ get the time of last tally of a level monitor
Getter: gets the time of the last tallied value : float Note
t is only available for level monitors
t is available even if the monitor is turned off
-
tally
(value, weight=1)¶ Parameters: - x (any, preferably int, float or translatable into int or float) – value to be tallied
- weight (float) – weight to be tallied
default : 1
-
to_days
(name=None)¶ makes a monitor with all x-values converted to days
Parameters: name (str) – name of the converted monitor
default: name of this monitorReturns: converted monitor Return type: Monitor Note
Only non level monitors with type float can be converted.
It is required that a time_unit is defined for the environment.
-
to_hours
(name=None)¶ makes a monitor with all x-values converted to hours
Parameters: name (str) – name of the converted monitor
default: name of this monitorReturns: converted monitor Return type: Monitor Note
Only non level monitors with type float can be converted.
It is required that a time_unit is defined for the environment.
-
to_microseconds
(name=None)¶ makes a monitor with all x-values converted to microseconds
Parameters: name (str) – name of the converted monitor
default: name of this monitorReturns: converted monitor Return type: Monitor Note
Only non level monitors with type float can be converted.
It is required that a time_unit is defined for the environment.
-
to_milliseconds
(name=None)¶ makes a monitor with all x-values converted to milliseconds
Parameters: name (str) – name of the converted monitor
default: name of this monitorReturns: converted monitor Return type: Monitor Note
Only non level monitors with type float can be converted.
It is required that a time_unit is defined for the environment.
-
to_minutes
(name=None)¶ makes a monitor with all x-values converted to minutes
Parameters: name (str) – name of the converted monitor
default: name of this monitorReturns: converted monitor Return type: Monitor Note
Only non level monitors with type float can be converted.
It is required that a time_unit is defined for the environment.
-
to_seconds
(name=None)¶ makes a monitor with all x-values converted to seconds
Parameters: name (str) – name of the converted monitor
default: name of this monitorReturns: converted monitor Return type: Monitor Note
Only non level monitors with type float can be converted.
It is required that a time_unit is defined for the environment.
-
to_time_unit
(time_unit, name=None)¶ makes a monitor with all x-values converted to the specified time unit
Parameters: - time_unit (str) – Supported time_units:
“years”, “weeks”, “days”, “hours”, “minutes”, “seconds”, “milliseconds”, “microseconds” - name (str) – name of the converted monitor
default: name of this monitor
Returns: converted monitor
Return type: Note
Only non level monitors with type float can be converted.
It is required that a time_unit is defined for the environment.- time_unit (str) – Supported time_units:
-
to_weeks
(name=None)¶ makes a monitor with all x-values converted to weeks
Parameters: name (str) – name of the converted monitor
default: name of this monitorReturns: converted monitor Return type: Monitor Note
Only non level monitors with type float can be converted.
It is required that a time_unit is defined for the environment.
-
to_years
(name=None)¶ makes a monitor with all x-values converted to years
Parameters: name (str) – name of the converted monitor
default: name of this monitorReturns: converted monitor Return type: Monitor Note
Only non level monitors with type float can be converted.
It is required that a time_unit is defined for the environment.
-
tx
(ex0=False, exoff=False, force_numeric=False, add_now=True)¶ tuple of array with timestamps and array/list with x-values
Parameters: - ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes
- exoff (bool) – if False (default), include self.off. if True, exclude self.off’s
non level monitors will return all values, regardless of exoff - force_numeric (bool) – if True (default), convert non numeric tallied values numeric if possible, otherwise assume 0
if False, do not interpret x-values, return as list if type is list - add_now (bool) – if True (default), the last tallied x-value and the current time is added to the result
if False, the result ends with the last tallied value and the time that was tallied
non level monitors will never add now
Returns: array with timestamps and array/list with x-values
Return type: tuple
Note
The value self.off is stored when monitoring is turned off
The timestamps are not corrected for any reset_now() adjustment.
-
value
¶ get/set the value of a level monitor
Getter: gets the last tallied value : any (often float) Setter: equivalent to m.tally() Note
value is only available for level monitors
value is available even if the monitor is turned off
-
value_duration
(value)¶ total duration of tallied values equal to value or in value
Parameters: value (any) – if list, tuple or set, check whether the tallied value is in value
otherwise, check whether the tallied value equals the given valueReturns: total of duration of tallied values in value or equal to value Return type: float Note
Not available for non level monitors
-
value_number_of_entries
(value)¶ count of the number of tallied values equal to value or in value
Parameters: value (any) – if list, tuple or set, check whether the tallied value is in value
otherwise, check whether the tallied value equals the given valueReturns: number of tallied values in value or equal to value Return type: int Note
Not available for level monitors
-
value_weight
(value)¶ total weight of tallied values equal to value or in value
Parameters: value (any) – if list, tuple or set, check whether the tallied value is in value
otherwise, check whether the tallied value equals the given valueReturns: total of weights of tallied values in value or equal to value Return type: int Note
Not available for level monitors
-
values
(ex0=False, force_numeric=False, sort_on_weight=False, sort_on_duration=False)¶ Parameters: - ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes
- force_numeric (bool) – if True, convert non numeric tallied values numeric if possible, otherwise assume 0
if False (default), do not interpret x-values, return as list if type is list - sort_on_weight (bool) – if True, sort the values on weight first (largest first), then on the values itself|n|
if False, sort the values on the values itself
False is the default for non level monitors. Not permitted for level monitors. - sort_on_duration (bool) – if True, sort the values on duration first (largest first), then on the values itself|n|
if False, sort the values on the values itself
False is the default for level monitors. Not permitted for non level monitors.
Returns: all tallied values
Return type: array/list
-
weight
(ex0=False)¶ sum of weights
Parameters: ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes Returns: sum of weights Return type: float Note
Not available for level monitors
-
weight_zero
()¶ sum of weights of zero entries
Returns: sum of weights of zero entries Return type: float Note
Not available for level monitors
-
x
(ex0=False, force_numeric=True)¶ array/list of tallied values
Parameters: - ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes
- force_numeric (bool) – if True (default), convert non numeric tallied values numeric if possible, otherwise assume 0
if False, do not interpret x-values, return as list if type is any (list)
Returns: all tallied values
Return type: array/list
Note
Not available for level monitors. Use xduration(), xt() or tx() instead.
-
x_map
(func, monitors=[], name=None)¶ maps a function to the x-values of the given monitors (static method)
Parameters: - func (function) – a function that accepts n x-values, where n is the number of monitors note that the function will not be called during the time any of the monitors is off
- monitors (list/tuple of additional monitors) – monitor(s) to be mapped
only allowed for level monitors- - name (str) – name of the mapped monitor
default: “mapped”
Returns: mapped monitor
Return type: Monitor, type ‘any’
-
xduration
(ex0=False, force_numeric=True)¶ array/list of tallied values
Parameters: - ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes
- force_numeric (bool) – if True (default), convert non numeric tallied values numeric if possible, otherwise assume 0
if False, do not interpret x-values, return as list if type is list
Returns: all tallied values
Return type: array/list
Note
not available for non level monitors
-
xt
(ex0=False, exoff=False, force_numeric=True, add_now=True)¶ tuple of array/list with x-values and array with timestamp
Parameters: - ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes
- exoff (bool) – if False (default), include self.off. if True, exclude self.off’s
non level monitors will return all values, regardless of exoff - force_numeric (bool) – if True (default), convert non numeric tallied values numeric if possible, otherwise assume 0
if False, do not interpret x-values, return as list if type is list - add_now (bool) – if True (default), the last tallied x-value and the current time is added to the result
if False, the result ends with the last tallied value and the time that was tallied
non level monitors will never add now
if now is <= last tallied value, nothing will be added, even if add_now is True
Returns: array/list with x-values and array with timestamps
Return type: tuple
Note
The value self.off is stored when monitoring is turned off
The timestamps are not corrected for any reset_now() adjustment.
-
xweight
(ex0=False, force_numeric=True)¶ array/list of tallied values
Parameters: - ex0 (bool) – if False (default), include zeroes. if True, exclude zeroes
- force_numeric (bool) – if True (default), convert non numeric tallied values numeric if possible, otherwise assume 0
if False, do not interpret x-values, return as list if type is list
Returns: all tallied values
Return type: array/list
Note
not available for level monitors
- name (str) – name of the monitor
Queue¶
-
class
salabim.
Queue
(name=None, monitor=True, fill=None, capacity=inf, env=None, *args, **kwargs)¶ Queue object
Parameters: - fill (Queue, list or tuple) – fill the queue with the components in fill
if omitted, the queue will be empty at initialization - name (str) – name of the queue
if the name ends with a period (.), auto serializing will be applied
if the name end with a comma, auto serializing starting at 1 will be applied
if omitted, the name will be derived from the class it is defined in (lowercased) - capacity (float) – mximum number of components the queue can contain.
if exceeded, a QueueFullError will be raised
default: inf - monitor (bool) – if True (default) , both length and length_of_stay are monitored
if False, monitoring is disabled. - env (Environment) – environment where the queue is defined
if omitted, default_env will be used
-
add
(component)¶ adds a component to the tail of a queue
Parameters: component (Component) – component to be added to the tail of the queue
may not be member of the queue yetNote
the priority will be set to the priority of the tail of the queue, if any or 0 if queue is empty
This method is equivalent to append()
-
add_at_head
(component)¶ adds a component to the head of a queue
Parameters: component (Component) – component to be added to the head of the queue
may not be member of the queue yetNote
the priority will be set to the priority of the head of the queue, if any or 0 if queue is empty
-
add_behind
(component, poscomponent)¶ adds a component to a queue, just behind a component
Parameters: Note
the priority of component will be set to the priority of poscomponent
-
add_in_front_of
(component, poscomponent)¶ adds a component to a queue, just in front of a component
Parameters: Note
the priority of component will be set to the priority of poscomponent
-
add_sorted
(component, priority)¶ adds a component to a queue, according to the priority
Parameters: - component (Component) – component to be added to the queue
may not be member of the queue yet - priority (type that can be compared with other priorities in the queue) – priority in the queue
Note
The component is placed just before the first component with a priority > given priority
- component (Component) – component to be added to the queue
-
all_monitors
()¶ returns all monitors belonging to the queue
Returns: all monitors Return type: tuple of monitors
-
animate
(*args, **kwargs)¶ Animates the components in the queue.
Parameters: - x (float) – x-position of the first component in the queue
default: 50 - y (float) – y-position of the first component in the queue
default: 50 - direction (str) – if “w”, waiting line runs westwards (i.e. from right to left)
if “n”, waiting line runs northeards (i.e. from bottom to top)
if “e”, waiting line runs eastwards (i.e. from left to right) (default)
if “s”, waiting line runs southwards (i.e. from top to bottom) if “t”, waiting line runs follows given trajectory - trajectory (Trajectory) – trajectory to be followed if direction == “t”
- reverse (bool) – if False (default), display in normal order. If True, reversed.
- max_length (int) – maximum number of components to be displayed
- xy_anchor (str) – specifies where x and y are relative to
possible values are (default: sw):
nw n ne
w c e
sw s se
- id (any) – the animation works by calling the animation_objects method of each component, optionally with id. By default, this is self, but can be overriden, particularly with the queue
- arg (any) – this is used when a parameter is a function with two parameters, as the first argument or
if a parameter is a method as the instance
default: self (instance itself)
Returns: reference to AnimationQueue object
Return type: AnimationQueue
Note
It is recommended to use sim.AnimateQueue instead
All measures are in screen coordinates
All parameters, apart from queue and arg can be specified as:
- a scalar, like 10
- a function with zero arguments, like lambda: title
- a function with one argument, being the time t, like lambda t: t + 10
- a function with two parameters, being arg (as given) and the time, like lambda comp, t: comp.state
- a method instance arg for time t, like self.state, actually leading to arg.state(t) to be called- x (float) – x-position of the first component in the queue
-
animate3d
(*args, **kwargs)¶ Animates the components in the queue in 3D.
Parameters: - x (float) – x-position of the first component in the queue
default: 0 - y (float) – y-position of the first component in the queue
default: 0 - z (float) – z-position of the first component in the queue
default: 0 - direction (str) – if “x+”, waiting line runs in positive x direction (default)
if “x-“, waiting line runs in negative x direction
if “y+”, waiting line runs in positive y direction
if “y-“, waiting line runs in negative y direction
if “z+”, waiting line runs in positive z direction
if “z-“, waiting line runs in negative z direction - reverse (bool) – if False (default), display in normal order. If True, reversed.
- max_length (int) – maximum number of components to be displayed
- layer (int) – layer (default 0)
- id (any) – the animation works by calling the animation_objects method of each component, optionally with id. By default, this is self, but can be overriden, particularly with the queue
- arg (any) – this is used when a parameter is a function with two parameters, as the first argument or
if a parameter is a method as the instance
default: self (instance itself)
Returns: reference to Animation3dQueue object
Return type: Animation3dQueue
Note
It is recommended to use sim.AnimatedQueue instead
All parameters, apart from queue and arg can be specified as:
- a scalar, like 10
- a function with zero arguments, like lambda: title
- a function with one argument, being the time t, like lambda t: t + 10
- a function with two parameters, being arg (as given) and the time, like lambda comp, t: comp.state
- a method instance arg for time t, like self.state, actually leading to arg.state(t) to be called- x (float) – x-position of the first component in the queue
-
append
(component)¶ appends a component to the tail of a queue
Parameters: component (Component) – component to be appened to the tail of the queue
may not be member of the queue yetNote
the priority will be set to the priority of the tail of the queue, if any or 0 if queue is empty
This method is equivalent to add()
-
arrival_rate
(reset=False)¶ returns the arrival rate
When the queue is created, the registration is reset.Parameters: reset (bool) – if True, number_of_arrivals is set to 0 since last reset and the time of the last reset to now
default: False ==> no resetReturns: arrival rate – number of arrivals since last reset / duration since last reset
nan if duration is zeroReturn type: float
-
base_name
()¶ Returns: base name of the queue (the name used at initialization) Return type: str
-
clear
()¶ empties a queue
removes all components from a queue
-
component_with_name
(txt)¶ returns a component in the queue according to its name
Parameters: txt (str) – name of component to be retrieved Returns: the first component in the queue with name txt – returns None if not found Return type: Component
-
copy
(name=None, copy_capacity=False, monitor=<function Queue.monitor>)¶ returns a copy of a queue
Parameters: - name (str) – name of the new queue
if omitted, “copy of ” + self.name() - monitor (bool) – if True, monitor the queue
if False (default), do not monitor the queue - copy_capacity (bool) – if True, the capacity will be copied
if False (default), the resulting queue will always be unrestricted
Returns: queue with all elements of self
Return type: Note
The priority will be copied from original queue. Also, the order will be maintained.
- name (str) – name of the new queue
-
count
(component)¶ component count
Parameters: component (Component) – component to count Returns: Return type: number of occurences of component in the queue Note
The result can only be 0 or 1
-
departure_rate
(reset=False)¶ returns the departure rate
When the queue is created, the registration is reset.Parameters: reset (bool) – if True, number_of_departures is set to 0 since last reset and the time of the last reset to now
default: False ==> no resetReturns: departure rate – number of departures since last reset / duration since last reset
nan if duration is zeroReturn type: float
-
deregister
(registry)¶ deregisters the queue in the registry
Parameters: registry (list) – list of registered queues Returns: queue (self) Return type: Queue
-
difference
(q, name=None, monitor=<function Queue.monitor>)¶ returns the difference of two queues
Parameters: - q (Queue) – queue to be ‘subtracted’ from self
- name (str) – name of the new queue
if omitted, self.name() - q.name() - monitor (bool) – if True, monitor the queue
if False (default), do not monitor the queue
Returns: Return type: queue containing all elements of self that are not in q
Note
the priority will be copied from the original queue. Also, the order will be maintained.
Alternatively, the more pythonic - operator is also supported, e.g. q1 - q2
-
extend
(source, clear_source=False)¶ extends the queue with components of source that are not already in self (at the end of self)
Parameters: - source (queue, list or tuple) –
- clear_source (bool) – if False (default), the elements will remain in source
if True, source will be cleared, so effectively moving all elements in source to self. If source is not a queue, but a list or tuple, the clear_source flag may not be set.
Returns: Return type: None
Note
The components in source added to the queue will get the priority of the tail of self.
-
head
()¶ Returns: the head component of the queue, if any. None otherwise Return type: Component Note
q[0] is a more Pythonic way to access the head of the queue
-
index
(component)¶ get the index of a component in the queue
Parameters: component (Component) – component to be queried
does not need to be in the queueReturns: index of component in the queue – 0 denotes the head,
returns -1 if component is not in the queueReturn type: int
-
insert
(index, component)¶ Insert component before index-th element of the queue
Parameters: - index (int) – component to be added just before index’th element
should be >=0 and <=len(self) - component (Component) – component to be added to the queue
Note
the priority of component will be set to the priority of the index’th component, or 0 if the queue is empty
- index (int) – component to be added just before index’th element
-
intersection
(q, name=None, monitor=False)¶ returns the intersect of two queues
Parameters: - q (Queue) – queue to be intersected with self
- name (str) – name of the new queue
if omitted, self.name() + q.name() - monitor (bool) – if True, monitor the queue
if False (default), do not monitor the queue
Returns: queue with all elements that are in self and q
Return type: Note
the priority will be set to 0 for all components in the resulting queue
the order of the resulting queue is as follows:
in the same order as in self.
Alternatively, the more pythonic & operator is also supported, e.g. q1 & q2
-
monitor
(value)¶ enables/disables monitoring of length_of_stay and length
Parameters: value (bool) – if True, monitoring will be on.
if False, monitoring is disabledNote
it is possible to individually control monitoring with length_of_stay.monitor() and length.monitor()
-
move
(name=None, monitor=<function Queue.monitor>, copy_capacity=False)¶ makes a copy of a queue and empties the original
Parameters: - name (str) – name of the new queue
- monitor (bool) – if True, monitor the queue
if False (default), do not monitor the yqueue - copy_capacity (bool) – if True, the capacity will be copied
if False (default), the new queue will always be unrestricted
Returns: - queue containing all elements of self (Queue)
- the capacity of the original queue will not be changed
Note
Priorities will be kept
self will be emptied
-
name
(value=None)¶ Parameters: value (str) – new name of the queue if omitted, no change Returns: Name of the queue Return type: str Note
base_name and sequence_number are not affected if the name is changed
All derived named are updated as well.
-
pop
(index=None)¶ removes a component by its position (or head)
Parameters: index (int) – index-th element to remove, if any
if omitted, return the head of the queue, if anyReturns: The i-th component or head – None if not existing Return type: Component
-
predecessor
(component)¶ predecessor in queue
Parameters: component (Component) – component whose predecessor to return
must be member of the queueReturns: predecessor of component, if any – None otherwise. Return type: Component
-
print_histograms
(exclude=(), as_str=False, file=None)¶ prints the histograms of the length and length_of_stay monitor of the queue
Parameters: - exclude (tuple or list) – specifies which monitors to exclude
default: () - as_str (bool) – if False (default), print the histograms if True, return a string containing the histograms
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: histograms (if as_str is True)
Return type: str
- exclude (tuple or list) – specifies which monitors to exclude
-
print_info
(as_str=False, file=None)¶ prints information about the queue
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
print_statistics
(as_str=False, file=None)¶ prints a summary of statistics of a queue
Parameters: - as_str (bool) – if False (default), print the statistics if True, return a string containing the statistics
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: statistics (if as_str is True)
Return type: str
-
register
(registry)¶ registers the queue in the registry
Parameters: registry (list) – list of (to be) registered objects Returns: queue (self) Return type: Queue Note
Use Queue.deregister if queue does not longer need to be registered.
-
remove
(component=None)¶ removes component from the queue
Parameters: component (Component) – component to be removed
if omitted, all components will be removed.Note
component must be member of the queue
-
rename
(value=None)¶ Parameters: value (str) – new name of the queue if omitted, no change Returns: self Return type: queue Note
in contrast to name(), this method returns itself, so can used to chain, e.g.
(q0 + q1 + q2 + q3).rename(‘q0 - q3’).print_statistics()
(q1 - q0).rename(‘difference of q1 and q0)’).print_histograms()
-
reset_monitors
(monitor=None, stats_only=None)¶ resets queue monitor length_of_stay and length
Parameters: - monitor (bool) – if True, monitoring will be on.
if False, monitoring is disabled
if omitted, no change of monitoring state - stats_only (bool) – if True, only statistics will be collected (using less memory, but also less functionality)
if False, full functionality
if omittted, no change of stats_only
Note
it is possible to reset individual monitoring with length_of_stay.reset() and length.reset()
- monitor (bool) – if True, monitoring will be on.
-
sequence_number
()¶ Returns: sequence_number of the queue – (the sequence number at initialization)
normally this will be the integer value of a serialized name, but also non serialized names (without a dot or a comma at the end) will be numbered)Return type: int
-
setup
()¶ called immediately after initialization of a queue.
by default this is a dummy method, but it can be overridden.
only keyword arguments are passed
-
successor
(component)¶ successor in queue
Parameters: component (Component) – component whose successor to return
must be member of the queueReturns: successor of component, if any – None otherwise Return type: Component
-
symmetric_difference
(q, name=None, monitor=<function Queue.monitor>)¶ returns the symmetric difference of two queues
Parameters: - q (Queue) – queue to be ‘subtracted’ from self
- name (str) – name of the new queue
if omitted, self.name() - q.name() - monitor (bool) – if True, monitor the queue
if False (default), do not monitor the queue
Returns: Return type: queue containing all elements that are either in self or q, but not in both
Note
the priority of all elements will be set to 0 for all components in the new queue. Order: First, elelements in self (in that order), then elements in q (in that order) Alternatively, the more pythonic ^ operator is also supported, e.g. q1 ^ q2
-
tail
()¶ Returns: the tail component of the queue, if any. None otherwise Return type: Component Note
q[-1] is a more Pythonic way to access the tail of the queue
-
union
(q, name=None, monitor=False)¶ Parameters: - q (Queue) – queue to be unioned with self
- name (str) – name of the new queue
if omitted, self.name() + q.name() - monitor (bool) – if True, monitor the queue
if False (default), do not monitor the queue
Returns: queue containing all elements of self and q
Return type: Note
the priority will be set to 0 for all components in the resulting queue
the order of the resulting queue is as follows:
first all components of self, in that order, followed by all components in q that are not in self, in that order.
Alternatively, the more pythonic | operator is also supported, e.g. q1 | q2
- fill (Queue, list or tuple) – fill the queue with the components in fill
Resource¶
-
class
salabim.
Resource
(name=None, capacity=1, initial_claimed_quantity=0, anonymous=False, preemptive=False, honor_only_first=False, honor_only_highest_priority=False, monitor=True, env=None, *args, **kwargs)¶ Parameters: - name (str) – name of the resource
if the name ends with a period (.), auto serializing will be applied
if the name end with a comma, auto serializing starting at 1 will be applied
if omitted, the name will be derived from the class it is defined in (lowercased) - capacity (float) – capacity of the resource
if omitted, 1 - initial_claimed_quantity (float) – initial claimed quantity. Only allowed to be non zero for anonymous resources
if omitted, 0 - anonymous (bool) – anonymous specifier
if True, claims are not related to any component. This is useful if the resource is actually just a level.
if False, claims belong to a component. - honor_only_first (bool) – if True, only the first component of requesters will be honoured (default: False)
- honor_only_highest_priority (bool) – if True, only component with the priority of the first requester will be honoured (default: False) Note: only respected if honor_only_first is False
- monitor (bool) – if True (default), the requesters queue, the claimers queue,
the capacity, the available_quantity and the claimed_quantity are monitored
if False, monitoring is disabled. - env (Environment) – environment to be used
if omitted, default_env is used
-
all_monitors
()¶ returns all mononitors belonging to the resource
Returns: all monitors Return type: tuple of monitors
-
base_name
()¶ Returns: base name of the resource (the name used at initialization) Return type: str
-
claimers
()¶ Returns: queue with all components claiming from the resource – will be an empty queue for an anonymous resource Return type: Queue
-
deregister
(registry)¶ deregisters the resource in the registry
Parameters: registry (list) – list of registered components Returns: resource (self) Return type: Resource
-
ispreemptive
()¶ Returns: True if preemptive, False otherwise Return type: bool
-
monitor
(value)¶ enables/disables the resource monitors
Parameters: value (bool) – if True, monitoring is enabled
if False, monitoring is disabledNote
it is possible to individually control monitoring with claimers().monitor() and requesters().monitor(), capacity.monitor(), available_quantity.monitor), claimed_quantity.monitor() or occupancy.monitor()
-
name
(value=None)¶ Parameters: value (str) – new name of the resource if omitted, no change Returns: Name of the resource Return type: str Note
base_name and sequence_number are not affected if the name is changed
All derived named are updated as well.
-
print_histograms
(exclude=(), as_str=False, file=None)¶ prints histograms of the requesters and claimers queue as well as the capacity, available_quantity and claimed_quantity timstamped monitors of the resource
Parameters: - exclude (tuple or list) – specifies which queues or monitors to exclude
default: () - as_str (bool) – if False (default), print the histograms if True, return a string containing the histograms
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: histograms (if as_str is True)
Return type: str
- exclude (tuple or list) – specifies which queues or monitors to exclude
-
print_info
(as_str=False, file=None)¶ prints info about the resource
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
print_statistics
(as_str=False, file=None)¶ prints a summary of statistics of a resource
Parameters: - as_str (bool) – if False (default), print the statistics if True, return a string containing the statistics
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: statistics (if as_str is True)
Return type: str
-
register
(registry)¶ registers the resource in the registry
Parameters: registry (list) – list of (to be) registered objects Returns: resource (self) Return type: Resource Note
Use Resource.deregister if resource does not longer need to be registered.
-
release
(quantity=None)¶ releases all claims or a specified quantity
Parameters: quantity (float) – quantity to be released
if not specified, the resource will be emptied completely
for non-anonymous resources, all components claiming from this resource will be released.Note
quantity may not be specified for a non-anonymous resoure
-
requesters
()¶ Returns: queue containing all components with not yet honored requests Return type: Queue
-
reset_monitors
(monitor=None, stats_only=None)¶ resets the resource monitors
Parameters: - monitor (bool) – if True, monitoring will be on.
if False, monitoring is disabled
if omitted, no change of monitoring state - stats_only (bool) – if True, only statistics will be collected (using less memory, but also less functionality)
if False, full functionality
if omittted, no change of stats_only
Note
it is possible to reset individual monitoring with claimers().reset_monitors(), requesters().reset_monitors, capacity.reset(), available_quantity.reset() or claimed_quantity.reset() or occupancy.reset()
- monitor (bool) – if True, monitoring will be on.
-
sequence_number
()¶ Returns: sequence_number of the resource – (the sequence number at initialization)
normally this will be the integer value of a serialized name, but also non serialized names (without a dot or a comma at the end) will be numbered)Return type: int
-
set_capacity
(cap)¶ Parameters: cap (float or int) – capacity of the resource
this may lead to honoring one or more requests.
if omitted, no change
-
setup
()¶ called immediately after initialization of a resource.
by default this is a dummy method, but it can be overridden.
only keyword arguments are passed
- name (str) – name of the resource
State¶
-
class
salabim.
State
(name=None, value=False, type='any', monitor=True, env=None, *args, **kwargs)¶ Parameters: - name (str) – name of the state
if the name ends with a period (.), auto serializing will be applied
if the name end with a comma, auto serializing starting at 1 will be applied
if omitted, the name will be derived from the class it is defined in (lowercased) - value (any, preferably printable) – initial value of the state
if omitted, False - monitor (bool) – if True (default) , the waiters queue and the value are monitored
if False, monitoring is disabled. - type (str) –
specifies how the state values are monitored. Using a int, uint of float type results in less memory usage and better performance. Note that you should avoid the number not to use as this is used to indicate ‘off’
- ”any” (default) stores values in a list. This allows for non numeric values. In calculations the values are forced to a numeric value (0 if not possible) do not use -inf
- ”bool” bool (False, True). Actually integer >= 0 <= 254 1 byte do not use 255
- ”int8” integer >= -127 <= 127 1 byte do not use -128
- ”uint8” integer >= 0 <= 254 1 byte do not use 255
- ”int16” integer >= -32767 <= 32767 2 bytes do not use -32768
- ”uint16” integer >= 0 <= 65534 2 bytes do not use 65535
- ”int32” integer >= -2147483647 <= 2147483647 4 bytes do not use -2147483648
- ”uint32” integer >= 0 <= 4294967294 4 bytes do not use 4294967295
- ”int64” integer >= -9223372036854775807 <= 9223372036854775807 8 bytes do not use -9223372036854775808
- ”uint64” integer >= 0 <= 18446744073709551614 8 bytes do not use 18446744073709551615
- ”float” float 8 bytes do not use -inf
- env (Environment) – environment to be used
if omitted, default_env is used
-
all_monitors
()¶ returns all mononitors belonging to the state
Returns: all monitors Return type: tuple of monitors
-
base_name
()¶ Returns: base name of the state (the name used at initialization) Return type: str
-
deregister
(registry)¶ deregisters the state in the registry
Parameters: registry (list) – list of registered states Returns: state (self) Return type: State
-
get
()¶ get value of the state
Returns: value of the state – Instead of this method, the state can also be called directly, like level = sim.State(“level”)
…
print(level())
print(level.get()) # identicalReturn type: any
-
monitor
(value=None)¶ enables/disables the state monitors and value monitor
Parameters: value (bool) – if True, monitoring will be on.
if False, monitoring is disabled
if not specified, no changeNote
- it is possible to individually control requesters().monitor(),
- value.monitor()
-
name
(value=None)¶ Parameters: value (str) – new name of the state if omitted, no change Returns: Name of the state Return type: str Note
base_name and sequence_number are not affected if the name is changed
All derived named are updated as well.
-
print_histograms
(exclude=(), as_str=False, file=None)¶ print histograms of the waiters queue and the value monitor
Parameters: - exclude (tuple or list) – specifies which queues or monitors to exclude
default: () - as_str (bool) – if False (default), print the histograms if True, return a string containing the histograms
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: histograms (if as_str is True)
Return type: str
- exclude (tuple or list) – specifies which queues or monitors to exclude
-
print_info
(as_str=False, file=None)¶ prints info about the state
Parameters: - as_str (bool) – if False (default), print the info if True, return a string containing the info
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: info (if as_str is True)
Return type: str
-
print_statistics
(as_str=False, file=None)¶ prints a summary of statistics of the state
Parameters: - as_str (bool) – if False (default), print the statistics if True, return a string containing the statistics
- file (file) – if None(default), all output is directed to stdout
otherwise, the output is directed to the file
Returns: statistics (if as_str is True)
Return type: str
-
register
(registry)¶ registers the state in the registry
Parameters: registry (list) – list of (to be) registered objetcs Returns: state (self) Return type: State Note
Use State.deregister if state does not longer need to be registered.
-
reset
(value=False)¶ reset the value of the state
Parameters: value (any (preferably printable)) – if omitted, False
if there is a change, the waiters queue will be checked to see whether there are waiting components to be honoredNote
This method is identical to set, except the default value is False.
-
reset_monitors
(monitor=None, stats_only=None)¶ resets the monitor for the state’s value and the monitors of the waiters queue
Parameters: - monitor (bool) – if True, monitoring will be on.
if False, monitoring is disabled
if omitted, no change of monitoring state - stats_only (bool) – if True, only statistics will be collected (using less memory, but also less functionality)
if False, full functionality
if omittted, no change of stats_only
- monitor (bool) – if True, monitoring will be on.
-
sequence_number
()¶ Returns: sequence_number of the state – (the sequence number at initialization)
normally this will be the integer value of a serialized name, but also non serialized names (without a dot or a comma at the end) will be numbered)Return type: int
-
set
(value=True)¶ set the value of the state
Parameters: value (any (preferably printable)) – if omitted, True
if there is a change, the waiters queue will be checked to see whether there are waiting components to be honoredNote
This method is identical to reset, except the default value is True.
-
setup
()¶ called immediately after initialization of a state.
by default this is a dummy method, but it can be overridden.
only keyword arguments will be passed
-
trigger
(value=True, value_after=None, max=inf)¶ triggers the value of the state
Parameters: - value (any (preferably printable)) – if omitted, True
- value_after (any (preferably printable)) – after the trigger, this will be the new value.
if omitted, return to the the before the trigger. - max (int) – maximum number of components to be honored for the trigger value
default: inf
Note
The value of the state will be set to value, then at most max waiting components for this state will be honored and next the value will be set to value_after and again checked for possible honors.
- value (any (preferably printable)) – if omitted, True
- name (str) – name of the state
Trajectories¶
-
class
salabim.
TrajectoryCircle
(radius, x_center=0, y_center=0, angle0=0, angle1=360, t0=None, vmax=None, v0=None, v1=None, acc=None, dec=None, orientation=None, env=None)¶ Circle (arc) trajectory, to be used in Animatexxx through x, y and angle methods
Parameters: - radius (float) – radius of the circle or arc
- x_center (float) – x-coordinate of the circle
- y_center (float) – y-coordinate of the circle
- angle0 (float) – start angle in degrees
default: 0 - angle1 (float) – end angle in degrees
default: 360 - t0 (float) – time the trajectory should start
default: env.now()
if not the first in a merged trajectory or AnimateQueue, ignored - vmax (float) – maximum speed, i.e. position units per time unit
default: 1 - v0 (float) – velocity at start
default: vmax - v1 (float) – velocity at end
default: vmax - acc (float) – acceleration rate (position units / time units ** 2)
default: inf (i.e. no acceleration) - dec (float) – deceleration rate (position units / time units ** 2)
default: inf (i.e. no deceleration) - orientation (float) – default: gives angle in the direction of the movement when calling angle(t)
if a one parameter callable, the angle in the direction of the movement will be callled
if a float, this orientation will always be returned as angle(t) - env (Environment) – environment where the trajectory is defined
if omitted, default_env will be used
-
duration
()¶ duration of trajectory
Returns: duration of trajectory (t1 - t0) Return type: float
-
in_trajectory
(t)¶ is t in trajectory?
Parameters: t (float) – time at which to evaluate Returns: is t in trajectory? Return type: bool
-
length
¶ length of traversed trajectory at time t or total length
Parameters: t (float) – time at which to evaluate lenght. If omitted, total length will be returned Returns: length – length of traversed trajectory at time t or
total length if t omittedReturn type: float
-
rendered_polygon
(time_step=1)¶ rendered polygon
Parameters: time_step (float) – defines at which point in time the trajectory has to be rendered
default : 1Returns: polygon – rendered from t0 to t1 with time_step
can be used directly in sim.AnimatePoints() or AnimatePolygon()Return type: list of x, y
-
t0
()¶ start time of trajectory
Returns: start time of trajectory Return type: float
-
t1
()¶ end time of trajectory
Returns: end time of trajectory Return type: float
-
class
salabim.
TrajectoryPolygon
(polygon, t0=None, vmax=None, v0=None, v1=None, acc=None, dec=None, orientation=None, spline=None, res=50, env=None)¶ Polygon trajectory, to be used in Animatexxx through x, y and angle methods
Parameters: - polygon (iterable of floats) – should be like x0, y0, x1, y1, …
- t0 (float) – time the trajectory should start
default: env.now()
if not the first in a merged trajectory or AnimateQueue, ignored - vmax (float) – maximum speed, i.e. position units per time unit
default: 1 - v0 (float) – velocity at start
default: vmax - v1 (float) – velocity at end
default: vmax - acc (float) – acceleration rate (position units / time units ** 2)
default: inf (i.e. no acceleration) - dec (float) – deceleration rate (position units / time units ** 2)
default: inf (i.e. no deceleration) - orientation (float) – default: gives angle in the direction of the movement when calling angle(t)
if a one parameter callable, the angle in the direction of the movement will be callled
if a float, this orientation will always be returned as angle(t) - spline (None or string) – if None (default), polygon is used as such
if ‘bezier’ (or any string starting with ‘b’ or ‘B’, Bézier splining is used
if ‘catmull_rom’ (or any string starting with ‘c’ or ‘C’, Catmull-Rom splining is used - res (int) – resolution of spline (ignored when no splining is applied)
- env (Environment) – environment where the trajectory is defined
if omitted, default_env will be used
Notes
bezier and catmull_rom splines require numpy to be installed.
-
angle
(t, _t0=None)¶ value of angle (in degrees)
Parameters: t (float) – time at which to evaluate angle Returns: evaluated angle (in degrees) Return type: float
-
duration
()¶ duration of trajectory
Returns: duration of trajectory (t1 - t0) Return type: float
-
in_trajectory
(t)¶ is t in trajectory?
Parameters: t (float) – time at which to evaluate Returns: is t in trajectory? Return type: bool
-
length
(t=None, _t0=None)¶ length of traversed trajectory at time t or total length
Parameters: t (float) – time at which to evaluate lenght. If omitted, total length will be returned Returns: length – length of traversed trajectory at time t or
total length if t omittedReturn type: float
-
rendered_polygon
(time_step=1)¶ rendered polygon
Parameters: time_step (float) – defines at which point in time the trajectory has to be rendered
default : 1Returns: polygon – rendered from t0 to t1 with time_step
can be used directly in sim.AnimatePoints() or AnimatePolygon()Return type: list of x, y
-
t0
()¶ start time of trajectory
Returns: start time of trajectory Return type: float
-
t1
()¶ end time of trajectory
Returns: end time of trajectory Return type: float
-
x
(t, _t0=None)¶ value of x
Parameters: t (float) – time at which to evaluate x Returns: evaluated x Return type: float
-
y
(t, _t0=None)¶ value of y
Parameters: t (float) – time at which to evaluate y Returns: evaluated y Return type: float
-
class
salabim.
TrajectoryStandstill
(xy, duration, orientation=0, t0=None, env=None)¶ Standstill trajectory, to be used in Animatexxx through x, y and angle methods
Parameters: - xy (tuple or list of 2 floats) – initial (and final) position. should be like x, y
- orientation (float or callable) – orientation (angle) in degrees
a one parameter callable is also accepted (and will be called with 0)
default: 0 - t0 (float) – time the trajectory should start
default: env.now()
if not the first in a merged trajectory or AnimateQueue, ignored - env (Environment) – environment where the trajectory is defined
if omitted, default_env will be used
-
angle
(t, _t0=None)¶ value of angle (in degrees)
Parameters: t (float) – time at which to evaluate angle Returns: evaluated angle (in degrees) Return type: float
-
duration
()¶ duration of trajectory
Returns: duration of trajectory (t1 - t0) Return type: float
-
in_trajectory
(t)¶ is t in trajectory?
Parameters: t (float) – time at which to evaluate Returns: is t in trajectory? Return type: bool
-
length
(t=None, _t0=None)¶ length of traversed trajectory at time t or total length
Parameters: t (float) – time at which to evaluate length. Returns: length – always 0 Return type: float
-
rendered_polygon
(time_step=1)¶ rendered polygon
Parameters: time_step (float) – defines at which point in time the trajectory has to be rendered
default : 1Returns: polygon – rendered from t0 to t1 with time_step
can be used directly in sim.AnimatePoints() or AnimatePolygon()Return type: list of x, y
-
t0
()¶ start time of trajectory
Returns: start time of trajectory Return type: float
-
t1
()¶ end time of trajectory
Returns: end time of trajectory Return type: float
-
x
(t, _t0=None)¶ value of x
Parameters: t (float) – time at which to evaluate x Returns: evaluated x Return type: float
-
y
(t, _t0=None)¶ value of y
Parameters: t (float) – time at which to evaluate y Returns: evaluated y Return type: float
Miscellaneous¶
-
salabim.
arange
(like numpy)¶ Parameters: - start (float) – start value
- stop (: float) – stop value
- step (float) – default: 1
Returns: Return type: Iterable
Note
If numpy is installed, uses numpy.arange
-
salabim.
audio_duration
(filename)¶ duration of a audio file (usually mp3)
Parameters: filename (str) – must be a valid audio file (usually mp3) Returns: duration in seconds Return type: float Note
Only supported on Windows and Pythonista. On other platform returns 0
-
salabim.
can_animate
(try_only=True)¶ Tests whether animation is supported.
Parameters: try_only (bool) – if True (default), the function does not raise an error when the required modules cannot be imported
if False, the function will only return if the required modules could be imported.Returns: True, if required modules could be imported, False otherwise Return type: bool
-
salabim.
can_video
(try_only=True)¶ Tests whether video is supported.
Parameters: try_only (bool) – if True (default), the function does not raise an error when the required modules cannot be imported
if False, the function will only return if the required modules could be imported.Returns: True, if required modules could be imported, False otherwise Return type: bool
-
salabim.
centered_rectangle
(width, height)¶ creates a rectangle tuple with a centered rectangle for use with sim.Animate
Parameters: - width (float) – width of the rectangle
- height (float) – height of the rectangle
-
salabim.
colornames
()¶ available colornames
Returns: dict with name of color as key, #rrggbb or #rrggbbaa as value Return type: dict
-
salabim.
random_seed
(seed=None, randomstream=None, set_numpy_random_seed=True)¶ Reseeds a randomstream
Parameters: - seed (hashable object, usually int) – the seed for random, equivalent to random.seed()
if “*”, a purely random value (based on the current time) will be used (not reproducable)
if the null string, no action on random is taken
if None (the default), 1234567 will be used. - set_numpy_random_seed (bool) – if True (default), numpy.random.seed() will be called with the given seed.
This is particularly useful when using External distributions.
If numpy is not installed, this parameter is ignored
if False, numpy.random.seed is not called. - randomstream (randomstream) – randomstream to be used
if omitted, random will be used
- seed (hashable object, usually int) – the seed for random, equivalent to random.seed()
-
salabim.
default_over3d
(val=None)¶ Set default_over3d
Parameters: val (bool) – if not None, set the default_over3d to val Returns: Return type: Current (new) value of default_over3d
-
salabim.
draw_box3d
(x_len=1, y_len=1, z_len=1, x=0, y=0, z=0, x_angle=0, y_angle=0, z_angle=0, x_ref=0, y_ref=0, z_ref=0, gl_color=(1, 1, 1), show=True, edge_gl_color=(1, 1, 1), show_edge=False, shaded=False, _show_lids=True)¶ draws a 3d box (should be added to the event loop by encapsulating with Animate3dBase)
Parameters: - x_len (int, optional) – [description], by default 1
- y_len (int, optional) – [description], by default 1
- z_len (int, optional) – [description], by default 1
- x (int, optional) – [description], by default 0
- y (int, optional) – [description], by default 0
- z (int, optional) – [description], by default 0
- x_angle (int, optional) – [description], by default 0
- y_angle (int, optional) – [description], by default 0
- z_angle (int, optional) – [description], by default 0
- x_ref (int, optional) – [description], by default 0
- y_ref (int, optional) – [description], by default 0
- z_ref (int, optional) – [description], by default 0
- gl_color (tuple, optional) – [description], by default (1, 1, 1)
- show (bool, optional) – [description], by default True
- edge_gl_color (tuple, optional) – [description], by default (1, 1, 1)
- show_edge (bool, optional) – [description], by default False
- shaded (bool, optional) – [description], by default False
- _show_lids (bool, optional) – [description], by default True
-
salabim.
draw_cylinder3d
(x0=0, y0=0, z0=0, x1=1, y1=1, z1=1, gl_color=(1, 1, 1), radius=1, number_of_sides=8, rotation_angle=0, show_lids=True)¶ draws a 3d cylinder (should be added to the event loop by encapsulating with Animate3dBase)
Parameters: - x0 (int, optional) – [description], by default 0
- y0 (int, optional) – [description], by default 0
- z0 (int, optional) – [description], by default 0
- x1 (int, optional) – [description], by default 1
- y1 (int, optional) – [description], by default 1
- z1 (int, optional) – [description], by default 1
- gl_color (tuple, optional) – [description], by default (1, 1, 1)
- radius (int, optional) – [description], by default 1
- number_of_sides (int, optional) – [description], by default 8
- rotation_angle (int, optional) – [description], by default 0
- show_lids (bool, optional) – [description], by default True
-
salabim.
draw_line3d
(x0=0, y0=0, z0=0, x1=1, y1=1, z1=1, gl_color=(1, 1, 1))¶ draws a 3d line (should be added to the event loop by encapsulating with Animate3dBase)
Parameters: - x0 (int, optional) – [description], by default 0
- y0 (int, optional) – [description], by default 0
- z0 (int, optional) – [description], by default 0
- x1 (int, optional) – [description], by default 1
- y1 (int, optional) – [description], by default 1
- z1 (int, optional) – [description], by default 1
- gl_color (tuple, optional) – [description], by default (1, 1, 1)
-
salabim.
draw_rectangle3d
(x0=0, y0=0, z=0, x1=1, y1=1, gl_color=(1, 1, 1))¶ draws a 3d rectangle (should be added to the event loop by encapsulating with Animate3dBase)
Parameters: - x0 (int, optional) – [description], by default 0
- y0 (int, optional) – [description], by default 0
- z (int, optional) – [description], by default 0
- x1 (int, optional) – [description], by default 1
- y1 (int, optional) – [description], by default 1
- gl_color (tuple, optional) – [description], by default (1, 1, 1)
-
salabim.
default_env
()¶ Returns: default environment Return type: Environment
-
salabim.
interpolate
(t, t0, t1, v0, v1)¶ does linear interpolation
Parameters: - t (float) – value to be interpolated from
- t0 (float) – f(t0)=v0
- t1 (float) – f(t1)=v1
- v0 (float, list or tuple) – f(t0)=v0
- v1 (float, list or tuple) – f(t1)=v1
if list or tuple, len(v0) should equal len(v1)
Returns: linear interpolation between v0 and v1 based on t between t0 and t1
Return type: float or tuple
Note
Note that no extrapolation is done, so if t<t0 ==> v0 and t>t1 ==> v1
This function is heavily used during animation.
-
salabim.
interp
(x, xp, fp, left=None, right=None)¶ linear interpolatation
Parameters: - x (float) – target x-value
- xp (list of float, tuples or lists) – values on the x-axis
- fp (list of float, tuples of lists) – values on the y-axis
should be same length as p
Returns: interpolated value
Return type: float, tuple or list
Notes
If x < xp[0], fp[0] will be returned
If x > xp[-1], fp[-1] will be returnedThis function is similar to the numpy interp function.
-
salabim.
linspace
(start, stop, num, endpoint=True)¶ like numpy.linspace, but returns a list
Parameters: - start (float) – start of the space
- stop (float) – stop of the space
- num (int) – number of points in the space
- endpoint (bool) – if True (default), stop is last point in the space
if False, space ends before stop
-
salabim.
over3d
(val=True)¶ context manager to change temporarily default_over3d
Parameters: val (bool) – temporary value of default_over3d
default: TrueNotes
Use as
with over3d(): an = AnimateText('test')
-
salabim.
random_seed
(seed=None, randomstream=None, set_numpy_random_seed=True) Reseeds a randomstream
Parameters: - seed (hashable object, usually int) – the seed for random, equivalent to random.seed()
if “*”, a purely random value (based on the current time) will be used (not reproducable)
if the null string, no action on random is taken
if None (the default), 1234567 will be used. - set_numpy_random_seed (bool) – if True (default), numpy.random.seed() will be called with the given seed.
This is particularly useful when using External distributions.
If numpy is not installed, this parameter is ignored
if False, numpy.random.seed is not called. - randomstream (randomstream) – randomstream to be used
if omitted, random will be used
- seed (hashable object, usually int) – the seed for random, equivalent to random.seed()
-
salabim.
regular_polygon
(radius=1, number_of_sides=3, initial_angle=0)¶ creates a polygon tuple with a regular polygon (within a circle) for use with sim.Animate
Parameters: - radius (float) – radius of the corner points of the polygon
default : 1 - number_of_sides (int) – number of sides (corners)
must be >= 3
default : 3 - initial_angle (float) – angle of the first corner point, relative to the origin
default : 0
- radius (float) – radius of the corner points of the polygon
-
salabim.
reset
()¶ resets global variables
used internally at import of salabim
might be useful for REPLs or for Pythonista
-
salabim.
searchsorted
(a, v, side='left')¶ search sorted
Parameters: - a (iterable) – iterable to be searched in, must be non descending
- v (float) – value to be searched for
- side (string) – If ‘left’ (default) the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of a).
Returns: Index where v should be inserted to maintain order
Return type: int
Note
If numpy is installed, uses numpy.searchstarted
-
salabim.
show_colornames
()¶ show (print) all available color names and their value.
-
salabim.
show_fonts
()¶ show (print) all available fonts on this machine
-
salabim.
spec_to_image
(spec)¶ convert an image specification to an image
Parameters: image (str or PIL.Image.Image) – if str: filename of file to be loaded
if null string: dummy image will be returned
if PIL.Image.Image: return this image untranslatedReturns: image Return type: PIL.Image.Image