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=(), /)[source]

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)[source]
class finesse.model.IOMatrix(model)[source]

Bases: object

clear()[source]
class finesse.model.InputMatrix(model)[source]

Bases: IOMatrix

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

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)[source]

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[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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[source]

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

property analysis[source]

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')[source]

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 elements 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 element 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 element 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)[source]

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[source]

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)[source]

See finesse.tracing.tools.compute_cavity_mismatches()

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

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)[source]

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.

Checks for all the degrees of freedom if the symbolic links to the driven parameters are still working.

Parameters

verbosebool, optional

Print extra information on all broken parameters

Raises

BrokenDOFLinkError

When a parameter is no longer correctly linked to their DOF.

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[source]

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 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[source]

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)[source]

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)[source]

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)[source]

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()[source]
detect_mismatches(ignore_AR=True, **kwargs)[source]

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[source]

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)[source]

Disconnects two elements A and B.

display_signal_blockdiagram(*nodes, **kwargs)[source]

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 dof_parameters: tuple[Parameter, ...][source]

Returns all parameters in this model that are being driven by a degree of freedom.

Returns

tuple[Parameter, …]

Tuple of parameters

property dofs: tuple[DegreeOfFreedom][source]
element_order(element)[source]

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

property elements[source]

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

property f0[source]

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

Getter:

Returns frequency in Hertz

property frequencies[source]

The frequencies stored in the model as a list instance.

Getter:

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

property gausses[source]

A dictionary of optical node to Gauss instance mappings.

Getter:

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

get(attr)[source]

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()[source]

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()[source]

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)[source]

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)[source]

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: ModelElement | str) tuple[ModelElement, ...][source]

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)[source]
get_network(network_type: str | NetworkType = NetworkType.FULL, add_edge_info=False) Graph[source]

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()[source]

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

get_parameters(*, include=None, exclude=None, are_changing=None, are_symbolic=None)[source]

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[source]

Labels for the HOMs present in this model.

property homs[source]

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)[source]

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)[source]

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[source]

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[source]

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[source]

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[source]

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[source]

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

Getter:

Returns frequency in Hertz

property lambda0[source]

The default wavelength to use for the model.

Getter:

Returns wavelength in meters

Setter:

Sets the wavelength in meters

property last_trace[source]

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)>)]
lock_dof_parameters(verbose: bool = False)[source]

Lock all parameters driven by all degrees of freedom in this model.

Parameters

verbosebool, optional

Print every parameter lock that is locked, by default False

property locks[source]
merge(other, from_comp, from_port, to_comp, to_port, name=None, L=0, nr=1)[source]

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 element.

Lfloat

Length of the connecting space.

nrfloat

Index of refraction of the connecting space.

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

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[source]

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)[source]

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[source]
property network[source]

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[source]

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][source]

The optical nodes stored in the model.

Getter:

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

property parameters[source]

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

parse(text, spec=None) Model[source]

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[source]

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[source]

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[source]

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.

property parsed_files: tuple[Path, ...][source]

Contains a history of all the KatScript files parsed by this model. This explicitly does not include katscript parsed as strings or changes made via the Python API. See finesse.model.Model.unparse() for a complete katscript representation of this model.

Note that file contents could have changed after parsing.

Returns

tuple[Path, …]

Tuple of paths of the parsed katscript files.

path(from_node, to_node, via_node=None, symbolic=False)[source]

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)[source]

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[source]

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, operator_labels: bool = False) Path[source]

Visualize the values of the DC fields in a model in a graph representation. Will run a DCFields / 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.

add_operatorsbool, optional

Show operator values directly as edge labels. Can clutter the view. By default False

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)[source]

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 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_port_graph(optical_only: bool = True)[source]
plot_symbolic_network() None[source]

Visualize the symbolic network with graphviz.

print_parsed_files()[source]

Print a history of all the KatScript files parsed by this model. This explicitly does not include katscript parsed as strings or changes made via the Python API. See finesse.model.Model.unparse() for a complete katscript representation of this model.

Note that file contents could have changed after parsing.

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)[source]

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)[source]

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[source]

Returns all readouts in the model.

reduce_get_attr(attr)[source]
reduce_set_attr(attr, value)[source]
remove(obj)[source]

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)[source]

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[source]

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()[source]

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

Restore possible broken symbolic links between degrees of freedom elements and the parameters they drive. Can be useful if check_dof_symbolic_links raised an exception.

Parameters

verbosebool, optional

Whether to print out the dofs and parameters being restored, by default False

lockbool, optional

Locks the parameters after restoring, by default True

run(analysis: Sweep, return_state: Literal[False] = False, progress_bar: bool = False, simulation_type=None, simulation_options=None) ArraySolution[source]
run(analysis: Sweep, return_state: Literal[True] = False, progress_bar: bool = False, simulation_type=None, simulation_options=None) tuple[ArraySolution, AnalysisState]
run(analysis: None = None, return_state: Literal[False] = False, progress_bar: bool = False, simulation_type=None, simulation_options=None) ArraySolution
run(analysis: None = None, return_state: Literal[True] = False, progress_bar: bool = False, simulation_type=None, simulation_options=None) tuple[ArraySolution, AnalysisState]

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)[source]

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)[source]

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

property signal_nodes: list[Node][source]

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[source]

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[source]

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)[source]

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)[source]

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)[source]

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)[source]

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()[source]

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

property symbolic_network: DiGraph[source]

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)[source]

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)[source]

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)[source]

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.

to_port_network(optical_only: bool = True)[source]
property trace_forest[source]

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[source]

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[source]

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()[source]

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

unlock_dof_parameters(verbose: bool = False)[source]

Unlock all parameters driven by all degrees of freedom in this model.

Parameters

verbosebool, optional

Print every parameter lock that is unlocked, by default False

unparse(inplace=True, warnings=True)[source]

Serialise the model to kat script.

Returns

str

The generated kat script.

unparse_file(path, inplace=True)[source]

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)[source]

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)[source]

Bases: IOMatrix

finesse.model.load(path: Path)[source]

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)[source]
finesse.model.make_optical_network_view(model)[source]

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