differt2d.scene module

Scenes for tracing rays between transmitters and receivers.

class Scene(transmitters=<factory>, receivers=<factory>, objects=())[source]

Bases: Module, Plottable, Generic[Obj]

2D Scene made of objects, one or more transmitting node(s), and one or more receiving node(s).

Parameters:
transmitters: Mapping[str, Point]

The transmitting nodes.

receivers: Mapping[str, Point]

The receiving nodes.

objects: Sequence[TypeVar(Obj, bound= Object, covariant=True)] = ()

The sequence of objects in the scene.

with_transmitters(**transmitters)[source]

Returns a copy of this scene, with the given transmitters.

Parameters:

transmitters (Point) – A mapping of transmitter names and points.

Return type:

Self

Returns:

The new scene.

with_receivers(**receivers)[source]

Returns a copy of this scene, with the given receivers.

Parameters:

receivers (Point) – A mapping of receiver names and points.

Return type:

Self

Returns:

The new scene.

with_objects(*objects)[source]

Returns a copy of this scene, with the given objects.

Parameters:

objects (Object) – A sequence of objects.

Return type:

Self

Returns:

The new scene.

filter_objects(filter_spec)[source]

Returns a copy of this scene, with the given objects filtered out.

Parameters:

filter_spec (Callable[[Object], bool]) – A callable indicating which objects should be kept.

Return type:

Self

Returns:

The new scene.

Examples:

A practical use case for this function is to plot a basic scene, but only perform ray tracing on a subset of the objects, e.g., simulating only vertex diffraction.

Warning

If you only want to simulate vertex diffraction, but still take the objects into account for possible obstruction, prefer using the filter_objects parameter in all_path_candidates and associated methods.

import jax
import matplotlib.pyplot as plt

from differt2d.geometry import FermatPath, Vertex
from differt2d.scene import Scene

ax = plt.gca()
scene = Scene.square_scene_with_wall()
wall = scene.objects[-1]
scene = scene.add_objects(*wall.get_vertices())
_ = scene.plot(ax)
scene = scene.filter_objects(lambda o: isinstance(o, Vertex))
key = jax.random.PRNGKey(1234)

for _, _, path, _ in scene.all_valid_paths(
    order=1,
    path_cls=FermatPath,
    key=key,
):
    path.plot(ax)

plt.show()  # doctest: +SKIP

(Source code, png, hires.png, pdf)

../_images/differt2d-scene-1.png
update_transmitters(**transmitters)[source]

Returns a copy of this scene, with the updated transmitters.

The new set of transmitters is the union of the previous set and the ones provided as arguments.

Parameters:

transmitters (Point) – A mapping of transmitter names and points.

Return type:

Self

Returns:

The new scene.

update_receivers(**receivers)[source]

Returns a copy of this scene, with the updated receivers.

The new set of receivers is the union of the previous set and the ones provided as arguments.

Parameters:

receivers (Point) – A mapping of receivers names and points.

Return type:

Self

Returns:

The new scene.

add_objects(*objects)[source]

Returns a copy of this scene, with the given objects, plus the scene objects.

Parameters:

objects (Object) – A sequence of objects.

Return type:

Self

Returns:

The new scene.

get_object(index)[source]

Returns the object at a corresponding index.

This method provides a way to index objects with a traced value.

Parameters:

index (Union[Array, ''], int]) – The scalar index, clamped between 0 and len(self.objects) - 1.

Return type:

TypeVar(Obj, bound= Object, covariant=True)

Returns:

The object.

Raises:

TypeError – If the all objects are not of the same type.

stacked_objects()[source]

Returns an object that is the result of stacking all objects in the scene.

Return type:

TypeVar(Obj, bound= Object, covariant=True)

Returns:

The stacked objects.

rename_transmitters(**transmitter_names)[source]

Returns a copy of this scene, with the specified transmitters renamed.

Parameters:

transmitter_names (str) – A mapping of transmitter old names and new names.

Return type:

Self

Returns:

The new scene.

rename_receivers(**receiver_names)[source]

