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

Ahead

The 'ahead of X [by Y]' polymorphic specifier.

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.

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.

Beyond

The 'beyond X by Y [from Z]' polymorphic specifier.

CanSee

The 'X can see Y' polymorphic operator.

DistanceFrom

The distance from {X} to {Y} polymorphic operator.

Facing

The 'facing X' polymorphic specifier.

FacingToward

The 'facing toward <vector>' specifier.

FieldAt

The '<VectorField> 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.

In

The 'in/on <region>' specifier.

Left

The 'left of <object>' operator.

LeftSpec

The 'left of X [by Y]' polymorphic specifier.

NotVisible

The 'not visible <region>' operator.

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.

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.

Visible

The 'visible <region>' operator.

VisibleFrom

The 'visible from <Point>' specifier.

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.

ego

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

endScenario

endSimulation

executeInBehavior

executeInGuard

executeInRequirement

executeInScenario

filter

finishScenarioSetup

globalParameters

in_initial_scenario

instantiateSimulator

isActive

Are we in the middle of compiling a Scenic module?

leftSpecHelper

localPath

makeRequirement

model

mutate

Function implementing the mutate statement.

param

Function implementing the param statement.

prepareScenario

record

record_final

record_initial

registerDynamicScenarioClass

registerExternalParameter

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

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.

resample

The built-in resample function.

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 when the verbosity is >0.

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.

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

Function implementing the require statement.

resample(dist)[source]

The built-in resample function.

param(*quotedParams, **params)[source]

Function implementing the param statement.

mutate(*objects)[source]

Function implementing the mutate statement.

verbosePrint(msg, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, level=1)[source]

Built-in function printing a message when the verbosity is >0.

(Or when the verbosity exceeds the specified level.)

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.

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.

FieldAt(X, Y)[source]

The ‘<VectorField> at <vector>’ operator.

RelativeTo(X, Y)[source]

The ‘X relative to Y’ polymorphic operator.

Allowed forms:

F relative to G (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>

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.

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.

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.

AngleTo(X)[source]

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

AngleFrom(X, Y)[source]

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

Follow(F, X, D)[source]

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

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]

Bases: scenic.core.distributions.Samplable, collections.abc.Sequence

A 2D vector, whose coordinates can be distributions.

rotatedBy(angle)[source]

Return a vector equal to this one rotated counterclockwise by the given angle.

Return type

scenic.core.vectors.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 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.

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)[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: scenic.core.vectors.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: scenic.core.distributions.Samplable

Abstract class for regions.

intersect(other, triedReversed=False)[source]

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

intersects(other)[source]

Check if this Region intersects another.

difference(other)[source]

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

union(other, triedReversed=False)[source]

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

Not supported by all region types.

static uniformPointIn(region)[source]

Get a uniform Distribution over points in a Region.

uniformPoint()[source]

Sample a uniformly-random point in this Region.

Can only be called on fixed Regions with no random parameters.

uniformPointInner()[source]

Do the actual random sampling. Implemented by subclasses.

containsPoint(point)[source]

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

containsObject(obj)[source]

Check if the Region contains an Object.

The default implementation assumes the Region is convex; subclasses must override the method if this is not the case.

getAABB()[source]

Axis-aligned bounding box for this Region. Implemented by some subclasses.

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: scenic.core.regions.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 (iterable) – 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) – orientation for the region

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

class PolygonalRegion(points=None, polygon=None, orientation=None, name=None)[source]

Bases: scenic.core.regions.Region

Region given by one or more polygons (possibly with holes)

class PolylineRegion(points=None, polyline=None, orientation=True, name=None)[source]

Bases: scenic.core.regions.Region

Region given by one or more polylines (chain of line segments)

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.

class Workspace(region=<AllRegion everywhere>)[source]

Bases: scenic.core.regions.Region

A workspace describing the fixed world of a scenario

show(plt)[source]

Render a schematic of the workspace 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.

appliedTo(obj)[source]

Return a mutated copy of the object. Implemented by subclasses.

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

Bases: scenic.core.distributions.Distribution

Uniform distribution over a range

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

Bases: scenic.core.distributions.Distribution

Distribution over a range of integers.

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

Bases: scenic.core.distributions.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 scenic.core.distributions.Options

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

Bases: scenic.core.distributions.Distribution

Normal distribution

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

Bases: scenic.core.distributions.Normal

Truncated normal distribution.

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

Bases: scenic.core.external_params.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: scenic.core.external_params.VerifaiParameter

A Range (real interval) sampled by VerifAI.

_defaultValueType

alias of float

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

Bases: scenic.core.external_params.VerifaiParameter

A DiscreteRange (integer interval) sampled by VerifAI.

_defaultValueType

alias of float

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

Bases: scenic.core.distributions.Options

An Options (discrete set) sampled by VerifAI.

class Point(<specifiers>)[source]

Implementation of 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.

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

Note

If you’re looking into Scenic’s internals, note that Point is actually a subclass of the internal Python class _Constructible.

class OrientedPoint(<specifiers>)[source]

Bases: scenic.core.object_types.Point

Implementation of the Scenic class OrientedPoint.

The default mutator for OrientedPoint adds Gaussian noise to heading with a standard deviation given by the headingStdDev property, then applies the mutator for Point.

Properties
  • heading (float; dynamic) – Heading of the OrientedPoint. Default value 0 (North).

  • viewAngle (float) – View cone angle for can see operator. Default value \(2\pi\).

class Object(<specifiers>)[source]

Bases: scenic.core.object_types.OrientedPoint

Implementation of 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 value True.

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

  • cameraOffset (Vector) – Position of the camera for the can see operator, relative to the object’s position. 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 by self.speed and self.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.

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/on <region>’ specifier.

Specifies ‘position’, with no dependencies. Optionally specifies ‘heading’ if the given Region 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 to ‘visible from ego’).

Specifies ‘position’, with no dependencies.

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 on ‘position’.

ApparentlyFacing(heading, fromPt=None)[source]

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

Specifies ‘heading’, depending on ‘position’.

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 on ‘width’. 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 on ‘width’. 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 on ‘length’. 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 on ‘length’. 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 optionally ‘heading’, 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: scenic.core.dynamics.GuardViolation

Raised when a precondition is violated when invoking a behavior.

exception InvariantViolation(behavior, lineno)[source]

Bases: scenic.core.dynamics.GuardViolation

Raised when an invariant is violated when invoking/resuming a behavior.

class PropertyDefault(requiredProperties, attributes, value)[source]

A default value, possibly with dependencies.

resolveFor(prop, overriddenDefs)[source]

Create a Specifier for a property from this default and any superclass defaults.

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

Bases: scenic.core.dynamics.Invocable, scenic.core.distributions.Samplable

Dynamic behaviors of agents.

Behavior statements are translated into definitions of subclasses of this class.

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

Bases: scenic.core.dynamics.Behavior

Monitors for dynamic simulations.

Monitor statements are translated into definitions of subclasses of this class.

class BlockConclusion(value)[source]

Bases: enum.Enum

An enumeration.

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

Bases: tuple

Parameters
  • name (str) –

  • value (Any) –

  • terminator (Optional[str]) –

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: scenic.core.dynamics.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)[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.