finesse.utilities package

Submodules

finesse.utilities.aberrations module

Functions for computing outputs for higher order aberrations of spherical optical components.

finesse.utilities.aberrations.spherical_surface(X, Y, R, degrees=0)

Computes the spherical height (sagitta) for a spherical mirror normal incidence. Will return NaNs for regions in X**2+Y**2 > R**2.

Parameters

X, Y[array_like| float]

Coordinates to compute surface at

Rfloat

Radius of curvature

degreesfloat

Angle of incidence in degrees

Returns

Z[array_like|float]

Height of the spherical surface

Notes

Coorindate system used is left-handed with positive R being in the +z direction. Formula is from equation 29 in [43].

finesse.utilities.blockdiag module

finesse.utilities.blockdiag.display_blockdiag_output(cell, output_format='svg', return_svg=False)

When called in a Jupyter/Ipython environment the block diagram is displayed.

Parameters

output_formatstr

svg or png

return_svgbool

Returns SVG data if requested

finesse.utilities.blockdiag.display_loops_blockdiag(model, *nodes, remove_mechanical_to_mechanical=True, **kwargs)

Displays a block diagram of a model using the blockdiag package. Only signal path (electronic and mechanical) connections are shown.

Parameters

modelfinesse.model.Model

Model to display

*nodesiterable[str]

Nodes to include in the diagram. This will include any path that have the nodes in

remove_mechanical_to_mechanicalbool, optional

If true, mechanical to mechanical node edges

**kwargs

options to pass to get_loops_blockdiag_code().

Returns

Nothing if return_svg=False

finesse.utilities.blockdiag.get_loops_blockdiag_code(model, *nodes, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, remove_mechanical_to_mechanical=True)

finesse.utilities.bug_report module

class finesse.utilities.bug_report.SourceType(*values)

Bases: Enum

INTERACTIVE = 'Interactive'
REPL = 'REPL'
SCRIPT = 'Script'
STDIN = 'stdin'
finesse.utilities.bug_report.bug_report(title: str | None = None, file: str | Path | None = None, include_source: bool = False)

Generate a markdown bug report, suitable for copy-pasting into chatrooms or GitLab issues. Contains the source code, the triggered exception (if any) and machine and python environment information.

Parameters

titlestr | None, optional

Title to insert on top of markdown, by default None

filestr | Path | None, optional

Whether to write the report to file. Will silently overwrite existing files, by default None

include_sourcebool, optional

Wether to include the source code that caused the exception (the contents of the Jupyter notebook or Python script file) into the bug report. Be careful when including source with proprietary/confidential information source in bug reports shared in public spaces like Gitlab or the Matrix channel. Defaults to False

finesse.utilities.bug_report.get_formatted_argv() str
finesse.utilities.bug_report.get_formatted_source() str
finesse.utilities.bug_report.get_formatted_traceback() str
finesse.utilities.bug_report.get_package_versions() str

Report all currently imported package version by looping over sys.modules and looking for ‘__version__’ attributes. Explicitly avoids calling into conda/pip since there are too many package managers to accommodate for.

Returns

str

list of <package> == <version> for every package

finesse.utilities.bug_report.get_source() str

Get source of the ‘__main__’ module. Supports Ipython (Jupyter Notebook, VSCode), interactive interpreter and regular python modules.

Returns

str

Source code

finesse.utilities.bug_report.get_source_type() SourceType

Type of source for the python code currently being executed.

Returns

SourceType

Interactive environment (jupyter), terminal REPL or plain python script

finesse.utilities.bug_report.ipynb_to_md(ipynb: dict) str

Converts notebook json object to markdown. Extracts markdown cells as raw text and code blocks wrapped in a python code block.

Parameters

ipynbdict

notebook json dict

Returns

str

Markdown representing notebook

finesse.utilities.bug_report.wrap_block(code: str, lang: str = 'python') str

Wraps a string in a markdown code block like.

`python print('foo') `

Parameters

codestr

code to wrap

langstr, optional

language of code, by default “python”

Returns

str

Markdown code block

finesse.utilities.collections module

class finesse.utilities.collections.OrderedSet(iterable=None)

Bases: object

An ordered set implementation using an Dictionary to maintain the order of elements. Dictionaries in recent Python versions are all ordered now.

Parameters

iterableiterable, optional

An optional iterable to initialize the ordered set with elements.

Attributes

_dictDict

The internal dictionary used to maintain order and uniqueness of elements.

Methods

add(item)

Add an element to the OrderedSet.

remove(item)

Remove an element from the OrderedSet.

difference_update(iterable)

Remove all elements from the OrderedSet that are also in the provided iterable.

update(iterable)

Add all elements from the provided iterable to the OrderedSet.

clear()

Remove all elements from the OrderedSet.

__contains__(item)

Check if an element is in the OrderedSet.

__iter__()

Return an iterator over the elements of the OrderedSet.

__len__()

Return the number of elements in the OrderedSet.

__repr__()

Return a string representation of the OrderedSet.

add(self, item)

Add an element to the OrderedSet.

Parameters

itemobject

The element to be added to the OrderedSet.

clear(self)

Remove all elements from the OrderedSet.

copy(self)

Create a shallow copy of this OrderedSet.

Returns

OrderedSet

A new OrderedSet with the same elements as the current set.

difference(self, other)

Return a new OrderedSet with elements that are the difference between the two.

Parameters

otherOrderedSet

Another OrderedSet to subtract from this set.

Returns

OrderedSet

A new OrderedSet with the difference between the sets.

difference_update(self, iterable)

Remove all elements from the OrderedSet that are also in the provided iterable.

Parameters

iterableiterable

An iterable containing elements to be removed from the OrderedSet.

issubset(self, other)

Check if this set is a subset of another set.

Parameters

otherOrderedSet

Another OrderedSet to check against.

Returns

bool

True if this set is a subset of other, False otherwise.

remove(self, item)

Remove an element from the OrderedSet.

Parameters

itemobject

The element to be removed from the OrderedSet.

Raises

KeyError

If the element is not present in the OrderedSet.

union(self, *others)

Return a new OrderedSet with elements from the union of this set and other.

Parameters

othersOrderedSet

Another OrderedSet to union with this set.

Returns

OrderedSet

A new OrderedSet with all unique elements from both sets.

update(self, iterable)

Add all elements from the provided iterable to the OrderedSet.

Parameters

iterableiterable

An iterable containing elements to be added to the OrderedSet.

finesse.utilities.components module

Utility functions related to component objects.

finesse.utilities.components.names_to_nodes(model, names, default_hints=())

Attempts to convert a list of node/dof/ports into nodes. This is to provide a way for actions to convert string names into nodes for simulation use. It attempts to provide useful default behaviours, and can accept “hints” on how to select nodes.

Parameters

namesiterable[str|(str, iterable[str])]

A collection of names to convert. A (name, hint) pair can also be provided where hint is an iterable of strings.

default_hintsiterable[str]

Default hint to use with particular set of names if no hints are provided.

Notes

Posible hints when name is a Port or DOF: - input : try and select a singular input node - output : try and select a singular output node

Examples

Selecting various nodes from a model with and without hinting:

>>> import finesse
>>> from finesse.utilities.components import names_to_nodes
>>> model = finesse.Model()
>>> model.parse('''
... l l1 P=100k
... mod mod1 f=10M midx=0.1 order=1 mod_type=pm
... m m1 R=1-m1.T T=0.014 Rc=-1984 xbeta=0n
... m m2 R=1 T=0 Rc=2245 xbeta=0n phi=0
... link(l1, mod1, m1, 3994, m2)
... dof DARM m1.dofs.z -1 m2.dofs.z +1
... ''')
>>> names_to_nodes(model, ('m1.p1', 'DARM.AC'), default_hints=('output'))
[<OpticalNode m1.p1.o @ 0x7f92c9a5c880>,
 <SignalNode DARM.AC.o @ 0x7f92c9a0e5b0>]
>>> names_to_nodes(model, ('m1.p1', 'DARM.AC'), default_hints=('input'))
[<OpticalNode m1.p1.i @ 0x7f92c9a5ca60>,
 <SignalNode DARM.AC.i @ 0x7f92c9a0e460>]
>>> names_to_nodes(model, ('m1.p1.o', 'DARM.AC.i'))
[<OpticalNode m1.p1.o @ 0x7f92c9a5c880>,
 <SignalNode DARM.AC.i @ 0x7f92c9a0e460>]