Returns a copy of this scene, with the specified receivers renamed.

Parameters:

receiver_names (str) – A mapping of receiver old names and new names.

Return type:

Self

Returns:

The new scene.

from_stacked_objects(*args, **kwargs) = Partial(   func=_JitWrapper(     fn='Scene.from_stacked_objects',     filter_warning=False,     donate_first=False,     donate_rest=False   ),   args=(differt2d.scene.Scene,),   keywords={} )
Parameters:
Return type:

_Return

classmethod from_walls_array(cls, walls)[source]

Creates an empty scene from an array of walls.

Parameters:

walls (Array, 'num_walls 2 2']) – An array of wall coordinates.

Return type:

Scene[Wall]

Returns:

The new scene.

classmethod from_geojson(s_or_fp, tx_loc='NW', rx_loc='SE')[source]

Creates a scene from a GEOJSON file, generating one Wall per line segment. TX and RX positions are located on the corner of the bounding box.

Parameters:
  • s_or_fp (Union[str, bytes, bytearray, Readable]) – Source from which to read the GEOJSON object, either a string-like or a file-like object.

  • tx_loc (Literal['N', 'E', 'S', 'W', 'C', 'NE', 'NW', 'SE', 'SW'], default: 'NW') – Where to place TX, see Plottable.get_location.

  • rx_loc (Literal['N', 'E', 'S', 'W', 'C', 'NE', 'NW', 'SE', 'SW'], default: 'SE') – Where to place RX, see Plottable.get_location.

Return type:

Self

Returns:

The scene representation of the GEOJSON.

Examples:

The following example was obtained from https://overpass-turbo.eu/ using following query:

[out:json][timeout:30];(
way["building"](50.66815414931746,4.624882042407989,50.66856810072477,4.6256572008132935);
relation["building"]["type"="multipolygon"](50.66815414931746,4.624882042407989,50.66856810072477,4.6256572008132935);
);out;>;out qt;

(Source code, png, hires.png, pdf)

../_images/differt2d-scene-2.png
classmethod from_scene_name(scene_name, *args, **kwargs)[source]

Generates a new scene from the given scene name.

Parameters:
  • scene_name (Literal['basic_scene', 'square_scene', 'square_scene_with_obstacle', 'square_scene_with_wall']) – The name of the scene.

  • args (Any) – Positional arguments passed to the constructor.

  • kwargs (Any) – Keyword arguments passed to the constructor.

Return type:

Self

Returns:

The scene.

classmethod random_uniform_scene(n_transmitters=1, n_walls=1, n_receivers=1, *, key)[source]

Generates a random scene, drawing coordinates from a random distribution.

Parameters:
  • key (Union[Array, ''], Array, '2']]) – The random key to be used.

  • n_transmitters (int, default: 1) – The number of transmitters.

  • n_walls (int, default: 1) – The number of walls.

  • n_receivers (int, default: 1) – The number of receivers.

Return type:

Scene[Wall]

Returns:

The scene.

Examples:

import matplotlib.pyplot as plt
import jax
from differt2d.scene import Scene

ax = plt.gca()
key = jax.random.PRNGKey(1234)
scene = Scene.random_uniform_scene(n_walls=5, key=key)
_ = scene.plot(ax)
plt.show()  # doctest: +SKIP

(Source code, png, hires.png, pdf)

../_images/differt2d-scene-3.png
classmethod basic_scene(tx_coords=Array([0.1, 0.1], dtype=float32), rx_coords=Array([0.302, 0.2147], dtype=float32))[source]

Instantiates a basic scene with a main room, and a second inner room in the lower left corner, with a small entrance.

Parameters:
  • tx_coords (Array, '2'], default: Array([0.1, 0.1], dtype=float32)) – The transmitter’s coordinates.

  • rx_coords (Array, '2'], default: Array([0.302 , 0.2147], dtype=float32)) – The receiver’s coordinates.

Return type:

Scene[Wall]

Returns:

The scene.

Examples:

