pyrayt package

Submodules

pyrayt.components module

class pyrayt.components.CircleOfRays(diameter=1, wavelength=0.633, *args, **kwargs)

Bases: pyrayt.components.Source

A Source that uniformly generates parallel rays about a circular arc.

Parameters
  • diameter (int, optional) – Diameter of the circle rays are generated about, defaults to 1

  • wavelength (float, optional) – wavelength of the rays, defaults to 0.633

class pyrayt.components.ConeOfRays(cone_angle, wavelength=0.633, *args, **kwargs)

Bases: pyrayt.components.Source

Source that generates a set of rays originating from the same point, uniformly distributed about the x-axis with the specified cone angle.

e.g: An un-rotated. source with a cone angle of 45 degrees will expand to a uniformly distributed circle with a radius of 10mm after traveling 10mm along the optical axis.

Parameters
  • cone_angle (float) – Angle between every ray and the optical axis, in degrees.

  • wavelength (float, optional) – [description], defaults to 0.633

class pyrayt.components.Lamp(width, length, max_angle=90, *args, **kwargs)

Bases: pyrayt.components.Source

Source that generates a lambertian distribution of rays. Every ray originates with a random position and direction about the surface of the lamp. The intensity of the distribution follows Lambert’s Cosine Law.

Parameters
  • width (float) – Width of the rectangular region that rays can generate from

  • length (float) – Length of the rectangular region that rays can generate from.

  • max_angle (float, optional) – The maximum angle a ray can generate projected along the x-axis, defaults to 90 (degrees)

Return type

None

class pyrayt.components.LineOfRays(spacing=1, wavelength=0.633, *args, **kwargs)

Bases: pyrayt.components.Source

Base Class for all Sources

Parameters

wavelength (float, optional) – Wavelength of the source, defaults to 0.633 (units in um)

class pyrayt.components.Source(wavelength=0.633, *args, **kwargs)

Bases: tinygfx.g3d.world_objects.WorldObject, abc.ABC

Base Class for all Sources

Parameters

wavelength (float, optional) – Wavelength of the source, defaults to 0.633 (units in um)

generate_rays(n_rays)

Generates a RaySet based on the source parameters.

Parameters

n_rays (int) – The number of rays to put in the resulting rayset

Returns

A set of rays whose position, direction, and wavelength are set based on the source type.

Return type

pyrayt.RaySet

property wavelength
class pyrayt.components.StaticLamp(width, length, max_angle=90, *args, **kwargs)

Bases: pyrayt.components.Lamp

Identical to a Lamp, except the ray generation function is cached so the same set of rays is generated across multiple simulations. Useful for running Monte-Carlo models where the random noise of the source is larger than the resolution you’re trying to capture at.

Source that generates a lambertian distribution of rays. Every ray originates with a random position and direction about the surface of the lamp. The intensity of the distribution follows Lambert’s Cosine Law.

Parameters
  • width (float) – Width of the rectangular region that rays can generate from

  • length (float) – Length of the rectangular region that rays can generate from.

  • max_angle (float, optional) – The maximum angle a ray can generate projected along the x-axis, defaults to 90 (degrees)

Return type

None

generate_rays(n_rays)

Generates a RaySet based on the source parameters.

Parameters

n_rays (int) – The number of rays to put in the resulting rayset

Returns

A set of rays whose position, direction, and wavelength are set based on the source type.

Return type

pyrayt.RaySet

class pyrayt.components.WedgeOfRays(angle, wavelength=0.633, *args, **kwargs)

Bases: pyrayt.components.Source

Source that generates a wedge of rays originating from a point, directed towards the positive x-axis along the y-axis. The angle of the rays is uniformly distributed between [-angle/2, angle/2].

Parameters
  • angle (float) – The full angle of the wedge source.

  • wavelength (float, optional) – Wavelength of the source, defaults to 0.633

pyrayt.components.aperture(size, aperture_size)