Hints do not insist on a particular output. For example, this is valid:

>>> names_to_nodes(model, ('m1.p1.o', ('DARM.AC.o', "input")))
finesse.utilities.components.refractive_index(port, symbolic=False)

Obtains the refractive index of the space attached to the port/node port.

Parameters

portPort or Node

Port or node.

Returns

nrfloat

The refractive index of the space attached to the port / node. Returns unity if no space is present.

finesse.utilities.control module

Control system functions.

finesse.utilities.control.zpk_fresp(zs, ps, k, w)

Evaluate the frequency response of a zpk filter.

The evaluation is done by multiplying the poles and zeros in pairs which is more numerically stable than multiplying all of the zeros and then dividing by all of the poles as is done with other tools when there are a large number of zeros and poles.

Parameters

zsarray

zeros of the filter

psarray

poles of the filter

kfloat

gain of the filter

warray

frequencies at which to compute the filter

finesse.utilities.cyomp module

finesse.utilities.cyomp.determine_nthreads_even(int pts, int divisor) int

Determine the number of threads to use for a routine with an outer loop of size pts.

Parameters

ptsint

Size of outer loop of routine to be parallelised.

divisorint

Estimate of scaling for number of threads where the nominal thread count will then be pts // divisor.

Returns

nthreadsint

Determined thread count. Or 1 if no openmp support available.

Notes

The divisor arg defines the nominal number of threads via nominal = pts // divisor. Hence, this argument should correspond to the best-estimate of multi-threaded performance scaling behaviour of the routine to follow.

The actual value returned will be either unity or an even number (depending on values of pts and divisor) which is clipped by the maximum number of threads as given by the OpenMP routine omp_get_max_threads.

If Finesse was compiled without OpenMP support then this always returns 1.

finesse.utilities.docs module

finesse.utilities.docs.class_to_url(cls: type) str

Get the api page for a finesse class. Always points to the latest release version

Parameters

clstype

A class defined in Finesse

Returns

str

The url to the api documentation page

finesse.utilities.docs.get_docs_url() str

Retrieves the documentation URL from the Finesse package metadata

Returns

str

documentation url

finesse.utilities.functools module

Higher order functions.

class finesse.utilities.functools.flagdispatchmethod(func)

Bases: valuedispatchmethod

Method decorator that performs single-dispatch based on a flag enumeration.

Transforms a method into a generic method, which can have different behaviours depending upon the value of its first argument (after self). The decorated method acts as the default implementation, and additional implementations can be registered using the register() attribute of the generic method.

The default implementation must accept at least one argument, the flags. Specialised implementations are not passed the flags. Both implementations are passed any additional positional and keyword arguments specified in the call to get.

As long as the given flag is contained within a registered flag enumeration, it triggers that corresponding method. The method corresponding to the first registered flag that matches is returned.

Based on functools.singledispatchmethod.

Examples

Define a class with a flag dispatch method, register a method to handle particular flags, and call it:

>>> from enum import auto, Flag
>>> from finesse.utilities.functools import flagdispatchmethod
>>> class Flags(Flag):
...     A = auto()
...     B = auto()
...     C = auto()
...     D = auto()
...
>>> class Example:
...     @flagdispatchmethod
...     def get(self, flag):
...          return f"got {flag} (default)"
...     @get.register(Flags.A)
...     def _(self):
...         return f"got {Flags.A}"
...     @get.register(Flags.B)
...     @get.register(Flags.C)
...     def _(self):
...         return f"got {Flags.B}"
...
>>> myobj = Example()
>>> myobj.get(Flags.A)
got Flags.A
>>> myobj.get(Flags.A | Flags.B)
got Flags.B|A (default)
>>> myobj.get(Flags.C)
got Flags.B
>>> myobj.get(Flags.D)
got Flags.D (default)
dispatch(enumeration)
class finesse.utilities.functools.valuedispatchmethod(func)

Bases: object

Method decorator that performs single-dispatch based on value.

Transforms a method into a generic method, which can have different behaviours depending upon the value of its first argument (after self). The decorated method acts as the default implementation, and additional implementations can be registered using the register() attribute of the generic method.

The default implementation must accept at least one argument, the value. Specialised implementations are not passed the value. Both implementations are passed any additional positional and keyword arguments specified in the call to get.

Values registered via register() must be hashable.

Based on functools.singledispatchmethod.

Examples

Define a class with a value dispatch method, register a method to handle particular values, and call it:

>>> from finesse.utilities.functools import valuedispatchmethod
>>> class Example:
...     @valuedispatchmethod
...     def get(self, value):
...          return f"got {value} (default)"
...     @get.register(1)
...     def _(self):
...         return "got 1"
...
>>> myobj = Example()
>>> myobj.get(1)
got 1
>>> myobj.get(2)
got 2 (default)
dispatch(value)
register(value)

Register a new implementation of the generic method for the given value.

finesse.utilities.graph module

Functions to aid manipulation of networkx graphs as well as some graph related utilities.

finesse.utilities.graph.class_graph(cls, G=None)

Creates a directed graph from a class and all of its base classes.

object is ignored because every class derives from object and so it just clutters up the graph.

finesse.utilities.graph.class_graph_from_module_graph(module_graph, G=None)

Creates a directed graph for all the classes and base classes in the module graph.

finesse.utilities.graph.copy_graph(G)

A trick I often see in networkx’s codebase to copy a graph.

type(G) returns the class of G (e.g. nx.DiGraph) which can accept a graph to make a copy of. Useful for writing ‘pure’ functions on graphs.

finesse.utilities.graph.default_key(d, key, default=None)
finesse.utilities.graph.flip_dict(dd)

Swap kay-value in a dictionary.

finesse.utilities.graph.get_orphan_nodes(G)

An orphan node is a node with no edges.

finesse.utilities.graph.get_sink_nodes(G)

A sink node is a node with no outgoing edges.

finesse.utilities.graph.get_source_nodes(G)

A source node is a node with no incoming edges.

finesse.utilities.graph.module_graph(module, G=None, external_modules=False, include_root_module=False)

Creates a directed graph from a module and all of its submodules. External submodules can be included in graph but they will not be traversed since that could cause the graph to walk an absurd number of packages.

The root module is typically not included since it tends to clutter the graph.

finesse.utilities.graph.remove_orphans(G, inplace=False)

Removes nodes with in and out degree 0 from graph G.

This should not need to be recursive.

finesse.utilities.graph.remove_sinks(G, recursive=True, inplace=False)

Removes nodes with out degree 0 from graph G.

Sometimes removing a out degree 0 node creates a new out degree 0 node. So it is necessary to remove out degree 0 nodes recursively.

finesse.utilities.graph.remove_sources(G, recursive=True, inplace=False)

Removes nodes with in degree 0 from graph G.

Sometimes removing a in degree 0 node creates a new in degree 0 node. So it is necessary to remove in degree 0 nodes recursively.

finesse.utilities.homs module

Functions for manipulating Higher Order Modes.

finesse.utilities.homs.HG_to_LG(n, m)

Returns the coefficients and mode indices of the Laguerre-Gaussian modes required to create a particular Hermote-Gaussian mode.

Parameters

n, m: integer

Indices of the HG mode to re-create.

Returns

coeffcients: array_like

Complex coefficients for each order=n+m LG mode required to re-create HG_n,m.

ps, ls: array_like

LG mode indices corresponding to coefficients.

finesse.utilities.homs.HG_to_LG_matrix(hgs, lgs)

Returns a matrix that will convert a Hermite-Gaussian mode vector into Laguerre- Gaussian modes. The HG and LG modes provided to this function must contain all the required modes. A 2nd order HG mode will require 2nd order LG modes.

Parameters

hgsarray_like

Array of (n,m) indicies

lgsarray_like

Array of (p,l) indicies

Returns

Kmatrix

Matrix to multiply with a HG mode vector to get the equivalent LG modes.

finesse.utilities.homs.insert_modes(modes, new_modes)

Inserts the mode indices in new_modes into the modes array at the correct (sorted) position(s).

Parameters

modesnumpy.ndarray

An array of HOM indices.

new_modessequence, str

A single mode index pair or an iterable of mode indices. Each element must unpack to two integer convertible values.

Returns

outnumpy.ndarray

A sorted array of HOM indices consisting of the original contents of modes with the mode indices from new_modes included.

Raises

ValueError

