scenic.syntax.veneer
Python implementations of Scenic language constructs.
This module is automatically imported by all Scenic programs. In addition to defining the built-in functions, operators, specifiers, etc., it also stores global state such as the list of all created Scenic objects.
Summary of Module Members
Functions
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
|
The |
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The |
|
|
Activate the veneer when beginning to compile a Scenic module. |
|
Whether a Region or distribution over Regions always provides an orientation. |
|
|
|
|
|
Deactivate the veneer after compiling a Scenic module. |
Function implementing loads and stores to the 'ego' pseudo-variable. |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Are we in the middle of compiling a Scenic module? |
|
|
Convert a path relative to the calling Scenic file into an absolute path. |
|
|
|
|
|
Function implementing the mutate statement. |
|
|
|
Function implementing the param statement. |
|
|
|
|
|
|
|
|
|
|
|
|
Register a parameter whose value is given by an external sampler. |
|
Add a Scenic object to the global list of created objects. |
Function implementing the require statement. |
|
Function implementing the 'require always' statement. |
|
Function implementing the 'require eventually' statement. |
|
The built-in resample function. |
|
Get the currently-running |
|
|
|
|
|
|
|
|
|
|
|
Function implementing the 'terminate simulation when' statement. |
|
Function implementing the 'terminate when' statement. |
|
Built-in function printing a message only in verbose mode. |
|
Function implementing loads and stores to the 'workspace' pseudo-variable. |
|
|
Classes
|
Member Details
- ego(obj=None)[source]
Function implementing loads and stores to the ‘ego’ pseudo-variable.
The translator calls this with no arguments for loads, and with the source value for stores.
- workspace(workspace=None)[source]
Function implementing loads and stores to the ‘workspace’ pseudo-variable.
See
ego
.
- verbosePrint(*objects, level=1, indent=True, sep=' ', end='\n', file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, flush=False)[source]
Built-in function printing a message only in verbose mode.
Scenic’s verbosity may be set using the
-v
command-line option. The simplest way to use this function is with code likeverbosePrint('hello world!')
orverbosePrint('details here', level=3)
; the other keyword arguments are probably only useful when replacing more complex uses of the Pythonprint
function.- Parameters:
objects – Object(s) to print (
str
will be called to make them strings).level (int) – Minimum verbosity level at which to print. Default is 1.
indent (bool) – Whether to indent the message to align with messages generated by Scenic (default true).
sep – As in
print
.end – As in
print
.file – As in
print
.flush – As in
print
.
- localPath(relpath)[source]
Convert a path relative to the calling Scenic file into an absolute path.
For example,
localPath('resource.dat')
evaluates to the absolute path of a file calledresource.dat
located in the same directory as the Scenic file where this expression appears.
- simulation()[source]
Get the currently-running
Simulation
.May only be called from code that runs at simulation time, e.g. inside dynamic behaviors and
compose
blocks of scenarios.
- require_always(reqID, req, line, name)[source]
Function implementing the ‘require always’ statement.
- require_eventually(reqID, req, line, name)[source]
Function implementing the ‘require eventually’ statement.
- terminate_when(reqID, req, line, name)[source]
Function implementing the ‘terminate when’ statement.
- terminate_simulation_when(reqID, req, line, name)[source]
Function implementing the ‘terminate simulation when’ statement.
- Front(X)
The
front of <object>
operator.
- Back(X)
The
back of <object>
operator.
- Left(X)
The
left of <object>
operator.
- Right(X)
The
right of <object>
operator.
- FrontLeft(X)
The
front left of <object>
operator.
- FrontRight(X)
The
front right of <object>
operator.
- BackLeft(X)
The
back left of <object>
operator.
- BackRight(X)
The
back right of <object>
operator.
- RelativeHeading(X, Y=None)[source]
The
relative heading of <heading> [from <heading>]
operator.If the
from <heading>
is omitted, the heading of ego is used.
- ApparentHeading(X, Y=None)[source]
The
apparent heading of <oriented point> [from <vector>]
operator.If the
from <vector>
is omitted, the position of ego is used.
- RelativePosition(X, Y=None)[source]
The
relative position of <vector> [from <vector>]
operator.If the
from <vector>
is omitted, the position of ego is used.
- DistanceFrom(X, Y=None)[source]
The
distance from X to Y
polymorphic operator.Allowed forms:
distance from <vector> [to <vector>] distance from <region> [to <vector>] distance from <vector> to <region>
If the
to <vector>
is omitted, the position of ego is used.
- DistancePast(X, Y=None)[source]
The
distance past <vector> of <oriented point>
operator.If the
of {oriented point}
is omitted, the ego object is used.
- RelativeTo(X, Y)[source]
The
X relative to Y
polymorphic operator.Allowed forms:
<value> relative to <value> # with at least one a field, the other a field or heading <vector> relative to <oriented point> # and vice versa <vector> relative to <vector> <heading> relative to <heading>
- OffsetAlong(X, H, Y)[source]
The
X offset along H by Y
polymorphic operator.Allowed forms:
<vector> offset along <heading> by <vector> <vector> offset along <field> by <vector>
- CanSee(X, Y)[source]
The
X can see Y
polymorphic operator.Allowed forms:
<point> can see <object> <point> can see <vector>
- class Vector(x, y)[source]
-
A 2D vector, whose coordinates can be distributions.
- class VectorField(name, value, minSteps=4, defaultStepSize=5)[source]
A vector field, providing a heading at every point.
- Parameters:
name (str) – name for debugging.
value – function computing the heading at the given
Vector
.minSteps (int) – Minimum number of steps for
followFrom
; default 4.defaultStepSize (float) – Default step size for
followFrom
; default 5. This is an upper bound: more steps will be taken as needed to ensure that no single step is longer than this value, but if the distance to travel is small then the steps may be smaller.
- followFrom(pos, dist, steps=None, stepSize=None)[source]
Follow the field from a point for a given distance.
Uses the forward Euler approximation, covering the given distance with equal-size steps. The number of steps can be given manually, or computed automatically from a desired step size.
- Parameters:
- static forUnionOf(regions)[source]
Creates a
PiecewiseVectorField
from the union of the given regions.If none of the regions have an orientation, returns
None
instead.
- class PolygonalVectorField(name, cells, headingFunction=None, defaultHeading=None)[source]
Bases:
VectorField
A piecewise-constant vector field defined over polygonal cells.
- Parameters:
name (str) – name for debugging.
cells – a sequence of cells, with each cell being a pair consisting of a Shapely geometry and a heading. If the heading is
None
, we call the given headingFunction for points in the cell instead.headingFunction – function computing the heading for points in cells without specified headings, if any (default
None
).defaultHeading – heading for points not contained in any cell (default
None
, meaning reject such points).
- class Region(name, *dependencies, orientation=None)[source]
Bases:
Samplable
Abstract class for regions.
- intersect(other)[source]
Get a
Region
representing the intersection of this one with another.If both regions have a preferred orientation, the one of
self
is inherited by the intersection.- Return type:
- difference(other)[source]
Get a
Region
representing the difference of this one and another.- Return type:
- union(other)[source]
Get a
Region
representing the union of this one with another.Not supported by all region types.
- Return type:
- static uniformPointIn(region)[source]
Get a uniform
Distribution
over points in aRegion
.
- containsPoint(point)[source]
Check if the
Region
contains a point. Implemented by subclasses.- Return type:
- containsObject(obj)[source]
Check if the
Region
contains anObject
.The default implementation assumes the
Region
is convex; subclasses must override the method if this is not the case.- Return type:
- class PointSetRegion(name, points, kdTree=None, orientation=None, tolerance=1e-06)[source]
Bases:
Region
Region consisting of a set of discrete points.
No
Object
can be contained in aPointSetRegion
, since the latter is discrete. (This may not be true for subclasses, e.g.GridRegion
.)- Parameters:
name (str) – name for debugging
points (arraylike) – set of points comprising the region
kdTree (
scipy.spatial.KDTree
, optional) – k-D tree for the points (one will be computed if none is provided)orientation (
VectorField
; optional) – preferred orientation for the regiontolerance (float; optional) – distance tolerance for checking whether a point lies in the region
- class RectangularRegion(position, heading, width, length, name=None)[source]
Bases:
Region
A rectangular region with a possibly-random position, heading, and size.
- class CircularRegion(center, radius, resolution=32, name=None)[source]
Bases:
Region
A circular region with a possibly-random center and radius.
- class SectorRegion(center, radius, heading, angle, resolution=32, name=None)[source]
Bases:
Region
A sector of a
CircularRegion
.This region consists of a sector of a disc, i.e. the part of a disc subtended by a given arc.
- Parameters:
center (
Vector
) – center of the corresponding disc.radius (float) – radius of the disc.
heading (float) – heading of the centerline of the sector.
angle (float) – angle subtended by the sector.
resolution (int; optional) – number of vertices to use when approximating this region as a polygon.
name (str; optional) – name for debugging.
- class PolygonalRegion(points=None, polygon=None, orientation=None, name=None)[source]
Bases:
Region
Region given by one or more polygons (possibly with holes).
The region may be specified by giving either a sequence of points defining the boundary of the polygon, or a collection of
shapely
polygons (aPolygon
orMultiPolygon
).- Parameters:
points – sequence of points making up the boundary of the polygon (or
None
if using the polygon argument instead).polygon –
shapely
polygon or collection of polygons (orNone
if using the points argument instead).orientation (
VectorField
; optional) – preferred orientation to use.name (str; optional) – name for debugging.
- property boundary: PolylineRegion
Get the boundary of this region as a
PolylineRegion
.
- class PolylineRegion(points=None, polyline=None, orientation=True, name=None)[source]
Bases:
Region
Region given by one or more polylines (chain of line segments).
The region may be specified by giving either a sequence of points or
shapely
polylines (aLineString
orMultiLineString
).- Parameters:
points – sequence of points making up the polyline (or
None
if using the polyline argument instead).polyline –
shapely
polyline or collection of polylines (orNone
if using the points argument instead).orientation (optional) – preferred orientation to use, or
True
to use an orientation aligned with the direction of the polyline (the default).name (str; optional) – name for debugging.
- property start
Get an
OrientedPoint
at the start of the polyline.The OP’s heading will be aligned with the orientation of the region, if there is one (the default orientation pointing along the polyline).
- property end
Get an
OrientedPoint
at the end of the polyline.The OP’s heading will be aligned with the orientation of the region, if there is one (the default orientation pointing along the polyline).
- signedDistanceTo(point)[source]
Compute the signed distance of the PolylineRegion to a point.
The distance is positive if the point is left of the nearest segment, and negative otherwise.
- Return type:
- pointAlongBy(distance, normalized=False)[source]
Find the point a given distance along the polyline from its start.
If normalized is true, then distance should be between 0 and 1, and is interpreted as a fraction of the length of the polyline. So for example
pointAlongBy(0.5, normalized=True)
returns the polyline’s midpoint.- Return type:
- class Workspace(region=<AllRegion everywhere>)[source]
Bases:
Region
A workspace describing the fixed world of a scenario.
- Parameters:
region (Region) – The region defining the extent of the workspace (default
everywhere
).
- class Mutator[source]
An object controlling how the
mutate
statement affects anObject
.A
Mutator
can be assigned to themutator
property of anObject
to control the effect of themutate
statement. When mutation is enabled for such an object using that statement, the mutator’sappliedTo
method is called to compute a mutated version. TheappliedTo
method can also decide whether to apply mutators inherited from superclasses.- appliedTo(obj)[source]
Return a mutated copy of the given object. Implemented by subclasses.
The mutator may inspect the
mutationScale
attribute of the given object to scale its effect according to the scale given inmutate O by S
.- Returns:
A pair consisting of the mutated copy of the object (which is most easily created using
_copyWith
) together with a Boolean indicating whether the mutator inherited from the superclass (if any) should also be applied.
- class Range(*args, **kwargs)[source]
Bases:
Distribution
Uniform distribution over a range
- class DiscreteRange(*args, **kwargs)[source]
Bases:
Distribution
Distribution over a range of integers.
- class Options(*args, **kwargs)[source]
Bases:
MultiplexerDistribution
Distribution over a finite list of options.
Specified by a dict giving probabilities; otherwise uniform over a given iterable.
- Uniform(*opts)[source]
Uniform distribution over a finite list of options.
Implemented as an instance of
Options
when the set of options is known statically, and an instance ofUniformDistribution
otherwise.
- class Normal(*args, **kwargs)[source]
Bases:
Distribution
Normal distribution
- class VerifaiParameter(*args, **kwargs)[source]
Bases:
ExternalParameter
An external parameter sampled using one of VerifAI’s samplers.
- static withPrior(dist, buckets=None)[source]
Creates a
VerifaiParameter
using the given distribution as a prior.Since the VerifAI cross-entropy sampler currently only supports piecewise-constant distributions, if the prior is not of that form it may be approximated. For most built-in distributions, the approximation is exact: for a particular distribution, check its
bucket
method.
- class VerifaiRange(*args, **kwargs)[source]
Bases:
VerifaiParameter
A
Range
(real interval) sampled by VerifAI.
- class VerifaiDiscreteRange(*args, **kwargs)[source]
Bases:
VerifaiParameter
A
DiscreteRange
(integer interval) sampled by VerifAI.
- class VerifaiOptions(*args, **kwargs)[source]
Bases:
Options
An
Options
(discrete set) sampled by VerifAI.
- class Point(<specifiers>)[source]
Bases:
Constructible
The Scenic base class
Point
.The default mutator for
Point
adds Gaussian noise toposition
with a standard deviation given by thepositionStdDev
property.- Properties:
position (
Vector
; dynamic) – Position of the point. Default value is the origin.visibleDistance (float) – Distance for
can see
operator. Default value 50.width (float) – Default value zero (only provided for compatibility with operators that expect an
Object
).length (float) – Default value zero.
mutationScale (float) – Overall scale of mutations, as set by the
mutate
statement. Default value zero (mutations disabled).positionStdDev (float) – Standard deviation of Gaussian noise to add to this object’s
position
when mutation is enabled with scale 1. Default value 1.
- property visibleRegion
The visible region of this object.
The visible region of a
Point
is a disc centered at itsposition
with radiusvisibleDistance
.
- class OrientedPoint(<specifiers>)[source]
Bases:
Point
The Scenic class
OrientedPoint
.The default mutator for
OrientedPoint
adds Gaussian noise toheading
with a standard deviation given by theheadingStdDev
property, then applies the mutator forPoint
.- Properties:
heading (float; dynamic) – Heading of the
OrientedPoint
. Default value 0 (North).viewAngle (float) – View cone angle for
can see
operator. Default value 2π.headingStdDev (float) – Standard deviation of Gaussian noise to add to this object’s
heading
when mutation is enabled with scale 1. Default value 5°.
- property visibleRegion
The visible region of this object.
The visible region of an
OrientedPoint
is a sector of the disc centered at itsposition
with radiusvisibleDistance
, oriented alongheading
and subtending an angle ofviewAngle
.
- class Object(<specifiers>)[source]
Bases:
OrientedPoint
The Scenic class
Object
.This is the default base class for Scenic classes.
- Properties:
width (float) – Width of the object, i.e. extent along its X axis. Default value 1.
length (float) – Length of the object, i.e. extent along its Y axis. Default value 1.
allowCollisions (bool) – Whether the object is allowed to intersect other objects. Default value
False
.requireVisible (bool) – Whether the object is required to be visible from the
ego
object. Default valueTrue
.regionContainedIn (
Region
orNone
) – ARegion
the object is required to be contained in. IfNone
, the object need only be contained in the scenario’s workspace.cameraOffset (
Vector
) – Position of the camera for thecan see
operator, relative to the object’sposition
. Default(0, 0)
.speed (float; dynamic) – Speed in dynamic simulations. Default value 0.
velocity (
Vector
; dynamic) – Velocity in dynamic simulations. Default value is the velocity determined byself.speed
andself.heading
.angularSpeed (float; dynamic) – Angular speed in dynamic simulations. Default value 0.
behavior – Behavior for dynamic agents, if any (see Dynamic Scenarios). Default value
None
.
- startDynamicSimulation()[source]
Hook called at the beginning of each dynamic simulation.
Does nothing by default; provided for objects to do simulator-specific initialization as needed.
- property visibleRegion
The visible region of this object.
The visible region of an
Object
is a circular sector as forOrientedPoint
, except that the base of the sector may be offset fromposition
by thecameraOffset
property (to allow modeling cameras which are not located at the center of the object).
- With(prop, val)[source]
The
with <property> <value>
specifier.Specifies the given property, with no dependencies.
- In(region)[source]
The
in/on <region>
specifier.Specifies
position
, with no dependencies. Optionally specifiesheading
if the givenRegion
has a preferred orientation.
- Beyond(pos, offset, fromPt=None)[source]
The
beyond X by Y from Z
polymorphic specifier.Specifies
position
, with no dependencies.Allowed forms:
beyond <vector> by <number> [from <vector>] beyond <vector> by <vector> [from <vector>]
If the
from <vector>
is omitted, the position of ego is used.
- VisibleFrom(base)[source]
The
visible from <Point>
specifier.Specifies
position
, with no dependencies.This uses the given object’s
visibleRegion
property, and so correctly handles the view regions of Points, OrientedPoints, and Objects.
- VisibleSpec()[source]
The
visible
specifier (equivalent tovisible from ego
).Specifies
position
, with no dependencies.
- NotVisibleSpec()[source]
The
not visible
specifier (equivalent tonot visible from ego
).Specifies
position
, depending onregionContainedIn
.
- OffsetBy(offset)[source]
The
offset by <vector>
specifier.Specifies
position
, with no dependencies.
- OffsetAlongSpec(direction, offset)[source]
The
offset along X by Y
polymorphic specifier.Specifies
position
, with no dependencies.Allowed forms:
offset along <heading> by <vector> offset along <field> by <vector>
- Facing(heading)[source]
The
facing X
polymorphic specifier.Specifies
heading
, with dependencies depending on the form:facing <number> # no dependencies; facing <field> # depends on 'position'
- FacingToward(pos)[source]
The
facing toward <vector>
specifier.Specifies
heading
, depending onposition
.
- ApparentlyFacing(heading, fromPt=None)[source]
The
apparently facing <heading> [from <vector>]
specifier.Specifies
heading
, depending onposition
.If the
from <vector>
is omitted, the position of ego is used.
- LeftSpec(pos, dist=0)[source]
The
left of X by Y
polymorphic specifier.Specifies
position
, depending onwidth
. See other dependencies below.Allowed forms:
left of <oriented point> [by <scalar/vector>] # optionally specifies 'heading'; left of <vector> [by <scalar/vector>] # depends on 'heading'.
If the
by <scalar/vector>
is omitted, zero is used.
- RightSpec(pos, dist=0)[source]
The
right of X by Y
polymorphic specifier.Specifies
position
, depending onwidth
. See other dependencies below.Allowed forms:
right of <oriented point> [by <scalar/vector>] # optionally specifies 'heading'; right of <vector> [by <scalar/vector>] # depends on 'heading'.
If the
by <scalar/vector>
is omitted, zero is used.
- Ahead(pos, dist=0)[source]
The
ahead of X by Y
polymorphic specifier.Specifies
position
, depending onlength
. See other dependencies below.Allowed forms:
ahead of <oriented point> [by <scalar/vector>] # optionally specifies 'heading'; ahead of <vector> [by <scalar/vector>] # depends on 'heading'.
If the
by <scalar/vector>
is omitted, zero is used.
- Behind(pos, dist=0)[source]
The
behind X by Y
polymorphic specifier.Specifies
position
, depending onlength
. See other dependencies below.Allowed forms:
behind <oriented point> [by <scalar/vector>] # optionally specifies 'heading'; behind <vector> [by <scalar/vector>] # depends on 'heading'.
If the
by <scalar/vector>
is omitted, zero is used.
- Following(field, dist, fromPt=None)[source]
The
following F from X for D
specifier.Specifies
position
, and optionallyheading
, with no dependencies.Allowed forms:
following <field> [from <vector>] for <number>
If the
from <vector>
is omitted, the position of ego is used.
- exception GuardViolation(behavior, lineno)[source]
Bases:
Exception
Abstract exception raised when a guard of a behavior is violated.
This will never be raised directly; either of the subclasses
PreconditionViolation
orInvariantViolation
will be used, as appropriate.
- exception PreconditionViolation(behavior, lineno)[source]
Bases:
GuardViolation
Raised when a precondition is violated when invoking a behavior.
- exception InvariantViolation(behavior, lineno)[source]
Bases:
GuardViolation
Raised when an invariant is violated when invoking/resuming a behavior.
- class PropertyDefault(requiredProperties, attributes, value)[source]
A default value, possibly with dependencies.
- class Behavior(*args, **kwargs)[source]
-
Dynamic behaviors of agents.
Behavior statements are translated into definitions of subclasses of this class.
- class Monitor(*args, **kwargs)[source]
Bases:
Behavior
Monitors for dynamic simulations.
Monitor statements are translated into definitions of subclasses of this class.
- class Modifier(name, value, terminator)[source]
Bases:
NamedTuple
- _asdict()
Return a new dict which maps field names to their values.
- classmethod _make(iterable)
Make a new Modifier object from a sequence or iterable
- _replace(**kwds)
Return a new Modifier object replacing specified fields with new values
- class DynamicScenario(*args, **kwargs)[source]
Bases:
Invocable
Internal class for scenarios which can execute during dynamic simulations.
Provides additional information complementing
Scenario
, which originally only supported static scenarios. The two classes should probably eventually be merged.- classmethod _requiresArguments()[source]
Whether this scenario cannot be instantiated without arguments.
- _prepare(delayPreconditionCheck=False)[source]
Prepare the scenario for execution, executing its setup block.
- _step()[source]
Execute the (already-started) scenario for one time step.
- Returns:
None
if the scenario will continue executing; otherwise a string describing why it has terminated.