finesse package

Subpackages

Submodules

finesse.config module

Configuration tools.

exception finesse.config.ConfigNotFoundError

Bases: Exception

Indicates a Finesse configuration could not be loaded.

finesse.config.autoconfigure()

Automatically configure runtime options based on the environment.

finesse.config.config_instance()

The Finesse configuration object for the current session.

Returns

configparser.RawConfigParser

The Finesse configuration object.

finesse.config.configure(plotting=False, jupyter_tracebacks=None, progress_bars=False)

Configure Finesse runtime options.

Parameters

plottingbool, optional

Initialise Finesse plot theme for display.

jupyter_tracebacksbool, optional

Show full tracebacks in Finesse errors when using Finesse in IPython. This setting does not work reliably in other environments.

progress_barsbool, optional

When True progress bars will be displayed when available.

See Also

finesse.plotting.tools.init()

finesse.constants module

Physical constants module exposing a single named-tuple which contains each of the constants values.

This tuple is imported in the top-level Finesse module - allowing access to this structure with:

from finesse import constants

# get the speed of light for example
c = constants.C_LIGHT

The table below lists all of the constants exposed in this module.

Name

Description

Exact value used

C_LIGHT

The speed of light in m/s.

299792458.0

PI

Mathematical constant \(\pi\).

3.14159265358979323846

finesse.cyexpr module

Compiled symbolic expressions used internally via parameters and element workspaces.

This sub-module only exposes C code so can only be used by other Cython extensions. The symbolic expression struct cy_expr is used in workspaces (see ElementWorkspace) and parameter code (see Parameter) for quick evaluation of changing symbolic expressions.

The cy_expr struct, and associated functions, are wrappers around the C based math parsing and evaluation engine, tinyexpr.

finesse.cyexpr.test_expr(op_str, value=None)

Python accessible function to test the parsing of strings.

Parameters

op_strstr

String containing operation, e.g., 0.0+1

Returns

ex.exprboolean

False on parse fail

finesse.datastore module

Finesse datastore tools.

