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

Above

The above X by Y polymorphic specifier.

Ahead

The ahead of X by Y polymorphic specifier.

AltitudeFrom

The altitude from <vector> to <vector> operator.

AltitudeTo

The angle to <vector> operator (using the position of ego as the reference).

Always

AngleFrom

The angle from <vector> to <vector> operator.

AngleTo

The angle to <vector> operator (using the position of ego as the reference).

ApparentHeading

The apparent heading of <oriented point> [from <vector>] operator.

ApparentlyFacing

The apparently facing <heading> [from <vector>] specifier.

At

The at <vector> specifier.

AtomicProposition

Back

The back of <object> operator.

BackLeft

The back left of <object> operator.

BackRight

The back right of <object> operator.

Behind

The behind X by Y polymorphic specifier.

Below

The below X by Y polymorphic specifier.

Beyond

The beyond X by Y from Z polymorphic specifier.

Bottom

The bottom of <object> operator.

BottomBackLeft

The bottom back left of <object> operator.

BottomBackRight

The bottom back right of <object> operator.

BottomFrontLeft

The bottom front left of <object> operator.

BottomFrontRight

The bottom front right of <object> operator.

CanSee

The X can see Y polymorphic operator.

ContainedIn

The contained in <region> specifier.

DistanceFrom

The distance from X to Y polymorphic operator.

DistancePast

The distance past <vector> of <oriented point> operator.

Eventually

Facing

The facing X polymorphic specifier.

FacingAwayFrom

The facing away from <vector> specifier.

FacingDirectlyAwayFrom

The facing directly away from <vector> specifier.

FacingDirectlyToward

The facing directly toward <vector> specifier.

FacingToward

The facing toward <vector> specifier.

FieldAt

The <vector field> at <vector> operator.

Follow

The follow <field> from <vector> for <number> operator.

Following

The following F from X for D specifier.

Front

The front of <object> operator.

FrontLeft

The front left of <object> operator.

FrontRight

The front right of <object> operator.

Implies

In

The in <region> specifier.

Intersects

The X intersects Y operator.

Left

The left of <object> operator.

LeftSpec

The left of X by Y polymorphic specifier.

Next

NotVisible

The not visible <region> operator.

NotVisibleFrom

The not visible from <point> specifier.

NotVisibleFromOp

The <region> not visible from <point> operator.

NotVisibleSpec

The not visible specifier (equivalent to not visible from ego).

OffsetAlong

The X offset along H by Y polymorphic operator.

OffsetAlongSpec

The offset along X by Y polymorphic specifier.

OffsetBy

The offset by <vector> specifier.

On

The on X specifier.

PropositionAnd

PropositionNot

PropositionOr

RelativeHeading

The relative heading of <heading> [from <heading>] operator.

RelativePosition

The relative position of <vector> [from <vector>] operator.

RelativeTo

The X relative to Y polymorphic operator.

Right

The right of <object> operator.

RightSpec

The right of X by Y polymorphic specifier.

Top

The top of <object> operator.

TopBackLeft

The top back left of <object> operator.

TopBackRight

The top back right of <object> operator.

TopFrontLeft

The top front left of <object> operator.

TopFrontRight

The top front right of <object> operator.

Until

Visible

The visible <region> operator.

VisibleFrom

The visible from <point> specifier.

VisibleFromOp

The <region> visible from <point> operator.

VisibleSpec

The visible specifier (equivalent to visible from ego).

With

The with <property> <value> specifier.

activate

Activate the veneer when beginning to compile a Scenic module.

alwaysProvidesOrientation

Whether a Region or distribution over Regions always provides an orientation.

beginSimulation

callWithStarArgs

deactivate

Deactivate the veneer after compiling a Scenic module.

directionalSpecHelper

ego

Function implementing loads and stores to the 'ego' pseudo-variable.

endScenario

endSimulation

executeInBehavior

executeInGuard

executeInRequirement

executeInScenario

filter

finishScenarioSetup

float

globalParameters

in_initial_scenario

instantiateSimulator

int

isActive

Are we in the middle of compiling a Scenic module?

len

localPath

Convert a path relative to the calling Scenic file into an absolute path.

makeRequirement

model

mutate

Function implementing the mutate statement.

new

override

param

Function implementing the param statement.

prepareScenario

projectVectorHelper

range

record

record_final

record_initial

registerDynamicScenarioClass

registerExternalParameter

Register a parameter whose value is given by an external sampler.

registerInstance

Add a Scenic instance to the global list of created objects.

registerObject

Add a Scenic object to the global list of created objects.

require

Function implementing the require statement.

require_always

Function implementing the 'require always' statement.

require_eventually

Function implementing the 'require eventually' statement.

require_monitor

resample

The built-in resample function.

round

simulation

Get the currently-running Simulation.

simulationInProgress

simulator

startScenario

str

terminate_after

terminate_simulation_when

Function implementing the 'terminate simulation when' statement.

terminate_when

Function implementing the 'terminate when' statement.

verbosePrint

Built-in function printing a message only in verbose mode.