>>> from differt2d.scene import Scene
>>>
>>> scene = Scene.basic_scene()
>>> scene.bounding_box()
Array([[0., 0.],
       [1., 1.]], dtype=float32)
>>> len(scene.objects)
7
>>> scene.transmitters["tx"].xy
Array([0.1, 0.1], dtype=float32)

(Source code, png, hires.png, pdf)

../_images/differt2d-scene-4.png
classmethod square_scene(tx_coords=Array([0.2, 0.2], dtype=float32), rx_coords=Array([0.5, 0.6], dtype=float32))[source]

Instantiates a square scene with one main room.

Parameters:
  • tx_coords (Array, '2'], default: Array([0.2, 0.2], dtype=float32)) – The transmitter’s coordinates.

  • rx_coords (Array, '2'], default: Array([0.5, 0.6], dtype=float32)) – The receiver’s coordinates.

Return type:

Scene[Wall]

Returns:

The scene.

Examples:

>>> from differt2d.scene import Scene
>>>
>>> scene = Scene.square_scene()
>>> scene.bounding_box()
Array([[0., 0.],
       [1., 1.]], dtype=float32)
>>> len(scene.objects)
4
>>> scene.transmitters["tx"].xy
Array([0.2, 0.2], dtype=float32)

(Source code, png, hires.png, pdf)

../_images/differt2d-scene-5.png
classmethod square_scene_with_wall(ratio=0.6, tx_coords=Array([0.2, 0.5], dtype=float32), rx_coords=Array([0.8, 0.5], dtype=float32))[source]

Instantiates a square scene with one main room, and vertical wall in the middle.

Parameters:
  • ratio (float, default: 0.6) – The ratio of the obstacle’s side length to the room’s side length.

  • tx_coords (Array, '2'], default: Array([0.2, 0.5], dtype=float32)) – The transmitter’s coordinates.

  • rx_coords (Array, '2'], default: Array([0.8, 0.5], dtype=float32)) – The receiver’s coordinates.

Return type:

Scene[Wall]

Returns:

The scene.

Examples:

>>> from differt2d.scene import Scene
>>>
>>> scene = Scene.square_scene_with_wall()
>>> scene.bounding_box()
Array([[0., 0.],
       [1., 1.]], dtype=float32)
>>> len(scene.objects)
5
>>> scene.transmitters["tx"].xy
Array([0.2, 0.5], dtype=float32)

(Source code, png, hires.png, pdf)

../_images/differt2d-scene-6.png
classmethod square_scene_with_obstacle(ratio=0.1, **kwargs)[source]

Instantiates a square scene with one main room, and one square obstacle in the center.

Parameters:
  • ratio (Union[Array, ''], float], default: 0.1) – The ratio of the obstacle’s side length to the room’s side length.

  • kwargs (Any) – Keyword arguments passed to square_scene.

Return type:

Scene[Wall]

Returns:

The scene.

Examples:

>>> from differt2d.scene import Scene
>>>
>>> scene = Scene.square_scene_with_obstacle()
>>> scene.bounding_box()
Array([[0., 0.],
       [1., 1.]], dtype=float32)
>>> len(scene.objects)
8
>>> scene.transmitters["tx"].xy
Array([0.2, 0.2], dtype=float32)

(Source code, png, hires.png, pdf)

../_images/differt2d-scene-7.png
plot(ax, *args, transmitters=True, transmitters_args=(), transmitters_kwargs=None, objects=True, objects_args=(), objects_kwargs=None, receivers=True, receivers_args=(), receivers_kwargs=None, annotate=True, **kwargs)[source]

Plot this object on the given axes and returns the results.