The datastore is intended for objects that should be cached during the execution of the current Python kernel. Code typically uses this instead of the more bug-prone singleton pattern (see #260).

finesse.datastore.getfield(key)

Get value with key key.

Parameters

keyany

The key.

Returns

any

The value.

finesse.datastore.hasfield(key)

Determine if the datastore key key exists.

Parameters

keyany

The singeton class to check.

Returns

bool

True if key exists, False otherwise.

finesse.datastore.init_singleton(cls, *args, **kwargs)

Instantiate cls and return the object for the current and future calls.

Parameters

clstype

The singeton class to retrieve. If cls has already been instantiated, the existing instance is returned and args and kwargs are ignored.

Other Parameters

args, kwargs

Positional and keyword arguments to pass to the cls call, to use if cls is not yet instantiated.

Returns

object

The instantiated singleton.

finesse.datastore.invalidate(key=None)

Invalidate the datastore.

Parameters

keystr, optional

The datastore key to invalidate. If None, the whole datastore is invalidated.

finesse.datastore.setfield(key, value, overwrite=False)

Initialize a field with key key and value value.

Parameters

keyany

The key. If it already exists in the datastore,

valueany

The value.

Returns

any

The value.

finesse.densematrix module

class finesse.densematrix.DenseMatrix(name)

Bases: object

Examples

Create a matrix with memory views of different submatrices for giving to components:

> DM = DenseMatrix(“abc”) > > DM.declare_equations(5, 0, ‘a’) > DM.declare_equations(5, 1, ‘b’) > DM.declare_equations(5, 2, ‘c’) > DM.declare_equations(2, 3, ‘d’) > > v1 = DM.declare_submatrix_view(0, 1, ‘b’) > v2 = DM.declare_subdiagonal_view(0, 2, ‘b’) > v3 = DM.declare_submatrix_view(3, 1, ‘b’) > > DM.construct() > > v1[:] = 1 > v2[:] = 0.5 > v3[:] = 0.75

class SubMatrixView(Matrix, _from, _to, name, mtype)

Bases: object

This class represents a sub-matrix view of a CCS sparse matrix. This allows code to access and set values without worrying about the underlying sparse compression being used. Although so far this is just for CCS formats.

This object will get a view of a n-by-m sub-matrix starting at index (i,j). The values of his matrix will be set initially to the coordinates.

property from_idx
property to_idx
property view
add_block(Neqs, index, name)

Parameters

NeqsPy_ssize_t

Number of equations this submatrix represents

_indexlong

Subcolumn index

nameunicode

Name used to indentify this coupling in the matrix for debugging

clear_rhs()
construct()

Constructing the matrix involves taking the metadata submatrix positions throughout the matrix and allocating the memory and building the various CCS matrix structures.

After this the matrix can be populated and sovled.

declare_equations(Neqs, index, name)

Adds a submatrix to the matrix along its diagonal. This defines what equations exist in the matrix, the submatrix values cannot be changed after this, they are always 1 Before other submatrices can be added to the matrix the diagonal must be specfied and how many equations it represents.

Parameters

NeqsPy_ssize_t

Number of equations this submatrix represents

_indexlong

Subcolumn index

nameunicode

Name used to indentify this coupling in the matrix for debugging

declare_subdiagonal_view(from_node, to_node, name)
declare_submatrix_view(from_node, to_node, name)
get_matrix_elements()
get_submatrix(_from, _to)
property name
property num_equations
print_matrix()
print_rhs()
set_rhs(index, value)
solve(transpose=False, conjugate=False)

Solve the matrix with options for transposing and conjugating.

If transpose is False, solves the linear system \(Ax = b\) using the Symbolic and Numeric objects stored by this class.

Otherwise, solves the linear system \(A^T x = b\) or \(A^H x = b\). The conjugate option is zero for \(A^T x = b\) or non-zero for \(A^H x = b\).

Parameters

transposebool

Flag determining whether to solve the transpose of the matrix.

conjugatebool

Flag determining whether to solve \(A^T x =b\) or \(A^H x = b\) for the transposed linear system.

Returns

outnp.ndarray

The (negative) solution vector.

finesse.element module

class finesse.element.ModelElement(*args, **kwargs)

Bases: object

Base for any object which can be an element of a Model.

When added to a model it will attempt to call the method _on_add so that the element can do some initialisation if required.

Parameters

namestr

Name of newly created model element.

property default_parameter_name

The default parameter to assume when the component is directly referenced.

This is used for example in kat script when the component is directly referenced in an expression, instead of the model parameter, e.g. ‘l1’ instead of ‘l1.P.’

Returns

str

The name of the default model parameter.

None

If there is no default.

property has_model

Returns true if this element has been associated with a Model.

info(eval_refs=False)

Element information.

Parameters

eval_refsbool

Whether to evaluate symbolic references to their numerical values. Defaults to False.

Returns

str

The formatted info.

info_parameter_table()

Info parameter table.

This provides a table with useful fields in addition to those contained in parameter_table().

Returns

str

The formatted extra info table.

None

If there are no info parameters.

property name

Name of the element.

Returns

str

The name of the element.

parameter_table(eval_refs=False, return_str=False)

Model parameter table.

Parameters

eval_refsbool

Whether to evaluate symbolic references to their numerical values. Does not have effect when return_str is False. Defaults to False.

return_strbool

Return str representation instead of finesse.utilities.tables.Table Necessary when setting eval_refs to True. Defaults to False.

Returns

finesse.utilities.tables.Table

The formatted parameter info table.

str

String representation of the table, if ‘return_str’ is True

None

If there are no parameters.

property parameters

Returns a list of the parameters available for this element.

property ref

Reference to the default model parameter, if set.

Returns

ParameterRef

Reference to the default model parameter, if set.

Raises

ValueError

If there is no default model parameter set for this element.

finesse.element_workspace module

class finesse.element_workspace.BaseCValues

Bases: object

Base class that elements should use for storing their parameter values. This contains a generic method for storing a pointers to the double parameter values, which is intialised using setup().

Each Parameter of an element should result in a double. This won’t handle any other types of data.

class finesse.element_workspace.ElementValues

Bases: object

Standard Python object which is used to store an Elements Parameter values. This is used in the default case where no optimised C class is provided.

class finesse.element_workspace.ElementWorkspace(sim, owner, values=None)

Bases: object

This is the most basic workspace for a model element. It keeps track of the owner element and its parameter values in the self.values object.

compile_cy_exprs(self) int
owner
owner_id

owner_id: ‘int’

sim
update_parameter_values(self)

Updates the self.values container which holds the latest values of this elements parameters.

values

finesse.enums module

class finesse.enums.ModulatorType(*values)

Bases: IntFlag

am = 0
pm = 1
class finesse.enums.PlaneOfIncidence(*values)

Bases: IntFlag

xz = 0
yz = 1

finesse.env module

Finesse environment information.

finesse.env.has_pygraphviz()

Determine if pygraphviz and graphviz are available on the current path.

Returns

bool

True if pygraphviz and graphviz are available, False otherwise.

Notes

This returns False if either pygraphviz or graphviz is not installed or correctly configured. If pygraphviz is installed but graphviz is not installed or could not be found, an import error complaining about something like “libagraph.so.1” is emitted (see the pygraphviz FAQ).

finesse.env.info(*args, **kwargs)
finesse.env.is_interactive()

Check if Finesse is being run from an interactive environment.

Returns

bool

True if a Jupyter notebook, Qt console or IPython shell is in use, False otherwise.

finesse.env.session_instance()
finesse.env.show_tracebacks(show_tb=None)

Get or set whether to show tracebacks in Jupyter/IPython in full form or just as a single error message.

Parameters

show_tbbool, optional

Set whether to show tracebacks; defaults to None, which doesn’t change the current setting.

Returns

bool

The current setting value (if show_tb was not set) or the previous setting value (if show_tb was set).

finesse.env.tb(colors=True)

Show the last traceback in full.

Parameters

colorsbool, optional

Use colored output (using ANSI escape sequences), by default True Can set to false if output is saved to a medium that doesn’t support it (for example, html and pdf docs)

finesse.env.traceback_handler_instance()
finesse.env.warn(*args, stacklevel=1, **kwargs)

finesse.exceptions module

Custom exception types raised by different Finesse functions and class methods.

exception finesse.exceptions.BeamTraceException(message, **kwargs)

Bases: FinesseException

exception finesse.exceptions.ComponentNotConnected(message, **kwargs)

Bases: FinesseException

exception finesse.exceptions.ContextualArgumentError(message, **kwargs)

Bases: FinesseException

An argument error with additional context.

This allows Finesse objects to provide additional information to the user when invalid values are passed to functions and methods.

empty

alias of _empty

exception finesse.exceptions.ContextualTypeError(param, value, allowed_types=None, name=None)

Bases: ContextualArgumentError

A type error with additional information about the available types.

message()
exception finesse.exceptions.ContextualValueError(params, extra_info=None)

Bases: ContextualArgumentError

A value error with additional information about value(s) that caused an error.

message()
exception finesse.exceptions.ConvergenceException(message, **kwargs)

Bases: FinesseException

Indicates an algorithm has failed to converge to some requested tolerance.

exception finesse.exceptions.DoubleConnectionError(message, **kwargs)

Bases: FinesseException

Thrown when a connections is made to a port that is already connected

exception finesse.exceptions.EvaluateResolvingSymbolError(message, **kwargs)

Bases: FinesseException

Thrown when trying to evaluate a parameter that is currently resolving.

exception finesse.exceptions.ExternallyControlledException(message, **kwargs)

Bases: FinesseException

Raised when a parameter value is changed but there are other elements that are controlling what the value is.

exception finesse.exceptions.FinesseException(message, **kwargs)

Bases: Exception

The exception type which gets raised upon a Finesse failure.

This identifies whether the current session is interactive or not, and consequently sets the level of verbosity. This can be overridden by calling show_tracebacks() with True.

exception finesse.exceptions.IllegalSelfReferencing(message, **kwargs)

Bases: FinesseException

Raised by elements who do not allow self referencing for arg/kwarg values.

exception finesse.exceptions.InvalidRTLError(message, **kwargs)

Bases: FinesseException

Thrown when the RTL parameters of a Surface component violate energy conservation.

exception finesse.exceptions.LostLock(message, **kwargs)

Bases: FinesseException

Thrown when the lock is lost by the locking algorithm. This is typically an issue of:

  • the error signal has been lost (no longer linear, rotated into a different quadrature

  • The error signal slope has become too small (need more lock gain) or too large (need less lock gain)

  • multiple locks are competing and dragging the interferometer to an unstable state.

In such cases you can run the lock action with the flag exception_on_fail=False to ensure it returns a finesse.analysis.actions.locks.RunLocksSolution. This solution can then be used to diagnose the issue, plot_error_signals and plot_control_signals are useful for this to see which error signals are causing an issue.

exception finesse.exceptions.ModelAttributeError(message, **kwargs)

Bases: FinesseException

exception finesse.exceptions.ModelClassAttributeError(target: Any, resolved_attrs: list[str], missing_name: str)

Bases: ModelAttributeError

Error indicating that a model path resolves to a class attribute.

E.g. l1.P.__dict__ or parse will resolve, but no usecase exists for referencing these class attributes in katscript.

exception finesse.exceptions.ModelMissingAttributeError(target: Any, resolved_attrs: list[str], missing_name: str)

Bases: ModelAttributeError

Error indicating a model path was not found.

Model paths can be e.g. l1.P or s1.p1.o.

This exists mainly so it can be caught by the parser.

exception finesse.exceptions.ModelParameterDefaultValueError(element)

Bases: FinesseException

Error indicating a model element has no default model parameter.

Some model parameters have defaults, such that they can be referenced in kat script using e.g. myvar instead of myvar.value. This error indicates a model element without such a default was referenced directly.

exception finesse.exceptions.ModelParameterSelfReferenceError(value, parameter)

Bases: FinesseException

Error indicating a model parameter cannot be set to refer to itself.

exception finesse.exceptions.NoABCDCoupling(message, **kwargs)

Bases: FinesseException

Raised when an ABCD coupling at a component is requested but does not exist.

exception finesse.exceptions.NoCouplingError(message, **kwargs)

Bases: FinesseException

Raised when a coupling at a component is requested but does not exist.

exception finesse.exceptions.NoLinearEquations(message, **kwargs)

Bases: FinesseException

Thrown when a simulation has no linear equations to solve.

exception finesse.exceptions.NodeException(message, node=None)

Bases: FinesseException

Exception associated with Node related run-time errors.

Objects of type NodeException store the error message as well as an optional reference to the node(s) which caused the exception to be raised.

Parameters

messagestr

The error message.

nodeNode, optional

A reference to the offending node(s), defaults to None. This can be a single node or a sequence of nodes.

property node

The node(s) responsible for raising this exception instance.

Getter:

Returns the node(s) (either a single Node object or a sequence of these objects) responsible for the exception (read-only).

exception finesse.exceptions.NotChangeableDuringSimulation(message, **kwargs)

Bases: FinesseException

Thrown when a parameter is attempted to be changed during a simulation but is marked as not changeable during a simulation.

exception finesse.exceptions.ParameterLocked(message, **kwargs)

Bases: FinesseException

exception finesse.exceptions.TotalReflectionError(message, from_node=None, to_node=None)

Bases: FinesseException

Exception indicating total reflection of a beam at a component when performing beam tracing.

Parameters

messagestr

The error message.

from_node, to_nodeNode

References to the offending source and target nodes, respectively.

property coupling

The tuple of (from, to) nodes responsible for the total reflection error.

Getter:

Returns the nodes responsible for the exception (read-only).

finesse.freeze module

Tools for making an arbitrary Finesse object freezable.

class finesse.freeze.Freezable

Bases: object

An object which can be frozen and unfrozen, it is frozen upon construction.

items()
keys()
values()
finesse.freeze.canFreeze(cls)

A function to be used as a decorator for classes which should have the ability to be frozen and unfrozen.

Parameters

clsobject

Class to make freezable, should never be called directly as this function is to be used as a decorator.

Returns

clsobject

The class with frozen attributes set.

Examples

To make a custom object in Finesse frozen simply use this function as a decorator to the class definition:

from finesse.freeze import canFreeze

@canFreeze
class FinesseObject:
    ...

finesse.frequency module

Frequency analysis tools.

class finesse.frequency.Frequency(name, symbol, index=None, *, audio=False, audio_carrier_index=None, audio_carrier_object=None, audio_order=0)

Bases: object

Represents a frequency “bin” with a specific index.

The value of the frequency is calculated from the name of the frequency.

Parameters

namestr

Name of the frequency.

orderint, optional

The order of the frequency, defaults to zero.

audio_carrier

Frequency object for the carrier frequency of this sideband, if it is a sideband.

Getter:

Returns the index of the frequency (read-only).

audio_carrier_index

The carrier frequency.

Getter:

Returns the carrier frequency index (read-only).

audio_order

Audio modulation order of this frequency.

Getter:

Returns the order of the frequency (read-only).

f
index

Index of the frequency object.

Getter:

Returns the index of the frequency (read-only).

is_audio

Is this an audio sideband frequency?

name

Name of the frequency object.

Getter:

Returns the name of the frequency (read-only).

symbol
class finesse.frequency.FrequencyContainer(frequencies, FrequencyContainer carrier_cnt=None)

Bases: object

Contains an array of frequency objects and their associated faster access C struct information.

frequencies
get_frequency_index(self, value)

For a given value (either float or symbolic) return the index of the frequency with the same value.

Parameters

value[number | symbolic]

Frequency value to test for

Returns

indexint

Index for this frequency container

get_info(self, Py_ssize_t index)
size
class finesse.frequency.Fsig(*args, **kwargs)

Bases: ModelElement

This element represents the signal frequency (fsig) used in a model. It is a unique element, which means only one can be added to any given model. This is done automatically with the name fsig. It has a single parameter f for the frequency of the signal.

The signal frequency must be set by the user to enable transfer functions and noise projections to be simulated.

Parameters

namestr

Name of this element

f[float|None]

Signal frequency to use in a model [Hz]. If set to None then no signal frequencies will be modelled in the simulation.

property f

f : [float|None] Signal frequency to use in a model [Hz]. If set to None then no signal frequencies will be modelled in the simulation.

finesse.frequency.generate_frequency_list(model)

For a given model a symbolic list of frequencies is generated. The result can be used to generate a set of frequencies bins to be modelled in a simulation.

This method relies on using Symbol. Using symbolic statements this method attempts to isolate uniqe frequency bins whilst leaving those changing during a simulation present.

Returns

List of Symbol

finesse.gaussian module

Gaussian beam related tools and utilities.

class finesse.gaussian.HGMode(q, n=0, m=0)

Bases: object

An object representation of a Hermite-Gauss mode.

Parameters

qBeamParam or complex, or length two sequence of

The beam parameter. Specify a tuple of (qx, qy) as this argument for an astigmatic beam.

nint, optional; default: 0

Tangential mode index.

mint, optional; default: 0

Sagittal mode index.

property m
property n
property qx
property qy
set_q(q)

Sets the beam parameter in both planes to the same value q.

Parameters

qBeamParam or complex

The beam parameter.

um(y, out=None)

Compute the beam profile in the tangential plane.

un(x, out=None)

Compute the beam profile in the tangential plane.

unm(x, y, out=None)

Compute the full transverse beam profile.

class finesse.gaussian.HGModes(q, modes, bool reverse_gouy=False, bool flip_odd_x_modes=False)

Bases: object

A class that calculates a selection of Hermite-Gaussian modes.

Parameters

q[complex | BeamParam]

Complex valued beam parameter. If one if given qx = qy. Otherwise an iterable of two must be given (qx, qy).

modestuple((n, m))

list of mode indices

zero_tem00_gouybool, optional

When True, the HG00 mode will have its gouy phase removed, and relatively removed from all other HG modes. ie. gouy = (n+m)*Gouy rather than (1+n+m)*Gouy

reverse_gouybool, optional

Gouy phase is removed from coupling coefficients when True

flip_odd_x_modesbool, optional

When True any output mode with an odd n index will have a negative sign applied. This should be used in reflection cases due to the coordinate system change.

Unm(self, int n, int m, double x, double y)
compute_1d_modes(self, double[::1] x, double[::1] y)

Calculates the Un and Um modes arrays for the modes that were specificied when creating this HGModes object.

Parameters

x, yndarray

Array of x and y data points to compute the modes over

Returns

Unndarray(shape=(N, x.size))

A 2D array of all the modes over the x array

Umndarray(shape=(N, y.size))

A 2D array of all the modes over the y array

compute_2d_modes(self, double[::1] x, double[::1] y)

Calculates the Unm modes that were specificied when creating this HGModes object.

Parameters

x, yndarray

Array of x and y data points to compute the modes over

Returns

Unmndarray(shape=(N, y.size, x.size))

A 3D array of all the modes over the x and y domain

compute_points(self, double[::1] x, double[::1] y)

Calculates the Unm modes over a set of (x,y) points.

Parameters

x, yndarray

Array of x and y data points to compute the modes over, size of x and y must be the same.

Returns

Unmndarray(shape=(x.size, N), dtype=complex)

A 2D array of all the modes over the x and y domain

flip_odd_x_modes
reverse_gouy
unique_m_modes
unique_map
unique_n_modes

finesse.locks module

Controlling an interferometer via error signals.

class finesse.locks.Lock(*args, **kwargs)

Bases: ModelElement

A simple lock which computes and applies the feedback to a given parameter using an error signal.

Parameters

namestr

Name of newly created lock.

error_signalAny

An error signal parameter or an object capable of producing a real-type error signal. This is typically a demodulated PowerDetector instance (or the name of the instance).

feedbackParameter

A parameter of the model to apply the locks’ feedback signal to.

gainfloat

Control loop gain.

accuracyfloat

Threshold to decide whether the loop is locked.

enabledboolean

If true this lock will run when the RunLocks() action is used. Explicitly specifying the name of the lock will override this setting, e.g. RunLocks(name).

offsetfloat

An offset that is applied to the error signal before it is used.

property accuracy

accuracy : float Threshold to decide whether the loop is locked.

property disabled
property enabled

enabled : boolean If true this lock will run when the RunLocks() action is used. Explicitly specifying the name of the lock will override this setting, e.g. RunLocks(name).

property error_signal

The error signal of the lock.

property feedback

A handle to the parameter which the feedback signal is applied to.

property gain

gain : float Control loop gain.

property offset

offset : float An offset that is applied to the error signal before it is used.

finesse.materials module

Material objects are a simple structure that contain commonly used properties for calculations. By default this includes Fused Silica and Silicon at 123K.

class finesse.materials.Material(alpha, nr, dndT, kappa, emiss, poisson, E, rho, C, T)

Bases: object

C

specific heat \([J \, \mathrm{kg}^{-1}]\)

E

Young’s modulus \([\mathrm{kg} \, m^{-3}]\)

T

The temperature material’s properties are defined at \([K]\)

alpha

Thermal expansion coefficient \(\alpha\)

dndT

Thermo refractive coefficient \(\frac{dn}{dT} \: [K^{-1}]\)

emiss

Emissivity

kappa

Thermal conductivity \(\kappa \: [W m^{-1}]\)

nr

Refractive index \(n\)

poisson

Poisson’s ratio

rho

Density \([\mathrm{kg} \, m^{-3}]\)

finesse.model module

A sub-module containing the configuration container class Model which is used for building and manipulating interferometer systems.

class finesse.model.Event(iterable=(), /)

Bases: list

Event subscription.

A list of callable objects. Calling the ‘fire’ method on an instance of this will cause a call to each item in the list in ascending order by index.

Example Usage:

>>> def f(x):
...     print 'f(%s)' % x
>>> def g(x):
...     print 'g(%s)' % x
>>> e = Event()
>>> e()
>>> e.append(f)
>>> e(123)
f(123)
>>> e.remove(f)
>>> e()
>>> e += (f, g)
>>> e(10)
f(10)
g(10)
>>> del e[0]
>>> e(2)
g(2)

Notes

Code from https://stackoverflow.com/questions/1092531/event-system-in-python

fire(*args, **kwargs)
class finesse.model.IOMatrix(model)

Bases: object

clear()
class finesse.model.InputMatrix(model)

Bases: IOMatrix

class finesse.model.Model(*katscripts: str, loadfile: str | PathLike | None = None)

Bases: Freezable

Optical configuration class for handling models of interferometers.

This class stores the interferometer configuration as a directed graph and contains methods to interface with this data structure.

Parameters

*katscripts: str

KatScripts to parse, parsed in order.

loadfile: Optional[str | PathLike]

If present, this file will be loaded and parsed before parsing the katscripts.

ABCD(from_node=None, to_node=None, via_node=None, path=None, direction='x', symbolic=False, solution_name=None)

See finesse.tracing.tools.compute_abcd()

Note

The only difference to the above function is that any of from_node, to_node, via_node can be specified as strings.

property Nhoms

Number of higher-order modes (HOMs) included in the model.

Getter:

Returns the number of HOMs in the model (read-only).

acc_gouy(from_node=None, to_node=None, via_node=None, path=None, q_in=None, direction='x', symbolic=False, degrees=True, **kwargs)

See finesse.tracing.tools.acc_gouy()

Note

The only difference to the above function is that any of from_node, to_node, via_node can be specified as strings.

add(obj, *, unremovable=False)

Adds an element (or sequence of elements) to the model - these can be ModelElement sub-class instances.

When the object is added, an attribute defined by obj.name is set within the model allowing access to the object just added via model.obj_name where obj_name = obj.name.

Parameters

objSub-class of ModelElement (or sequence of)

The object(s) to add to the model.

unremovablebool, optional

When True, this object will not be able to be removed from this model

Returns

elementModelElement

The object that was added

Raises

Exception

If the matrix has already been built, the component has already been added to the model or obj is not of a valid type.

add_all_ad(node, f=0)

Adds amplitude detectors at the specified node and frequency f for all Higher Order Modes in the model.

Parameters

nodeOpticalNode

Node to add the detectors at.

fscalar, Parameter or ParameterRef

Frequency of the field to detect.

Returns

detslist

A list of all the amplitude detector instances added to the model.

add_fd_to_every_node(freq=0)

Adds a FieldDetector at every optical node in model at a given frequency The name of each FieldDetector is automatically generated using the following pattern: E_<component>_<port>_<node>

Parameters

fscalar, Parameter or ParameterRef

Frequency of the field to detect.

Returns

detslist

A list of all the field detector instances added to the model.

add_frequency(freq)

Add a specific optical carrier frequency to the model description.

Parameters

float or Frequency

The frequency to add.

add_matched_gauss(node, name=None, priority=0, matched_to=None)

Adds a Gauss object mode matched to the model at the specified node. If matched_to is given then the Gauss object will be matched to this, otherwise it will be mode matched to whichever dependency the node relies upon currently.

Parameters

node OpticalNode

The node instance to add the Gauss at.

namestr, optional

Optional name of the new Gauss object. If not specified then the name will be automatically given as “AUTO_MM_nodename” where nodename is the node’s full name.

priorityint, optional; default: 0

The priority value of the Gauss object. See TraceDependency.priority for details on the argument.

matched_toTraceDependency, optional

The trace dependency to solely match to.

add_parameter(name, value, *, description=None, dtype=<class 'float'>, units='', is_geometric=False, changeable_during_simulation=True)

Adds a new parameter to the Model. This can be used to add a custom parameter to the model that are not defined by elements themselves.

Parameters

namestr

Name of the parameter

valuenumeric | symbolic

The initial value of the parameter, this can be a simple numeric value or some FINESSE symbolic

desriptionstr, optional

A descritive text of what this parameter is

dtypestr, optional

The datatype, typically float, int, bool

unitsstr, optional

Units of the parameter for display purposes

is_geometricbool, optional

Whether this parameter is being used to recompute what the ABCD state of the model is. This should only be true if this is directly used to set what the ABCD matrices are. If you are just using a reference of this for another geometric parameter this does not have to be True.

changeable_during_simulationbool, optional

Whether this parameter is allowed to be changed during the simulation

add_to_model_namespacebool, optional

Whether to add this to the main model namespace or not

Examples

Here we add some new parameters:

>>> import finesse
>>> model = finesse.Model()
>>> A = model.add_parameter('A', 1, units='W')
>>> B = model.add_parameter('B', A.ref +1)

These act like normal element parameters, so references can be made to make symbolic equations and links between elements. These will be unparsed as variables in KatScript:

>>> print(model.unparse())
variable A value=1.0 units='W'
variable B value=(A+1)
property all_parameters

Returns a generator of all the parameters in this model and the elements added to this model.

property analysis

The root action to apply to the model when Model.run() is called.

Getter:

Returns the root analysis attached to this model.

Setter:

Sets the model’s root analysis.

beam_trace(order=None, disable=None, enable_only=None, symmetric=True, store=True, solution_name='beam_trace')

Performs a full beam trace on the model, calculating the beam parameters at each optical node.

Beam tracing requires at least one stable TraceDependency object - defined as a Gauss or Cavity object - in the model. Note that Cavity objects are not determined automatically, they must be explicitly added to the model.

The order in which the beam tracing is performed is as follows:

  • All internal cavity traces are carried out initially, i.e. any nodes that are part of a path of a Cavity instance in the model will be traced using the cavity eigenmode as the basis. See the note below for what happens in the case of overlapping cavities.

  • If order is not specified, then the dependency ordering given by Model.trace_order is used; i.e. beam traces are performed from each dependency in this list where any overlapping trees from multiple dependencies will always use the first dependency’s tree.

  • If order is specified, then beam traces from each dependency given in this argument will be carried out in the given order, in the same way as above. This effectively allows temporary overriding of the trace order for specific beam trace calls.

Certain dependencies can be switched off via the disable or enable_only arguments.

Full details on the beam tracing algorithm are given in Tracing the beam.

Note

Overlapping cavities

In complicated configurations, such as dual-recycled Michelson interferometers, it is often the case that there will be overlapping cavities; i.e. cavities which share common optical nodes in their paths. This naturally leads to the question - in which basis are these common nodes being set?

The algorithm used by this method will prioritise the internal trace of the cavity as follows:

  • If order is not given then the cavity appearing first in Model.trace_order will be used for setting the beam parameters of all nodes in this cavity path - including any nodes which are shared with other cavity instances.

  • Otherwise, the cavity appearing first in order will be used in the same way.

Parameters

ordersequence, optional; default: None

A priority list of dependencies to trace in order. These dependencies can be either Cavity / Gauss objects or the names of these objects. If this argument is not specified then beam tracing will be performed using the order defined in Model.trace_order.

This argument allows temporary overriding of the model trace order for a given beam trace call, without needing to change the TraceDependency.priority values of any dependencies in the model (which would affect all future beam traces in which order is not specified). Note that, if specifying this argument, a sub-set of the trace dependencies in the model can be given — any dependencies not in the given order will retain their original ordering.

disablesequence, optional: default: None

A single dependency or list of dependencies to disable. These dependencies can be either Cavity / Gauss objects or the names of these objects.

Note that this argument is ignored if enable_only is specified.

enable_onlysequence, optional: default: None

A single dependency or list of dependencies to explicity enable, all other dependencies will be switched off for the trace call. These dependencies can be either Cavity / Gauss objects or the names of these objects.

symmetricbool, optional; default: true

Flag to determine whether the beam parameters at OpticalNode.opposite nodes of each node encountered during the beam trace get set to the BeamParam.reverse() of the “forward” propagated beam parameter.

storebool, optional; default: True

Flag to determine whether to store the results of a beam trace in in the Model.last_trace property. Note that if this is set to False then accessing beam parameters via OpticalNode instances directly will give the last stored beam parameter at that node (i.e. not those given by this trace call).

Raises

exBeamTraceException

If there are no Gauss objects or stable Cavity instances present in the model.

ex_v: ValueError

If order was specified and it contains an invalid item.

ex_trTotalReflectionError

If a Beamsplitter object is present in the model with an angle of incidence and associated refractive indices giving total internal reflection.

Returns

outBeamTraceSolution

An object representing the results of the tracing routine.

built(simulation_type=None, simulation_options=None)

Context manager for making a simulation to work with. Once the context manager has been closed the simulation object and all its memory will be freed up.

Parameters

simulation_optionsdict

Options for type of simulation to run and its settings

Yields

BaseSimulation

Simulation object to interact with after it has been built.

Examples

>>> import finesse
>>> model = finesse.script.parse('''
... ... some KatScript ...
... ''')
>>>
>>> with model.built() as sim:
...     # interact with simulation object
...     ...
property cavities

The cavities stored in the model as a tuple object.

Getter:

Returns a tuple of the cavities in the model (read-only).

cavity_mismatch(cav1=None, cav2=None)

See finesse.tracing.tools.compute_cavity_mismatches()

cavity_mismatches_table(direction=None, percent=False, numfmt='{:.2e}')

Prints the mismatches between each cavity in an easily readable table format.

If either of each cavity in a coupling is unstable then the mismatch values between these will be displayed as nan.

Parameters

directionstr, optional; default: None

The plane to compute mismatches in, “x” for tangential, “y” for sagittal. If not given then tables for both planes will be printed.

percentbool, optional; default: False

Whether mismatch values are displayed in terms of percentage. Defaults to False such that the values are given as fractional mismatches.

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. Defaults to “{:.4f}”.

chain(*args, start=None, port=None)

Utility function for connecting multiple connectable objects in a sequential list together. Between each item the connection details can be specified, such as length or refractive index. This function also adds the elements to the model and returns those as a tuple to for the user to store if required.

Examples

Make a quick 1m cavity and store the added components into variables:

l1, m1, m2 = ifo.chain(Laser('l1'), Mirror('m1'), 1, Mirror('m2'))

Or be more specific about connection parameters by providing a dictionary. This dictionary is passed to the Model.connect() method as kwargs so see there for which options you can specify. For optical connections we can set lengths and refractive index of the space using a dictionary:

ifo.chain(
    Laser('l1'),
    Mirror('AR'),
    {'L':1e-2, 'nr':1.45},
    Mirror('HR')
)

In the above case a auto-generated space name will be made. If you want to explicitly set a name use {‘L’:1e-2, ‘nr’:1.45, ‘name’:”my_space”},

The starting point of the chain can be specfied for more complicated setups like a Michelson:

ifo = Model()
ifo.chain(Laser('lsr'), Beamsplitter('bs'))

# connecting YARM to BS
ifo.chain(
    1,
    Mirror('itmy'),
    1,
    Mirror('etmy'),
    start=ifo.bs,
    port=2,
)

# connecting XARM to BS
ifo.chain(
    1,
    Mirror('itmx'),
    1,
    Mirror('etmx'),
    start=ifo.bs,
    port=3,
)

Parameters

start: component, optional

This is the component to start the chain from. If None, then a completely new chain of components is generated.

port: int, optional (required if start defined)

The port number at the start component provided to start the chain from. This must be a free unconnected port at the start component or an exception will be thrown.

Returns

tuple

A tuple containing the objects added. The start component is never returned.

component_tree(root: ModelElement | str | None = None, network_type: str | NetworkType = NetworkType.COMPONENT, show_detectors: bool = False, show_ports: bool = False, radius: int | None = None, directed: bool = False) TreeNode

Retrieves a tree containing the network representing the components connected to the specified root. See also Visualizing the model.

Parameters

rootstr | ModelElement | Node | None, optional

Root element/node to start drawing the tree from. Is also used in combination with radius, for distance based filtering, by default None. When network_type is components, None will default to the first finesse.components.laser.Laser found in the model.

network_typestr | NetworkType, optional

Which network to plot, can be one of ‘optical’, ‘component’, ‘full’, by default NetworkType.COMPONENT

show_detectorsbool, optional

Whether to add detectors to the graph, by default False

show_portsbool, optional

Whether to show by which ports components are connected, by default False

radiusint >= 1 | None, optional

Must be used in combination with root, only include nodes of the network that are radius or less edges away from the root node, by default None, meaning that no nodes are filtered out.

directedbool, optional

Whether to use directed distance-based filtering, by default False. If set to True, will only include outgoing edges from the root node. See also the undirected argument of networkx.generators.ego.ego_graph()

Returns

TreeNode

The root tree node, with connected components as branches.

Raises

ValueError

If the specified root is not a model element.

Notes

Uses networkx.generators.ego.ego_graph() for the distance-based filtering.

property components

The components stored in the model as a tuple object.

Getter:

Returns a tuple of the components in the model (read-only).

compute_space_gouys(deg=True, **kwargs)

Calculate the Gouy phases accumulated over each space.

If you want to display these phases in a nicely formatted table then use Model.space_gouys_table().

Parameters

degbool, optional; default = True

Whether to convert each phase to degrees.

kwargsKeyword arguments

Arguments to pass to Model.beam_trace().

Returns

gouysdict

A dictionary of space: gouy where space is a Space object and gouy is another dict consisting of "x" and "y" keys mapping to the Gouy phase values for the tangential and sagittal planes, respectively.

connect(A, B, L=0, nr=1, gain=1, *, delay=None, name=None, verbose=False, connector=None)

Connects two ports in a model together. The ports should be of the same type, e.g. both optical ports.

This method will also accept components from the user, in such cases it will loop through the ports and use the first one in .ports that is currently unconnected.

As connect will try to be somewhat smart in guessing what the user is trying to connect, use verbose=True to print what is actually getting connected.

Parameters

AConnector or Port

Component to connect

BConnector or Port

Other component to connect

Lfloat, optional

Length of newly created Space or Wire instance. If connecting electronics, L will be treated as a delay in seconds

nrfloat, optional

Index of refraction of newly created Space.

gainfloat, symbol, optional

Gain of a wire connection for simply scaling between two signals

delayfloat, optional

Delay time for electrical connections.

namestr, optional

Name of newly created Space or Wire instance.

verbosebool, optional

When True, the actual connections being made will be printed.

Raises

Exception

If matrix has already been built, either of compA or compB are not present in the model, either of portA or portB are already connected or either of portA or portB are not valid options at the specified component(s).

create_mismatch(node, w0_mm=0, z_mm=0)

Sets the beam parameters such that a mismatch of the specified percentage magnitude (in terms of \(w_0\) and \(z\)) exists at the given node.

Parameters

nodeOpticalNode

The node to to create the mismatch at.

w0_mmfloat or sequence, optional

The percentage magnitude of the mismatch in the waist size. This can also be a two-element sequence specifying the waist size mismatches for an astigmatic beam. Defaults to zero percent for both planes.

z_mmfloat or sequence, optional

The percentage magntiude of the mismatch in the distance to the waist. This can also be a two-element sequence specifying the distance to waist mismatches for an astigmatic beam. Defaults to zero percent for both planes.

Returns

gaussGauss

The Gauss object created or modified via this mismatch.

deepcopy()
detect_mismatches(ignore_AR=True, **kwargs)

Detect the mode mismatches in the model.

If you want to display these mismatches in a nicely formatted table then use Model.mismatches_table().

Parameters

ignore_ARbool, optional

When True, with surfaces with R=0 the reflection mismatch is ignored

kwargsKeyword arguments

Arguments to pass to Model.beam_trace().

Returns

mismatchesdict

A dictionary of (n1, n2): mms where n1 is the From node and n2 is the To node. The value mms is another dict consisting of "x" and "y" keys mapping to the mismatch values for the tangential and sagittal planes, respectively.

property detectors

The detectors stored in the model as a tuple object.

Getter:

Returns a tuple of the detectors in the model (read-only).

disconnect(A, B)

Disconnects two elements A and B.

display_signal_blockdiagram(*nodes, **kwargs)

Displays a block diagram of the signal paths in this model. It will only contain electrical and mechanical connections made. Optical couplings are not shown.

Parameters

remove_mechanical_to_mechanicalbool, optional

If true, mechanical to mechanical node edges are removed. On by default as the result block diagram is complicated.

*nodesfinesse.components.node.Node

Nodes to show the path of

property dofs
element_order(element)

Get the order in which element was added to the model.

property elements

Dictionary of all the model elements with the keys as their names.

property f0

The default frequency to use for the model. This is determined by the value of lambda0.

Getter:

Returns frequency in Hertz

property frequencies

The frequencies stored in the model as a list instance.

Getter:

Returns a list of the model frequencies (read-only).

property gausses

A dictionary of optical node to Gauss instance mappings.

Getter:

Returns the dictionary of user defined beam parameter nodes (read-only).

get(attr)

Get an attribute of the model using a string path representation like l1.p1.o.q. If a finesse.element.ModelElement, finesse.components.node.Node, or a finesse.components.node.Port is given it will try to return the equivalent object in this model.

Parameters

attr[str | ModelElement | Node | Port]

An object to get from the model. Could be a generic string, or

Examples

Parse a simple model and extract the laser power model parameter:

>>> import finesse
>>> kat = finesse.Model()
>>> kat.parse('''
... l l1 P=2
... s s1 l1.p1 m1.p1
... m m1 R=0.5 T=0.5
... pd Pr m1.p1
... pd Pt m1.p2
... ''')
>>> kat.get("l1.P")
<l1.P=2.0 @ 0x11aa56588>

See Also

finesse.model.Model.get_element()

get_active_signal_nodes()

Returns the electrical and mechanical nodes that are active in a model, i.e. ones that need to be solved for because:

  • they have both input and output edges

  • have output edges and is a signal input

  • is used by a detector

  • has an input optical edge and some output edge

This could be more sophisticated and perhaps use the graph in a more correct way. For example, this will not prune some long line of electrical components connected to a mechanical node that drives some optical field. Or in other words, it will not determine if an input edge has an active node on the other end.

Returns

tuple of nodes

get_changing_edges_elements()

Returns

tuple(set of (node1-name, node2-name) edges, dict(weakref(element):list))

Returns a list of the network edges that will be changing, further information on the edge can be retreived directly from the model network. Also returned is a dictionary of elements and which parameter is changing

get_element(value)

Returns an element in this model that matches the requested value. This input can be either a string name or an element that might be owned by another model. In the latter case the name attribute will be extracted from the value and a search done in this model for an equivalent element.

Parameters

value[str|`Element`]

Name or equivalently named Element object to extract from this model.

Raises

KeyError when element cannot be found or FinesseException when the input value cannot be used.

Examples

>>> import finesse
>>> model = finesse.Model()
>>> model.parse('''
... l l1 P=1
... l l2 P=2
... ''')
>>> model.get_element('l1'), model.get_element('l2')
(<'l1' @ 0x122cf9fa0 (Laser)>, <'l2' @ 0x122cf9f40 (Laser)>)

Creating a copy of the model and getting elements will return elements with the same name but different id.

>>> model2 = model.deepcopy()
>>> model2.get_element('l1'), model2.get_element('l2')
(<'l1' @ 0x122d35c10 (Laser)>, <'l2' @ 0x122d35df0 (Laser)>)

Now if we try and select l1 using an element from a different model we should get the correct element with name l1 from that model

>>> model.get_element(model2.l1)
<'l1' @ 0x122cf9fa0 (Laser)>
>>> model2.get_element(model.l1)
<'l1' @ 0x122d35c10 (Laser)>
get_elements_connected_to(element)

Returns a set of elements that element is connected to.

Parameters

elementstr or :class:.`Element`

Element to query connections of

get_elements_of_type(*element_type: type | str) tuple[ModelElement, ...]

Extracts elements of a specific type from this model.

Parameters

*element_typetype or sequence of types

The element type(s) to retrieve.

Returns

tuple

The filtered results.

Examples

>>> IFO.get_elements_of_type(finesse.components.Mirror)
(<'m2' @ 0x7ff81a50b6a0 (Mirror)>, <'m1' @ 0x7ff81a50be48 (Mirror)>)
>>> tuple(IFO.get_elements_of_type("Mirror"))
(<'m2' @ 0x7ff81a50b6a0 (Mirror)>, <'m1' @ 0x7ff81a50be48 (Mirror)>)
>>> IFO.get_elements_of_type(finesse.components.Mirror, finesse.components.Beamsplitter))
(<'m2' @ 0x7ff81a50b6a0 (Mirror)>, <'m1' @ 0x7ff81a50be48 (Mirror)>, <'bs1' @ 0x7ff81a50bf33 (Beamsplitter)>)
get_frequency_object(frequency_value)
get_network(network_type: str | NetworkType = NetworkType.FULL, add_edge_info=False) Graph

Get specified network.

Parameters

network_typestr, optional

The network type to export: full (nodes, ports and components), “components” (just components), or “optical” (the optical subnetwork).

Returns

networkx.DiGraph

The network.

Raises

ValueError

If the specified network_type is unknown.

get_open_ports()

Return all optical ports that are not connected to a space.

get_parameters(*, include=None, exclude=None, are_changing=None, are_symbolic=None)

Get all or a filtered list of parameters from all elements in the model.

Parameters

include[iterable|str], optional

Parameters that should be included.

If a single string is given it can be a Unix file style wildcard (See fnmatch). A value of None means everything is included.

If an iterable is provided it must be a list of names or Parameter objects.

exclude[iterable|str], optional

Parameters that should not be included.

If a single string is given it can be a Unix file style wildcard (See fnmatch). A value of None means nothing is excluded.

If an iterable is provided it must be a list of names or Parameter objects.

are_changingboolean, optional

Filter if Parameter has a value that will be marked as changing during a simulation. Note this might be a user changing variable or a symbolic value whose arguments are changing.

are_symbolicboolean, optional

Filter if Parameter has a symbolic value. If set to None, not filtering is done.

Returns

parameterslist

List of filtered Parameters

Examples

>>> model = finesse.Model()
>>> model.parse('''
... l l1
... l l2
... lens L1 f=100
... link(l1, L1, l2)
... pd P1 L1.p1.o
... pd P2 L1.p2.o
... ''')
>>> print(model.get_parameters(include='*f*'))
>>> print(model.get_parameters(include='*f*', exclude='l2*'))
[<fsig.f=None @ 0x7f7fc449a580>, <l1.f=0.0 @ 0x7f7fc449a340>,
 <l2.f=0.0 @ 0x7f7fc449a880>, <L1.f=100.0 @ 0x7f7fc449aac0>]
[<fsig.f=None @ 0x7f7fc449a580>, <l1.f=0.0 @ 0x7f7fc449a340>,
 <L1.f=100.0 @ 0x7f7fc449aac0>]
property hom_labels

Labels for the HOMs present in this model.

property homs

An array of higher-order modes (HOMs) included in the model.

Getter:

Returns a copy of the array of the HOMs in the model.

Setter:

Sets the HOMs to be included in the model. See Model.modes() for the options available.

include_modes(modes)

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

Parameters

modessequence, str

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

info(modes=True, components=True, detectors=True, cavities=True, locks=True)

Get string containing information about this model.

Parameters

modes, components, detectors, cavities, locksbool, optional

Show model component information.

Returns

str

The model information.

property input_matrix_dc

The DC input matrix is used to relate degrees of freedoms and readouts within a model. This information is used to generate DC locks to put the model at an operating point defined by the error signals used.

Getter:

Returns an InputMatrix object.

property is_built

Flag indicating whether the model has been built.

When this evaluates to True, the structure of the underlying matrix should not be changed.

Getter:

True if the model has been built, False otherwise.

property is_modal

Flag indicating whether the model is modal or plane-wave.

Getter:

True if the modal is modal, False if it is plane-wave.

property is_traced

Flag indicating whether the model has been traced.

Warning

This flag only indicates whether a beam trace has been performed on the model, it does not mean that the last stored beam trace (i.e. Model.last_trace) corresponds to the latest state of the model.

Getter:

True if the mode has been traced at least once, False otherwise.

property k0

The default wavenumber used for the model. This is determinde by the value of lambda0.

Getter:

Returns frequency in Hertz

property lambda0

The default wavelength to use for the model.

Getter:

Returns wavelength in meters

Setter:

Sets the wavelength in meters

property last_trace

An instance of BeamTraceSolution containing the output of the most recently stored beam trace performed on the model.

Getter:

Returns a copy of the most recently stored beam trace output. Read- only.

Connect multiple components together in one quick command. In many models a collection of components just need to be connected together without having to specify each port exactly. This command accepts multiple components as arguments, each is connected to the next. Interally the link command is creating spaces and wires between components but giving them automatically generated names. Therefore, the link command is useful when you are not interested in what the spaces or wires are called, which is often the case in readout paths or signal feedback loops.

This command will try to connect components in the “obvious” way. For example, a collection of two-port optical components will be connected one after another, the second port of the first item connected to the first port of the second component, etc.

Explicit ports can also be provided if exact connections are required. For example, at a beamsplitter, if you want to link through on transmission then use …, BS.p1, BS.p3, …. Using just BS here would result in using the first and second ports, a reflection.

Links can contain a mix of optical and signal nodes. When going from optical to signal nodes they must be specified verbosely. For example, a DC readout component PD, you would need to specify …, PD, PD.DC, ….

Parameters

*args[Components | float | Port]

Separate arguments of either components or ports. A float value will create a space or wire with the provided length or time delay.

verbosebool, optional

Print out what the link command is doing

Examples

Here we make a linear optical cavity

>>> model = finesse.Model()
>>> model.parse('''
... l l1
... m ITM T=0.014 R=1-ITM.T
... m ETM T=50u R=1-ETM.T
... bs BS R=0.5 T=0.5
... # A local readout on tranmission of the cavity
... l lo
... readout_dc TRANS
... fsig(1)
... link(l1, ITM, 4000, ETM, BS.p1, BS.p2, TRANS, verbose=True)
... link(lo, BS.p4)
... ''')

Flagging the verbose argument will result in the linking process being printed for further clarification of what it is doing. Multiple links can be done to specify separate paths as is done above for the connection between lo and BS.

The auto-generated spaces can be seen with:

>>> print(list(model.spaces.items()))
[('l1_p1__ITM_p1', <'l1_p1__ITM_p1' @ 0x7f98da6ab760 (Space)>),
('ITM_p2__ETM_p1', <'ITM_p2__ETM_p1' @ 0x7f98da6b8ac0 (Space)>),
('ETM_p2__BS_p1', <'ETM_p2__BS_p1' @ 0x7f98da6b8a90 (Space)>),
('BS_p2__TRANS_p1', <'BS_p2__TRANS_p1' @ 0x7f98db1f37c0 (Space)>),
('lo_p1__BS_p4', <'lo_p1__BS_p4' @ 0x7f98da6ab4c0 (Space)>)]

Links can also be used to do quick feedback loops and connections. For example, the small signal DC output of the readout above could be connected to the laser amplitude modulation using:

>>> link(l1, ITM, 4000, ETM, BS, TRANS, TRANS.DC, l1.amp)

Similarly, the auto-generated wires can be seen with:

>>> print(list(model.wires.items()))
[('TRANS_DC__l1_amp', <'TRANS_DC__l1_amp' @ 0x7f98da6d8ac0 (Wire)>)]
property locks
merge(other, from_comp, from_port, to_comp, to_port, name=None, L=0, nr=1)

Merges the model other with this model using a connection at the specified ports.

Note

Upon completion of this method call the Model instance other will be invalidated. All components and nodes within other will be associated with only this model.

Parameters

otherModel

A model configuration to merge into this model instance.

from_compSub-class of Connector

The component to start a connection from.

from_portint

Port of from_comp to initiate the connection from.

to_compSub-class of Connector

The component to bridge the connection to.

to_portint

Port of to_comp to bridge the connection to.

namestr

Name of connecting Space instance.

Lfloat

Length of the connecting space.

nrfloat

Index of refraction of the connecting space.

mismatches_table(ignore_AR=True, numfmt='{:.4f}', **kwargs)

Prints the mismatches computed by Model.detect_mismatches() to an easily readable table.

Parameters

ignore_ARbool, optional

When True, with surfaces with R=0 the reflection mismatch is ignored

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. Defaults to “{:.4f}”.

kwargsKeyword arguments

Arguments to pass to Model.beam_trace().

property mode_index_map

An ordered dictionary where the key type is the modes in the model and the mapped type is the index of the mode.

Getter:

Returns the map of modes to indices (read-only).

modes(modes=None, maxtem=None, include=None, remove=None)

Select the HOM indices to include in the model.

See Selecting the modes to model for examples on using this method.

Parameters

modessequence, 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 “off”, “even”, “odd”, “x” or “y”.

maxtemint, optional; default: None

Optional maximum mode order.

includesequence, str, optional

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

removesequence, str, optional

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

See Also

Model.include_modesInsert mode indices into Model.homs at the

correct (sorted) positions.

Model.remove_modes : Remove mode index pairs from the model.

Examples

See Selecting the modes to model.

property modes_setting
property network

The directed graph object containing the optical configuration as a networkx.DiGraph instance.

The network stores Node instances as nodes and Space instances as edges, where the former has access to its associated component via Node.component.

See the NetworkX documentation for further details and a reference to the data structures and algorithms within this module.

Getter:

Returns the directed graph object containing the configuration (read-only).

property optical_network

A read-only view of the directed graph object stored by Model.network but only containing nodes of type OpticalNode and only with edges that have couplings to optical nodes.

Getter:

Returns the optical-only directed graph-view (read-only).

property optical_nodes: list[Node]

The optical nodes stored in the model.

Getter:

Returns a list of all the optical nodes in the model (read-only).

property parameters

Returns any parameters added to this model, see also Model.all_parameters.

parse(text, spec=None) Model

Parses kat script and adds the resulting objects to the model.

Parameters

textstr

The kat script to parse.

specKatSpec, optional

The language specification to use. Defaults to the shared KatSpec instance.

Returns

finesse.model.Model

Return the model (return self, not a copy)

See Also

parse_file : Parse script file. parse_legacy : Parse Finesse 2 kat script. parse_legacy_file : Parse Finesse 2 kat script file.

parse_file(path, spec=None) Model

Parses kat script from a file and adds the resulting objects to the model.

Parameters

pathstr, pathlib.Path, or file-like

The path or file object to read kat script from. If an open file object is passed, it will be read from and left open. If a path is passed, it will be opened, read from, then closed.

specKatSpec, optional

The language specification to use. Defaults to the shared KatSpec instance.

Returns

finesse.model.Model

Return the model (return self, not a copy)

See Also

parse : Parse script. parse_legacy : Parse Finesse 2 kat script. parse_legacy_file : Parse Finesse 2 kat script file.

parse_legacy(text) Model

Parses legacy (Finesse 2) kat script and adds the resulting objects to the model.

Parameters

textstr

The kat script to parse.

Returns

finesse.model.Model

Return the model (return self, not a copy)

See Also

parse_legacy_file : Parse Finesse 2 kat script file. parse : Parse Finesse 3 kat script. parse_file : Parse Finesse 3 kat script file.

parse_legacy_file(path) Model

Parses legacy (Finesse 2) kat script from a file and adds the resulting objects to the model.

Parameters

pathstr, pathlib.Path, or file-like

The path or file object to read kat script from. If an open file object is passed, it will be read from and left open. If a path is passed, it will be opened, read from, then closed.

Returns

finesse.model.Model

Return the model (return self, not a copy)

See Also

parse_legacy : Parse Finesse 2 kat script. parse : Parse Finesse 3 kat script. parse_file : Parse Finesse 3 kat script file.

path(from_node, to_node, via_node=None, symbolic=False)

Retrieves an ordered container of the path trace between the specified nodes.

The return type is an OpticalPath instance which stores an underlying list of the path data (see the documentation for OpticalPath for details).

Parameters

from_nodeNode

Node to trace from.

to_nodeNode

Node to trace to.

via_nodeNode (or sequence of)

Node(s) to traverse via in the path.

symbolicbool, optional

Whether to make a symbolic calculation of path lengths

Returns

outOpticalPath

A container of the nodes and components between from_node and to_node in order.

Raises

e1NodeException

If either of from_node, to_node are not contained within the model.

e2networkx.NetworkXNoPath

If no path can be found between from_node and to_node.

phase_config(zero_k00=False, zero_tem00_gouy=True)

Coupling coefficient and Gouy phase scaling:

  • phase_level 3 == zero_k00=True, zero_tem00_gouy=True

  • phase_level 2 == zero_k00=False, zero_tem00_gouy=True

  • phase_level 1 == zero_k00=True, zero_tem00_gouy=False

  • phase_level 0 == zero_k00=False, zero_tem00_gouy=False

See also Phase configuration settings

This can be used to change the computation of light field phases in the Hermite-Gauss mode. In general, in the presence of higher order modes, the “macroscopic length” of a space is no longer an integer number of wavelengths for the TEM00 mode because of the Gouy phase. Furthermore, the coupling coefficients \(k_{nmnm}\) contribute to the phase when there is a mode mismatch. For correct analysis these effects have to be taken into account. On the other hand, these extra phase offsets make it very difficult to set a resonance condition or operating point intuitively. In most cases another phase offset can be added to all modes so that the phase of the TEM00 becomes zero.

This method allows setting these phase offsets for the propagation through free space, for the coupling coefficients, or both. Regardless of the setting, the phases for all higher modes are changed accordingly such that the relative phases remain correct.

Parameters

zero_k00bool, optional

Scale phase for k0000 (TEM00 to TEM00) coupling coefficients to 0. Defaults to True.

zero_tem00_gouybool, optional

Ensure that all Gouy phases for TEM00 are 0. Defaults to True.

property phase_level

An integer corresponding to the phase level given to the phase command of a Finesse 2 kat script.

Getter:

Returns the phase level.

Setter:

Sets the phase level - turns on/off specific flags for the scaling of coupling coefficient and Gouy phases.

plot_dcfields_graph(path: Path | str | None = None, show: bool = True, add_fields: bool = True, add_operators: bool = False) Path

Visualize the values of the DC fields in a model in a graph representation. Will run a finesse.analysis.actions.dc.DCFields action under the hood.

Parameters

modelfinesse.Model

Model to visualize

pathPath | str | None, optional

Save the resulting image to the given path. Defaults to None, which saves in a temporary file that is displayed if ‘show’ is set to True.

showbool, optional

Whether to show the resulting image. In Jupyter environments, shows the plot inline, otherwise opens a webbrowser. Defaults to True.

add_fieldsbool, optional

Whether to show the DC fields values in the nodes of the graph, by default True

add_operatorsbool, optional

Whether to show the couplings between nodes as edge tooltips, by default False. Only supported for plane-wave single frequency models for now.

Returns

pathlib.Path

Path where the svg was saved

Raises

ModuleNotFoundError

If pygraphviz is not installed

NotImplementedError

When add_operators is True, but the model is not plane-wave single frequency

plot_graph(layout: str = 'neato', graphviz=True, network_type: str | NetworkType = NetworkType.COMPONENT, root: str | ModelElement | Node | None = None, show_detectors: bool = False, radius: int | None = None, directed: bool = False, path: Path | None = None, show: bool = True, format: Literal['png', 'svg'] = 'svg', **kwargs)

Plot the node network. See also Visualizing the model

Parameters

layoutstr, optional

The networkx plotting layout engine, see NetworkX manual for more details. Choose from: circular, fruchterman_reingold, kamada_kawai, multipartite, planar, random, shell, spectral, spiral, spring, neato, dot, fdp, sfdp, or circo

graphvizbool, optional

Whether to use the graphviz library for better node layouts (needs optional dependency), by default True

network_typestr | NetworkType, optional

Which network to plot, can be one of ‘optical’, ‘component’, ‘full’, by default NetworkType.COMPONENT

rootstr | ModelElement | Node | None, optional

In combination with radius, the root node of the graph to use for distance based filtering, by default None. When network_type is components, None will default to the first finesse.components.laser.Laser found in the model.

show_detectorsbool, optional

Whether to add detectors to the graph, by default False

radiusint >= 1 | None, optional

Must be used in combination with root, only include nodes of the network that are radius or less edges away from the root node, by default None, meaning that no nodes are filtered out.

directedbool, optional

Whether to use directed distance-based filtering, by default False. If set to True, will only include outgoing edges from the root node. See also the undirected argument of networkx.generators.ego.ego_graph()

pathPath | None, optional

Save the resulting image to the given path. Defaults to None, which saves in a temporary file that is displayed if ‘show’ is set to True.

showbool, optional

Whether to show the resulting image. In Jupyter environments, shows the plot inline, otherwise opens a webbrowser for svgs and PIL for pngs. Defaults to True.

Notes

Uses networkx.generators.ego.ego_graph() for the distance-based filtering.

plot_symbolic_network() None

Visualize the symbolic network with graphviz.

propagate_beam(from_node=None, to_node=None, via_node=None, path=None, q_in=None, direction='x', symbolic=False, simplify=False, solution_name=None, **kwargs)

See finesse.tracing.tools.propagate_beam()

Note

The only difference to the above function is that any of from_node, to_node, via_node can be specified as strings.

propagate_beam_astig(from_node=None, to_node=None, via_node=None, path=None, qx_in=None, qy_in=None, symbolic=False, solution_name=None, **kwargs)

See finesse.tracing.tools.propagate_beam_astig()

Note

The only difference to the above function is that any of from_node, to_node, via_node can be specified as strings.

property readouts

Returns all readouts in the model.

reduce_get_attr(attr)
reduce_set_attr(attr, value)
remove(obj)

Removes an object from the model.

Note

If a string is passed, it will be looked up via self.elements.

Parameters

objFrequency or sub-class of ModelElement

The object to remove from the model.

Raises

Exception

If the matrix has already been built or there is no component with the given name in the model.

remove_modes(modes)

Removes the mode indices in modes from the Model.homs array.

Parameters

modessequence, str

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

replace(replace: str | Connector, sub: str, component: str | None = None, optical_ports: None | list[str] = None, mechanical_ports: None | list[str] = None, electrical_ports: None | list[str] = None, verbose: bool = False) str

Unparse the model and replace one of its components with a new section of katscript. Returns the katscript for the model with component replaced.

Parameters

replacestr | Connector

Which component to replace.

substr

New section of katscript that will replace the katscript line defining the component to replace.

componentstr | None, optional

Replacement string for any references of the component name, by default None

optical_portsNone | list[str], optional

Replacement ports for any references of the component optical ports, by default None

mechanical_portsNone | list[str], optional

Replacement ports for any references of the component mechanical ports, by default None

electrical_portsNone | list[str], optional

Replacement ports for any references of the component electrical ports, by default None

verbosebool, optional
Whether to print a diff between the current and new KatScript,

by default False

Returns

str

KatScript with the component replaced.

Raises

FinesseException

When the component to replace is not of type Connector.

reset_sim_trace_config()

Resets the simulation beam tracing configuration dict, given by Model.sim_trace_config, to the default values.

run(analysis=None, return_state=False, progress_bar=False, simulation_type=None, simulation_options=None)

Runs the current analysis set for this model. If no analysis has been set in the model and the analysis argument is None, then this will run a Noxaxis() on the current model.

If a separate analysis has been provided with the analysis argument then this will be run instead of what has been set to model.analysis.

Parameters

analysis[str, Action], optional

KatScript code for an analysis or an analysis object to run.

return_statebool, optional

Whether to return the state of each model generated by this analysis.

progress_barbool, optional

Whether to show progress bars or not

Returns

solSolution Object

Solution to the analysis being performed

statesobjects, only when return_state == True

States generated by the analysis

Examples

Run a model with the analysis specified in the original KatScript:

>>> import finesse
>>> model = finesse.Model()
>>> model.parse('''
... l l1
... pd P l1.p1.o
... ''')
>>> model.run("for(l1.P, [0, 1, 2, 3], print(l1.P))")

Or you can run a separate analysis:

>>> model.run("noxaxis()")
save(path: Path)

Save the model to a file. This uses the dill library to pickle the model which will save all the model data and the current state. This is not gauraunteed to work across python versions or across diferrent platforms and systems. It should only be used to load and save models within the same python environment and not for long term storage. Files will be overwritten if they already exist.

Parameters

pathPath

The path to save the model to. If no extension is given then a .pkl will be added.

Returns

pathPath

The path the model was saved to.

Examples

>>> model.save('mymodel.pkl')
>>> loaded_model = finesse.model.load('mymodel.pkl')
set(attr, value)

Set an attribute of the model using a string path representation like l1.p1.o.q.

property signal_nodes: list[Node]

The signal nodes stored in the model.

Getter:

Returns a list of all the signal nodes in the model (read-only).

property sim_initial_trace_args

Filtered dictionary of Model.sim_trace_config corresponding to only those options which match the arguments of Model.beam_trace().

The arguments of Model.beam_trace(), see the linked docs for descriptions of each of these. These config values are passed to the initial beam trace call when building a modal simulation, thereby determining the structure of both the Model.trace_forest used for computing the initial beam parameters, as well as the trace forest of changing beam paths as stored by the simulation itself.

Note

The return value is a new filtered dict, not a sub-view of Model.sim_trace_config, thus modifying this dict does not affect the entries in Model.sim_trace_config.

property sim_trace_config

Dictionary corresponding to beam tracing configuration options for simulations.

The (string) keys of this dict are:

  • The arguments of Model.beam_trace(), see the linked docs for descriptions of each of these. These config values are passed to the initial beam trace call when building a modal simulation, thereby determining the structure of both the Model.trace_forest used for computing the initial beam parameters, as well as the trace forest of changing beam paths as stored by the simulation itself.

  • “retrace” — flag determining whether beam tracing is re-executed, during a simulation, whenever some dependent parameter changes. This is True by default, meaning that any paths in the model with changing geometric parameters will automatically be retraced during the simulation. Setting this to False means that the initial beam parameters (from the beam trace executed at the start of the simulation) are used for all data points, regardless of whether any geometric parameter is changing or not.

  • “unstable_handling” — the strategy to use when encountering unstable optical cavities during a simulation (as a potential result of scanning geometric parameters). The accepted values for this config option are:

    • “auto” — (default) contingency TraceForest instances are created when entering unstable cavity regions; or, if there are no stable TraceDependency objects, detector outputs are masked appropriately in these regions.

    • “mask” — detector outputs masked appropriately whenever an unstable cavity is encountered; i.e. nothing else (scatter matrices, gouy phases, refills etc.) is computed for such data points.

    • “abort” — immediately aborts the simulation, if an unstable cavity is encountered,

      by raising a BeamTraceException.

Hint

Most of the time it is better to use Model.sim_trace_config_manager() to temporarily set simulation beam tracing configuration options, rather than modifying the entries here directly (which then requires manual re-setting as outlined below).

Getter:

Beam tracing configuration options for simulations.

Examples

One can use this property to change the behaviour of beam tracing for a simulation. For example, this:

model.sim_trace_config["disable"] = "cav1"

would switch off tracing from the trace-dependency named “cav1” during a simulation.

It can also be used to temporarily override the trace order used, without modifying TraceDependency.priority values and, thus, without modifying the actual Model.trace_order. For example:

model.sim_trace_config["order"] = ["gL0", "cav2", "cav1"]

would set the trace ordering for the next simulation using this model to the order given.

To reset the sim_trace_config dict entries to the default values, call Model.reset_sim_trace_config().

sim_trace_config_manager(**kwargs)

Change the Model.sim_trace_config within a context.

This provides a convenient pattern through which one can temporarily set the simulation beam tracing behaviour in a with block. The method Model.reset_sim_trace_config() is called on exit.

Parameters

kwargskeyword arguments

See Model.sim_trace_config.

Examples

Temporarily change the tracing order:

with model.sim_trace_config_manager(order=["cavXARM", "gaussBS", "cavYARM"]):
    out = model.run("noxaxis()")

Disable certain dependencies in a context:

with model.sim_trace_config_manager(disable="cavIMC"):
    out = model.run("noxaxis()")

Switch off re-tracing and enable only two specific trace dependencies:

with model.sim_trace_config_manager(
    retrace=False, enable_only=["cavXARM", "cavYARM"]
):
    out = model.run("noxaxis()")

Use asymmetric tracing and mask all data points where any unstable cavity is encountered:

with model.sim_trace_config_manager(symmetric=False, unstable_handling="mask"):
    out = model.run("noxaxis()")
sort_elements(key)

Sort the display order of the elements in the model.

This order is used for determining the order of plot traces and other listings.

Element sorting is useful for example when parsing KatScript into a model, where adding of elements to the model may not be performed in the same order as the corresponding definitions in the script. To ensure consistency to the user, this method can be used to sort the parsed elements back into their original script order.

Notes

The sort performed by this method is stable.

Parameters

keycallable

Specifies a function that takes a single argument - a tuple containing the element name and object - and returns a comparison key.

space_gouys_table(deg=True, numfmt='{:.4f}', **kwargs)

Prints the space Gouy phases, as computed by Model.compute_space_gouys(), to an easily readable table.

Parameters

degbool, optional; default = True

Whether to convert each phase to degrees.

fmtber_formatstr 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. Defaults to “{:.4f}”.

kwargsKeyword arguments

Arguments to pass to Model.beam_trace().

sub_model(from_node, to_node)

Obtains a subgraph of the complete configuration graph between the two specified nodes.

Parameters

from_nodeNode

Node to trace from.

to_nodeNode

Node to trace to.

Returns

Gnetworkx.graphviews.SubDiGraph

A SubGraph view of the subgraph between from_node and to_node.

switch_off_homs()

Turns off HOMs, switching the model to a plane wave basis.

property symbolic_network: DiGraph

Network showing the symbolic relationships between parameters in the model. Note that orphans are removed for clarity.

Returns

nx.DiGraph

Directional graph of the symbolic relationship between parameter values

tag_node(node, tag)

Tag a node with a unique name.

Access to this node can then be performed with:

node = model.<tag_name>

Parameters

nodeNode

An instance of a node already present in the model.

tagstr

Unique tag name of the node.

temporary_parameters(include=None, exclude=None)

Context manager that lets user change any ModelParameter then return it to the original value once completed. When the Model is in this temporary state it cannot have any structural changes, such as adding or removing components.

There is also the ability to include or exclude certain parameters from reverting back to their previous values if needed.

Parameters

includeiterable or str, optional

Parameters that should be reverted once the context has exitted.

If a single string is given it can be a Unix file style wildcard (See fnmatch). A value of None means everything is included.

If an iterable is provided it must be a list of names or Parameter objects.

excludeiterable or str, optional

Parameters that should not be reverted once the context has exitted.

If a single string is given it can be a Unix file style wildcard (See fnmatch). A value of None means nothing is excluded.

If an iterable is provided it must be a list of names or Parameter objects.

Examples

import finesse
model = finesse.Model()
model.parse('''
l l1 P=1
m m1 R=0.99 T=0.01 Rc=-1934
m m2 R=1 T=0 Rc=2245
m m3 R=1 T=0 Rc=10000
'''
)
with model.temporary_parameters():
    model.m1.Rc = 100
    print(model.m1.Rc)
print(model.m1.Rc)

# Only reset m2 parameters
with model.temporary_parameters(include="m2.*"):
    ...

# Only reset m2.phi and m1.phi parameters
with model.temporary_parameters(include=("m2.phi", "m1.phi")):
    ...

# Reset everything apart from all phi parameters
with model.temporary_parameters(exclude="*.phi"):
    ...

# Reset everything apart from all phi parameters
with model.temporary_parameters(exclude="m[1-3].phi"):
    ...
to_component_network(add_edge_info: bool = False)

Generate an undirected graph containing components as the nodes of the graph and connections (spaces, wires) between component nodes as the edges of the graph.

Returns

networkx.Graph

The component network.

property trace_forest

The TraceForest instance held by the model.

This is a representation of the beam tracing paths from each dependency which takes on a form corresponding to the last call to Model.beam_trace(). See the documentation for TraceForest itself for details on what exactly this object is, and the various methods and properties it exposes.

Hint

Most of the time users will not need to touch this property as it is generally just used internally. Beam tracing functionality should instead be used via the carefully designed interfaces, i.e: Model.beam_trace() for full model beam traces, Model.propagate_beam() for propagating an arbitrary beam through a path etc. See tracing.tools for details on various beam tracing tools.

Despite the above, it can sometimes be useful to query this property to get a visual representation of how the beam tracing paths look in your model. To do this one can simply print the return of this property, i.e.:

print(model.trace_forest)

to get a forest-like structure of all the beam tracing trees which represent the current state (as of the last Model.beam_trace() call) of the model.

Getter:

The TraceForest object associated with this model. Read-only.

property trace_order

A list of beam tracing dependencies, ordered by their tracing priority.

Dependency (i.e. Cavity and Gauss) objects are ordered in this list according to the priority in which they will be traced during the beam tracing routine.

This ordering is strictly defined as follows:

Dependencies will be sorted in order of descending TraceDependency.priority value. Any dependencies which have equal TraceDependency.priority value are sorted alphabetically according to their names.

Please be aware that this means if no priority values have been given to any TraceDependency instance in the model, as is the default when creating these objects, then this trace order list is simply sorted alphabetically by the dependency names.

Note

Regardless of their positions in this list, the internal traces of Cavity objects will always be performed first. Internal cavity traces are defined as the traces which propagate the cavity eigenmode through all the nodes of the cavity path.

Importantly, however, the order in which Cavity objects appear in this trace order list will also determine the order in which their internal traces are performed. This is relevant only for when there are overlapping cavities in the model - recycling cavities in dual-recycled Michelson interferometer configurations are a typical case of this.

As always see Model.beam_trace() and Tracing the beam for more details on the inner workings of the beam tracing routines.

Temporary overriding of this order for a given Model.beam_trace() call can be performed by specifying the order argument for this method call.

To override this ordering for a simulation, one should use the "order" keyword argument of Model.sim_trace_config_manager() to temporarily use any arbitrary dependency order within a context.

Getter:

Returns a list giving the order in which dependencies will be traced. Read-only.

property trace_order_names

A convenience property to retrieve a list of the names of each TraceDependency instance in Model.trace_order.

Getter:

Returns a list of the names of the dependencies in the order they will be traced. Read-only.

unbuild()

If a model has been built then this function undoes the process so the model can be changed and rebuilt if required.

unparse(inplace=True, warnings=True)

Serialise the model to kat script.

Returns

str

The generated kat script.

unparse_file(path, inplace=True)

Serialise the model to kat script in a file.

Parameters

pathstr, pathlib.Path, or file-like

The path or file object to write kat script to. If an open file object is passed, it will be written to and left open. If a path is passed, it will be opened, written to, then closed.

update_gauss(node, qx=None, qy=None)

Update the value of a manual beam parameter (i.e. Gauss object) at the specified node.

Parameters

nodeOpticalNode

The node instance to update the gauss at.

qxBeamParam or complex, optional

Beam parameter in tangential plane.

qyBeamParam or complex, optional

Beam parameter in sagittal plane.

class finesse.model.OutputMatrix(model)

Bases: IOMatrix

finesse.model.load(path: Path)

Load a model from a file. This uses the dill library to unpickle the model. This is not gauraunteed to work across python versions or across diferrent platforms and systems. It should only be used to load and save models within the same python environment and not for long term storage.

Parameters

pathPath

The path to load the model from.

Returns

Model

The loaded model.

Examples

>>> model.save('mymodel.pkl')
>>> loaded_model = finesse.model.load('mymodel.pkl')
finesse.model.locked_when_built(func)
finesse.model.make_optical_network_view(model)

From a given model return a view of the full network that just contains the optical nodes and edges.

finesse.parameter module

class finesse.parameter.EnumCaster(enum, validate)

Bases: object

Enums are irritating as they don’t act like normal types. You need to getitem to go from value to key. They also don’t cast themselves back to themselves as float(1.0) would.

class finesse.parameter.GeometricParameter(parameter_info, owner)

Bases: Parameter

Specialised parameter class for variables which are dependencies of ABCD matrices. These include surface radii of curvature, lens focal lengths, beamsplitter angles of incidence, space lengths and space refractive indices.

When setting the value of a GeometricParameter outside of a simulation, the dependent ABCD matrices get updated via the update_abcd_matrices C method. Inside a simulation, the ABCD matrix elements are updated in a much more efficient way via the connector workspaces.

value
class finesse.parameter.Parameter(parameter_info, owner)

Bases: object

changeable_during_simulation

True if this parameter cannot be changed during a simulation.

datatype

The underlying C datatype of this parameter.

datatype_cast(self, value, ignore_failure=False)

Casts a value into the datatype of this parameter.

If ignore_failure is True then if this value cannot be cast it is just returned.

description
eval(self, bool keep_changing_symbols=False)

Evaluates the value of this parameter.

If the parameter is dependant on some symbolic statement this will evaluate that. If it is not the value itself is returned. This method should be used when filling in matrices for computing solutions of a model.

eval_string

Whether to cal ‘eval’ on the parameter value in the string representation

full_name
is_changing

True if this parameter will be changing during a simulation.

is_default_for_owner

Whether this parameter is the default for the owning model element.

is_externally_controlled

Whether this parameter is being externally controlled by another element.

is_geometric
is_nr
is_symbolic

True if this parameter’s value is symbolic.

is_tunable

True if this parameter will be directly changed during a simulation.

lambdify(self, *args)

Returns a lambda function that returns the value of this parameter.

Parameters in a symbolic function can be kept as variables by passing the Parameter object as optional arguments. The returned lambda function will then have len(args) arguments - effectively subsituting values at call time.

locked

If locked, this parameters value cannot be changed.

name
owner

The component/element this parameter is associated with, this could be a finesse.element.ModelElement or a finesse.model.Model.

ref

Returns a reference to this parameter’s value to be used in symbolic expressions.

remove_external_setter(self, element)

Stops an element from being an external setter.

Parameters

elementModelElement

Element that is controlling this parameter

resolve(self)

When this parameters value has some dependency whose value has not yet been set, like during parsing, its value will be a callable object, this method will call this function to return the value.

set_descendants(self, set descendants) void
set_external_setter(self, element, symbol)

Sets an element as an external controller of the value of this parameter. It is used in cases where an element is physically imposing its value onto this one, such as degrees of freedom.

Parameters

elementModelElement

Element that will be controlling this parameter

symbolsymbolic expression

The expression that this element is imposing upon the parameter.

state
units
value
class finesse.parameter.ParameterRef(param)

Bases: Symbol

A symbolic instance of a parameter in the model.

A parameter is owned by some model element, which can be used to connect its value to other aspects of the simulation.

property cyexpr_name

Name of the parameter reference in cyexpr compatibility format.

This is equivalent to ParameterRef.name but with "." replaced with "_", converted to lower case and encoded in UTF-8 format as a bytes object.

The above format makes this compatible with passing to the underlying math evaluator engine (tinyexpr) used via the cyexpr sub-module.

Note

This should, typically, never need to be used outside of internal usage. It exists primarily to act as the owner for the parameter name strings (avoiding dangling pointers in the expression code).

Getter:

Returns the cyexpr compatible name format of the pref name (read-only).

eval(self, keep_changing_symbols=False, subs=None, keep=None, **kwargs)
property full_name
property name
property owner
property parameter
class finesse.parameter.ParameterState(*values)

Bases: IntFlag

NONE = 4
Numeric = 1
Symbolic = 3
Unresolved = 2
class finesse.parameter.PostValidator(post_validate)

Bases: object

class finesse.parameter.Validator(validate)

Bases: object

finesse.parameter.bool_parameter(name, description, units=None, validate=None, post_validate=None, is_default=False, is_geometric=False, changeable_during_simulation=True)

A parameter of an element whose value is decribed by a True or False value.

finesse.parameter.deref(parameter)

Get the Parameter from a ParameterRef or Parameter (no-op).

This is useful in actions which require a parameter but may be passed either a parameter or parameter reference.

finesse.parameter.enum_parameter(name, description, enum, units=None, validate=None, post_validate=None, is_default=False, is_geometric=False, changeable_during_simulation=True)

A parameter of an element whose value is decribed by a Enum definition.

Enum must only use integer values to describe its members. Unlike a general python Enum which can use strings.

finesse.parameter.float_parameter(name, description, units=None, validate=None, post_validate=None, is_default=False, is_geometric=False, changeable_during_simulation=True)

A parameter of an element whose value is decribed by a 64-bit floating point number.

finesse.parameter.info_parameter(name, description, units=None)

Decorator to register an info parameter field in the class.

Info parameters are purely informative properties, and cannot be directly scanned using an axis.

finesse.parameter.int_parameter(name, description, units=None, validate=None, post_validate=None, is_default=False, is_geometric=False, changeable_during_simulation=True)

A parameter of an element whose value is decribed by a 64-bit integer number.

class finesse.parameter.parameterproperty(full_name, doc=None)

Bases: property

Descriptor class for declaring a simulation parameter. A simulation parameter is one that can be changed during a simulation and affect the resulting outputs. The idea is that output dependant variables should be marked as having been changed or will be changed during a simulation run. This allows us to then optimise parts of the model, as we can determine what will or will not be changing. This descriptor is paired with the :class:Parameter.

Parameters can then be superficially locked once a model has been built so accidentally changing some parameter that isn’t expected to change can flag a warning.

getter(self, fget)
setter(self, fset)

finesse.paths module

Containers for paths traversed through a configuration.

class finesse.paths.OpticalPath(path, symbolic=False)

Bases: object

Represents a path traversing through optical connections of a Model instance.

The underlying data stored by instances of this class are lists of two-element tuples containing optical nodes and the components that they connect into. This list is formatted as [(from_node, to_comp)] where from_node is an OpticalNode instance and to_comp can be any sub-class instance of Connector; from_node is then an input node to to_comp.

A handle to the underlying list can be obtained through accessing the property OpticalPath.data. This is not required for iterating through the path entries however, as this class provides iterator access itself.

Parameters

pathlist

A list of 2-tuples containing the path data; first element stores the OpticalNode, second element stores the component this node feeds into.

symbolicbool, optional

Whether to compute symbolic lengths

property components

The path data with only the component sequence.

Getter:

Returns a list of the sequence of traversed components.

property components_only

The path data with only the component sequence.

Getter:

Returns a list of the sequence of traversed components.

property data

A handle to the underlying path data.

Getter:

Returns the list of 2-tuples containing the path data.

property nodes

The path data with only the OpticalNode sequence.

Getter:

Returns a list of the sequence of traversed optical nodes.

property nodes_only

The path data with only the OpticalNode sequence.

Getter:

Returns a list of the sequence of traversed optical nodes.

property optical_length

This returns the optical path length, i.e. the geometric length of each space scaled by its refractive index.

Getter:

Returns the total traversed length of the optical path (in metres).

property physical_length

This returns the physical path length.

Getter:

Returns the total length (in metres).

property spaces

The spaces in the optical path.

Getter:

Yields the spaces in the optical path.

table()

Show the components of the path in a table.

finesse.symbols module

Symbolic manipulations (expand, collect, etc.) are based on the book:

Cohen JS. Computer algebra and symbolic computation: mathematical methods. First edition, 2003.

class finesse.symbols.Constant(value, name=None)

Bases: Symbol

Defines a constant symbol that can be used in symbolic math.

Parameters

valuefloat, int

Value of constant

namestr, optional

Name of the constant to use when printing

eval(subs=None, **kwargs)

Evaluate this constant.

If a substitution is available the value of that will be used instead of self.value

property is_named

Was this constant given a specific name.

property name
substitute(subs)

Uses a dictionary to substitute terms in this expression with another. This does not perform any evaluation of any terms, unlike eval(subs=…).

Parameters

subsdict

Dictionary of substitutions to make. Keys can be the actual symbol or the name of the symbol in string form. Values must all be proper symbols.

class finesse.symbols.Function(name, operation, *args)

Bases: Symbol

This is a symbol to represent a mathematical function. This could be a simple addition, or a more complicated multi-argument function.

It supports creating new mathematical operations:

import math
import cmath

cos   = lambda x: finesse.symbols.Function("cos", math.cos, x)
sin   = lambda x: finesse.symbols.Function("sin", math.sin, x)
atan2 = lambda y, x: finesse.symbols.Function("atan2", math.atan2, y, x)

Complex math can also be used:

import numpy as np
angle = lambda x: finesse.symbols.Function("angle", np.angle, x)
print(f"{angle(1+1j)} = {angle(1+1j).eval()}")

Parameters

namestr

The operation name. This is used for dumping operations to kat script.

operationcallable

The function to pass the arguments of this operation to.

Other Parameters

*args

The arguments to pass to operation during a call.

property contains_unresolved_symbol

Whether the operation contains any unresolved symbols.

Getter:

Returns true if any symbol in the operation is an instance of Resolving, false otherwise. Read-only.

eval(**kwargs)

Evaluates the operation.

Parameters

subsdict, optional

Parameter substitutions can be given via an optional subs dict (mapping parameters to substituted values).

keepiterable, str

A collection of names of variables to keep as variables when evaluating.

Notes

A division by zero will return a NaN, rather than raise an exception.

Returns

resultnumber or array-like

The single-valued result of evaluation of the operation (if no substitutions given, or all substitutions are scalar-valued). Otherwise, if any parameter substitution was a numpy.ndarray, then a corresponding array of results.

substitute(subs)

Uses a dictionary to substitute terms in this expression with another. This does not perform any evaluation of any terms, unlike eval(subs=…).

Parameters

subsdict

Dictionary of substitutions to make. Keys can be the actual symbol or the name of the symbol in string form. Values must all be proper symbols.

class finesse.symbols.LazySymbol(name, function, *args)

Bases: Symbol

A generic way to make some lazily evaluated symbol.

The value is dependant on a lambda function and some arbitrary arguments which will be called when the symbol is evaluated.

Parameters

namestr

Human readable string name for the symbol

functioncallable

Function to call when evaluating the symbol

*argsobjects

Arguments to pass to function when evaluating

Examples

>>> a = LazyVariable('a', lambda x: x**2, 10)
>>> print(a)
<Symbolic='(a*10)' @ 0x7fd6587e6760>
>>> print((a*10).eval())
1000
eval(**kwargs)
property name
finesse.symbols.MAKE_LOP(name, opfn)
finesse.symbols.MAKE_LOP_simplify_truediv()
finesse.symbols.MAKE_ROP(name, opfn)
finesse.symbols.MAKE_ROP_simplify_truediv()
finesse.symbols.MAKE_simplify_add(dir)
finesse.symbols.MAKE_simplify_mul(dir)
finesse.symbols.MAKE_simplify_neg()
finesse.symbols.MAKE_simplify_pos()
finesse.symbols.MAKE_simplify_pow(dir)
finesse.symbols.MAKE_simplify_sub(dir)
class finesse.symbols.Matrix(name)

Bases: Symbol

A Matrix symbol.

eval(**kwargs)
class finesse.symbols.Resolving

Bases: Symbol

A special symbol that represents a symbol that is not yet resolved.

This is used in the parser to support self-referencing parameters.

An error is thrown if the value is attempted to be read.

eval(**kwargs)
property name
class finesse.symbols.Symbol

Bases: ABC

all(predicate, memo=None)

Returns all the symbols that are present in this expression which satisify the predicate.

Parameters

predicatecallable

Method which takes in an argument and returns True if it matches.

Examples

To select all Constant`s and `Variable`s from an expression `y:

>>> y.all(lambda a: isinstance(a, (Constant, Variable)))
arccos()
arcsin()
arctan()
arctan2(x)
changing_parameters()
collect()

Collects like terms in the expressions.

conj()
conjugate()
cos()
deg2rad()
degrees()
abstractmethod eval() float | complex | int
exp()
expand()

Performs a basic expansion of the symbolic expression.

expand_symbols()

A method that expands any symbolic parameter references that are themselves symbolic. This can be used to get an expression that only depends on references that are numeric.

Examples

>>> import finesse
>>> model = finesse.Model()
>>> model.parse(
...     '''
...     var d 300
...     var c 6000
...     var b c+d
...     var a b+1
...     '''
... )
>>> model.a.value.expand_symbols()
<Symbolic='((c+d)+1)' @ 0x7faa4d351c10>

Parameters

symSymbolic

Symbolic equation to expand

property imag
property is_changing

Returns True if one of the arguements of this symbolic object is varying whilst a :class:`` is running.

lambdify(*args, expand_symbols=False, ignore_unused_symbols=False)

Converts this symbolic expression into a function that can be called.

Parameters

argsSymbols

Symbols to use to make up the arguments of the generated function. If none are provided then the current values of ParameterRef`s are used and `Variables are left as they are.

expand_symbolsbool, optional

If True, the expression will first have any dependent variables expanded. See .expand_symbols.

log()
log10()
parameters(memo=None)

Returns all the parameters that are present in this symbolic expression.

Parameters are symbols whose values are attached to a model

rad2deg()
radians()
property real
sin()
sqrt()
substitute(mapping)

Uses a dictionary to substitute terms in this expression with another. This does not perform any evaluation of any terms, unlike eval(subs=…).

Notes

The symbolic substitution implemented here is not recursive, consider:

>>> y = a + b
>>> y.subs({a:a+b, b:a}) # results in => a+b+a

Here b is not replaced in the substitutions. The only time this happens is if one mapping is purely numeric:

>>> y.subs({a:a+b, b:1}) # results in => a+2

Parameters

mappingdict

Dictionary of substitutions/mappings to make. Keys can be the actual symbol or the name of the symbol in string form. Values must all be proper symbols.

sympy_simplify()

Converts this expression into a Sympy symbol.

tan()
to_binary_add_mul()

Converts a symbolic expression to use binary forms of operator.add and operator.mul operators, rather than the n-ary operator_add and operator_mul.

Returns

Symbol

to_nary_add_mul()

Converts a symbolic expression to use n-ary forms of operator_add and operator_mul operators, rather than the binary-ary operator.add and operator.mul.

Returns

Symbol

to_sympy()

Converts a Finesse symbolic expression into a Sympy expression.

Warning: for large functions this can be quite slow.

property value

The current value of this symbol

class finesse.symbols.Variable(name)

Bases: Symbol

Makes a variable symbol that can be used in symbolic math. Values must be substituted in when evaluating an expression.

Examples

Using some variables to make an expression and evaluating it:

>>> import numpy as np
>>> x = Variable('x')
>>> y = Variable('y')
>>> z = 4*x**2 - np.cos(y)
>>> print(f"{z} = {z.eval(subs={x:2, y:3})} : x={2}, y={3}")
(4*x**2-y) = 13 : x=2, y=3

Parameters

valuefloat, int

Value of constant

namestr, optional

Name of the constant to use when printing

eval(subs=None, keep=None, **kwargs)

Evaluates this variable and returns either itself or a substituted value.

Parameters

subsdict

Dictionary of object

keepiterable, str

A collection of names of variables to keep as variables when evaluating. Keep will override any substitution.

property name
finesse.symbols.add_sort_key(a)
finesse.symbols.as_symbol(x)
finesse.symbols.base_exponent(y)
finesse.symbols.coefficient_and_term(y)
finesse.symbols.collect(y)
finesse.symbols.display(a, dunder=())

For a given Symbol this method will return a human readable string representing the various operations it contains.

Parameters

aSymbol

Symbol to print

dundertuple

Names of variables to display with double underscores pre- and suf-fixing the names.

Returns

String form of Symbol

finesse.symbols.eval_symbolic_numpy(a, *keep)
finesse.symbols.evaluate(x)

Evaluates a symbol or N-dimensional array of symbols.

Parameters

xSymbol or array-like

A symbolic expression or an array of symbolic expressions.

Returns

outfloat, complex, numpy.ndarray

A single value for the evaluated expression if x is not array-like, otherwise an array of the evaluated expressions.

finesse.symbols.expand(y)
finesse.symbols.expand_mul(y)
finesse.symbols.expand_pow(y)
finesse.symbols.finesse2sympy(expr, iter_num=0)

Notes

It might be common for this this function to throw a NotImplementedError. This function maps, by hand, various operator and numpy functions to sympy. If you come across this error, you’ll need to update the if-statement to include the missing operations. Over time this should get fixed for most use cases.

finesse.symbols.is_integer(n)

Checks if n is an integer.

Parameters

nstr, float

Input to check

finesse.symbols.mul_sort_key(a)

Sorting key for multiplication arguments. Puts constants first then others

finesse.symbols.np_eval_symbolic_numpy(a, *keep)
finesse.symbols.operator_add(*args)
finesse.symbols.operator_mul(*args)
finesse.symbols.operator_sub(*args)
finesse.symbols.reduce_mul_args(args)

Sorts and reduces a multiply operation arguments.

Collect constants and sort variables by their str.

finesse.symbols.simplification(allow_flagged=False)

When used any symbolic operations will apply various simplification rules rather than recording everything symbolic operation, to preserve intent. This is useful when you want situations like 0*a -> 0, or a*a -> a**2. A complete simplification is not applied but it will generally yeild more efficient symbolic expressions. Intent preservation is required by KatScript so that it can serialise and deserialise (unparse and parse) a model into a script form without losing specific equations. For example, it often useful to record how many minus signs or factors of two have been used in an expression, rather than cancelling them out for record keeping.

Parameters

allow_flaggedbool, optional

When True, it will not throw an error if already in a simplification state.

finesse.symbols.sympy2finesse(expr, symbol_dict=None, iter_num=0)

finesse.tree module

Tree data structure.

class finesse.tree.TreeNode(str name, TreeNode parent=None, bool empty=True, str edge_info=None)

Bases: object

Container for tree-like structures.

Tree nodes can contain other tree nodes, allowing these objects to be built into a tree-like hierarchy useful for representing connections between components, nested data sets, etc.

Parameters

namestr

The node name.

parent: TreeNode, optional

The parent tree node, if not the root.

emptybool, optional

Whether this node is considered “empty”, which determines which character to use to represent the node in the tree; defaults to True.

edge_infostr, optional

String information on how this node is connected to its parent node. Will be used in TreeNode.draw_tree()

add(self, child)
children

children: list

draw_tree(self, fn_name=None, title=None, show_max_children=None)

Draws the solution tree in text form.

Based on https://stackoverflow.com/a/49638425/2251982.

Parameters

fn_namecallable, optional

Function to return the name of a TreeNode given the TreeNode itself. Defaults to using TreeNode.name.

titlestr, optional

The tree title. If not specified, no title is printed.

show_max_childrenint, optional

Maximum number of children to show in the tree; defaults to showing all children.

Returns

str

The tree in textual form.

edge_info

edge_info: str

empty

empty: ‘bool’

classmethod from_network(cls, network, root)

Create a tree node hierarchy from an acyclic network.

Notes

Cyclic networks are handled by networkx.algorithms.traversal.depth_first_search.dfs_tree(), so this method does not need to detect and avoid such cycles.

Parameters

networknetworkx.Graph

The network that is to be represented as a tree.

roothashable

The network node to use as the root of the tree.

Raises

ValueError

When the specified network is not a forest.

get(self, ipath)
get_all_children(self)
get_all_parents(self)
get_path(self)
ls(self, ipath='/')
name
parent

parent: finesse.tree.TreeNode

finesse.warnings module

Finesse-specific warnings.

exception finesse.warnings.CavityUnstableWarning

Bases: FinesseWarning

A cavity geometry has become unstable and its eigenmode is no longer calculable.

exception finesse.warnings.FinesseWarning

Bases: Warning

A generic warning thrown by Finesse.

exception finesse.warnings.InvalidSweepVariableWarning

Bases: FinesseWarning

An invalid variable value was used during a sweep action.

Can occur when trying to sweep relative to an infinite value, or using a NaN.

exception finesse.warnings.KeywordUsedWarning

Bases: FinesseWarning

A KatScript keyword was used as a name for some element in the model.

exception finesse.warnings.ModelParameterSettingWarning

Bases: FinesseWarning

An elements parameter is not using its prefer setter method.

exception finesse.warnings.UnreasonableComponentValueWarning

Bases: FinesseWarning

A not-wrong-but-probably-unreasonable component value was set.

Module contents

Finesse is a Python package for simulating interferometers in the frequency domain.