If new_modes is not a mode index pair or iterable of mode indices.

See Also

make_modes

Examples

Make an array of even modes and insert new modes into this:

>>> modes = make_modes("even", 2)
>>> modes
array([[0, 0], [0, 2], [2, 0]], dtype=int32)
>>> insert_modes(modes, ["11", "32"])
array([[0, 0], [0, 2], [1, 1], [2, 0], [3, 2]], dtype=int32)
finesse.utilities.homs.jacobi_real_x(n, a, b, x)

Jacobi Polynomial P_n^{a,b}(x) for real x.

                n    / n+a \ / n+b \ / x-1 \^(s) / x+1 \^(n-s)
P_n^{a,b}(x)= Sum    |     | |     | | --- |     | --- |
                s=0  \ n-s / \   s / \  2  /     \  2  /

Parameters

n, a, bint

Polynomial coefficients

xfloat

Polynomial argument

Notes

Implementation of Jacobi function using binominal coefficients. This can handle values of alpha, beta < -1 which the special.eval_jacobi function does not.

finesse.utilities.homs.lens_diopt_to_f(f, d)

Convert a dioptre shift, at a lens, to a focal length.

Parameters

ffloat

The initial focal length of the lens.

dfloat, array-like

A value or array of values representing the dioptre shift.

Returns

outfloat, array-like

The new value(s) of the focal length.

finesse.utilities.homs.make_modes(select=None, maxtem=None)

Construct a 2D numpy.ndarray of HOM indices.

Parameters

selectsequence, str, optional; default: None

Identifier for the mode indices to generate. This can be:

  • An iterable of mode indices, where each element in the iterable must unpack to two integer convertible values.

  • A string identifying the type of modes to include, must be one of “even”, “odd”, “x” or “y”.

maxtemint, optional; default: None

Optional maximum mode order, applicable only for when select is a string. This is ignored if select is not a string.

Returns

modesnumpy.ndarray

An array of mode indices.

Raises

ValueError

If either of the arguments select, maxtem are invalid or non-unique.

See Also

insert_modes : Add modes to an existing mode indices array at the correct positions.

Examples

Modes up to a maximum order of 2:

>>> make_modes(maxtem=2)
array([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [2, 0]], dtype=int32)

Even modes up to order 4:

>>> make_modes("even", maxtem=4)
array([[0, 0], [0, 2], [0, 4], [2, 0], [2, 2], [4, 0]], dtype=int32)

Sagittal modes up to order 3:

>>> make_modes("y", maxtem=3)
array([[0, 0], [0, 1], [0, 2], [0, 3]], dtype=int32)

Modes from a list of strings:

>>> make_modes(["00", "11", "22"])
array([[0, 0], [1, 1], [2, 2]], dtype=int32)
finesse.utilities.homs.make_modes_LG(maxtem)

Returns an array of LG modes ordered in increasing polynomial order, 2p+|l|.

Parameters

maxtemint

Maximum LG order to include, maxtem > 0.

Returns

plarray_like

array of (p,l) indicies

finesse.utilities.homs.remove_modes(modes, remove)
finesse.utilities.homs.surface_diopt_to_roc(roc, d)

Convert a dioptre shift, at a surface, to a radius of curvature.

Parameters

rocfloat

The initial radius of curvature of the surface.

dfloat, array-like

A value or array of values representing the dioptre shift.

Returns

outfloat, array-like

The new values of the radius of curvature.

finesse.utilities.logging module

Loging utilities.

class finesse.utilities.logging.FinesseStreamHandler(*args, **kwargs)

Bases: StreamHandler

Finesse stream handler.

This class provides a mechanism to exclude displayed log channels by wildcard. It is otherwise identical to logging.StreamHandler.

exclude(pattern)
filter(record)

Determine if a record is loggable by consulting all the filters.

The default is to allow the record to be logged; any filter can veto this by returning a false value. If a filter attached to a handler returns a log record instance, then that instance is used in place of the original log record in any further processing of the event by that handler. If a filter returns any other true value, the original log record is used in any further processing of the event by that handler.

If none of the filters return false values, this method returns a log record. If any of the filters return a false value, this method returns a false value.

Changed in version 3.2: Allow filters to be just callables.

Changed in version 3.12: Allow filters to return a LogRecord instead of modifying it in place.

reset_exclude_patterns()

Empty the configured log channel exclude patterns, and return what was there.

finesse.utilities.logging.logs(logger, level=None, handler=None, close=True)

Emit logs at or above level in the encapsulated context, optionally using the specified handler.

See the Python logging cookbook for more information.

Parameters

loggerlogging.Logger

The logger to use for the encapsulated context.

levelstr or int, optional

The minimum log levels to emit. The standard log levels “debug”, “info”, “warning”, “error” and “critical” are supported, as are their corresponding level numbers (see logging).

handlerlogging.Handler, optional

The handler to add to logger for the encapsulated context.

closebool, optional

Close handler once finished. Defaults to True.

Examples

Print debug logs during parsing, excluding compilation messages.

>>> import logging
>>> from finesse import Model
>>> from finesse.utilities import logs
>>> from finesse.utilities.logging import FinesseStreamHandler
>>> handler = FinesseStreamHandler()
>>> handler.exclude("finesse.script.compiler")
>>> model = Model()
>>> with logs(logging.getLogger(), level="debug", handler=handler):
>>>     model.parse("laser l1 P=1")
finesse.utilities.logging.tracebacks(tracebacks=True)

Show or hide tracebacks in the encapsulated context.

Some environments, such as Jupyterlab, hide tracebacks by default. This context allows tracebacks to be forcefully shown or hidden temporarily.

Parameters

tracebacksbool, optional

Show tracebacks. Defaults to True.

Examples

Print tracebacks during a run.

>>> from finesse import Model
>>> from finesse.utilities import tracebacks
>>> model = Model()
>>> with tracebacks():
>>>     model.parse("laser l1 L=1")

finesse.utilities.maps module

Collection of tools for computing different maps.

class finesse.utilities.maps.BinaryReader(fileName)

Bases: object

MetroPro binary data format reader.

read(typeName, size=None)

Read a datatype from the binary file.

Parameters

typenamestr

See BinaryReader.typeNames.

sizeint

Number of bytes to read

seek(offset, refPos=0)

Offset in bytes and refPos gives reference position, where 0 means origin of the file, 1 uses current position and 2 uses the end of the file.

typeNames = {'char': 's', 'double': 'd', 'float': 'f', 'int16': 'h', 'int32': 'i', 'int64': 'q', 'int8': 'b', 'uint16': 'H', 'uint32': 'I', 'uint64': 'Q', 'uint8': 'B'}
exception finesse.utilities.maps.BinaryReaderEOFException

Bases: Exception

finesse.utilities.maps.circular_aperture(x, y, R_ap, x_offset=0, y_offset=0)

Circular aperture map.

Parameters

x, yarray

1D arrays describing uniform 2D grid to compute map over in meters

Rfloat

Radius of aperture in meters

x_offset, y_offsetfloat, optional

Offset of aperture from origin

finesse.utilities.maps.make_coordinates(N, a)

Makes the 1D and square 2D grid of coordinates for map calculations.

Parameters

N_samplesint

Number of samples in each dimension (N x N)

afloat

Dimension of square grid (a x a) to generate

Returns

x,yarray_like[float]

1D arrays for the x and y coordinates

X,Y,Rarray_like[float]

2D Arrays of the X, Y, and radial R coordinates

finesse.utilities.maps.overlap_1D_curvature_coefficients(x, z, weight_spot: float)

Computes the amount of spot size weighted quadratic x**2 term there is present in some 1D data.

Parameters

xndarray(dtype=float)

Sample points, ideally should be symmetric about 0.

zndarray(dtype=float)

function at sample points x

weight_spotfloat

Spot size to use as weighting

Returns

quadratic_termdouble

Weighted quadratic term of z

Notes

This function is essentially evaluating a weighted Hermite polynomial overlap integral with z(x) to determine the linear term.

\[\int_{\min(x)}^{\max(x)} H_{2}(x) z(x) W(x) dx\]

Where the weighting function is \(W(x) = exp(-x**2)\).

finesse.utilities.maps.overlap_1D_tilt_coefficients(x, z, weight_spot: float)

Computes the amount of spot size weighted linear x term there is present in some 1D data.

Parameters

xndarray(dtype=float)

Sample points, ideally should be symmetric about 0.

