finesse.plotting package

Subpackages

Submodules

finesse.plotting.graph module

Graph plotting.

finesse.plotting.graph.create_graphviz_table(fields, frequencies, homs)
finesse.plotting.graph.graphviz_draw(model=None, network=None, draw_labels=True, angle=0, overlap=True, ratio=0.45, edge_len=1.0, size=(13, 7), pad=(0.0, 0.0), format: Literal['png', 'svg'] = 'svg', maxiter=500, layout='neato', mode=None, path=None, show=True)

This should get merged with plot_graphviz at some point.

Draws a graphviz figure using neato layout. The default settings are tested to produce a passable drawing of the aLIGO DRMI graph.

Parameters

anglefloat or bool

The angle parameter rotates the graph by angle degrees relative to the first edge in the graph, which most of the time is the edge coming out of the laser. Set angle=False to disable rotation and let graphviz decide how to rotate the graph.

overlapbool or str

Setting for how graphviz deals with node overlaps. Set to False for graphviz to attempt to remove overlaps. Note that overlap removal runs as a post-processing step after initial layout and usually makes the graph look worse.

ratiofloat

Post processing step to stretch the graph. Used for stretching horizontally to compoensate for wider nodes to fit node labels.

pathPath or None

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

The svg format sometimes crops the image too hard, which results in clipped nodes or edges, if that happens increase the pad graph_attr or use the png format.