Creates a planar baffle with a central opening specified by the aperture_size argument. Rays that intersect the baffle are absorbed but will transmit through the apertured region.

Parameters
  • size (float | Tuple[float, float]) – The size of the absorbing region of the aperture. See Specifying Apertures for additional details.

  • aperture_size (Union[float, Tuple[float, float]]) – The size of the aperture opeining. See Specifying Apertures for additional details.

Returns

A planar aperture with both baffle and opening centered at the origin, coplanar to the YZ plane.

Return type

cg.Intersectable

pyrayt.components.baffle(aperture)

Creates a planar baffle that absorbs all intersecting rays.

Parameters

aperture (Union[float, Tuple[float, float]]) – Aperture specification for the baffle. see Specifying Apertures for additional details.

Returns

a planar baffle centered at the origin, coplanar to the YZ Plane.

Return type

tinygfx.g3d.world_objects.Intersectable

pyrayt.components.biconvex_lens(r1, r2, thickness, **kwargs)

Creates a thick lens with two convex surfaces.

Any radii values less than zero will be treated as the absolute value of the input. passing math.inf for either radius will make that surface planar.

Parameters
  • r1 (float) – Radius of curvature for the first lens surface.

  • r2 (float) – Radius of curvature for the second lens surface.

  • thickness (float) – full thickness of the lens. If the thickness is set such that the two surface curvatures ‘clip’ into eachother inside of the aperture bounds, the resulting aperture will be set by the clip point.

  • kwargs – Additional keyword arguments

Returns

A traceable lens centered at the origin. The returned lens is oriented such that the first surfaces faces the -X axis, and the second surface faces +X. The aperture is defined in the YZ Plane.

Return type

tinygfx.g3d.world_objects.Intersectable

pyrayt.components.equilateral_prism(side_length, width, material=<pyrayt.materials.SellmeierRefractor object>)

Creates an equilateral prism.

Parameters
  • side_length (float) – Side length of the triangular edges.

  • width (float) – Width of the prism.

  • material (pyrayt.materials.TracableMaterial, optional) – Prism material, defaults to matl.glass[“BK7”]

Returns

An equilateral prism with the body center located at the origin. The triangular faces are parallel to the YZ plane and the base of the prism is parallel to the XY plane.

Return type

cg.csg.Intersectable

pyrayt.components.parabolic_mirror(focus, thickness, **kwargs)

Creates a parabolic mirror defined by the below surface.

\[x(y,z)=\frac{1}{4f} (y^2+z^2) - f\]

Only the parabolic surface is reflective, and all sidewalls are absorbing.

Parameters
  • focus (float) – focal length of the parabola

  • thickness (float) – Back thickness of the mirror. The parabola will be extended with an absorbing surface that extends until x=-(focus + thickness)

  • kwargs – additional keyword arguments

Returns

A Parabolic mirror whose focus is on the origin.

Return type

tinygfx.g3d.world_objects.Intersectable

pyrayt.components.plane_mirror(thickness, **kwargs)

Creates a plane mirror where every side is reflective. If o

Parameters
  • thickness (float) – The mirror thickness. A thickness of zero will result in a 2D planar mirror.

  • kwargs – additional keyword arguments.

Returns

A mirror composed of two reflective surfaces, each of which is parallel to the YZ plane. The first surface is at x=-thickness, and the second surface is at x=0. The mirrors aperture is centered at the origin unless modified by off_axis.

Return type

tinygfx.g3d.world_objects.Intersectable

pyrayt.components.plano_convex_lens(r, thickness, **kwargs)

Creates a thick lens with one convex surface and one planar surface.

Parameters
  • r (float) – Radius of curvature for the spherical surface. A radius value less than zero will be treated as the absolute value of the input. passing math.inf for the radius will make the second surface planar, resulting in a planar window.

  • thickness (float) – full thickness of the lens. If the thickness is set such that the two surface curvatures ‘clip’ into each other inside of the aperture bounds, the resulting aperture will be set by the clip point.

  • kwargs – Additional keyword arguments