zndarray(dtype=float)

function at sample points x

weight_spotfloat

Spot size to use as weighting

Returns

linear_termdouble

Weighted linear term of z

Notes

This function is essentially evaluating a weighted Hermite polynomial overlap integral with z(x) to determine the linear term.

\[\int_{\min(x)}^{\max(x)} H_{1}(x) z(x) W(x) dx\]

Where the weighting function is \(W(x) = exp(-x**2)\).

finesse.utilities.maps.overlap_curvature_coefficients(x, y, z, weight_spot: float)

Computes the amount of x and y curvature terms present in a map’s displacement data.

This is computed by evaluating a weighted Hermite polynomial overlap integral in an efficient manner.

Parameters

x, yarray_like

1D Array of x and y describing the 2D plane of z

zarray_like

2D optical path depth [metres]

weight_spotfloat

Beam spot size to weight over

Returns

k20, k02complex

Complex-valued overlap coefficients for the HG20 and HG02 mode

finesse.utilities.maps.overlap_piston_coefficient(x, y, z, weight_spot: float)

Computes the amount of weighted piston term there is in some 2D data like a surface map. This is computed by evaluating a weighted Hermite polynomial overlap integral in an efficient manner.

Parameters

x, yarray_like

1D Array of x and y describing the 2D plane of z

zarray_like

2D optical path depth [metres]

weight_spotfloat

Beam spot size to weight over

Returns

pistonfloat

amount of piston term

finesse.utilities.maps.overlap_tilt_coefficients(x, y, z, weight_spot: float)

Computes the amount of yaw and pitch terms present in a map’s displacement data.

This is computed by evaluating a weighted Hermite polynomial overlap integral in an efficient manner.

Parameters

x, yarray_like

1D Array of x and y describing the 2D plane of z

zarray_like

2D optical path depth [metres]

weight_spotfloat

Beam spot size to weight over

Returns

k10, k01complex

Complex-valued overlap tilt for the HG10 and HG01 mode

finesse.utilities.maps.read_metropro_file(filename)

Reading the metroPro binary data files. Translated from Hiro Yamamoto’s ‘LoadMetroProData.m’.

Parameters

filename

Name of metropro data file.

finesse.utilities.maps.read_metropro_header(binary)

Reads header of the metroPro binary format files. Translated from the readerHeader() function within the ‘LoadMetroProData.m’ function written by Hiro Yamamoto.

Parameters

binaryBinaryReader

Name of metropro data file.

finesse.utilities.maps.rms(x, y, z, weight_spot: float, xo: float = 0, yo: float = 0)

Computes the spot weight RMS over some 2D data, such as optical path depth.

Parameters

x, yarray_like

1D Array of x and y describing the 2D plane of z

zarray_like

2D optical path depth [metres]

weight_spotfloat

Beam spot size to weight over

xo, yofloat

Origin of the beam position

Returns

rmsfloat

Root mean squared in units of whatever z is

Notes

Based on Equation 4 in:

A. Brooks, et.al Overview of Advanced LIGO adaptive optics Appl. Opt. 55, 8256-8265 (2016)

finesse.utilities.maps.surface_point_absorber(xs, ys, w, h, power_absorbed, alpha=5.5e-07, kappa=1.38, zero_min=False)

Models the surface deformation from a small point absorber in a coating of a mirror. It calcaultes the thermo-elastic deformation due to excess heat being deposited in the mirror.

Parameters

xs, ysarray

1D array for the x and y axis to calculate the distortion over

wdouble

Area of the absorber size

hdouble

Thickness of mirror

power_absorbeddouble

Amount of power absorbed over the area w

alphadouble, optional

Thermo-elastic coefficient of material, default value for fused silica

kappadouble, optional

Thermal conductivity of the material, default value for fused silica

Returns

Height map in meters

Notes

Equation from:
  1. Brooks, et.al “Point absorbers in Advanced LIGO,” Appl. Opt. (2021)

finesse.utilities.misc module

Miscellaneous utility functions for any part of Finesse.

class finesse.utilities.misc.DeprecationHelper(old_name, new_name, new_target, until_version)

Bases: object

Used for deprecating classes.

finesse.utilities.misc.calltracker(func)

Decorator used for keeping track of whether the current state is inside the decorated function or not.

Sets an attribute has_been_called on the function which gets switched on when the function is being executed and switched off after the function has returned. This allows you to query func.has_been_called for determining whether the code being executed has been called from within func.

finesse.utilities.misc.check_name(name)

Checks the validity of a component or node name.

A name is valid if it contains only alphanumeric characters and underscores, and is not empty.

Parameters

namestr

The name to check.

Returns

namestr

The name passed to this function if valid.

Raises

ValueError

If name contains non-alphanumeric / underscore characters.

finesse.utilities.misc.deprecation_warning(msg, until_version)

Function that warns a user about a deprecation. If the current version is past when this feature is deprecated it will raise DeprecationWarning instead.

Parameters

msgstr

Message to warn user with.

until_versionstr

PEP 440 version string. After this version an exception is thrown.

Raises

DeprecationWarning

When current version is >= until_version

finesse.utilities.misc.doc_element_parameter_table(cls)

Prints table for a particular element class.

finesse.utilities.misc.find(x, value)

Finds value in the list x and returns its index, returning None if value is not in the list.

finesse.utilities.misc.find_nearest(x, value, index=False)
finesse.utilities.misc.graph_layouts()

Available NetworkX and graphviz (if installed) graph plotting layouts.

finesse.utilities.misc.graphviz_layouts()

Available graphviz graph plotting layouts.

finesse.utilities.misc.inheritors(klass: type) set[type]

Returns all classes that inherit from klass

Parameters

klasstype

Class to get inheritors from

Returns

set[type]

set of classes that are a subclass of klass

finesse.utilities.misc.is_iterable(obj)

Reliable check for whether an object is iterable.

Note that strings are treated as non-iterable objects when performing this check. This will only return true for iterable non-str objects.

Returns

flagbool

True if obj is iterable, False otherwise.

finesse.utilities.misc.networkx_layouts()

Available NetworkX graph plotting layouts.

finesse.utilities.misc.opened_file(filename, mode)

Get an open file regardless of whether a string or an already open file is passed.

Adapted from numpy.loadtxt().

Parameters

filenamestr, pathlib.Path, or file-like

The path or file object to ensure is open. If filename is an already open file object, it is yielded as-is, and is not closed after the wrapped context exits. If filename is a string, it is opened with the specified mode and yielded, then closed once the wrapped context exits.

modestr

The mode to open filename with, if it is not already open.

Yields

io.FileIO

The open file with the specified mode.

Notes

If filename is an open file, mode is ignored; it is the responsibility of the calling code to check that it is opened with the correct mode.

finesse.utilities.misc.pairwise(iterable)

Iterates through each pair in a iterable.

Parameters

iterablecollections.abc.Iterable

An iterable object.

Returns

zip

A zip object whose .next() method returns a tuple where the i-th element comes from the i-th iterable argument.

finesse.utilities.misc.reduce_getattr(obj, key: str, delimiter: str = '.')

Applies a nested getattr with reduce to select an attribute of a nested object within obj.

Parameters

objobject

Object to search

keystr

Delimited string of attributes

delimiterstr, optional

Delimiter character of key

Returns

Attribute of object

finesse.utilities.misc.valid_name(name)

Validate the specified name.

finesse.utilities.network_filter module

class finesse.utilities.network_filter.ComponentNetworkFilter(model: Model, root: str | ModelElement | Node | None = None, radius: int | None = None, undirected: bool = True, add_edge_info: bool = False, add_detectors: bool = False)

Bases: NetworkFilterBase

network_type: ClassVar[NetworkType] = 'component'
class finesse.utilities.network_filter.FullNetworkFilter(model: Model, root: str | ModelElement | Node | None = None, radius: int | None = None, undirected: bool = True, add_edge_info: bool = False, add_detectors: bool = False)

Bases: NodeNetworkFilter

network_type: ClassVar[NetworkType] = 'full'
class finesse.utilities.network_filter.NetworkFilterBase(model: Model, root: str | ModelElement | Node | None = None, radius: int | None = None, undirected: bool = True, add_edge_info: bool = False, add_detectors: bool = False)

Bases: ABC

Abstract base class that implements distance based filtering of a model graph. Should mostly be used to directly call the run method after initialization, not guaranteed that the state makes sense if it is kept alive.