Parameters:
  • ax – The axes to plot on.

  • args (Any) – Arguments passed to the plot function.

  • kwargs (Any) – Keyword arguments passed to the plot function.

  • transmitters (bool, default: True) – If set, includes transmitters in the plot.

  • transmitters_args (tuple, default: ()) – Arguments passed to each transmitter’s plot function.

  • transmitters_kwargs (Optional[Mapping[str, Any]], default: None) – Keyword arguments passed to each transmitter’s plot function.

  • objects (bool, default: True) – If set, includes objects in the plot.

  • objects_args (tuple, default: ()) – Arguments passed to the each object’ plot function.

  • objects_kwargs (Optional[Mapping[str, Any]], default: None) – Keyword arguments passed to each object’ plot function.

  • receivers (bool, default: True) – If set, includes receivers in the plot.

  • receivers_args (tuple, default: ()) – Arguments passed to each receiver’s plot function.

  • receivers_kwargs (Optional[Mapping[str, Any]], default: None) – Keyword arguments passed to each receiver’s plot function.

  • annotate (bool, default: True) – If set, will annotate all transmitters and receivers with their name, and append the corresponding artists to the returned list.

Return type:

list[Artist]

Returns:

The artist(s).

bounding_box()[source]

Returns the bounding box of this object.

This is: [[min_x, min_y], [max_x, max_y]].

Return type:

Array, '2 2']

Returns:

The min. and max. coordinates of this object.

get_closest_transmitter(coords)[source]

Returns the closest transmitter to the given coordinates.

Parameters:

coords (Array, '2']) – The x-y coordinates.

Return type:

tuple[str, Array, '']]

Returns:

The closet transmitter (name) and its distance to the coordinates.

get_closest_receiver(coords)[source]

Returns the closest receivers to the given coordinates.

Parameters:

coords (Array, '2']) – The x-y coordinates.

Return type:

tuple[str, Array, '']]

Returns:

The closet receiver (name) and its distance to the coordinates.

all_transmitter_receiver_pairs()[source]

Returns all possible pairs of (transmitter, receiver) in the scene.

Each pair P := ((KE, E), (KR, R)) is made of the following:

  • KE the name of the transmitter (key);

  • E the actual transmitter Point (value);

  • KR the name of the receiver (key);

  • R the actual receiver Point (value).

Return type:

Iterator[tuple[tuple[str, Point], tuple[str, Point]]]

Returns:

A generator of all possible pairs.

all_path_candidates(min_order=0, max_order=1, *, order=None, filter_objects=None)[source]

Returns all path candidates, from any of the transmitters to any of the receivers, as a list of array of indices.

Note that it only includes indices for objects.

Note

Internally, it uses differt_core.rt.graph.CompleteGraph to generate the sequence of all path candidates efficiently.

Parameters:
  • min_order (int, default: 0) – The minimum order of the path, i.e., the number of interactions.

  • max_order (int, default: 1) – The maximum order of the path, i.e., the number of interactions.

  • order (Optional[int], default: None) – If provided, it is equivalent to setting min_order=order and max_order=order.

  • filter_objects (Optional[Callable[[Object], bool]], default: None) – A callable indicating which objects should be used for path candidates.

Return type:

list[Array, 'num_path_candidates order']]

Returns:

The list of list of indices.

get_interacting_objects(path_candidate)[source]

Returns the list of interacting objects from a path candidate.

An interacting object is simply an object on which the path should pass.

Parameters:
  • path_candidates – A path candidate, as returned by all_path_candidates.

  • path_candidate (Int[jaxlib._jax.Array, 'order'])

Return type:

list[Interactable]

Returns:

The list of interacting objects.

all_paths(path_cls=<class 'differt2d.geometry.ImagePath'>, path_cls_kwargs=None, min_order=0, max_order=1, order=None, filter_objects=None, *, key=None, **kwargs)[source]

Returns all paths from any of the transmitters to any of the receivers, using the given method, see, differt2d.geometry.ImagePath differt2d.geometry.FermatPath and differt2d.geometry.MinPath.