Returns

A traceable lens centered at the origin, oriented such that the planar surface faces the -X axis, and the spherical surface faces +X. The aperture is defined in the YZ Plane.

Return type

tinygfx.g3d.world_objects.Intersectable

pyrayt.components.spherical_mirror(radius, thickness, **kwargs)

Creates a spherical mirror defined by the surface function.

\[x(y,z) = r-\sqrt{r^2-(x^2+y^2)}\]

Only the spherical surface is reflective, all sidewalls are absorbing.

Parameters
  • radius (float) – radius of the spherical surface. must be > 0. A radius of math.inf will result in a plane mirror.

  • thickness (float) – back thickness of the mirror. The mirror’s aperture will be extended with an absorbing surface up to the plane defined by x=-thickness. If the resulting back-plane clips into the spherical surface, the surface will be cut off at the back-plane

  • kwargs

Returns

A spherical mirror with an absorbing backplane facing towards the -X axis, and a spherical surface facing towards +X. The focal point of the mirror is at (r/2, 0, 0).

Return type

tinygfx.g3d.world_objects.Intersectable

pyrayt.components.thick_lens(r1, r2, thickness, **kwargs)

Creates a Thick lens with arbitrary surface curvature.

See https://en.wikipedia.org/wiki/Radius_of_curvature_(optics) for convention on positive vs. negative radius of curvature.

Parameters
  • r1 (float) – Radius of curvature for the first lens surface. Set to np.inf for a planar surface.

  • r2 (float) – Radius of curvature for the second lens surface. Set to np.inf for a planar surface.

  • thickness (float) – Thickness of the lens along the optical (x) axis. For a biconvex lens this will be the thickest point, for a concave lens it will be the thinnest.

Returns

A traceable lens centered at the origin. The returned lens is oriented such that the first surfaces faces the -X axis, and the second surface faces +X. The aperture is defined in the YZ Plane

Return type

cg.Intersectable

pyrayt.materials module

class pyrayt.materials.BasicRefractor(refractive_index, *args, **kwargs)

Bases: pyrayt.materials.Glass

A simplified refractive model for nondispersive materials

Parameters

refractive_index (float) – refractive index of the material.

index_at(wavelength)

Calculates the refractive index of the glass for the given wavelength.

Parameters

wavelength (Union[float, np.ndarray]) – The wavelength to sample, can be either a single float or a numpy array. Expected units are microns.

Returns

The refractive index of the material, the shape of the returned value will match the shape/type of the wavelength argument.

Return type

Union[float, np.ndarray]

class pyrayt.materials.Glass(*args, **kwargs)

Bases: pyrayt.materials.TracableMaterial

Abstract base class for glasses with convenience functions for common parameters.

abbe()

Calculates the Abbe number of the material.

Return type

float

abstract index_at(wavelength)

Calculates the refractive index of the glass for the given wavelength.

Parameters

wavelength (Union[float, np.ndarray]) – The wavelength to sample, can be either a single float or a numpy array. Expected units are microns.

Returns

The refractive index of the material, the shape of the returned value will match the shape/type of the wavelength argument.

Return type

Union[float, np.ndarray]

trace(surface, ray_set)

Trace Function for the material. Calculates the interaction of a RaySet with a material, modifying the ray set in place.

Parameters
  • surface (cg.TracerSurface) – The surface the material is attached to, used to calculate surface normals

  • ray_set (RaySet) – the set of rays whose interaction is being calculated

Returns

a reference to the original ray_set with parameters updated to accurately represent the state of the ray after interacting with the surface.

Return type

RaySet

class pyrayt.materials.SellmeierRefractor(b1=0, b2=0, b3=0, c1=0, c2=0, c3=0)

Bases: pyrayt.materials.Glass

A dispersive Refractive index model based on the Sellmeier equation. The six arguments (b1->b3, c1->c3) follow the expected convention found in literature.

Sellmeier Coefficients for common glasses can be found at refractiveindex.info.