Used by finesse.model.Model.plot_graph() and finesse.model.Model.component_tree(), see also their docstrings for more clarification on the arguments.

add_detectors: bool = False
add_edge_info: bool = False
model: Model
property network: Graph

Returns

nx.Graph

The relevant network for this filter

network_type: ClassVar[NetworkType]
radius: int | None = None
root: str | ModelElement | Node | None = None
property root_str: str

Transforms the root argument into a string that represents a node in the relevant graph. Must implement _root_to_str and _root_options in the subclass to makes this work.

Returns

str

Root node as the string name in the graph

run() Graph

Runs the filter and returns the filtered graph. Modifies self.network in place, so can not be called repeatedly.

Returns

nx.Graph

The filtered graph.

undirected: bool = True
class finesse.utilities.network_filter.NetworkType(*values)

Bases: Enum

COMPONENT = 'component'
FULL = 'full'
OPTICAL = 'optical'
property filter_class: type[NetworkFilterBase]

Get the relevant filter class for this network type.

Returns

type[NetworkFilterBase]

The relevant filter class

get_network(model: Model, add_edge_info: bool = False) nx.Graph

Retrieve the relevant network for this network type.

Parameters

modelModel

Model to retrieve the netwrok from

add_edge_infobool, optional

Add metadata to the component network on via which ports components are connected, by default False. Ignore for any type other than NetworkType.COMPONENT

Returns

nx.Graph

The relevant model graph

Raises

NotImplementedError

If there is no implementation for newly added network types.

class finesse.utilities.network_filter.NodeNetworkFilter(model: Model, root: str | ModelElement | Node | None = None, radius: int | None = None, undirected: bool = True, add_edge_info: bool = False, add_detectors: bool = False)

Bases: NetworkFilterBase

class finesse.utilities.network_filter.OpticalNetworkFilter(model: Model, root: str | ModelElement | Node | None = None, radius: int | None = None, undirected: bool = True, add_edge_info: bool = False, add_detectors: bool = False)

Bases: NodeNetworkFilter

network_type: ClassVar[NetworkType] = 'optical'

finesse.utilities.numbers module

finesse.utilities.numbers.clip_with_tolerance(number: float, _min: float, _max: float, tol: float = 1e-12) float

Clips a number to the range [_min, _max] if it is in [_min - tol, _max + tol], otherwise just returns the number.

Useful for correcting numerical precision errors after calculating physical quantities.

Parameters

numberfloat

Number to clip

_minfloat

lower end of clipping range

_maxfloat

higher end of clipping range

tolfloat, optional

Absolute tolerance, by default 1e-12

Returns

float

The clipped number

finesse.utilities.polyfit module

Functions for fitting polynomials.

finesse.utilities.polyfit.polyfit2d(x, y, z, kx, ky, *, order=None, weights=None)

Two dimensional polynomial fitting by least squares. Fits the functional form f(x,y) = z.

Parameters

x, y: array-like, 1d

x and y coordinates.

z: np.ndarray, 2d

Surface to fit.

kx, ky: int

Polynomial order in x and y, respectively.

order: int or None

If None, all coefficients up to maxiumum kx, ky, ie. up to and including x^kx*y^ky, are considered. If int, coefficients up to a maximum of kx+ky <= order are considered.

weight: array_like, 2d

Weighting to use for fit. Same dimenstions as z

Returns

Return parameters from np.linalg.lstsq.

soln: np.ndarray

Array of polynomial coefficients.

residuals: np.ndarray

residuals

rank: int

rank

s: np.ndarray

s

Notes

Resultant fit can be evaluated with polyfit2d_eval().

Based on code from: https://stackoverflow.com/questions/33964913/equivalent-of-polyfit-for-a-2d-polynomial-in-python

finesse.utilities.polyfit.polyfit2d_eval(x, y, soln, kx, ky)

Evaluate polynomial fit from polyfit2d()

Parameters

x, y: array-like, 1d

x and y coordinates.

soln: np.ndarray

Array of polynomial coefficients.

kx, ky: int

Polynomial order in x and y, respectively.

finesse.utilities.polyfit.polyfit2d_index(kx, a, b)

Returns index of polynomial from the result of polyfit2d() for \(x^{a} y^{b}\).

Parameters

kxint

X polynomial order computed

a, bint

x and y polynomial order

finesse.utilities.polyfit.polyfit2d_indices(kx, ky)

Get indicies of polynomials returned by polyfit2d().

Parameters

kx, ky: int

Polynomial order in x and y, respectively.

Returns

indicesarray_like

Array of x^a y^b powers

finesse.utilities.storage module

Methods for saving outputs to files.

Currently just uses pickles until HDF is working.

finesse.utilities.storage.create_object_dataset(grp, key, obj)
finesse.utilities.storage.dict_to_json(d)
finesse.utilities.storage.dump_solution_hdf(sol, filename)
finesse.utilities.storage.load(filename, format=None)
finesse.utilities.storage.load_solution_hdf(filename)
finesse.utilities.storage.np_dtype_from_json(data)
finesse.utilities.storage.np_dtype_to_json(dtype)

Converts a numpy dtype into a json string format.

finesse.utilities.storage.object_to_hdf(obj)
finesse.utilities.storage.save(obj, filename, format=None)

Saves a Finesse solution object to a file. Two options are available: HDF5 and Pickle.

Parameters

objSolution

Solution object generated by a Finesse simulation

filenamestr

A path and filename to save the output. If the path does not exist it will be created.

formatstr, optional

For HDF files use one of “.h5”, “.hdf5”, “.hdf” or pickle files use one of “.pkl”, “.pickle”. If None then the extension of the filename is used.

finesse.utilities.storage.str_array_to_hdf(s)
finesse.utilities.storage.to_generic_hdf(obj, grp)

Used to convert a generic Python class into a HDF group.

Scalar values (as determined by np.isscalar) are added as HDF group attributes. This includes class attributes that are int, float, strings, etc. Attributes that are representable with a numpy array are written as datasets within the group. Any attribute that does not fit in the above will be pickled and added as a byte stream dataset.

finesse.utilities.storage.type_from_json(data)
finesse.utilities.storage.type_to_json(_type)

finesse.utilities.tables module

Defines classes for displaying tables.

This code is inspired by the tabulate package which can be found at https://github.com/astanin/python-tabulate/ and on PyPI

class finesse.utilities.tables.NumberTable(table, colnames=None, rownames=None, colfunc=None, bgcolfunc=None, norm=None, numfmt=None, compact=False)

Bases: Table

Create a table of numbers to display via pretty printing or html.

Parameters

tablearray or list-of-lists

A two dimensional object containing the values of the table.

colnamesarray or list, optional

An array or list with the same length as the second dimension of table. These are the column names displayed in the first row. If rownames are given this may contain an additional element to display a name of the rownames.

rownamesarray or list, optional

An array or list with the same length as the first dimension of table. These are the row names displayed in the first column.

colfuncfunc, optional

A function to assign colors to all values displayed. It will get called with table as argument and must return an array with shape table.shape + (4,) and type float with color values ranging from 0 to 1. The returned array will be interpreted as RGBA color data, but the the A value will be ignored. If any value in a RGB triple is negative, no color will be applied to the corresponding cell. Accepts matplotlib colormaps.

bgcolfuncfunc, optional

A function to set the backgroundcolors of the cells, works like colorfunc.

normfunc, optional

This function is applied to the table data before passing it to the color functions. This is intended for normalization functions from matplotlib.colors when using matplotlib colormaps, but can be useful with other functions like numpy.gradient.

numfmtstr or func or array, optional

Either a function to format numbers or a formatting string. The function must return a string. Can also be an array with one option per row, column or cell.

compactboolean, optional

Skip internal row separators to save space when printing as string.

make_colors(table, colorfunc, backgroundcolorfunc, norm)

Calculate the colors for the table.

Produces an array with RGB color values in the range [0, 255] for every cell by calling colorfunc(norm(table)) and backgroundcolorfunc(norm(table)).

Parameters

tablearray

The data table without headers. Should contain numbers, but accepts arbitrary data as long as the color and norm functions can handle it.

colorfunccallable or None

A function producing RGB color data for every cell. Color values must be in [0,1]. If None the array is filled with (-1,-1,-1).

backgroundcolorfunccallable or None

A function producing RGB color data for every cell. Color values must be in [0,1]. If None the array is filled with (-1,-1,-1).