Parameters:
  • path_cls (type[Path], default: <class 'differt2d.geometry.ImagePath'>) – Method to be used to find the path coordinates.

  • path_cls_kwargs (Optional[Mapping[str, Any]], default: None) – Keyword arguments passed to path_cls.from_tx_objects_rx.

  • min_order (int, default: 0) – The minimum order of the path, i.e., the number of interactions.

  • max_order (int, default: 1) – The maximum order of the path, i.e., the number of interactions.

  • order (Optional[int], default: None) – If provided, it is equivalent to setting min_order=order and max_order=order.

  • filter_objects (Optional[Callable[[Object], bool]], default: None) – A callable indicating which objects should be used for path candidates.

  • key (Union[Array, ''], Array, '2'], None], default: None) – The random key to be used to find the paths. Depending on path_cls, this can be mandatory.

  • kwargs (Any) – Keyword arguments passed to Path.is_valid.

Return type:

Iterator[tuple[str, str, Union[Array, '*batch'], Array, '*batch']], Path, Array, 'order']]]

Returns:

The generator of paths, as (transmitter name, receiver name, valid, path, path_candidate) tuples, where validity path validity can be later evaluated using is_true(valid).

all_valid_paths(approx=None, **kwargs)[source]

Returns only valid paths as returned by all_paths, by filtering out paths using is_true.

Parameters:
Return type:

Iterator[tuple[str, str, Path, Array, 'order']]]

Returns:

The generator of valid paths, as (transmitter name, receiver name, path, path_candidate) tuples.

accumulate_over_paths(fun, fun_args=(), fun_kwargs=None, *, reduce_all=False, **kwargs)[source]

Repeatedly calls fun on all paths between each pair of (transmitter, receiver) in the scene, and accumulates the results.

Produces an iterator with each (transmitter, receiver) pair.

Parameters:
  • fun (Callable[[Point, Point, Path, list[Interactable]], Array, '']]) – The function to evaluate on each path.

  • fun_args (tuple, default: ()) – Positional arguments passed to fun.

  • fun_kwargs (Optional[Mapping[str, Any]], default: None) – Keyword arguments passed to fun.

  • reduce_all (bool, default: False) – Whether to reduce the output by summing all accumulated results. This is especially useful if you only care about the total accumulated results.

  • kwargs (Any) – Keyword arguments passed to all_paths.

Return type:

Union[Iterator[tuple[str, str, Array, '']]], Array, '']]

Returns:

An iterator of transmitter name, receiver name and the corresponding accumulated result, or the sum of accumulated results if reduce_all=True.

accumulate_on_transmitters_grid_over_paths(X, Y, fun, fun_args=(), fun_kwargs=None, *, reduce_all=False, grad=False, value_and_grad=False, path_cls=<class 'differt2d.geometry.ImagePath'>, path_cls_kwargs=None, transmitter_cls=<class 'differt2d.geometry.Point'>, min_order=0, max_order=1, order=None, filter_objects=None, key=None, **kwargs)[source]

Repeatedly calls fun on all paths between the receivers in the scene and every transmitter coordinate in (X, Y), and accumulates the results over one array that has the same shape a X and Y.

Produces an iterator with one element for each receiver location.

Parameters:
  • X (Array, 'm n']) – The grid of x-coordinates.

  • Y (Array, 'm n']) – The grid of y-coordinates.

  • fun (Callable[[Point, Point, Path, list[Interactable]], Array, '']]) – The function to evaluate on each path.

  • fun_args (tuple, default: ()) – Positional arguments passed to fun.

  • fun_kwargs (Optional[Mapping[str, Any]], default: None) – Keyword arguments passed to fun.

  • reduce_all (bool, default: False) – Whether to reduce the output by summing all accumulated results. This is especially useful if you only care about the total accumulated results.

  • grad (bool, default: False) – If set, returns the gradient of fun with respect to the transmitter’s position. The output array(s) will then have an additional axis of size two.

  • value_and_grad (bool, default: False) – If set, returns both the fun and its gradient. Takes precedence over setting grad=True.

  • path_cls (type[Path], default: <class 'differt2d.geometry.ImagePath'>) – Method to be used to find the path coordinates.

  • path_cls_kwargs (Optional[Mapping[str, Any]], default: None) – Keyword arguments passed to path_cls.from_tx_objects_rx.

  • transmitter_cls (type[Point], default: <class 'differt2d.geometry.Point'>) – A point constructor called on every transmitter, should inherit from Point.

  • min_order (int, default: 0) – The minimum order of the path, i.e., the number of interactions.

  • max_order (int, default: 1) – The maximum order of the path, i.e., the number of interactions.

  • order (Optional[int], default: None) – If provided, it is equivalent to setting min_order=order and max_order=order.

  • filter_objects (Optional[Callable[[Object], bool]], default: None) – A callable indicating which objects should be used for path candidates.

  • key (Union[Array, ''], Array, '2'], None], default: None) – The random key to be used to find the paths. Depending on path_cls, this can be mandatory.

  • kwargs – Keyword arguments passed to Path.is_valid.