index_at(wavelength)

Calculates the refractive index of the glass for the given wavelength.

Parameters

wavelength (Union[float, np.ndarray]) – The wavelength to sample, can be either a single float or a numpy array. Expected units are microns.

Returns

The refractive index of the material, the shape of the returned value will match the shape/type of the wavelength argument.

Return type

Union[float, np.ndarray]

class pyrayt.materials.TracableMaterial(base_material=GoochMaterial(base_color=RGBAColor([0., 0., 0., 1.]), warm_color=RGBAColor([1., 0.5, 0., 1.]), cool_color=RGBAColor([0., 0., 1., 1.]), alpha=0.3, beta=0.3), *args, **kwargs)

Bases: tinygfx.g3d.materials.gooch.Material

Base class for any material that can be traced with RayTracer objects

Parameters

base_material – The base material to render the object with. used by the tinygfx module.

shade(rays, normals, light_positions)
Parameters
  • rays (numpy.ndarray) –

  • normals (numpy.ndarray) –

  • light_positions (numpy.ndarray) –

Return type

numpy.ndarray

abstract trace(surface, ray_set)

Trace Function for the material. Calculates the interaction of a RaySet with a material, modifying the ray set in place.

Parameters
  • surface (cg.TracerSurface) – The surface the material is attached to, used to calculate surface normals

  • ray_set (RaySet) – the set of rays whose interaction is being calculated

Returns

a reference to the original ray_set with parameters updated to accurately represent the state of the ray after interacting with the surface.

Return type

RaySet

pyrayt.materials.absorber = <pyrayt.materials._AbsorbingMaterial object>

A bulk absorbing material

pyrayt.materials.glass = {'BK7': <pyrayt.materials.SellmeierRefractor object>, 'SF2': <pyrayt.materials.SellmeierRefractor object>, 'SF5': <pyrayt.materials.SellmeierRefractor object>, 'ideal': <pyrayt.materials.BasicRefractor object>}

A Dictionary of common glasses.

pyrayt.materials.mirror = <pyrayt.materials._ReflectingMaterial object>

A perfectly reflecting material

pyrayt.utils module

pyrayt.utils.lensmakers_equation(r1, r2, n_lens, thickness)

Calculates the focal length of a thick spherical lens using the lensmaker’s equation.

Parameters
  • r1 (float) – the first radius of curvature, positive for convex, negative for concave

  • r2 (float) – the second radius of curvature, negative for convex, positive for concave

  • n_lens (float) – the refractive index of the lens

  • thickness (float) – The thickness of the lens

Returns

The focal length of the lens based on the paraxial approximation

Return type

float

pyrayt.utils.wavelength_to_rgb(wavelength, gamma=0.8)

Calculated the Appropriate RGB value for a wavelength of light based on linear interpolation. Wavelengthts outside of 0.38-0.75um are clipped to the limits.

Parameters
  • wavelength (Tuple[float, np.ndarray]) – The wavelength of light to calculate color for, in microns. Can be either a float or an array of floats

  • gamma (float, optional) – Scaling coefficient for the colors, defaults to 0.8

Returns

An array of [R,G,B] values. Each index of the array corresponds to the RGB value of the wavelength at the same index of the input array.

Return type

np.ndarray

Module contents

All variables in pyrayt._pyrayt are pulled into the pyrayt namespace when the package is imported.

class pyrayt._pyrayt.RaySet(n_rays)

Bases: numpy.ndarray

A chunk of continuous memory that stores all rays in a simulation and their metatdata. RayTracer objects generate a RaySet during during simulations and incrementally stores results in a Pandas dataframe. Raysets should not be created by the user. A slice of metadata for call rays in the set can be accessed through class properties.

Parameters
  • n_rays – How many rays are in the set

  • args – Additional arguments to be passed to the next class in the MRO

  • kwargs – Additional Keyword arguments to be passed to the next class in the MRO

fields = ('generation', 'intensity', 'wavelength', 'index', 'id')