normcallable or None

A normalization applied before calling the color functions. If None it is replaced by a function that does nothing.

Returns

color

The array produced by colorfunc

backgroundcolor

The array produced by backgroundcolorfunc

make_string(obj, row, col)

Convert obj to a string using self.number_format[row, column].

If the cell is a header or self.number_format[row, column] is None, obj is converted with str. If self.number_format[row, column] is a function self.number_format[row, column](obj) is called. If self.number_format[row, column] is a string self.number_format[row, col].format(obj) is called.

class finesse.utilities.tables.Table(table, headerrow=True, headercolumn=False, color=(-1, -1, -1), backgroundcolor=(-1, -1, -1), alignment='left', compact=False)

Bases: object

Basic class to display tables via pretty printing or html.

This class is a container object for formatted tables. All entries should either be strings or have a __str__ method with readable output. The table can be pretty printed for console and displayed as html. Additionally the table can be saved to a csv file using the same syntax as the csv package or rendered as latex code.

Parameters

tablearray or list

A two dimensional array or list-of-lists containing strings.

headerrowbool, default=True

Whether the first row is a header.

headercolumnbool, default=False

Whether the first column is a header.

colorarray, optional

An array with shape table.shape + (3,) of type int containing RGB color data to control the textcolor. If any value in a RGB triple is negative, no color will be applied to the corresponding cell.

backgroundcolorarray, optional

An array to set the backgroundcolors of the cells, works like color.

alignmentarray, optional

An array with on of (“left”, “center”, “right) for each cell.

compactboolean, optional

Skip internal row separators to save space when printing as string.

Notes

Instead of arrays, color, backgroundcolor and alignment can be given only one option per row, column or total. This will be expanded for the whole table.

apply_ansi_colors(text, color, backgroundcolor)

Add the color codes to the string if necessary.

Colors should be given as RGB tuples with integer values from [0,255].

escape_latex(text)

Replace special characters in latex with their latex representation.

expand_string(text, width, align='right')

Expand a string to have a certain length.

Add blank spaces to the string to get its visible length to width. align controls whether the spaces are added in front, at the end or both. text will be converted to str.

Parameters

textstr

Can also be an objection with __str__ defined.

widthint

Desired length

alignstr, optional

Must be one of “right”, “left” or “center”. Defaults to “right”.

Raises

ValueError

If the string is shorter than the given length or align is not one of the given options.

generate_grid_table()

Create the whole table.

generate_html_cell(row, column, style=None)

Generate html code for the table cell at position (row, column).

style may contain pairs of style options with their values.

generate_html_table()
generate_row(i, start, headerdivision, division, end)

Create the `i`th row with the given elements.

generate_seperating_row(start, line, intersection, headerintersection, end)

Generate the string separating two rows.

get_max_column_width(j)

Determine the maximum width of an entry in this column and add 2.

get_visible_length(text)

Get the visible length of the string.

Parameters

text : str

Returns

int

The number of non combining characters after removing ANSI escape sequences.

Notes

Using code from https://stackoverflow.com/questions/14693701/how-can- i-remove-the-ansi-escape-sequences-from-a-string-in-python and https://stackoverflow.com/questions/33351599/how-do-i-get-the- visible-length-of-a-combining-unicode-string-in-python

latex()

Make latex code that produces the table.

If the table cells have colored text, the xcolor package must be used in the latex file, the backgroundcolor is not used.

make_latex_colors()

Define the colors used in the table for latex.

make_latex_str(row, column)

Create latex code for the cell at position (row, column).

print()

Show the table.

Will use html rendering if possible, otherwise pretty prints the table.

write_csv(csvfile, dialect='excel', **fmtparams)

Write the table data to a csv file using the csv package.

Parameters

csvfile :

Any object with a write method. The file the data will be written to.

dialectcsv.Dialect or str, default=”excel”

The CSV dialect to use. may be an instance of csv.Dialect or any subclass thereof or any string in csv.list_dialects().

**fmtparamsdict, optional

Formatting parameters for csv.writer

Returns

The writer object used.

finesse.utilities.text module

Text utilities.

finesse.utilities.text.add_linenos(linenos, lines)

Add line numbers to the start of lines.

Parameters

linenossequence of int

The line numbers, in the same order as lines.

linessequence of str

The lines.

Returns

sequence of str

The lines with prepended line numbers.

finesse.utilities.text.format_bullet_list(items, indent=4, bullet_char='-')

Format items into a bullet list.

finesse.utilities.text.format_section(header, body, ruler=True, ruler_char='=')

Format text in sections.

finesse.utilities.text.get_close_matches(word: str, options: Iterable[str], edit_distance: int = 2, case_sensitive: bool = True) Iterable[str] | None

Wrapper around the py-spellchecker module. Filters words from options that are similar to word, using the ‘Levenshtein distance’.

Parameters

wordstr

word to match

optionsIterable[str]

Iterable to select matches from

edit_distanceint, optional

See https://en.wikipedia.org/wiki/Levenshtein_distance, by default 2

case_sensitivebool, optional

Whether to consider different case different characters, by default True

Returns

Iterable[str] | None

Words that are within edit_distance of word

finesse.utilities.text.ngettext(n, fsingle, fplural, sub=True)

Get the singular or plural form of the specified messages based on n.

Simplified version of the Python standard library function gettext.ngettext().

Parameters

nint

The number to use to decide which form to return.

fsingle, fpluralstr

Single and plural templates.

subbool, optional

Substitute n into the templates. Defaults to True.

Examples

>>> ngettext(1, "{n} item", "{n} items")
'1 item'
>>> ngettext(5, "{n} item", "{n} items")
'5 items'

The template doesn’t have to contain {n}: >>> ngettext(5, “item”, “items”) ‘items’

Setting sub=False turns off substitution: >>> ngettext(5, “{n} item”, “{n} items”, sub=False) ‘{n} items’

finesse.utilities.text.option_list(sequence, final_sep='or', quotechar=None, sort=False, prefix=None)

Build a list from sequence with commas and a final “or”.

As in Python’s error messages (e.g. “‘func’ missing 3 requied positional arguments: ‘a’, ‘b’, and ‘c’”), this function adds an Oxford comma for sequences of length > 2.

Parameters

sequencesequence

The options to create a list with.

final_sepstr, optional

The final separator when sequence has more than one item. Defaults to or.

quotecharstr, optional

Quote the items in sequence with this character. Defaults to no quotes.

sortbool, optional

Sort the items sequence alphabetically. Defaults to false.

prefixstr, optional

Concatenates the prefix with all items in sequence. Defaults to false.

finesse.utilities.text.scale_si(number, units=None)

Convert number to an SI-scaled string representation, with optional unit.

Examples

>>> scale_si(123.45e-6)
'123.45u'
>>> scale_si(370e-6, units="m")
'370 um'
finesse.utilities.text.stringify(item)

Recursively stringify item.

This is useful for when it doesn’t make sense or isn’t possible to override the __repr__ method of an object to get a compact string representation.

finesse.utilities.text.stringify_graph_gml(graph)

Convert the specified NetworkX graph to string representation using GML markup.

finesse.utilities.types module

finesse.utilities.types.issubtype(cls, annotation)

Check that cls is compatible with typing annotation annotation.

Parameters

clstype

The type to check for membership of annotation.

annotationtyping type

The annotation to check.

finesse.utilities.units module

Convenience objects and functions for unit manipulation.

class finesse.utilities.units.SI(*values)

Bases: Enum

Enum defining common SI unit constant names. Look-up the corresponding values with the finesse.utilities.SI_MAP dictionary.

Examples

To get the constant for SI.MILLI simply look-up:

>>> SI_MAP[SI.MILLI]
1e-3
ATTO = 2
CENTI = 8
DECI = 9
FEMTO = 3
GIGA = 13
KILO = 11
MEGA = 12
MICRO = 6
MILLI = 7
NANO = 5
NONE = 10
PETA = 15
PICO = 4
TERA = 14
YOCTO = 0
ZEPTO = 1
finesse.utilities.units.get_SI_value(name)

Get an SI value by name.

Valid names correspond to the values() of the finesse.utilities.SI_LABEL dict.

Parameters

namestr

Label name of the SI value (e.g. “m” for milli, “G” for giga).

Returns

valuefloat

Value corresponding to the SI name.

finesse.utilities.wigner module