finesse.plotting.graph.graphviz_draw_beam_trace(model=None, network=None, draw_labels=True, angle=0, overlap=True, ratio=0.45, edge_len=1.0, size=(13, 7), pad=(0.5, 0.5), format: ~typing.Literal['png', 'svg'] = 'svg', maxiter=500, layout='neato', mode=None, cmap=<matplotlib.colors.ListedColormap object>)
finesse.plotting.graph.plot_dcfields_graph(model: Model, 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

finesse.plotting.graph.plot_graph(network, layout, graphviz=True, path=None, show=True, format: Literal['png', 'svg'] = 'svg', **kwargs)
finesse.plotting.graph.plot_graphviz(network, layout)

Plot graph with graphviz.

The pygraphviz Python package must be installed and available on the current Python path, and graphviz must be available on the system path.

Parameters

networknetworkx.Graph

The network to plot.

layoutstr

The layout type to use. Any layout algorithm provided by graphviz is supported.

Raises

ValueError

If the specified layout is not supported.

ImportError

If graphviz or pygraphviz is not installed.

finesse.plotting.graph.plot_nx_graph(network, layout, node_labels=True, node_attrs=False, edge_attrs=False, node_color_key=None, edge_color_key=None, label_font_size=12, attr_font_size=6, edge_font_size=6, bounding_ellipses=True, format: Literal['png', 'svg'] = 'svg', path: Path | None = None, show=True, **kwargs)

Plot graph with NetworkX.

Parameters

networknetworkx.Graph

The network to plot.

layoutstr

The layout type to use. Any layout algorithm provided by networkx.drawing.layout is supported.

node_labelsbool, optional

Show node names; defaults to True.

node_attrsbool or list, optional

Show node data. This can be True, in which case all node data is shown, or a list, in which case only the specified keys are shown. Defaults to True.

edge_attrsbool or list, optional

Show edge data. This can be True, in which case all edge data is shown, or a list, in which case only the specified keys are shown. Defaults to True.

node_color_keycallable, optional

Key function accepting a node and its attribute dict and returning a group. Each group is assigned a unique color. If not specified, nodes are not colored.

edge_color_keycallable, optional

Key function accepting an edge (u, v) and its attribute dict and returning a group. Each group is assigned a unique color. If not specified, edges are not colored.

label_font_size, attr_font_size, edge_font_sizeint, optional

Font size for node labels, attributes and edges. Defaults to 12, 6 and 6, respectively.

bounding_ellipses: bool, optional

Hijack the node label bounding boxes to draw the node labels inside of an ellipse (similar to graphviz neato layout). This guarantees the label is readable, but the arrow direction might not always be clear and might not combine well with node_color_key. Defaults to True.

pathPath or None

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.

Other Parameters

kwargs

Anything else supported by networkx.drawing.nx_pylab.draw().

Raises

ValueError

If the specified layout is not supported.

Exception

If the graph cannot be represented with the specified layout.

finesse.plotting.graph.show_graphviz(A: pygraphviz.AGraph, format: str, path: str | Path | None, layout: str, show: bool) pathlib.Path

finesse.plotting.plot module

class finesse.plotting.plot.Plotter(solution)

Bases: object

Handler for plotting outputs from a simulation.

animation = <module 'matplotlib.animation' from '/usr/local/lib/python3.13/site-packages/matplotlib/animation.py'>
static choose_plot_func(logx, logy, magnitude_axis=None)
colors = <module 'matplotlib.colors' from '/usr/local/lib/python3.13/site-packages/matplotlib/colors.py'>
make_amp_phase_images(ax1, ax2, extent, z1, z2, cmap, degrees, det, log, anim_axis, aspect='auto', transpose=False)
make_images(fig, extent, z, cmap, det, log, anim_axis, aspect='auto', cbar_label=None, transpose=False)
static make_text_handle(text_former, units, x, y, index=0, color='white', fig=None, ax=None)
output_axis_label(obj, ax=None)
parameter_axis_label(param, axis='x', ax=None)
plot(*detectors, log=False, logx=None, logy=None, degrees=True, cmap=None, show=True, separate=True, _test_fig_handles=None)

Plots the outputs from the specified detectors of a given solution out, or all detectors in the executed model if detectors is None.

Detectors are sorted by their type and the outputs of each are plotted on their own figure accordingly - i.e. all amplitude detector outputs are plotted on one figure, all power detector outputs on another figure etc.

Note

It is recommended to use this function with finesse.plotting.tools.init(). This then means that all figures produced by this function will use matplotlib rcParams corresponding to the style selected.

For example:

import finesse
finesse.init_plotting()

model = finesse.parse(\"""
l L0 P=1

s s0 L0.p1 ITM.p1

m ITM R=0.99 T=0.01 Rc=inf
s CAV ITM.p2 ETM.p1 L=1
m ETM R=0.99 T=0.01 Rc=10

modes maxtem=4

gauss L0.p1.o q=(-0.4+2j)
cav FP ITM.p2.o ITM.p2.i

ad ad00 ETM.p1.i f=L0.f n=0 m=0
ad ad02 ETM.p1.i f=L0.f n=0 m=2

pd C ETM.p1.i
\""")
model.run("xaxis(L0.f, (-100M), 100M, 1000, lin)").plot(logy=True, figsize_scale=2)

will produce two figures (one for the power-detector output and another for the amplitude detectors) which use rcParams from the default style-sheet. Using figsize_scale here then scales these figures whilst keeping the proportions defined in this style-sheet constant.

Multi-dimensional scan plotting behaviour

If multiple parameters have been scanned in the underlying model associated with this solution object, then the form of the resulting plots produced here will depend on a number of options:

  • If two parameters have been scanned then all non-CCD detector ouputs will be plotted

    on separate image plot figures. All CCD plots will be ignored.

  • If a single parameter has been scanned and index is not specified then all CCD detector

    outputs will be plotted on separate animated figures. Or if index is specified, then all CCD detector outputs will be plotted on separate image plot figures at the specified index of the scanned axis.

Parameters

detectorssequence or str or type or Detector, optional

An iterable (or singular) of strings (corresponding to detector names), Detector instances or detector types. Defaults to None so that all detector outputs are plotted.

logbool, optional

Use log-log scale. Also applies to image plots so that colours are normalised on a log-scale between limits of image data. Defaults to False.

logxbool, optional

Use log-scale on x-axis if appropriate, defaults to the value of log.

logybool, optional

Use log-scale on y-axis if appropriate, defaults to the value of log.

degreesbool, optional

Plots angle and phase outputs in degrees, defaults to True.

showbool, optional

Shows all the produced figures if true, defaults to True.

separatebool, optional

Plots the output of different detector types on different axes if true, defaults to True.

Returns

figuresdict

A dictionary mapping type(detector) and detector names to corresponding Figure objects. Note that some keys, i.e. those of each type(detector) and the names of the detectors of that type, share the same values.

animationsdict

A dictionary of detector.name : animation mappings.

plt = <module 'matplotlib.pyplot' from '/usr/local/lib/python3.13/site-packages/matplotlib/pyplot.py'>
static select_detector_cmap(cmaps, det)
finesse.plotting.plot.add_arrow(line, position=None, direction='right', size=15, color=None)

Add an arrow to a line.

Parameters

lineLine2D object

The line to which the arrow will be added.

positionfloat or iterable[float], optional

The x-position of the arrow. If None, the mean of xdata is taken. should be fractional of line x range, 0.5 is in the middle.

direction{‘left’, ‘right’}, optional

The direction of the arrow. Default is ‘right’.

sizeint, optional

The size of the arrow in fontsize points. Default is 15.

colorstr, optional

The color of the arrow. If None, the line color is taken.

Examples

>>> import matplotlib.pyplot as plt
>>> line, = plt.plot(np.linspace(0, 1), np.linspace(10, -10))
>>> add_arrow(line, [0, 0.5, 1])

Notes

This function adds an arrow to a line plot using the matplotlib library.

References

finesse.plotting.plot.bode(f, *Y, axs=None, return_axes=True, figsize=(6, 6), db=True, wrap=True, **kwargs)

Create a Bode plot for a complex array.

Parameters

farray_like

Frequencies

*Yarray_like

Complex valued transfer functions evaluated at frequencies f

axsAxes, optional

Axes to use to plot transfer functions on. Magnitude plotted on axs[0] and phase on axs[1].

dbbool, optional

Plot magnitude in dB

wrapbool, optional

Wrap phase

figsizetuple

Figure size

**kwargs

Additional arguments are passed to the semilog calls

Examples

>>> axs = bode(f, CLG, label='CLG')
>>> bode(f, CHR, axs=axs, label='CHR')
finesse.plotting.plot.get_2d_field(modes, amplitudes, qs, x=None, y=None, samples=100, scale=3, zero_tem00_gouy=True)

Computes the 2D optical field for a given set of modes, modal amplitudes, and beam parameters.

x and y dimensions can be specified if required, otherwise it will return an area of scale times the spot sizes. When x and y are provided scale and samples will not do anything.

Parameters

modesarray_like

Pairs of modes (n,m). Can be an 2xN array or a list or tuple of modes.

amplitudesarray_like

Array of complex amplitudes for each mode

qsBeamParam or Tuple(BeamParam, BeamParam)

Compex beam parameter object for x and y planes. If singular value give, qx = qy.

xarray_like, optional

x points

yarray_like, optional

y points

samplesint, optional

Number of sample points to use in x and y

scalefloat, optional

Number of sample points to use in x and y

zero_tem00_gouybool, optional

If True, the Gouy phase of the TEM00 mode removed from all modes.

Returns

xdouble[::1]

x points

ydouble[::1]

y points

fieldcomplex[:, ::1]

Complex optical field of size samples x samples

finesse.plotting.plot.plot_field(modes, amplitudes, qs, *, x=None, y=None, samples=100, scale=3, zero_tem00_gouy=True, ax=None, colorbar=True, **kwargs)

Plots a 2D optical field for a given set of modes, modal amplitudes, and beam parameters.

x and y dimensions can be specified if required, otherwise it will return an area of scale times the spot sizes. When x and y are provided scale and samples will not do anything.

Parameters

modesarray_like

Pairs of modes (n,m). Can be an 2xN array or a list or tuple of modes.

amplitudesarray_like

Array of complex amplitudes for each mode

qsBeamParam or Tuple(BeamParam, BeamParam)

Compex beam parameter object for x and y planes. If singular value give, qx = qy.

x, yndarray, optional

Specify x and y coordinates to plot beam

samplesint, optional

Number of sample points to use in x and y

scalefloat, optional

Number of sample points to use in x and y

zero_tem00_gouybool, optional

If True, the Gouy phase of the TEM00 mode removed from all modes.

axAxis, optional

A Matplotlib axis to put the image on. If None, a new figure will be made.

colorbarbool

When True the colorbar will be added

**kwargs

Extra keyword arguments will be passed to the pcolormesh plotting function.

finesse.plotting.plot.rescale_axes_SI_units(*, xaxis=None, fmt_xaxis='{:g}', yaxis=None, fmt_yaxis='{:g}', ax=None)

Rescales either the x or y axes on a matplotlib axis object by some SI scale factor. This works by just changing the major tick labels rather than rescaling any data used so can be used after any plot has been made.

Parameters

xaxis, yaxisstr

An SI scaling character, see finesse.utilities.units.SI_LABEL

fmt_xaxis, fmt_yaxisstr

Python format string for setting the format of the ticks

Examples

Recsale a plot into units of milli on the xaxis and kilo on the y with 2 decimal places on x and 3 on y:

rescale_axes_SI_units(
    xaxis='m', fmt_xaxis="{:.2f}",
    yaxis='k', fmt_yaxis="{:.3f}"
)
finesse.plotting.plot.ws_phase_space(W, S, OL, cmap='bone', levels=None, wscale='mm', sscale='m', contour_kwargs=None, clabel_kwargs=None, show=True, fig=None, ax=None)

Plots the overlap contours for WS phase space data.

The return values of ws_overlap_grid() correspond to the first three arguments of this function.

Parameters

Wnumpy.ndarray

The W space (as a 2D grid).

Snumpy.ndarray

The S space (as a 2D grid).

OLnumpy.ndarray

The overlap as a function of the WS phase space (as a 2D grid).

cmapstr or colormap, optional; default: “bone”

A matplotlib colormap, or its name.

levelslist, optional; default: None

List of contour levels to pass to contour plotting explicitly.

wscalestr, optional; default: “mm”

Units for W-axis (i.e. beam size units).

sscalestr, optional; default: “m”

Reciprocal units for S-axis (i.e. defocus units).

contour_kwargsdict, optional

Dictionary of keyword arguments to pass to matplotlib contour function. If not specified then the following defaults are used:

  • “colors”: “k”

  • “linestyles”: “–”

  • “linewidths”: 0.5

clabel_kwargsdict, optional

Dictionary of keyword arguments to pass to matplotlib clabel function. If not specified then the following defaults are used:

  • “colors”: same as contour_kwargs

  • “inline”: True

showbool, optional; default: True

Whether to show the figure immediately.

figFigure, optional, default: None

The figure object to use. If not specified a new figure will be drawn.

axAxes, optional, default: None

The axes to use. If not specified the first pair will be used, or created. Ignored if fig is None.

Returns

figFigure

Handle to the matplotlib Figure.

axAxes

Handle to the matplotlib Axis.

See Also

ws_overlap_grid

finesse.plotting.plot.z_w0_mismatch_contour(qref, ax=None, N=100, fmt=None, **kwargs)

For a given Matplotlib axis this will produce a mode-mismatch contour background. The axes are assumed to be z in the x and w0 in y. Limits are automatically taken from the current axes limits.

Parameters

qrefcomplex, BeamParam

Reference beamparameter to generate contours with respect to.

axAxes, optional

Axes to plot on, if None plt.gca() is called

Nint, optional

Number of samples in each axis to use

**kwargs

Values are passed to plt.contourf function.

finesse.plotting.plot.z_w0_mismatch_contourf(qref, ax=None, N=100, **kwargs)

For a given Matplotlib axis this will produce a mode-mismatch filled contour background. The axes are assumed to be z in the x and w0 in y. Limits are automatically taken from the current axes limits.

Parameters

qrefcomplex, BeamParam

Reference beamparameter to generate contours with respect to.

axAxes, optional

Axes to plot on, if None plt.gca() is called

Nint, optional

Number of samples in each axis to use

**kwargs

Values are passed to plt.contourf function.

finesse.plotting.tools module

finesse.plotting.tools.add_colorbar(im, **kwargs)

Adds a vertical color bar to an image plot.

Parameters

im : matplotlib.image.AxesImage

An image plot, e.g. return value of a call to plt.imshow().

Returns

Handle to the colorbar.

finesse.plotting.tools.init(mode='display', dpi=None, fmts=None)

Sets up default plotting parameters for a desired display mode.

Parameters

modestr

Display mode to use, either ‘display’ or ‘paper’.

dpiint, optional

DPI (Dots per inch) to display and save figures with. Defaults to current setting.

fmtslist of str, optional

List of image formats to allow for display when running under IPython; defaults to DEFAULT_FORMATS.

Module contents

Plotting tools for Finesse, providing convenient style templates for matplotlib.pyplot and functions for quick visualisation of detector and/or probe outputs.

class finesse.plotting.Plotter(solution)

Bases: object

Handler for plotting outputs from a simulation.

animation = <module 'matplotlib.animation' from '/usr/local/lib/python3.13/site-packages/matplotlib/animation.py'>
static choose_plot_func(logx, logy, magnitude_axis=None)
colors = <module 'matplotlib.colors' from '/usr/local/lib/python3.13/site-packages/matplotlib/colors.py'>
make_amp_phase_images(ax1, ax2, extent, z1, z2, cmap, degrees, det, log, anim_axis, aspect='auto', transpose=False)
make_images(fig, extent, z, cmap, det, log, anim_axis, aspect='auto', cbar_label=None, transpose=False)
static make_text_handle(text_former, units, x, y, index=0, color='white', fig=None, ax=None)
output_axis_label(obj, ax=None)
parameter_axis_label(param, axis='x', ax=None)
plot(*detectors, log=False, logx=None, logy=None, degrees=True, cmap=None, show=True, separate=True, _test_fig_handles=None)

Plots the outputs from the specified detectors of a given solution out, or all detectors in the executed model if detectors is None.

Detectors are sorted by their type and the outputs of each are plotted on their own figure accordingly - i.e. all amplitude detector outputs are plotted on one figure, all power detector outputs on another figure etc.

Note

It is recommended to use this function with finesse.plotting.tools.init(). This then means that all figures produced by this function will use matplotlib rcParams corresponding to the style selected.

For example:

import finesse
finesse.init_plotting()

model = finesse.parse(\"""
l L0 P=1

s s0 L0.p1 ITM.p1

m ITM R=0.99 T=0.01 Rc=inf
s CAV ITM.p2 ETM.p1 L=1
m ETM R=0.99 T=0.01 Rc=10

modes maxtem=4

gauss L0.p1.o q=(-0.4+2j)
cav FP ITM.p2.o ITM.p2.i

ad ad00 ETM.p1.i f=L0.f n=0 m=0
ad ad02 ETM.p1.i f=L0.f n=0 m=2

pd C ETM.p1.i
\""")
model.run("xaxis(L0.f, (-100M), 100M, 1000, lin)").plot(logy=True, figsize_scale=2)

will produce two figures (one for the power-detector output and another for the amplitude detectors) which use rcParams from the default style-sheet. Using figsize_scale here then scales these figures whilst keeping the proportions defined in this style-sheet constant.

Multi-dimensional scan plotting behaviour

If multiple parameters have been scanned in the underlying model associated with this solution object, then the form of the resulting plots produced here will depend on a number of options:

  • If two parameters have been scanned then all non-CCD detector ouputs will be plotted

    on separate image plot figures. All CCD plots will be ignored.

  • If a single parameter has been scanned and index is not specified then all CCD detector

    outputs will be plotted on separate animated figures. Or if index is specified, then all CCD detector outputs will be plotted on separate image plot figures at the specified index of the scanned axis.

Parameters

detectorssequence or str or type or Detector, optional

An iterable (or singular) of strings (corresponding to detector names), Detector instances or detector types. Defaults to None so that all detector outputs are plotted.

logbool, optional

Use log-log scale. Also applies to image plots so that colours are normalised on a log-scale between limits of image data. Defaults to False.

logxbool, optional

Use log-scale on x-axis if appropriate, defaults to the value of log.

logybool, optional

Use log-scale on y-axis if appropriate, defaults to the value of log.

degreesbool, optional

Plots angle and phase outputs in degrees, defaults to True.

showbool, optional

Shows all the produced figures if true, defaults to True.

separatebool, optional

Plots the output of different detector types on different axes if true, defaults to True.

Returns

figuresdict

A dictionary mapping type(detector) and detector names to corresponding Figure objects. Note that some keys, i.e. those of each type(detector) and the names of the detectors of that type, share the same values.

animationsdict

A dictionary of detector.name : animation mappings.

plt = <module 'matplotlib.pyplot' from '/usr/local/lib/python3.13/site-packages/matplotlib/pyplot.py'>
static select_detector_cmap(cmaps, det)
finesse.plotting.bode(f, *Y, axs=None, return_axes=True, figsize=(6, 6), db=True, wrap=True, **kwargs)

Create a Bode plot for a complex array.

Parameters

farray_like

Frequencies

*Yarray_like

Complex valued transfer functions evaluated at frequencies f

axsAxes, optional

Axes to use to plot transfer functions on. Magnitude plotted on axs[0] and phase on axs[1].

dbbool, optional

Plot magnitude in dB

wrapbool, optional

Wrap phase

figsizetuple

Figure size

**kwargs

Additional arguments are passed to the semilog calls

Examples

>>> axs = bode(f, CLG, label='CLG')
>>> bode(f, CHR, axs=axs, label='CHR')
finesse.plotting.context(style, after_reset=False)

Sets matplotlib.pyplot parameters to use the given style type within the current context.

See list_styles() for a list of all available styles.

Parameters

stylestr

Name of the style to use.

after_resetbool

If True, apply style after resetting settings to their defaults; otherwise, apply style on top of the current settings.

Examples

To use the default.mplstyle style-sheet temporarily, use the with statement as so:

import finesse.plotting as fplt
with fplt.context('default'):
    ...
finesse.plotting.graphviz_draw(model=None, network=None, draw_labels=True, angle=0, overlap=True, ratio=0.45, edge_len=1.0, size=(13, 7), pad=(0.0, 0.0), format: Literal['png', 'svg'] = 'svg', maxiter=500, layout='neato', mode=None, path=None, show=True)

This should get merged with plot_graphviz at some point.

Draws a graphviz figure using neato layout. The default settings are tested to produce a passable drawing of the aLIGO DRMI graph.

Parameters

anglefloat or bool

The angle parameter rotates the graph by angle degrees relative to the first edge in the graph, which most of the time is the edge coming out of the laser. Set angle=False to disable rotation and let graphviz decide how to rotate the graph.

overlapbool or str

Setting for how graphviz deals with node overlaps. Set to False for graphviz to attempt to remove overlaps. Note that overlap removal runs as a post-processing step after initial layout and usually makes the graph look worse.

ratiofloat

Post processing step to stretch the graph. Used for stretching horizontally to compoensate for wider nodes to fit node labels.

pathPath or None

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

The svg format sometimes crops the image too hard, which results in clipped nodes or edges, if that happens increase the pad graph_attr or use the png format.

finesse.plotting.init(mode='display', dpi=None, fmts=None)

Sets up default plotting parameters for a desired display mode.

Parameters

modestr

Display mode to use, either ‘display’ or ‘paper’.

dpiint, optional

DPI (Dots per inch) to display and save figures with. Defaults to current setting.

fmtslist of str, optional

List of image formats to allow for display when running under IPython; defaults to DEFAULT_FORMATS.

finesse.plotting.list_styles()

Lists all the styles (.mplstyle files) available to use.

Returns

list

A list containing the names of all available styles.

finesse.plotting.plot_field(modes, amplitudes, qs, *, x=None, y=None, samples=100, scale=3, zero_tem00_gouy=True, ax=None, colorbar=True, **kwargs)

Plots a 2D optical field for a given set of modes, modal amplitudes, and beam parameters.

x and y dimensions can be specified if required, otherwise it will return an area of scale times the spot sizes. When x and y are provided scale and samples will not do anything.

Parameters

modesarray_like

Pairs of modes (n,m). Can be an 2xN array or a list or tuple of modes.

amplitudesarray_like

Array of complex amplitudes for each mode

qsBeamParam or Tuple(BeamParam, BeamParam)

Compex beam parameter object for x and y planes. If singular value give, qx = qy.

x, yndarray, optional

Specify x and y coordinates to plot beam

samplesint, optional

Number of sample points to use in x and y

scalefloat, optional

Number of sample points to use in x and y

zero_tem00_gouybool, optional

If True, the Gouy phase of the TEM00 mode removed from all modes.

axAxis, optional

A Matplotlib axis to put the image on. If None, a new figure will be made.

colorbarbool

When True the colorbar will be added

**kwargs

Extra keyword arguments will be passed to the pcolormesh plotting function.

finesse.plotting.plot_graph(network, layout, graphviz=True, path=None, show=True, format: Literal['png', 'svg'] = 'svg', **kwargs)
finesse.plotting.plot_graphviz(network, layout)

Plot graph with graphviz.

The pygraphviz Python package must be installed and available on the current Python path, and graphviz must be available on the system path.

Parameters

networknetworkx.Graph

The network to plot.

layoutstr

The layout type to use. Any layout algorithm provided by graphviz is supported.

Raises

ValueError

If the specified layout is not supported.

ImportError

If graphviz or pygraphviz is not installed.

finesse.plotting.plot_nx_graph(network, layout, node_labels=True, node_attrs=False, edge_attrs=False, node_color_key=None, edge_color_key=None, label_font_size=12, attr_font_size=6, edge_font_size=6, bounding_ellipses=True, format: Literal['png', 'svg'] = 'svg', path: Path | None = None, show=True, **kwargs)

Plot graph with NetworkX.

Parameters

networknetworkx.Graph

The network to plot.

layoutstr

The layout type to use. Any layout algorithm provided by networkx.drawing.layout is supported.

node_labelsbool, optional

Show node names; defaults to True.

node_attrsbool or list, optional

Show node data. This can be True, in which case all node data is shown, or a list, in which case only the specified keys are shown. Defaults to True.

edge_attrsbool or list, optional

Show edge data. This can be True, in which case all edge data is shown, or a list, in which case only the specified keys are shown. Defaults to True.

node_color_keycallable, optional

Key function accepting a node and its attribute dict and returning a group. Each group is assigned a unique color. If not specified, nodes are not colored.

edge_color_keycallable, optional

Key function accepting an edge (u, v) and its attribute dict and returning a group. Each group is assigned a unique color. If not specified, edges are not colored.

label_font_size, attr_font_size, edge_font_sizeint, optional

Font size for node labels, attributes and edges. Defaults to 12, 6 and 6, respectively.

bounding_ellipses: bool, optional

Hijack the node label bounding boxes to draw the node labels inside of an ellipse (similar to graphviz neato layout). This guarantees the label is readable, but the arrow direction might not always be clear and might not combine well with node_color_key. Defaults to True.

pathPath or None

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.

Other Parameters

kwargs

Anything else supported by networkx.drawing.nx_pylab.draw().

Raises

ValueError

If the specified layout is not supported.

Exception

If the graph cannot be represented with the specified layout.

finesse.plotting.rescale_axes_SI_units(*, xaxis=None, fmt_xaxis='{:g}', yaxis=None, fmt_yaxis='{:g}', ax=None)

Rescales either the x or y axes on a matplotlib axis object by some SI scale factor. This works by just changing the major tick labels rather than rescaling any data used so can be used after any plot has been made.

Parameters

xaxis, yaxisstr

An SI scaling character, see finesse.utilities.units.SI_LABEL

fmt_xaxis, fmt_yaxisstr

Python format string for setting the format of the ticks

Examples

Recsale a plot into units of milli on the xaxis and kilo on the y with 2 decimal places on x and 3 on y:

rescale_axes_SI_units(
    xaxis='m', fmt_xaxis="{:.2f}",
    yaxis='k', fmt_yaxis="{:.3f}"
)
finesse.plotting.use(style)

Sets matplotlib.pyplot parameters to use the given style type.

See list_styles() for a list of all available styles.

Parameters

stylestr

Name of the style to use.

Examples

To set-up your plots to use the default.mplstyle style-sheet, simply write:

import finesse.plotting as fplt
fplt.use('default')