The metadata fields that can be accessed from the rayset

property generation

A view of the set holding the generation number for all rays.

Returns

np.ndarray

property id

A view of the set holding the unique ray ID of all rays.

Returns

np.ndarray

property index

A view of the set holding the current refractive index of all rays.

Returns

np.ndarray

property intensity

A view of the set holding the intensity for all rays.

Returns

np.ndarray

property metadata

A slice of all metadata for the set.

Return type

np.ndarray

property n_rays

How many rays are stored in the set

Return type

int

property rays

A 2x4xn view of the set holding the ray’s spatial data. View[0,:] is the position of all rays as 4D homogeneous coordinates, and view[1,:] is the normalized direction.

Return type

np.ndarray view

property wavelength

A view of the set holding the wavelength of all rays, in um.

Returns

np.ndarray

class pyrayt._pyrayt.RayTracer(sources, components, rays_per_source=10, generation_limit=10)

Bases: object

A Simulator that traces rays generated by a set of sources through a set of components.

Parameters
  • sources (list) – either a single source or an iterable of sources to use for the simulation

  • components (list) – either a single component or an interable of components to use for the simulation

  • rays_per_source – How many rays should be generated for each source in the simulation

  • generation_limit – The maximum generation allowed for a ray before it is terminated by the ray-tracer

calculate_source_ids()

Calculates the Source ID for every ray in the dataframe, adding it as a column

get_generation_limit()

Getter function for the generation limit attribute.

Returns

the current generation limit

get_rays_per_source()

Getter function for the rays per source attribute

Returns

how many rays each source generates

Return type

int

get_results()

Returns a dataframe of the Ray Trace Results.

Returns

pandas dataframe

get_system()

Returns the list of current components. This is a view into the current components list, not a shallow copy. Use caution when updating the results of this function.

Returns

List[tinygfx.g3d.world_objects.Intersectable]

load_components(components)

Overwrites the current component list with a new set of components to trace.

Parameters

components (List[tinygfx.g3d.world_objects.Intersectable]) – a single component or iterable set of components.

Return type

None

ray_intensity_threshold = 0.1

The intensity threshold for rays in the simulation. After each intersection, any rays with intensity values below the threshold are removed from the simulation.

ray_offset_value = 1e-06

How far to offset rays from their intersected surface between successive generations. prevents rays from immediately intersecting with the previously intersected surface.

reset()

Reset the simulation, destroying the current results dataframe.

Returns

set_generation_limit(limit)

Setter function for the generation limit attribute

Parameters

limit – the new generation limit

set_rays_per_source(n_rays)

Set how many rays each source generates in a simulation

Parameters

n_rays (int) – the number of rays to generate per source.

Return type

None

show(view='xy', axis=None, color_function=None, ray_width=0.01, **kwargs)

Plot the ray trace results in a MatPlotLib figure with orthographic projection. If no trace has been run, the componets are rendered and displayed instead.

Parameters
  • view – the projected axis of the results, options are ‘xy’ or ‘xz’

  • axis – the matplotlib axis to plot the results in, if no axis is provided the current axis is resolved using plt.gca()

  • color_function – Color function to use when drawing rays, options are ‘wavelength’, or ‘source’. By default will color all rays a uniform color.

  • ray_width – Width of the rays to draw. This is passed to pyplot.quiver() as ‘width’.

  • kwargs – additional keyword arguments to pass to draw(), which renders the components

Return type

None

trace()
class pyrayt._pyrayt.pin(*objects_to_pin)

Bases: object

A context manager that pins a number of components at their given position and rotation. On exiting the context, all components are reset to their original states.

e.g:

lens = pyrayt.components.lens(10, -10, 1)
lens.get_position() # [0,0,0,1]

with pin(lens):
    # in the context manager you can freely manipulate the position of objects
    lens.move_x(100)
    lens.get_position() # [100, 0, 0, 1]

# Once the context manager exits, any changes to position are reverted
lens.get_position() # [0, 0, 0, 1]