Wigner moment operators and functions written to work on an optical fields described in a HG mode basis, rather than a cartesian grid, which makes many calculations faster and more pratical when working in FINESSE.

Code is predominantly written by Alexei Ciobanu, some code tidying and documentation by Daniel Brown.

finesse.utilities.wigner.D_hg(n, q, lam=1.064e-06, include_gouy=False)
finesse.utilities.wigner.D_hg_full(N, q, lam=1.064e-06, include_gouy=False)
finesse.utilities.wigner.E_1D_to_2D(E_1D, homs)
class finesse.utilities.wigner.WignerMomentsHG(xu: float, xy: float, xv: float, xx: float, ux: float, uy: float, uv: float, uu: float, yx: float, yu: float, yv: float, yy: float, vx: float, vu: float, vy: float, vv: float, wig_matrix: ndarray, m2: float, m2x: float, m2y: float, wig_zx: float, wig_zrx: float, wig_qx: complex, wig_wx: float, wig_qy: complex, wig_wy: float, wig_x: float, wig_y: float, wig_u: float, wig_v: float)

Bases: object

Wigner moment outputs from the Hermite-Gaussian wigner function wigner_moments_2D_hg().

Attributes

xu, xy, xv, xx, ux, uy, uv, uu, yx, yu, yv, yy, vx, vu, vy, vv: float

elements of the wigner matrix for easier access

wig_matrixarray_like

4x4 Wigner moment matrix

m2, m2x, m2yfloat

Total M2 (M-squared) value, and the M2 values in the x and y directions

wig_qx, wig_qycomplex

x and y complex gaussian beam parameter for this Wigner basis

wig_zx, wig_zr, wig_wx, wig_zx, wig_zr, wig_wy

Waist position, Rayleigh range, and spot size of the Wigner bases in the x and y directions

wig_x, wig_yfloat

Displacement of beam in units of meters

wig_u, wig_vfloat

Angle of beam in units of radians

m2: float
m2x: float
m2y: float
uu: float
uv: float
ux: float
uy: float
vu: float
vv: float
vx: float
vy: float
wig_matrix: ndarray
wig_qx: complex
wig_qy: complex
wig_u: float
wig_v: float
wig_wx: float
wig_wy: float
wig_x: float
wig_y: float
wig_zrx: float
wig_zx: float
xu: float
xv: float
xx: float
xy: float
yu: float
yv: float
yx: float
yy: float
finesse.utilities.wigner.X_hg(n, q, lam=1.064e-06, include_gouy=False)
finesse.utilities.wigner.X_hg_full(N, q, lam=1.064e-06, include_gouy=False)
finesse.utilities.wigner.gauss_norm(n, q, lam=1.064e-06, include_gouy=True)

The normalization factor for a 1D HG electric field distribution to ensure that the overlap integral equates to 1.

Traditionally the normalization includes a Gouy phase factor for free space propagation but that can be turned off by setting include_gouy=False

Parameters

nint

1D Hermite-gaussian mode order

qcomplex

Gaussian beam parameter

lamfloat

Wavelength

finesse.utilities.wigner.herm(n, x)
finesse.utilities.wigner.q2w(q, lam=1.064e-06)

Get beam size from q parameter.

Parameters

qcomplex

Gaussian beam parameter

lamfloat

Wavelength

finesse.utilities.wigner.q2w0(q, lam=1.064e-06)

Get waist size from q parameter.

Parameters

qcomplex

Gaussian beam parameter

lamfloat

Wavelength

finesse.utilities.wigner.wigner_moments_2D_hg(E, qx, qy, lam=1.064e-06, assume_wigner_matrix_symmetry=True, include_gouy=False)

Function for computing the Wigner moments of a set of HG mode amplitudes in a given basis (qx,qy). This function also computes other useful metrics from the Wigner moments such as the M2 (M-squared) and the Wigner basis of a beam.

Parameters

Earray_like

HG mode coefficient matrix. If you have a 1D array of HG mode amplitudes use the E_1D_to_2D method to convert it first.

qx, qycomplex | finesse.gaussian.BeamParam

x and y direction complex guassian beam paramters

lamfloat

wavelength of light used

include_gouybool

Include Gouy phase in HG normalisation [experimental]

assume_wigner_matrix_symmetrybool

When True only lower half of the Wigner matrix is calculated

Returns

resultWignerMomentsHG

Collection of calculations outputs from Wigner moment calculations

Notes

It should be noted that the Wigner basis calculation and the M2 values along each axis (m2x, m2y) are only valid in the case where the general astigmatic wigner moments of the beam are close to zero. The general astigmatic components of a wigner distribution are xv, vx, yu, uy and potentially xy, yx, uv, vu (not sure about those).

Module contents

Useful common utility functions and classes used throughout the Finesse package.

class finesse.utilities.OrderedSet(iterable=None)

Bases: object

An ordered set implementation using an Dictionary to maintain the order of elements. Dictionaries in recent Python versions are all ordered now.

Parameters

iterableiterable, optional

An optional iterable to initialize the ordered set with elements.

Attributes

_dictDict

The internal dictionary used to maintain order and uniqueness of elements.

Methods

add(item)

Add an element to the OrderedSet.

remove(item)

Remove an element from the OrderedSet.

difference_update(iterable)

Remove all elements from the OrderedSet that are also in the provided iterable.

update(iterable)

Add all elements from the provided iterable to the OrderedSet.

clear()

Remove all elements from the OrderedSet.

__contains__(item)

Check if an element is in the OrderedSet.

__iter__()

Return an iterator over the elements of the OrderedSet.

__len__()

Return the number of elements in the OrderedSet.

__repr__()

Return a string representation of the OrderedSet.

add(self, item)

Add an element to the OrderedSet.

Parameters

itemobject

The element to be added to the OrderedSet.

clear(self)

Remove all elements from the OrderedSet.

copy(self)

Create a shallow copy of this OrderedSet.

Returns

OrderedSet

A new OrderedSet with the same elements as the current set.

difference(self, other)

Return a new OrderedSet with elements that are the difference between the two.

Parameters

otherOrderedSet

Another OrderedSet to subtract from this set.

Returns

OrderedSet

A new OrderedSet with the difference between the sets.

difference_update(self, iterable)

Remove all elements from the OrderedSet that are also in the provided iterable.

Parameters

iterableiterable

An iterable containing elements to be removed from the OrderedSet.

issubset(self, other)

Check if this set is a subset of another set.

Parameters

otherOrderedSet

Another OrderedSet to check against.

Returns

bool

True if this set is a subset of other, False otherwise.

remove(self, item)

Remove an element from the OrderedSet.

Parameters

itemobject

The element to be removed from the OrderedSet.

Raises

KeyError

If the element is not present in the OrderedSet.

union(self, *others)

Return a new OrderedSet with elements from the union of this set and other.

Parameters

othersOrderedSet

Another OrderedSet to union with this set.

Returns

OrderedSet

A new OrderedSet with all unique elements from both sets.

update(self, iterable)

Add all elements from the provided iterable to the OrderedSet.

Parameters

iterableiterable

An iterable containing elements to be added to the OrderedSet.

class finesse.utilities.SI(*values)

Bases: Enum

Enum defining common SI unit constant names. Look-up the corresponding values with the finesse.utilities.SI_MAP dictionary.

Examples

To get the constant for SI.MILLI simply look-up:

>>> SI_MAP[SI.MILLI]
1e-3
ATTO = 2
CENTI = 8
DECI = 9
FEMTO = 3
GIGA = 13
KILO = 11
MEGA = 12
MICRO = 6
MILLI = 7
NANO = 5
NONE = 10
PETA = 15
PICO = 4
TERA = 14
YOCTO = 0
ZEPTO = 1
finesse.utilities.add_linenos(linenos, lines)

Add line numbers to the start of lines.

Parameters

linenossequence of int

The line numbers, in the same order as lines.

linessequence of str

The lines.

Returns

sequence of str

The lines with prepended line numbers.

finesse.utilities.check_name(name)

Checks the validity of a component or node name.

A name is valid if it contains only alphanumeric characters and underscores, and is not empty.

Parameters

namestr

The name to check.

Returns

namestr

The name passed to this function if valid.

Raises

ValueError

If name contains non-alphanumeric / underscore characters.

finesse.utilities.class_to_url(cls: type) str

Get the api page for a finesse class. Always points to the latest release version

Parameters

clstype

A class defined in Finesse

Returns

str

