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:
-
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_objectsparameter inall_path_candidatesand 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)
- 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
objectswith a traced value.
- stacked_objects()[source]¶
Returns an object that is the result of stacking all objects in the scene.
See also
- 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={} )¶
- 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, seePlottable.get_location.rx_loc (
Literal['N','E','S','W','C','NE','NW','SE','SW'], default:'SE') – Where to place RX, seePlottable.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)
- classmethod from_scene_name(scene_name, *args, **kwargs)[source]¶
Generates a new scene from the given scene name.
- Parameters:
- 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:
- Return type:
- 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)
- 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:
- 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)
- 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:
- 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)
- 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:
- 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)
- 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 tosquare_scene.
- Return type:
- 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)
- 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:
- 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.
- 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:
- all_path_candidates(min_order=0, max_order=1, *, order=None, filter_objects=None)[source]¶
Returns all path candidates, from any of the
transmittersto any of thereceivers, as a list of array of indices.Note that it only includes indices for objects.
Note
Internally, it uses
differt_core.rt.graph.CompleteGraphto 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 settingmin_order=orderandmax_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:
- 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
transmittersto any of thereceivers, using the given method, see,differt2d.geometry.ImagePathdiffert2d.geometry.FermatPathanddiffert2d.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 topath_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 settingmin_order=orderandmax_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 onpath_cls, this can be mandatory.kwargs (
Any) – Keyword arguments passed toPath.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 usingis_true.
- accumulate_over_paths(fun, fun_args=(), fun_kwargs=None, *, reduce_all=False, **kwargs)[source]¶
Repeatedly calls
funon 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 tofun.fun_kwargs (
Optional[Mapping[str,Any]], default:None) – Keyword arguments passed tofun.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.
- Return type:
- 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
funon 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 aXandY.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 tofun.fun_kwargs (
Optional[Mapping[str,Any]], default:None) – Keyword arguments passed tofun.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 offunwith 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 thefunand its gradient. Takes precedence over settinggrad=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 topath_cls.from_tx_objects_rx.transmitter_cls (
type[Point], default:<class 'differt2d.geometry.Point'>) – A point constructor called on every transmitter, should inherit fromPoint.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 settingmin_order=orderandmax_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 onpath_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
funon 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 aXandY.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 tofun.fun_kwargs (
Optional[Mapping[str,Any]], default:None) – Keyword arguments passed tofun.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 offunwith 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 thefunand its gradient. Takes precedence over settinggrad=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 topath_cls.from_tx_objects_rx.receiver_cls (
type[Point], default:<class 'differt2d.geometry.Point'>) – A point constructor called on every receiver, should inherit fromPoint.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 settingmin_order=orderandmax_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 onpath_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.