workspace

Function implementing loads and stores to the 'workspace' pseudo-variable.

wrapStarredValue

Classes

Modifier

ParameterTableProxy

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.

require(reqID, req, line, name, prob=1)[source]

Function implementing the require statement.

resample(dist)[source]

The built-in resample function.

param(params)[source]

Function implementing the param statement.

mutate(*objects, scale=1)[source]

Function implementing the mutate statement.

verbosePrint(*objects, level=1, indent=True, sep=' ', end='\n', file=sys.stdout, 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 like verbosePrint('hello world!') or verbosePrint('details here', level=3); the other keyword arguments are probably only useful when replacing more complex uses of the Python print 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 called resource.dat located in the same directory as the Scenic file where this expression appears. Note that the path is returned as a pathlib.Path object.

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.

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.

Visible(region)[source]

The visible <region> operator.

NotVisible(region)[source]

The not visible <region> operator.

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.

Top(X)

The top of <object> operator.

Bottom(X)

The bottom of <object> operator.

TopFrontLeft(X)

The top front left of <object> operator.

TopFrontRight(X)

The top front right of <object> operator.

TopBackLeft(X)

The top back left of <object> operator.

TopBackRight(X)

The top back right of <object> operator.

BottomFrontLeft(X)

The bottom front left of <object> operator.

BottomFrontRight(X)

The bottom front right of <object> operator.

BottomBackLeft(X)

The bottom back left of <object> operator.

BottomBackRight(X)

The bottom 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.

Follow(F, X, D)[source]

The follow <field> from <vector> for <number> operator.

AngleTo(X)[source]

The angle to <vector> operator (using the position of ego as the reference).

AngleFrom(X=None, Y=None)[source]

The angle from <vector> to <vector> operator.

AltitudeTo(X)[source]

The angle to <vector> operator (using the position of ego as the reference).

AltitudeFrom(X=None, Y=None)[source]

The altitude from <vector> to <vector> operator.

FieldAt(X, Y)[source]

The <vector field> at <vector> operator.

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>
<orientation> relative to <orientation>
Return type:

Union[Vector, float, Orientation]

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 <vector>
<point> can see <point>
Intersects(X, Y)[source]

The X intersects Y operator.

VisibleFromOp(region, base)[source]

The <region> visible from <point> operator.

NotVisibleFromOp(region, base)[source]

The <region> not visible from <point> operator.

class Vector(x, y, z=0)[source]

Bases: Samplable, Sequence

A 3D vector, whose coordinates can be distributions.

sphericalCoordinates()[source]

Returns this vector in spherical coordinates (rho, theta, phi)

rotatedBy(angleOrOrientation)[source]

Return a vector equal to this one rotated counterclockwise by angle/orientation.

Return type:

Vector

angleWith(other)[source]

Compute the signed angle between self and other.

The angle is positive if other is counterclockwise of self (considering the smallest possible rotation to align them).

Return type:

float

class Orientation(rotation)[source]

An orientation in 3D space.

classmethod fromQuaternion(quaternion)[source]

Create an Orientation from a quaternion (of the form (x,y,z,w))

Return type:

Orientation

classmethod fromEuler(yaw, pitch, roll)[source]

Create an Orientation from yaw, pitch, and roll angles (in radians).

Return type:

Orientation

property yaw: float

Yaw in the global coordinate system.

property pitch: float

Pitch in the global coordinate system.

property roll: float

Roll in the global coordinate system.

property eulerAngles: Tuple[float, float, float]

Global intrinsic Euler angles yaw, pitch, roll.

localAnglesFor(orientation)[source]

Get local Euler angles for an orientation w.r.t. this orientation.

That is, considering self as the parent orientation, find the Euler angles expressing the given orientation.

Return type:

Tuple[float, float, float]

globalToLocalAngles(yaw, pitch, roll)[source]

Convert global Euler angles to local angles w.r.t. this orientation.

Equivalent to localAnglesFor but takes Euler angles as input.

Return type:

Tuple[float, float, float]

class VectorField(name, value, minSteps=4, defaultStepSize=5)[source]

A vector field, providing an orientation 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:
  • pos (Vector) – point to start from.

  • dist (float) – distance to travel.

  • steps (int) – number of steps to take, or None to compute the number of steps based on the distance (default None).

  • stepSize (float) – length used to compute how many steps to take, or None to use the field’s default step size.

static forUnionOf(regions, tolerance=0)[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 Shape(dimensions, scale)[source]

Bases: ABC

An abstract base class for Scenic shapes.

Represents a physical shape in Scenic. Does not encode position or orientation, which are handled by the Region class. Does contain dimension information, which is used as a default value by any Object with this shape and can be overwritten.

If dimensions and scale are both specified the dimensions are first set by dimensions, and then scaled by scale.

Parameters:
  • dimensions – The raw (before scaling) dimensions of the shape.

  • scale – Scales all the dimensions of the shape by a multiplicative factor.

property containsCenter

Whether or not this object contains its central point

class MeshShape(mesh, dimensions=None, scale=1, initial_rotation=None)[source]

Bases: Shape

A Shape subclass defined by a trimesh.base.Trimesh object.

The mesh passed must be a trimesh.base.Trimesh object that represents a well defined volume (i.e. the is_volume property must be true), meaning the mesh must be watertight, have consistent winding and have outward facing normals.

Parameters:
  • mesh – A mesh object.

  • dimensions – The raw (before scaling) dimensions of the shape. If dimensions and scale are both specified the dimensions are first set by dimensions, and then scaled by scale.

  • scale – Scales all the dimensions of the shape by a multiplicative factor. If dimensions and scale are both specified the dimensions are first set by dimensions, and then scaled by scale.

  • initial_rotation – A 3-tuple containing the yaw, pitch, and roll respectively to apply when loading the mesh. Note the initial_rotation must be fixed.

classmethod fromFile(path, unify=True, **kwargs)[source]

Load a mesh shape from a file, attempting to infer filetype and compression.

For example: “foo.obj.bz2” is assumed to be a compressed .obj file. “foo.obj” is assumed to be an uncompressed .obj file. “foo” is an unknown filetype, so unless a filetype is provided an exception will be raised.

Parameters:
  • path (str) – Path to the file to import.

  • filetype (str) – Filetype of file to be imported. This will be inferred if not provided. The filetype must be one compatible with trimesh.load.

  • compressed (bool) – Whether or not this file is compressed (with bz2). This will be inferred if not provided.

  • binary (bool) – Whether or not to open the file as a binary file.

  • unify (bool) – Whether or not to attempt to unify this mesh.

  • kwargs – Additional arguments to the MeshShape initializer.

class BoxShape(dimensions=(1, 1, 1), scale=1, initial_rotation=None)[source]

Bases: MeshShape

A box shape with all dimensions 1 by default.

class CylinderShape(dimensions=(1, 1, 1), scale=1, initial_rotation=None, sections=24)[source]

Bases: MeshShape

A cylinder shape with all dimensions 1 by default.

class ConeShape(dimensions=(1, 1, 1), scale=1, initial_rotation=None)[source]

Bases: MeshShape

A cone shape with all dimensions 1 by default.

class SpheroidShape(dimensions=(1, 1, 1), scale=1, initial_rotation=None)[source]

Bases: MeshShape

A spheroid shape with all dimensions 1 by default.

class MeshVolumeRegion(*args, **kwargs)[source]

Bases: MeshRegion

A region representing the volume of a mesh.

The mesh passed must be a trimesh.base.Trimesh object that represents a well defined volume (i.e. the is_volume property must be true), meaning the mesh must be watertight, have consistent winding and have outward facing normals.

The mesh is first placed so the origin is at the center of the bounding box (unless centerMesh is False). The mesh is scaled to dimensions, translated so the center of the bounding box of the mesh is at positon, and then rotated to rotation.

Meshes are centered by default (since centerMesh is true by default). If you disable this operation, do note that scaling and rotation transformations may not behave as expected, since they are performed around the origin.

Parameters:
  • mesh – The base mesh for this region.

  • name – An optional name to help with debugging.

  • dimensions – An optional 3-tuple, with the values representing width, length, height respectively. The mesh will be scaled such that the bounding box for the mesh has these dimensions.

  • position – An optional position, which determines where the center of the region will be.

  • rotation – An optional Orientation object which determines the rotation of the object in space.

  • orientation – An optional vector field describing the preferred orientation at every point in the region.

  • tolerance – Tolerance for internal computations.

  • centerMesh – Whether or not to center the mesh after copying and before transformations.

  • onDirection – The direction to use if an object being placed on this region doesn’t specify one.

intersects(other, triedReversed=False)[source]

Check if this region intersects another.

This function handles intersect calculations for MeshVolumeRegion with: * MeshVolumeRegion * MeshSurfaceRegion * PolygonalFootprintRegion

containsPoint(point)[source]

Check if this region’s volume contains a point.

containsObject(obj)[source]

Check if this region’s volume contains an Object.

intersect(other, triedReversed=False)[source]

Get a Region representing the intersection of this region with another.

This function handles intersection computation for MeshVolumeRegion with: * MeshVolumeRegion * PolygonalFootprintRegion * PolygonalRegion * PathRegion * PolylineRegion

union(other, triedReversed=False)[source]

Get a Region representing the union of this region with another.

This function handles union computation for MeshVolumeRegion with:
difference(other, debug=False)[source]

Get a Region representing the difference of this region with another.

This function handles union computation for MeshVolumeRegion with: * MeshVolumeRegion * PolygonalFootprintRegion

distanceTo(point)[source]

Get the minimum distance from this region to the specified point.

voxelized(pitch, lazy=False)[source]

Returns a VoxelRegion representing a filled voxelization of this mesh

_erodeOverapproximate(maxErosion, pitch)[source]

Compute an overapproximation of this region eroded.

Erode as much as possible, but no more than maxErosion, outputting a VoxelRegion. Note that this can sometimes return a larger region than the original mesh

_bufferOverapproximate(minBuffer, pitch)[source]

Compute an overapproximation of this region buffered.

Buffer as little as possible, but at least minBuffer. If pitch is less than 1, the output is a VoxelRegion. If pitch is 1, a fast path is taken which returns a BoxRegion.

getSurfaceRegion()[source]

Return a region equivalent to this one, except as a MeshSurfaceRegion

getVolumeRegion()[source]

Returns this object, as it is already a MeshVolumeRegion

class MeshSurfaceRegion(*args, orientation=True, **kwargs)[source]

Bases: MeshRegion

A region representing the surface of a mesh.

The mesh is first placed so the origin is at the center of the bounding box (unless centerMesh is False). The mesh is scaled to dimensions, translated so the center of the bounding box of the mesh is at positon, and then rotated to rotation.

Meshes are centered by default (since centerMesh is true by default). If you disable this operation, do note that scaling and rotation transformations may not behave as expected, since they are performed around the origin.

If an orientation is not passed to this mesh, a default orientation is provided which provides an orientation that aligns an object’s z axis with the normal vector of the face containing that point, and has a yaw aligned with a yaw of 0 in the global coordinate system.

Parameters:
  • mesh – The base mesh for this region.

  • name – An optional name to help with debugging.

  • dimensions – An optional 3-tuple, with the values representing width, length, height respectively. The mesh will be scaled such that the bounding box for the mesh has these dimensions.

  • position – An optional position, which determines where the center of the region will be.

  • rotation – An optional Orientation object which determines the rotation of the object in space.

  • orientation – An optional vector field describing the preferred orientation at every point in the region.

  • tolerance – Tolerance for internal computations.

  • centerMesh – Whether or not to center the mesh after copying and before transformations.

  • onDirection – The direction to use if an object being placed on this region doesn’t specify one.

intersects(other, triedReversed=False)[source]

Check if this region’s surface intersects another.

This function handles intersection computation for MeshSurfaceRegion with: * MeshSurfaceRegion * PolygonalFootprintRegion

containsPoint(point)[source]

Check if this region’s surface contains a point.

distanceTo(point)[source]

Get the minimum distance from this object to the specified point.

getFlatOrientation(pos)[source]

Get a flat orientation at a point in the region.

Given a point on the surface of the mesh, returns an orientation that aligns an instance’s z axis with the normal vector of the face containing that point. Since there are infinitely many such orientations, the orientation returned has yaw aligned with a global yaw of 0.

If pos is not within self.tolerance of the surface of the mesh, a RejectionException is raised.

getVolumeRegion()[source]

Return a region equivalent to this one, except as a MeshVolumeRegion

getSurfaceRegion()[source]

Returns this object, as it is already a MeshSurfaceRegion

class BoxRegion(*args, **kwargs)[source]

Bases: MeshVolumeRegion

Region in the shape of a rectangular cuboid, i.e. a box.

By default the unit box centered at the origin and aligned with the axes is used.

Parameters are the same as MeshVolumeRegion, with the exception of the mesh parameter which is excluded.

class SpheroidRegion(*args, **kwargs)[source]

Bases: MeshVolumeRegion

Region in the shape of a spheroid.

By default the unit sphere centered at the origin and aligned with the axes is used.

Parameters are the same as MeshVolumeRegion, with the exception of the mesh parameter which is excluded.

class PathRegion(points=None, polylines=None, tolerance=1e-08, orientation=True, name=None)[source]

Bases: Region

A region composed of multiple polylines in 3D space.

One of points or polylines should be provided.

Parameters:
  • points – A list of points defining a single polyline.

  • polylines – A list of list of points, defining multiple polylines.

  • orientation (optional) – preferred orientation to use, or True to use an orientation aligned with the direction of the path (the default).

  • tolerance – Tolerance used internally.

_segmentDistanceHelper(point)[source]

Returns distance to point from each line segment

class Region(name, *dependencies, orientation=None)[source]

Bases: Samplable, ABC

An abstract base class for Scenic Regions

abstract uniformPointInner()[source]

Do the actual random sampling. Implemented by subclasses.

abstract containsPoint(point)[source]

Check if the Region contains a point. Implemented by subclasses.

Return type:

bool

abstract containsObject(obj)[source]

Check if the Region contains an Object

Return type:

bool

abstract containsRegionInner(reg, tolerance)[source]

Check if the Region contains a Region

Return type:

bool

abstract distanceTo(point)[source]

Distance to this region from a given point.

Return type:

float

abstract projectVector(point, onDirection)[source]

Returns point projected onto this region along onDirection.

abstract property AABB

Axis-aligned bounding box for this Region.

intersects(other)[source]

Check if this Region intersects another.

Return type:

bool

intersect(other, triedReversed=False)[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:

Region

union(other, triedReversed=False)[source]

Get a Region representing the union of this one with another.

Not supported by all region types.

Return type:

Region

difference(other)[source]

Get a Region representing the difference of this one and another.

Not supported by all region types.

Return type:

Region

_trueContainsPoint(point)[source]

Whether or not this region could produce point when sampled.

By default this method calls containsPoint, but should be overwritten if containsPoint does not properly represent the points that can be sampled.

Return type:

bool

static uniformPointIn(region, tag=None)[source]

Get a uniform Distribution over points in a Region.

orient(vec)[source]

Orient the given vector along the region’s orientation, if any.

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 a PointSetRegion, 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 region

  • tolerance (float; optional) – distance tolerance for checking whether a point lies in the region

class RectangularRegion(position, heading, width, length, name=None)[source]

Bases: PolygonalRegion

A rectangular region with a possibly-random position, heading, and size.

Parameters:
  • position (Vector) – center of the rectangle.

  • heading (float) – the heading of the length axis of the rectangle.

  • width (float) – width of the rectangle.

  • length (float) – length of the rectangle.

  • name (str; optional) – name for debugging.

class CircularRegion(center, radius, resolution=32, name=None)[source]

Bases: PolygonalRegion

A circular region with a possibly-random center and radius.

Parameters:
  • center (Vector) – center of the disc.

  • radius (float) – radius of the disc.

  • resolution (int; optional) – number of vertices to use when approximating this region as a polygon.

  • name (str; optional) – name for debugging.

class SectorRegion(center, radius, heading, angle, resolution=32, name=None)[source]

Bases: PolygonalRegion

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, z=0, orientation=None, name=None, additionalDeps=[])[source]

Bases: Region

Region given by one or more polygons (possibly with holes) at a fixed z coordinate.

The region may be specified by giving either a sequence of points defining the boundary of the polygon, or a collection of shapely polygons (a Polygon or MultiPolygon).

Parameters:
  • points – sequence of points making up the boundary of the polygon (or None if using the polygon argument instead).

  • polygonshapely polygon or collection of polygons (or None if using the points argument instead).

  • z – The z coordinate the polygon is located at.

  • 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 (a LineString or MultiLineString).

Parameters:
  • points – sequence of points making up the polyline (or None if using the polyline argument instead).

  • polylineshapely polyline or collection of polylines (or None 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 orientation 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 orientation 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:

float

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:

Vector

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).

show3D(viewer)[source]

Render a schematic of the workspace (in 3D) for debugging

show2D(plt)[source]

Render a schematic of the workspace (in 2D) for debugging

zoomAround(plt, objects, expansion=1)[source]

Zoom the schematic around the specified objects

scenicToSchematicCoords(coords)[source]

Convert Scenic coordinates to those used for schematic rendering.

class Mutator[source]

An object controlling how the mutate statement affects an Object.

A Mutator can be assigned to the mutator property of an Object to control the effect of the mutate statement. When mutation is enabled for such an object using that statement, the mutator’s appliedTo method is called to compute a mutated version. The appliedTo 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 in mutate 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(low, high)[source]

Bases: Distribution

Uniform distribution over a range

class DiscreteRange(low, high, weights=None, emptyMessage='empty DiscreteRange')[source]

Bases: Distribution

Distribution over a range of integers.

class Options(opts)[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 of UniformDistribution otherwise.

Discrete

alias of Options

class Normal(mean, stddev)[source]

Bases: Distribution

Normal distribution

class TruncatedNormal(mean, stddev, low, high)[source]

Bases: Normal

Truncated normal distribution.

class VerifaiParameter(domain)[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(low, high, buckets=None, weights=None)[source]

Bases: VerifaiParameter

A Range (real interval) sampled by VerifAI.

_defaultValueType

alias of float

class VerifaiDiscreteRange(low, high, weights=None)[source]

Bases: VerifaiParameter

A DiscreteRange (integer interval) sampled by VerifAI.

_defaultValueType

alias of float

class VerifaiOptions(opts)[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 to position with a standard deviation given by the positionStdDev property.

Properties:
  • position (Vector; dynamic) – Position of the point. Default value is the origin (0,0,0).

  • width (float) – Default value 0 (only provided for compatibility with operators that expect an Object).

  • length (float) – Default value 0.

  • height (float) – Default value 0.

  • baseOffset (Vector) – Only provided for compatibility with the on (region | Object | vector) specifier. Default value is (0,0,0).

  • contactTolerance (float) – Only provided for compatibility with the specifiers that expect an Object. Default value 0.

  • onDirection (Vector) – The direction used to determine where to place this Point on a region, when using the modifying on specifier. See the on region page for more details. Default value is None, indicating the direction will be inferred from the region this object is being placed on.

  • visibleDistance (float) – Distance used to determine the visible range of this object. Default value 50.

  • viewRayDensity (float) – By default determines the number of rays used during visibility checks. This value is the density of rays per degree of visible range in one dimension. The total number of rays sent will be this value squared per square degree of this object’s view angles. This value determines the default value for viewRayCount, so if viewRayCount is overwritten this value is ignored. Default value 5.

  • viewRayCount (None | tuple[float, float]) – The total number of horizontal and vertical view angles to be sent, or None if this value should be computed automatically. Default value None.

  • viewRayDistanceScaling (bool) – Whether or not the number of rays should scale with the distance to the object. Ignored if viewRayCount is passed. Default value False.

  • mutationScale (float) – Overall scale of mutations, as set by the mutate statement. Default value 0 (mutations disabled).

  • positionStdDev (tuple[float, float, float]) – Standard deviation of Gaussian noise for each dimension (x,y,z) to be added to this object’s position when mutation is enabled with scale 1. Default value (1,1,0), mutating only the x,y values of the point.

property visibleRegion

The visible region of this object.

The visible region of a Point is a sphere centered at its position with radius visibleDistance.

canSee(other, occludingObjects=(), debug=False)[source]

Whether or not this Point can see other.

Parameters:
  • other – A Point, OrientedPoint, or Object to check for visibility.

  • occludingObjects – A list of objects that can occlude visibility.

Return type:

bool

class OrientedPoint <specifiers>[source]

Bases: Point

The Scenic class OrientedPoint.

The default mutator for OrientedPoint adds Gaussian noise to yaw, pitch and roll, using the three standard deviations (for yaw/pitch/roll respectively) given by the orientationStdDev property. It then also applies the mutator for Point. By default the standard deviations for pitch and roll are zero so that, by default, only yaw is mutated.

Properties:
  • yaw (float; dynamic) – Yaw of the OrientedPoint in radians in the local coordinate system provided by parentOrientation. Default value 0.

  • pitch (float; dynamic) – Pitch of the OrientedPoint in radians in the local coordinate system provided by parentOrientation. Default value 0.

  • roll (float; dynamic) – Roll of the OrientedPoint in radians in the local coordinate system provided by parentOrientation. Default value 0.

  • parentOrientation (Orientation) – The local coordinate system that the OrientedPoint’s yaw, pitch, and roll are interpreted in. Default value is the global coordinate system, where an object is flat in the XY plane, facing North.

  • orientation (Orientation; dynamic; final) – The orientation of the OrientedPoint relative to the global coordinate system. Derived from the yaw, pitch, roll, and parentOrientation of this OrientedPoint and non-overridable.

  • heading (float; dynamic; final) – Yaw value of this OrientedPoint in the global coordinate system. Derived from orientation and non-overridable.

  • viewAngles (tuple[float,float]) – Horizontal and vertical view angles of this OrientedPoint in radians. Horizontal view angle can be up to 2π and vertical view angle can be up to π. Values greater than these will be truncated. Default value is (2π, π)

  • orientationStdDev (tuple[float,float,float]) – Standard deviation of Gaussian noise to add to this object’s Euler angles (yaw, pitch, roll) when mutation is enabled with scale 1. Default value (5°, 0, 0), mutating only the yaw of this OrientedPoint.

property visibleRegion

The visible region of this object.

The visible region of an OrientedPoint restricts that of Point (a sphere with radius visibleDistance) based on the value of viewAngles. In general, it is a capped rectangular pyramid subtending an angle of viewAngles[0] horizontally and viewAngles[1] vertically, as long as those angles are less than π/2; larger angles yield various kinds of wrap-around regions. See ViewRegion for details.

canSee(other, occludingObjects=(), debug=False)[source]

Whether or not this OrientedPoint can see other.

Parameters:
  • other – A Point, OrientedPoint, or Object to check for visibility.

  • occludingObjects – A list of objects that can occlude visibility.

Return type:

bool

distancePast(vec)[source]

Distance past a given point, assuming we’ve been moving in a straight line.

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 of 1 inherited from the object’s shape.

  • length (float) – Length of the object, i.e. extent along its Y axis. Default value of 1 inherited from the object’s shape.

  • height (float) – Height of the object, i.e. extent along its Z axis. Default value of 1 inherited from the object’s shape.

  • shape (Shape) – The shape of the object, which must be an instance of Shape. The default shape is a box, with default unit dimensions.

  • allowCollisions (bool) – Whether the object is allowed to intersect other objects. Default value False.

  • regionContainedIn (Region or None) – A Region the object is required to be contained in. If None, the object need only be contained in the scenario’s workspace.

  • baseOffset (Vector) – An offset from the position of the Object to the base of the object, used by the on (region | Object | vector) specifier. Default value is (0, 0, -self.height/2), placing the base of the Object at the bottom center of the Object’s bounding box.

  • contactTolerance (float) – The maximum distance this object can be away from a surface to be considered on the surface. Objects are placed at half this distance away from a point when the on (region | Object | vector) specifier or a directional specifier like (left | right) of Object [by scalar] is used. Default value 1e-4.

  • sideComponentThresholds (DimensionLimits) – Used to determine the various sides of an object (when using the default implementation). The three interior 2-tuples represent the maximum and minimum bounds for each dimension’s (x,y,z) surface. See defaultSideSurface for details. Default value ((-0.5, 0.5), (-0.5, 0.5), (-0.5, 0.5)).

  • cameraOffset (Vector) – Position of the camera for the can see operator, relative to the object’s position. Default (0, 0, 0).

  • requireVisible (bool) – Whether the object is required to be visible from the ego object. Default value False.

  • occluding (bool) – Whether or not this object can occlude other objects. Default value True.

  • showVisibleRegion (bool) – Whether or not to display the visible region in the Scenic internal visualizer.

  • color (tuple[float, float, float, float] or tuple[float, float, float] or None) – An optional color (with optional alpha) property that is used by the internal visualizer, or possibly simulators. All values should be between 0 and 1. Default value None

  • velocity (Vector; dynamic) – Velocity in dynamic simulations. Default value is the velocity determined by speed and orientation.

  • speed (float; dynamic) – Speed in dynamic simulations. Default value 0.

  • angularVelocity (Vector; dynamic)

  • angularSpeed (float; dynamic) – Angular speed in dynamic simulations. Default value 0.

  • behavior – Behavior for dynamic agents, if any (see Dynamic Scenarios). Default value None.

  • lastActions – Tuple of actions taken by this agent in the last time step (or None if the object is not an agent or this is the first time step).

startDynamicSimulation()[source]

Hook called when the object is created in a dynamic simulation.

Does nothing by default; provided for objects to do simulator-specific initialization as needed.

Changed in version 3.0: This method is called on objects created in the middle of dynamic simulations, not only objects present in the initial scene.

containsPoint(point)[source]

Whether or not the space this object occupies contains a point

distanceTo(point)[source]

The minimal distance from the space this object occupies to a given point

intersects(other)[source]

Whether or not this object intersects another object or region

property visibleRegion

The visible region of this object.

The visible region of an Object is the same as that of an OrientedPoint (see OrientedPoint.visibleRegion) except that it is offset by the value of cameraOffset (which is the zero vector by default).

canSee(other, occludingObjects=(), debug=False)[source]

Whether or not this Object can see other.

Parameters:
  • other – A Point, OrientedPoint, or Object to check for visibility.

  • occludingObjects – A list of objects that can occlude visibility.

Return type:

bool

property corners

A tuple containing the corners of this object’s bounding box

property occupiedSpace

A region representing the space this object occupies

property _isConvex

Whether this object’s shape is convex

property boundingBox

A region representing this object’s bounding box

property inradius

A lower bound on the inradius of this object

property planarInradius

A lower bound on the planar inradius of this object.

This is defined as the inradius of the polygon of the occupiedSpace of this object projected into the XY plane, assuming that pitch and roll are both 0.

property surface

A region containing the entire surface of this object

property onSurface

The surface used by the on specifier.

This region is used to sample position when another object is placed on this object. By default the top surface of this object (topSurface), but can be overwritten by subclasses.

property topSurface

A region containing the top surface of this object

For how this surface is computed, see defaultSideSurface.

property rightSurface

A region containing the right surface of this object

For how this surface is computed, see defaultSideSurface.

property leftSurface

A region containing the left surface of this object

For how this surface is computed, see defaultSideSurface.

property frontSurface

A region containing the front surface of this object

For how this surface is computed, see defaultSideSurface.

property backSurface

A region containing the back surface of this object

For how this surface is computed, see defaultSideSurface.

property bottomSurface

A region containing the bottom surface of this object

For how this surface is computed, see defaultSideSurface.

property _isPlanarBox

Whether this object is a box aligned with the XY plane.

With(prop, val)[source]

The with <property> <value> specifier.

Specifies the given property, with no dependencies.

At(pos)[source]

The at <vector> specifier.

Specifies position, with no dependencies.

In(region)[source]

The in <region> specifier.

Specifies position, and optionally, parentOrientation if the given region has a preferred orientation, with no dependencies.

ContainedIn(region)[source]

The contained in <region> specifier.

Specifies position, regionContainedIn, and optionally, parentOrientation if the given region has a preferred orientation, with no dependencies.

On(thing)[source]

The on X specifier.

Specifies position, and optionally, parentOrientation if the given region has a preferred orientation. Depends on onDirection, baseOffset, and contactTolerance.

Note that while on can be used with Region, Object and Vector, it cannot be used with a distribution containing anything other than Region.

May be used to modify an already-specified position property.

Allowed forms:

on <region> on <object> on <vector>

Beyond(pos, offset, fromPt=None)[source]

The beyond X by Y from Z polymorphic specifier.

Specifies position, and optionally parentOrientation, 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 _observingEntity and position, with no dependencies.

NotVisibleFrom(base)[source]

The not visible from <point> specifier.

Specifies _nonObservingEntity and position, depending on regionContainedIn.

See VisibleFrom.

VisibleSpec()[source]

The visible specifier (equivalent to visible from ego).

Specifies _observingEntity and position, with no dependencies.

NotVisibleSpec()[source]

The not visible specifier (equivalent to not visible from ego).

Specifies _nonObservingEntity and position, depending on regionContainedIn.

OffsetBy(offset)[source]

The offset by <vector> specifier.

Specifies position, and optionally parentOrientation, with no dependencies.

OffsetAlongSpec(direction, offset)[source]

The offset along X by Y polymorphic specifier.

Specifies position, and optionally parentOrientation, with no dependencies.

Allowed forms:

offset along <heading> by <vector>
offset along <field> by <vector>
Facing(heading)[source]

The facing X polymorphic specifier.

Specifies yaw, pitch, and roll, depending on parentOrientation, and depending on the form:

facing <number>     # no further dependencies;
facing <field>      # depends on 'position'
ApparentlyFacing(heading, fromPt=None)[source]

The apparently facing <heading> [from <vector>] specifier.

Specifies yaw, depending on position and parentOrientation.

If the from <vector> is omitted, the position of ego is used.

FacingToward(pos)[source]

The facing toward <vector> specifier.

Specifies yaw, depending on position and parentOrientation.

FacingDirectlyToward(pos)[source]

The facing directly toward <vector> specifier.

Specifies yaw and pitch, depends on position and parentOrientation.

FacingAwayFrom(pos)[source]

The facing away from <vector> specifier.

Specifies yaw, depending on position and parentOrientation.

FacingDirectlyAwayFrom(pos)[source]

The facing directly away from <vector> specifier.

Specifies yaw and pitch, depending on position and parentOrientation.

LeftSpec(pos, dist=None)[source]

The left of X by Y polymorphic specifier.

Specifies position, and optionally, parentOrientation, depending on width.

Allowed forms:

left of <oriented point> [by <scalar/vector>]
left of <vector> [by <scalar/vector>]

If the by <scalar/vector> is omitted, the object’s contact tolerance is used.

RightSpec(pos, dist=None)[source]

The right of X by Y polymorphic specifier.

Specifies position, and optionally parentOrientation, depending on width.

Allowed forms:

right of <oriented point> [by <scalar/vector>]
right of <vector> [by <scalar/vector>]

If the by <scalar/vector> is omitted, zero is used.

Ahead(pos, dist=None)[source]

The ahead of X by Y polymorphic specifier.

Specifies position, and optionally parentOrientation, depending on length.

Allowed forms:

ahead of <oriented point> [by <scalar/vector>]
ahead of <vector> [by <scalar/vector>]

If the by <scalar/vector> is omitted, the object’s contact tolerance is used.

Behind(pos, dist=None)[source]

The behind X by Y polymorphic specifier.

Specifies position, and optionally parentOrientation, depending on length.

Allowed forms:

behind <oriented point> [by <scalar/vector>]
behind <vector> [by <scalar/vector>]

If the by <scalar/vector> is omitted, the object’s contact tolerance is used.

Above(pos, dist=None)[source]

The above X by Y polymorphic specifier.

Specifies position, and optionally parentOrientation, depending on height.

Allowed forms:

above <oriented point> [by <scalar/vector>]
above <vector> [by <scalar/vector>]

If the by <scalar/vector> is omitted, the object’s contact tolerance is used.

Below(pos, dist=None)[source]

The below X by Y polymorphic specifier.

Specifies :prop`position`, and optionally parentOrientation, depending on height.

Allowed forms:

below <oriented point> [by <scalar/vector>]
below <vector> [by <scalar/vector>]

If the by <scalar/vector> is omitted, the object’s contact tolerance is used.

Following(field, dist, fromPt=None)[source]

The following F from X for D specifier.

Specifies position, and optionally parentOrientation, 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 or InvariantViolation will be used, as appropriate.

exception PreconditionViolation(behavior, lineno)[source]

Bases: GuardViolation

Exception raised when a precondition is violated.

Raised when a precondition is violated when invoking a behavior or when a precondition encounters a RejectionException, so that rejections count as precondition violations.

exception InvariantViolation(behavior, lineno)[source]

Bases: GuardViolation

Exception raised when an invariant is violated.

Raised when an invariant is violated when invoking/resuming a behavior or when an invariant encounters a RejectionException, so that rejections count as invariant violations.

exception RejectionException[source]

Bases: Exception

Exception used to signal that the sample currently being generated must be rejected.

_scenic_default

alias of PropertyDefault

class Behavior(*args, **kwargs)[source]

Bases: Invocable, Samplable

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 BlockConclusion(value)[source]

Bases: Enum

An enumeration.

class Modifier(name, value, terminator)[source]

Bases: NamedTuple

Parameters:
name: str

Alias for field number 0

value: Any

Alias for field number 1

terminator: Optional[str]

Alias for field number 2

_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.

_bindTo(scene)[source]

Bind this scenario to a sampled scene when starting a new simulation.

_prepare(delayPreconditionCheck=False)[source]

Prepare the scenario for execution, executing its setup block.

_start()[source]

Start the scenario, starting its compose block, behaviors, and monitors.

_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.

_stop(reason, quiet=False)[source]

Stop the scenario’s execution, for the given reason.

_addRequirement(ty, reqID, req, line, name, prob)[source]

Save a requirement defined at compile-time for later processing.

_addDynamicRequirement(ty, req, line, name)[source]

Add a requirement defined during a dynamic simulation.

_addMonitor(monitor)[source]

Add a monitor during a dynamic simulation.