The url to the api documentation page

finesse.utilities.clip_with_tolerance(number: float, _min: float, _max: float, tol: float = 1e-12) float

Clips a number to the range [_min, _max] if it is in [_min - tol, _max + tol], otherwise just returns the number.

Useful for correcting numerical precision errors after calculating physical quantities.

Parameters

numberfloat

Number to clip

_minfloat

lower end of clipping range

_maxfloat

higher end of clipping range

tolfloat, optional

Absolute tolerance, by default 1e-12

Returns

float

The clipped number

finesse.utilities.format_bullet_list(items, indent=4, bullet_char='-')

Format items into a bullet list.

finesse.utilities.format_section(header, body, ruler=True, ruler_char='=')

Format text in sections.

finesse.utilities.graph_layouts()

Available NetworkX and graphviz (if installed) graph plotting layouts.

finesse.utilities.graphviz_layouts()

Available graphviz graph plotting layouts.

finesse.utilities.insert_modes(modes, new_modes)

Inserts the mode indices in new_modes into the modes array at the correct (sorted) position(s).

Parameters

modesnumpy.ndarray

An array of HOM indices.

new_modessequence, str

A single mode index pair or an iterable of mode indices. Each element must unpack to two integer convertible values.

Returns

outnumpy.ndarray

A sorted array of HOM indices consisting of the original contents of modes with the mode indices from new_modes included.

Raises

ValueError

If new_modes is not a mode index pair or iterable of mode indices.

See Also

make_modes

Examples

Make an array of even modes and insert new modes into this:

>>> modes = make_modes("even", 2)
>>> modes
array([[0, 0], [0, 2], [2, 0]], dtype=int32)
>>> insert_modes(modes, ["11", "32"])
array([[0, 0], [0, 2], [1, 1], [2, 0], [3, 2]], dtype=int32)
finesse.utilities.is_iterable(obj)

Reliable check for whether an object is iterable.

Note that strings are treated as non-iterable objects when performing this check. This will only return true for iterable non-str objects.

Returns

flagbool

True if obj is iterable, False otherwise.

finesse.utilities.logs(logger, level=None, handler=None, close=True)

Emit logs at or above level in the encapsulated context, optionally using the specified handler.

See the Python logging cookbook for more information.

Parameters

loggerlogging.Logger

The logger to use for the encapsulated context.

levelstr or int, optional

The minimum log levels to emit. The standard log levels “debug”, “info”, “warning”, “error” and “critical” are supported, as are their corresponding level numbers (see logging).

handlerlogging.Handler, optional

The handler to add to logger for the encapsulated context.

closebool, optional

Close handler once finished. Defaults to True.

Examples

Print debug logs during parsing, excluding compilation messages.

>>> import logging
>>> from finesse import Model
>>> from finesse.utilities import logs
>>> from finesse.utilities.logging import FinesseStreamHandler
>>> handler = FinesseStreamHandler()
>>> handler.exclude("finesse.script.compiler")
>>> model = Model()
>>> with logs(logging.getLogger(), level="debug", handler=handler):
>>>     model.parse("laser l1 P=1")
finesse.utilities.make_modes(select=None, maxtem=None)

Construct a 2D numpy.ndarray of HOM indices.

Parameters

selectsequence, str, optional; default: None

Identifier for the mode indices to generate. This can be:

  • An iterable of mode indices, where each element in the iterable must unpack to two integer convertible values.

  • A string identifying the type of modes to include, must be one of “even”, “odd”, “x” or “y”.

maxtemint, optional; default: None

Optional maximum mode order, applicable only for when select is a string. This is ignored if select is not a string.

Returns

modesnumpy.ndarray

An array of mode indices.

Raises

ValueError

If either of the arguments select, maxtem are invalid or non-unique.

See Also

insert_modes : Add modes to an existing mode indices array at the correct positions.

Examples

Modes up to a maximum order of 2:

>>> make_modes(maxtem=2)
array([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [2, 0]], dtype=int32)

Even modes up to order 4:

>>> make_modes("even", maxtem=4)
array([[0, 0], [0, 2], [0, 4], [2, 0], [2, 2], [4, 0]], dtype=int32)

Sagittal modes up to order 3:

>>> make_modes("y", maxtem=3)
array([[0, 0], [0, 1], [0, 2], [0, 3]], dtype=int32)

Modes from a list of strings:

>>> make_modes(["00", "11", "22"])
array([[0, 0], [1, 1], [2, 2]], dtype=int32)
finesse.utilities.networkx_layouts()

Available NetworkX graph plotting layouts.

finesse.utilities.ngettext(n, fsingle, fplural, sub=True)

Get the singular or plural form of the specified messages based on n.

Simplified version of the Python standard library function gettext.ngettext().

Parameters

nint

The number to use to decide which form to return.

fsingle, fpluralstr

Single and plural templates.

subbool, optional

Substitute n into the templates. Defaults to True.

Examples

>>> ngettext(1, "{n} item", "{n} items")
'1 item'
>>> ngettext(5, "{n} item", "{n} items")
'5 items'

The template doesn’t have to contain {n}: >>> ngettext(5, “item”, “items”) ‘items’

Setting sub=False turns off substitution: >>> ngettext(5, “{n} item”, “{n} items”, sub=False) ‘{n} items’

finesse.utilities.opened_file(filename, mode)

Get an open file regardless of whether a string or an already open file is passed.

Adapted from numpy.loadtxt().

Parameters

filenamestr, pathlib.Path, or file-like

The path or file object to ensure is open. If filename is an already open file object, it is yielded as-is, and is not closed after the wrapped context exits. If filename is a string, it is opened with the specified mode and yielded, then closed once the wrapped context exits.

modestr

The mode to open filename with, if it is not already open.

Yields

io.FileIO

The open file with the specified mode.

Notes

If filename is an open file, mode is ignored; it is the responsibility of the calling code to check that it is opened with the correct mode.

finesse.utilities.option_list(sequence, final_sep='or', quotechar=None, sort=False, prefix=None)

Build a list from sequence with commas and a final “or”.

As in Python’s error messages (e.g. “‘func’ missing 3 requied positional arguments: ‘a’, ‘b’, and ‘c’”), this function adds an Oxford comma for sequences of length > 2.

Parameters

sequencesequence

The options to create a list with.

final_sepstr, optional

The final separator when sequence has more than one item. Defaults to or.

quotecharstr, optional

Quote the items in sequence with this character. Defaults to no quotes.

sortbool, optional

Sort the items sequence alphabetically. Defaults to false.

prefixstr, optional

Concatenates the prefix with all items in sequence. Defaults to false.

finesse.utilities.pairwise(iterable)

Iterates through each pair in a iterable.

Parameters

iterablecollections.abc.Iterable

An iterable object.

Returns

zip

A zip object whose .next() method returns a tuple where the i-th element comes from the i-th iterable argument.

finesse.utilities.refractive_index(port, symbolic=False)

Obtains the refractive index of the space attached to the port/node port.

Parameters

portPort or Node

Port or node.

Returns

nrfloat

The refractive index of the space attached to the port / node. Returns unity if no space is present.

finesse.utilities.stringify(item)

Recursively stringify item.

This is useful for when it doesn’t make sense or isn’t possible to override the __repr__ method of an object to get a compact string representation.

finesse.utilities.stringify_graph_gml(graph)

Convert the specified NetworkX graph to string representation using GML markup.

finesse.utilities.tracebacks(tracebacks=True)

Show or hide tracebacks in the encapsulated context.

Some environments, such as Jupyterlab, hide tracebacks by default. This context allows tracebacks to be forcefully shown or hidden temporarily.

Parameters

tracebacksbool, optional

Show tracebacks. Defaults to True.

Examples

Print tracebacks during a run.

>>> from finesse import Model
>>> from finesse.utilities import tracebacks
>>> model = Model()
>>> with tracebacks():
>>>     model.parse("laser l1 L=1")
finesse.utilities.valid_name(name)

Validate the specified name.

finesse.utilities.zpk_fresp(zs, ps, k, w)

Evaluate the frequency response of a zpk filter.

The evaluation is done by multiplying the poles and zeros in pairs which is more numerically stable than multiplying all of the zeros and then dividing by all of the poles as is done with other tools when there are a large number of zeros and poles.

Parameters

zsarray

zeros of the filter

psarray

poles of the filter

kfloat

gain of the filter

warray

frequencies at which to compute the filter