Return type:

Union[Iterator[tuple[str, Union[Array, 'm n'], Array, 'm n 2'], tuple[Array, 'm n'], Array, 'm n 2']]]]], Array, 'm n'], Array, 'm n 2'], tuple[Array, 'm n'], Array, 'm n 2']]]

Returns:

An iterator of receiver name and the corresponding accumulated result, or the sum of accumulated results if reduce_all=True.

accumulate_on_receivers_grid_over_paths(X, Y, fun, fun_args=(), fun_kwargs=None, *, reduce_all=False, grad=False, value_and_grad=False, path_cls=<class 'differt2d.geometry.ImagePath'>, path_cls_kwargs=None, receiver_cls=<class 'differt2d.geometry.Point'>, min_order=0, max_order=1, order=None, filter_objects=None, key=None, **kwargs)[source]

Repeatedly calls fun on all paths between the transmitters in the scene and every receiver coordinate in (X, Y), and accumulates the results over one array that has the same shape a X and Y.

Produces an iterator with one element for each transmitter location.

Parameters:
  • X (Array, 'm n']) – The grid of x-coordinates.

  • Y (Array, 'm n']) – The grid of y-coordinates.

  • fun (Callable[[Point, Point, Path, list[Interactable]], Array, '']]) – The function to evaluate on each path.

  • fun_args (tuple, default: ()) – Positional arguments passed to fun.

  • fun_kwargs (Optional[Mapping[str, Any]], default: None) – Keyword arguments passed to fun.

  • reduce_all (bool, default: False) – Whether to reduce the output by summing all accumulated results. This is especially useful if you only care about the total accumulated results.

  • grad (bool, default: False) – If set, returns the gradient of fun with respect to the receiver’s position. The output array(s) will then have an additional axis of size two.

  • value_and_grad (bool, default: False) – If set, returns both the fun and its gradient. Takes precedence over setting grad=True.

  • path_cls (type[Path], default: <class 'differt2d.geometry.ImagePath'>) – Method to be used to find the path coordinates.

  • path_cls_kwargs (Optional[Mapping[str, Any]], default: None) – Keyword arguments passed to path_cls.from_tx_objects_rx.

  • receiver_cls (type[Point], default: <class 'differt2d.geometry.Point'>) – A point constructor called on every receiver, should inherit from Point.

  • min_order (int, default: 0) – The minimum order of the path, i.e., the number of interactions.

  • max_order (int, default: 1) – The maximum order of the path, i.e., the number of interactions.

  • order (Optional[int], default: None) – If provided, it is equivalent to setting min_order=order and max_order=order.

  • filter_objects (Optional[Callable[[Object], bool]], default: None) – A callable indicating which objects should be used for path candidates.

  • key (Union[Array, ''], Array, '2'], None], default: None) – The random key to be used to find the paths. Depending on path_cls, this can be mandatory.

  • kwargs – Keyword arguments passed to Path.is_valid.

Return type:

Union[Iterator[tuple[str, Union[Array, tuple[Array, Array]]]], Array, tuple[Array, Array]]

Returns:

An iterator of transmitter name and the corresponding accumulated result, or the sum of accumulated results if reduce_all=True.

SceneName

Literal type for all valid scene names.

alias of Literal[‘basic_scene’, ‘square_scene’, ‘square_scene_with_obstacle’, ‘square_scene_with_wall’]