finesse.script package

Submodules

finesse.script.adapter module

Interface between script and Finesse.

Adapters provide a programmatic way to retrieve useful information about KatScript directives using their corresponding Python objects, and vice versa. This is primarily used for the compiler and generator, but is also used to improve syntax suggestions and error messages.

The adapter class hierarchy is intentionally very generic. By default, an ordinary KatScript directive corresponding to an ordinary Finesse object is quite simple to specify and should “just work”. When special behaviour is required, e.g. in cases where the KatScript directive has different arguments than the corresponding Python object (e.g. tem) or where there is no corresponding Python object (e.g. modes), the methods and members of the adapter can be overridden.

class finesse.script.adapter.AnalysisDocumenter(*, item_type, **kwargs)

Bases: NumpyStyleDocstringGetterMixin, FunctionalSyntaxMixin, ItemDocumenter

class finesse.script.adapter.AnalysisDump(analysis: Any, adapter: ItemAdapter, parameters: List[ArgumentDump] | List[List[ArgumentDump]], is_default: bool)

Bases: object

A set of analysis parameters and metadata.

adapter: ItemAdapter
analysis: Any
is_default: bool
property item_name
parameters: List[ArgumentDump] | List[List[ArgumentDump]]
class finesse.script.adapter.AnalysisDumper(*, item_type, **kwargs)

Bases: SignatureAttributeParameterMixin, ItemDumper

dump(adapter, analysis)

Get analysis dump object(s) for analysis.

Parameters

adapterItemAdapter

The adapter corresponding to this getter.

analysisAction

The action to dump.

Yields

AnalysisDump

Object containing a mapping of keyword argument names to ArgumentDump objects and whether they are all default values.

class finesse.script.adapter.AnalysisFactory(*, item_type)

Bases: ItemFactory

class finesse.script.adapter.AnalysisSetter(*, item_type, **kwargs)

Bases: SignatureAttributeParameterMixin, ItemSetter

class finesse.script.adapter.Argument(name: str, kind: ~finesse.script.adapter.ArgumentType = ArgumentType.ANY, default: ~typing.Any = <class 'finesse.script.adapter._empty'>, annotation: ~typing.Any = <class 'finesse.script.adapter._empty'>)

Bases: object

A generic instruction argument.

This is similar but not identical to inspect.Parameter. Arguments in the Finesse sense are more general than inspect.Parameter since they can refer to KatScript arguments, and KatScript instructions may not necessarily define their supported arguments via Python class signatures.

annotation

alias of _empty

default

alias of _empty

property has_no_default
kind: ArgumentType = _ParameterKind.POSITIONAL_OR_KEYWORD
name: str
class finesse.script.adapter.ArgumentDump(name: str, kind: ~finesse.script.adapter.ArgumentType = ArgumentType.ANY, default: ~typing.Any = <class 'finesse.script.adapter._empty'>, annotation: ~typing.Any = <class 'finesse.script.adapter._empty'>, value: ~typing.Any = <class 'finesse.script.adapter._empty'>, other_defaults: ~typing.List[~typing.Any] = None, reference: bool = False)

Bases: Argument

A Finesse object argument name, its current value, default value, kind, annotation, and whether it should be dumped by value or reference.

This encapsulates an argument for a script instruction. It can represent Finesse object parameters like floats, strings and model parameters, and is primarily used to generate KatScript representations of Finesse objects.

property is_default

Whether the value is the parameter’s default.

other_defaults: List[Any] = None
reference: bool = False
value

alias of _empty

class finesse.script.adapter.ArgumentType(*values)

Bases: Enum

Signature argument types.

While we just copy those defined by inspect, note that the definitions here are more abstract than those of inspect: these refer to the different flavours of script argument, which may or may not map directly to or from a Python type’s call signature.

ANY = _ParameterKind.POSITIONAL_OR_KEYWORD
KEYWORD_ONLY = _ParameterKind.KEYWORD_ONLY
POS_ONLY = _ParameterKind.POSITIONAL_ONLY
VAR_KEYWORD = _ParameterKind.VAR_KEYWORD
VAR_POS = _ParameterKind.VAR_POSITIONAL
class finesse.script.adapter.BoundArgument(name: str, kind: ~finesse.script.adapter.ArgumentType = ArgumentType.ANY, default: ~typing.Any = <class 'finesse.script.adapter._empty'>, annotation: ~typing.Any = <class 'finesse.script.adapter._empty'>, var_sequence: int = None)

Bases: Argument

A concrete argument originating from a call to a setter.

This is the same as Argument except in its handling of variadic arguments. Where this represents a variadic argument, it contains information as to which variadic argument it represents (either the sequence number or keyword). It is used to resolve self-references and to map compilation errors back to the original script.

var_sequence: int = None
class finesse.script.adapter.CommandDump(adapter: ItemAdapter, parameters: List[ArgumentDump] | List[List[ArgumentDump]], is_default: bool)

Bases: object

A set of command parameters and metadata.

adapter: ItemAdapter
is_default: bool
property item_name
parameters: List[ArgumentDump] | List[List[ArgumentDump]]
class finesse.script.adapter.CommandMethodDocumenter(*, sig_ignore=('self',), **kwargs)

Bases: NumpyStyleDocstringGetterMixin, FunctionalSyntaxMixin, ItemDocumenter

class finesse.script.adapter.CommandMethodSetter(*, sig_ignore=('self',), **kwargs)

Bases: SignatureAttributeParameterMixin, ItemSetter

class finesse.script.adapter.CommandPropertyDocumenter(*, item_type, **kwargs)

Bases: CommandMethodDocumenter

class finesse.script.adapter.CommandPropertyDumper(*, item_type, default=<class 'finesse.script.adapter._empty'>, **kwargs)

Bases: SignatureAttributeParameterMixin, ItemDumper

class finesse.script.adapter.CommandPropertySetter(*, item_type, **kwargs)

Bases: CommandMethodSetter

finesse.script.adapter.EMPTY_VALUE

alias of _empty

class finesse.script.adapter.ElementDocumenter(*, item_type, **kwargs)

Bases: NumpyStyleDocstringGetterMixin, ElementSyntaxMixin, ItemDocumenter

class finesse.script.adapter.ElementDump(element: ModelElement, adapter: ItemAdapter, parameters: List[ArgumentDump] | List[List[ArgumentDump]], is_default: bool)

Bases: object

A set of element parameters and metadata.

adapter: ItemAdapter
element: ModelElement
is_default: bool
parameters: List[ArgumentDump] | List[List[ArgumentDump]]
class finesse.script.adapter.ElementDumper(*, item_type, **kwargs)

Bases: SignatureAttributeParameterMixin, ItemDumper

class finesse.script.adapter.ElementFactory(last=False, **kwargs)

Bases: ItemFactory

class finesse.script.adapter.ElementSetter(*, item_type, **kwargs)

Bases: SignatureAttributeParameterMixin, ItemSetter

class finesse.script.adapter.ElementSyntaxMixin(*, sig_type=None, sig_ignore=None, **kwargs)

Bases: SyntaxMixin

class finesse.script.adapter.FunctionalSyntaxMixin(*, sig_type=None, sig_ignore=None, **kwargs)

Bases: SyntaxMixin

class finesse.script.adapter.ItemAdapter(full_name, short_name=None, other_names=None, getter=None, factory=None, setter=None, documenter=None, singular=False, build_last=False)

Bases: object

Adapter defining how a script instruction maps to/from a Python type.

This encapsulates the required information to take a script instruction and generate a corresponding Python object (e.g. a Laser from a laser l1 … instruction), to add it to a Model (or in the case of commands, set some model attribute), to dump that Python object back to script, and to generate documentation.

Parameters

full_namestr

The instruction’s unabbreviated name. This must be alphanumeric and can contain underscores but no spaces.

short_namestr, optional

The instruction’s short form name, used when generating compact script. If not specified, full_name is used in cases where the short form is desired.

other_namessequence, optional

Any other supported names for this instruction.

getterItemDumper, optional

Object handling the retrieval of parameters from the Python object corresponding to this instruction.

factoryItemFactory, optional

Object handling the creation of the Python object corresponding to this instruction.

setterItemSetter, optional

Object handling the setting of parameters in the Python object corresponding to this instruction’s parameters.

documenterItemDocumenter

Object handling the retrieval of docstrings and syntax suggestions for the instruction.

singularbool, optional

Flag indicating that this instruction can be defined only once per script. Defaults to False.

build_lastbool, optional

Whether to build the Python object last, regardless of dependencies. This is useful for elements with implicit dependencies (see e.g. the cavity adapter). Be careful using this flag because statements for other adapters that depend on statements for adapters with this flag will be built first. Defaults to False.

property aliases

The instruction alias(es).

Getter:

Sequence of aliases for this instruction.

class finesse.script.adapter.ItemDocumenter(*, item_type)

Bases: ItemHandler

abstract property docstring
syntax(spec, adapter, short_names=True, optional_as_positional=False, multiline=None)
syntax_correction(user_directive, spec, optional_as_positional=False, multiline=False)

Suggest syntax using the user’s directive.

class finesse.script.adapter.ItemDumper(*, item_type)

Bases: ItemHandler

class finesse.script.adapter.ItemFactory(*, item_type)

Bases: ItemHandler

class finesse.script.adapter.ItemHandler(*, item_type)

Bases: object

Root class for all dumper, setter, factory and documenter objects.

class finesse.script.adapter.ItemSetter(*, item_type)

Bases: ItemHandler

abstractmethod arguments()

The supported constructor arguments for this item.

Returns

dict

Mapping of argument names to Argument objects for this setter.

bind_argument(name_or_index)

Return a bound argument object for name.

Parameters

name_or_indexstr or int

The argument keyword or index.

Returns

BoundArgument

The argument metadata corresponding to name_or_index.

keyword_args(only=False)

The non-positional-only arguments of the call signature.

Parameters

onlybool, optional

Only include keyword-only arguments; defaults to False.

Returns

dict

The call object’s keyword parameters.

positional_args(only=False, keyword_defaults=True)

The non-keyword-only arguments of the call signature.

Parameters

onlybool, optional

Only include positional-only arguments. Defaults to False.

keyword_defaultsbool, optional

Include keyword arguments that have default values. Defaults to True.

Returns

dict

The call object’s positional parameters.

update_parameter(item, argument, value)

Update the built item’s name parameter to value.

This is used to update a parameter after the item has been created and added to the model, such as when resolving self-references.

Parameters

itemobject

The item.

argumentBoundArgument

The item argument corresponding to the value to update.

valueobject

The new value.

property var_keyword_argument
property var_positional_argument
class finesse.script.adapter.NumpyStyleDocstringGetterMixin(*, doc_type=None, **kwargs)

Bases: object

argument_descriptions()

The types and descriptions for each argument as parsed from the docstring.

Returns

dict

Mapping of arguments to their type and docstrings as listed in the object’s docstring. Note that the arguments may not correspond to signature argument names; numpydoc allows arguments to share docstrings so some keys may be e.g. n, m.

property doc_type
property docstring

The Python API item’s docstring.

Note: unlike inspect.getdoc(), this method returns only the docstring directly defined in doc_type, rather than taking the inherited docstring if not found. If no docstring is defined, None is returned.

extended_summary()

The item’s extended summary, parsed from the docstring.

summary()

The item’s summary, parsed from the docstring.

class finesse.script.adapter.SignatureArgumentMixin(*, sig_type=None, sig_ignore=None, **kwargs)

Bases: object

Mixin providing ability to retrieve signature arguments from a Python function.

Parameters

sig_typetype, optional

The signature type to retrieve arguments from. Defaults to item_type.

sig_ignoresequence, optional

Signature argument names to ignore.

arguments()
property sig_type
class finesse.script.adapter.SignatureAttributeParameterMixin(ref_args=None, var_pos_attr=None, var_keyword_attr=None, **kwargs)

Bases: SignatureArgumentMixin

Mixin providing the ability to get and set item parameters by inspecting its constructor signature arguments matching equivalently named object attributes.

Parameters

ref_argssequence, optional

Names of arguments that should be considered to be references. Corresponding ArgumentDump objects produced by this class will have their reference flags set to True to indicate to the generator that these should be treated as references instead of values.

var_pos_attrstr or callable, optional

The name of the field containing a sequence of variadic positional argument values, or a callable that returns the name of the field to set given the sequence number of the variadic argument, if the signature supports variadic positional arguments. Defaults to “args”.

var_keyword_attrstr or callable, optional

The name of the field containing a mapping of variadic keyword arguments to values, or a callable that returns the name of the field to set given the name of the keyword argument, if the signature supports variadic positional arguments. Defaults to the identity function.

dump_parameters(adapter, item)

Build parameter mapping by retrieving object attributes using the signature.

update_parameter(item, argument, value)
class finesse.script.adapter.SyntaxMixin(*, sig_type=None, sig_ignore=None, **kwargs)

Bases: SignatureArgumentMixin

finesse.script.compiler module

Kat model compiler.

This takes parsed productions, figures out the dependencies and builds the model in the correct order.

Sean Leavey <sean.leavey@ligo.org>

class finesse.script.compiler.KatCompiler(spec=None)

Bases: object

Kat model compiler.

compile(string, **kwargs)

Compile the contents of string.

Parameters

stringstr

The string to compile kat script from.

Other Parameters

kwargs

Keyword arguments supported by compile_file().

Returns

Model

The model compiled from reading string.

compile_file(fobj, model=None, resolve=True, build=True)

Compile the contents of the specified file.

Parameters

fobjio.FileIO

The file object to compile kat script from. This should be opened in text mode.

modelModel, optional

An existing model to compile the contents of fobj into. If not specified, a new, empty model is created.

resolvebool, optional

Resolve the parsed script. If False, the parsed contents is added to graph but no sanity checks are performed and nothing is returned. Defaults to True.

buildbool, optional

Build the parsed script. If False, no Finesse objects will be added to the model and nothing will be returned. Defaults to True.

Returns

Model or None

If resolve and build are True, the model compiled from reading fobj; None otherwise.

Raises

KatSyntaxError

If a syntax error is present in the contents of fobj.

property script
exception finesse.script.compiler.KatCycleError(script, cyclic_nodes)

Bases: KatScriptError

Cyclic parameters.

exception finesse.script.compiler.KatDirectiveBuildError(error, directive, script, statement_node, adapter, graph, spec)

Bases: KatDirectiveError

Error during the building of a directive (i.e. the call to the Finesse Python object).

exception finesse.script.compiler.KatDirectiveError(error, directive, script, error_items, spec, add_syntax_hint=False)

Bases: KatScriptError

Error compiling a directive (either resolving or building).

exception finesse.script.compiler.KatIncorrectFormError(user_directive_token, script, spec)

Bases: KatSyntaxError

Error representing an element, command or analysis that uses the wrong syntax form.

For example, this is thrown when a command is written in “element” KatScript form, and vice versa.

This is technically a syntax error, but it is not caught there because it doesn’t know which directives use which type of syntax.

exception finesse.script.compiler.KatParameterBuildError(error, script, param_node, graph)

Bases: KatScriptError

Error during the building of a directive parameter.

exception finesse.script.compiler.KatParameterSelfReferenceException

Bases: Exception

Indication that a parameter contains a self-reference that must be resolved later.

finesse.script.containers module

Token and production containers for use in the tokenizer and parser.

class finesse.script.containers.Addressable

Bases: object

Mixin defining interface to retrieve strings containing script lines.

abstract property bounds

Container bounds.

Getter:

KatBounds for this container.

script(bounds=None)

Get the script in the interval [start, stop) defined by bounds.

Lines between start and stop with no tokens are yielded as empty lines. Gaps between the columns spanned by tokens on the same line are yielded as spaces.

Parameters

boundsKatBounds, optional

Bounds within which to retrieve script. Defaults to the whole script.

Returns

str

The script.

script_lines(bounds)

The script within bounds by line.

Parameters

boundsKatBounds

The bounds to retrieve script between.

Returns

list

Lines within bounds. Where bounds starts or stops mid-way through a line, only the part of the line that falls within bounds is contained in the corresponding line.

property start

Start coordinate.

Getter:

The start KatCoordinate.

property stop

Stop coordinate.

Getter:

The stop KatCoordinate.

class finesse.script.containers.ArgumentContainer(arguments: List[TokenContainer])

Bases: TokenContainer

Mixin for containers that contain arguments.

arguments: List[TokenContainer]
property tokens

Tokens contained in the container.

Getter:

list of KatToken objects within this container.

class finesse.script.containers.BaseCustomToken(lineno: int, start_index: int, stop_index: int, type: str, raw_value: Any)

Bases: KatToken

A custom token.

class finesse.script.containers.ExtraTokenContainer(extra: List[KatToken])

Bases: TokenContainer

Mixin for containers that contain extra tokens.

extra: List[KatToken]
property tokens

Tokens contained in the container.

Getter:

list of KatToken objects within this container.

class finesse.script.containers.KatArray(extra: List[KatToken], arguments: List[TokenContainer])

Bases: ArgumentContainer, ExtraTokenContainer, TokenContainer

Represents a kat script array.

class finesse.script.containers.KatBooleanToken(lineno: int, start_index: int, stop_index: int, type: str, raw_value: Any)

Bases: BaseCustomToken

A boolean token.

property value
class finesse.script.containers.KatBounds(start: KatCoordinate, stop: KatCoordinate)

Bases: object

Kat script start and stop bounds.

This represents a block of text in a kat script file.

isempty()

Whether the contents contained within the bounds is empty.

Returns

bool

True if empty, False otherwise.

lcontract(newstart)

Contract start boundary.

Parameters

newstartKatCoordinate

The new start coordinate.

Returns

KatBounds

The contracted bounds.

Raises

ValueError

If newstart is not >= current start coordinate.

lexpand(newstart)

Expand start boundary.

Parameters

newstartKatCoordinate

The new start coordinate.

Returns

KatBounds

The expanded bounds.

Raises

ValueError

If newstart is not <= current start coordinate.

rcontract(newstop)

Contract stop boundary.

Parameters

newstopKatCoordinate

The new stop coordinate.

Returns

KatBounds

The contracted bounds.

Raises

ValueError

If newstop is not <= current stop coordinate.

rexpand(newstop)

Expand stop boundary.

Parameters

newstopKatCoordinate

The new stop coordinate.

Returns

KatBounds

The expanded bounds.

Raises

ValueError

If newstop is not >= current stop coordinate.

start: KatCoordinate
stop: KatCoordinate
class finesse.script.containers.KatCoordinate(lineno: int, index: int)

Bases: object

Kat script file coordinate supporting comparison operations.

compact()

Compact coordinate representation.

Returns

str

Compact coordinates.

index: int
lineno: int
class finesse.script.containers.KatElement(directive: KatToken, extra: List[KatToken], arguments: List[TokenContainer], name: KatToken)

Bases: ArgumentContainer, ExtraTokenContainer, KatScriptItem

Represents a parsed element statement and any corresponding arguments.

missing_argument_meta_token()

A meta token at one position after that of the last argument token.

This is used to create error markers pointing to the location of missing parameters.

name: KatToken
property node_name
property tokens

Tokens contained in the container.

Getter:

list of KatToken objects within this container.

property unique_name_token
class finesse.script.containers.KatExpression(extra: List[KatToken], arguments: List[TokenContainer], operator: KatToken)

Bases: ArgumentContainer, ExtraTokenContainer, TokenContainer

Represents a kat script expression.

property lhs
operator: KatToken
property rhs
property tokens

Tokens contained in the container.

Getter:

list of KatToken objects within this container.

class finesse.script.containers.KatFile(text: str)

Bases: Addressable

Container with kat script lines (no concrete tokens).

add(string)

Add string to end of file.

Parameters

stringstr

The string to add to the end of the file.

property bounds

Container bounds.

Getter:

KatBounds for this container.

text: str
class finesse.script.containers.KatFixMeToken(lineno: int, start_index: int, stop_index: int, type: str, raw_value: Any)

Bases: BaseCustomToken

A “fixme” token used by the unparser to represent an invalid value.

property value
class finesse.script.containers.KatFunction(directive: KatToken, extra: List[KatToken], arguments: List[TokenContainer])

Bases: ArgumentContainer, ExtraTokenContainer, KatScriptItem

Represents a parsed kat function statement and any corresponding arguments.

missing_argument_meta_token()

A meta token at one position after that of the last argument token.

This is used to create error markers pointing to the location of missing parameters.

property name

The token that represents the function name.

This is used by the error handler for invalid keyword arguments, for example.

property node_name
property unique_name_token
class finesse.script.containers.KatGroupedExpression(extra: List[KatToken], arguments: List[TokenContainer])

Bases: ArgumentContainer, ExtraTokenContainer, TokenContainer

Represents a kat script expression group, i.e. (<expression>).

property expression
class finesse.script.containers.KatKwarg(key: KatToken, equals: KatToken, value: KatToken | KatFunction | KatExpression | KatGroupedExpression | KatArray)

Bases: TokenContainer

Represents a kat argument containing a key, value and ‘=’.

equals: KatToken
key: KatToken
property tokens

Tokens contained in the container.

Getter:

list of KatToken objects within this container.

value: KatToken | KatFunction | KatExpression | KatGroupedExpression | KatArray
class finesse.script.containers.KatMetaToken(lineno: int, start_index: int, stop_index: int, type: str)

Bases: TokenMixin

A token that may not map to a real token.

Meta tokens are employed by KatTokenizer when converting whitespace and newline tokens used as delimiters into DELIMITER. The use of a single meta token for DELIMITER in this case simplifies the parser rules.

By definition, the value of a meta token does not matter so the class doesn’t support having one. Similarly, to help prevent bugs, an exception is raised if the token is attempted to be displayed.

class finesse.script.containers.KatNoneToken(lineno: int, start_index: int, stop_index: int, type: str, raw_value: Any)

Bases: BaseCustomToken

A null token.

property value
class finesse.script.containers.KatNumberToken(lineno: int, start_index: int, stop_index: int, type: str, raw_value: Any)

Bases: BaseCustomToken

A number token.

SI_NUMBER_PATTERN = re.compile('.*[pnumkMGT]$')
property value
class finesse.script.containers.KatNumericalArray(extra: List[KatToken], arguments: List[TokenContainer])

Bases: KatArray

Represents a kat script numerical array.

classmethod from_array(array)

Convert array to numerical array.

class finesse.script.containers.KatScript(extra: List[KatToken], arguments: List[TokenContainer])

Bases: ArgumentContainer, ExtraTokenContainer, TokenContainer

Represents a kat script.

class finesse.script.containers.KatScriptItem(directive: KatToken)

Bases: TokenContainer

Represents a top level kat script item.

directive: KatToken
abstractmethod missing_argument_meta_token()

A meta token at one position after that of the last argument token.

This is used to create error markers pointing to the location of missing parameters.

abstract property node_name
property tokens

Tokens contained in the container.

Getter:

list of KatToken objects within this container.

abstract property unique_name_token
class finesse.script.containers.KatStringToken(lineno: int, start_index: int, stop_index: int, type: str, raw_value: Any)

Bases: BaseCustomToken

A string token.

property value
class finesse.script.containers.KatToken(lineno: int, start_index: int, stop_index: int, type: str, raw_value: Any)

Bases: TokenMixin

A real token with the corresponding text’s location, type and value.

property display_value
raw_value: Any
to_meta()

Convert token to a meta token.

Returns

KatMetaToken

The current token, as a meta token.

to_new_position(start)

Copy token, updating its start (and stop) position.

Parameters

startKatCoordinate

The token’s new start position.

Returns

KatToken

New copy of self, with updated start position.

property value
classmethod with_new_type(tok, new_type)

Convert token to a different type.

Parameters

tokKatToken

The token to convert.

new_typestr

The new token type.

Returns

KatToken

The kat token, copied from tok, with type new_type.

class finesse.script.containers.KatWhitespaceToken(lineno: int, start_index: int, stop_index: int, type: str, raw_value: Any)

Bases: BaseCustomToken

A whitespace token.

property display_value
class finesse.script.containers.TokenContainer

Bases: Addressable

Container with concrete token instances.

property bounds

Container bounds.

Getter:

KatBounds for this container.

property first_token

First container token by coordinate.

Getter:

first KatToken within this container.

property last_token

Last container token by coordinate.

Getter:

last KatToken within this container.

property sorted_tokens

Tokens contained in the container, in ascending coordinate order.

Getter:

sorted list of KatToken objects within this container.

abstract property tokens

Tokens contained in the container.

Getter:

list of KatToken objects within this container.

class finesse.script.containers.TokenMixin(lineno: int, start_index: int, stop_index: int, type: str)

Bases: TokenContainer

A class that provides functionality shared by KatMetaToken and KatToken.

Injected this way to prevent KatToken inheriting from KatMetaToken, which would be confusing since they are both tokens, but one represent real tokens while the other does not.

property bounds

Container bounds.

Getter:

KatBounds for this container.

lineno: int
start_index: int
stop_index: int
property tokens

Tokens contained in the container.

Getter:

list of KatToken objects within this container.

type: str

finesse.script.exceptions module

Kat script exceptions.

These are special exceptions that add extra context-specific information when errors occur during parsing or unparsing.

exception finesse.script.exceptions.KatMissingAfterDirective(container, directive)

Bases: KatSyntaxError

Error for when an element name or function ‘(’ is missing.

exception finesse.script.exceptions.KatParsingError(message, **kwargs)

Bases: FinesseException

An error during the parsing process.

This handles errors raised by the tokenizer, parser and builder. These are, confusingly, collectively referred to as the “parser”.

exception finesse.script.exceptions.KatParsingInputSizeWarning

Bases: UserWarning

Warns the users of an unreasonable input size, either the in the total size of the katscript or the length of an individual line.

Both of these might lead to recursion errors or low performance.

exception finesse.script.exceptions.KatParsingWarning

Bases: UserWarning

A warning during the parsing, indicating that exceptions might occur later.

exception finesse.script.exceptions.KatScriptError(error, container, error_items, syntax=None)

Bases: KatParsingError

Detailed kat script error.

Parameters

errorstr or Exception

The error or error message.

containerAddressable

The kat script container, used to show lines before/after error lines if requested.

error_itemssequence of sequences of Addressable

The error(s) to show. Each item of the topmost sequence should itself be an ordered sequence of Addressable objects in increasing order of depth. The last item is considered to be where the error occurred, but the start and end lines (plus optional buffer) of each of the other items are also shown.

syntaxstr, optional

Syntax suggestion to display to the user.

MAX_BUFFER_LINES = 1
chunkify()

Convert the error script into a dict of line numbers to (str, is_error) sequences.

Each (str, is_error) chunk contains a piece of the script specified in error_items, with the is_error flag set depending on whether each error item appeared last in a error_items sequence, which specifies that it is an error as opposed to just useful related code.

Returns

dict

Mapping of line numbers to lists of (str, bool) tuples indicating script chunks and whether they contain an error.

property error_lines
items_to_linemarkers(items)
message()
rubric()
exception finesse.script.exceptions.KatSyntaxError(message, script, token)

Bases: KatScriptError

Error with kat syntax.

finesse.script.generator module

Kat script generator.

class finesse.script.generator.CommandContainer(adapter, params)

Bases: object

Container for top level commands, used by the generator.

class finesse.script.generator.ElementContainer(element)

Bases: object

Container for top level model elements, used by the generator.

class finesse.script.generator.KatUnbuilder(show_warnings=True, spec=None)

Bases: object

Model to KatScript converter.

This class defines single-dispatch methods to recursively fill Finesse objects into a KatGraph. The graph is then serialised to KatScript via KatUnfiller.

The single-dispatch uses the type of the object to create appropriate nodes and edges in the KatGraph.

Typically unbuilding starts with the passing of a Model to unbuild() or unbuild_file(). The single-dispatch method that handles models then extracts the elements, commands and analyses and passes them recursively to the same single-dispatch, whereupon matching fill methods further handle them. The underlying tokens that form Finesse objects are eventually reached by recursively calling the fill method, and these are added as terminal nodes in the graph and connected to their parents by edges.

Special behaviour applies in some cases. One such case is the handling of objects from containers with corresponding type annotations specifying that they are Parameter objects. These are assumed to have name KatScript representation, rather than value. This is used for example in the dumping of axis parameters, which must be written as e.g. xaxis(m1.phi, …) rather than xaxis(0, …) (in the case that m1.phi has value 0).

IGNORED_ELEMENTS = ['Fsig']
LITERAL_MAP = {'(': 'LPAREN', ')': 'RPAREN', '*': 'TIMES', '**': 'POWER', '+': 'PLUS', ',': 'COMMA', '-': 'MINUS', '/': 'DIVIDE', '//': 'FLOORDIVIDE', '=': 'EQUALS', '[': 'LBRACKET', ']': 'RBRACKET'}
UNARY_OPERATORS = {'neg': '-', 'pos': '+'}
property index
property lineno
property position
unbuild(*args, **kwargs)
unbuild_file(fobj, item, ref_graph=None, ref_node=None, directive_defaults=False, argument_defaults=False, prefer_keywords=True)

Generate KatScript for item and write to fobj.

Parameters

fobjio.FileIO

The file object to write KatScript to. This should be opened in text mode.

itemobject

The object to generate KatScript for. This is normally a Model but can be any Finesse object.

ref_graphKatGraph, optional

The reference syntax graph to use during KatScript generation. If specified, the nodes representing item and any Finesse objects contained therein will be copied and updated from it. This preserves formatting such as whitespace and comments.

ref_nodestr, optional

The reference node to use when unparsing item. This is only used if ref_graph is specified. If ref_graph is given but ref_node is not, ref_node is assumed to be the graph root. If the graph does not contain a root node, a ValueError is raised.

directive_defaultsbool, optional

Generate default elements, commands and actions even if they are set to their default values and would therefore generate Finesse objects in the same state when later parsed. If ref_graph is specified and an element, command or action is present as a node, however, it is generated regardless of whether its value is the default or not. Defaults to False.

argument_defaultsbool, optional

Generate optional arguments that are set to their default values and would therefore generate Finesse objects in the same state when later parsed. If ref_graph is specified and a keyword argument is present as a node, however, it is generated regardless of whether its value is the default or not. Defaults to False.

prefer_keywordsbool, optional

Prefer generating keyword arguments over positional arguments, where allowed. If a parameter can be a keyword argument, i.e. it is not positional-only, it is dumped as a keyword argument if this is True. This setting is ignored if ref_node is specified and a reference argument for the parameter is found (whereupon the original style is reused). Defaults to True.

class finesse.script.generator.KatUnfiller

Bases: object

KatGraph to kat script.

production(node, graph)
unfill(node, graph)
unfill_file(fobj, node, graph)
class finesse.script.generator.KatUnparser

Bases: object

TokenContainer to kat script.

unparse(container)
unparse_file(fobj, container)
class finesse.script.generator.KatUntokenizer

Bases: object

Token to kat script.

untokenize(tokens)
untokenize_file(fobj, tokens)

finesse.script.graph module

Graph represening a parsed kat script file.

class finesse.script.graph.KatEdgeType(*values)

Bases: Flag

ARGUMENT = 1
DEPENDENCY = 2
class finesse.script.graph.KatGraph(*args, backend=None, **kwargs)

Bases: DiGraph

Kat script graph.

argument(argument_node, adapter)

Get argument corresponding to node argument_node.

This returns the argument object for a syntax graph node. It is useful for retrieving the names for positional arguments during parsing, but works for keyword arguments too.

Returns

BoundArgument

The argument specified in the script corresponding to argument_node.

Raises

TypeError

When argument_node corresponds to a positional argument that doesn’t exist in the setter signature defined in adapter.

argument_node_order(node)

Get the order attribute of the edge linking argument node to its parent.

classmethod branch_base(path, reference)

The branch base node name for path, relative to reference.

dependent_argument_nodes(node, **kwargs)
dependent_arguments_edge_data(parent, data)

Get mapping of dependent argument nodes to the value of the data attribute on the edge connecting them to parent.

directive_graph(node)
filter_argument_nodes(node, key)
filter_dependent_nodes(node, key)
in_edge_source_nodes_by_edge_type(node, edge_types, **kwargs)
in_edges_by_edge_type(node, edge_types, **kwargs)
is_independent(node)

Check if the node has no external dependencies.

A node is independent if it is a terminal type or if its arguments have no non- argument incoming edges.

classmethod is_subpath(path, reference)

Check if path is a subpath of reference.

is_tree()
classmethod item_node_name(name, parent_path)
merge(other)

Merge other graph into this graph, rewriting paths in other if there are name collisions.

Merging two identical graphs kat –> kat.0 –> kat.0.1, the result would be:

kat --> kat.0 --> kat.0.1
    --> kat.1 --> kat.1.1

Notes

self and other must be trees (is_tree() returns True).

nodes_by_node_type(node_type, **kwargs)

Get nodes by type, with optional data.

out_edge_target_nodes_by_edge_type(node, edge_types, **kwargs)
out_edges_by_edge_type(node, edge_types, **kwargs)
param_target_element_path(target, root_node)

The owning element path for target.

Target should be in the form “element_name{.param_name{.param_name {…}}}.

classmethod path_parent(path)
plot(*args, **kwargs)
sorted_dependent_argument_nodes(node, **kwargs)
class finesse.script.graph.KatNodeType(*values)

Bases: Flag

ARRAY = 32
COMPILER_TERMINAL_NODES = 1152
CONSTANT = 512
DEPENDENT_NODES = 256
DIRECTIVE_NODES = 6
ELEMENT = 2
EXPRESSION = 8
FUNCTION = 4
GENERATOR_TERMINAL_NODES = 1920
GROUPED_EXPRESSION = 16
KEYWORD = 1024
NUMERICAL_ARRAY = 64
REFERENCE = 256
ROOT = 1
VALUE = 128

finesse.script.highlighter module

KatScript lexer for syntax highlighting with Pygments.

Note that this plugin is used in the documentation as well, it provides the syntax highlighting for the code-block:katscript directive

class finesse.script.highlighter.KatScriptPygmentsLexer(**options)

Bases: Lexer

aliases = ['katscript', 'kat']

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

filenames = ['*.kat']

A list of fnmatch patterns that match filenames which contain content for this lexer. The patterns in this list should be unique among all lexers.

get_tokens_unprocessed(text)

This method should process the text and return an iterable of (index, tokentype, value) tuples where index is the starting position of the token within the input text.

It must be overridden by subclasses. It is recommended to implement it as a generator to maximize effectiveness.

name = 'KatScript'

Full name of the lexer, in human-readable form

token_map = {'BOOLEAN': ('Keyword', 'Reserved'), 'COMMA': ('Punctuation',), 'COMMENT': ('Comment',), 'DIVIDE': ('Operator',), 'EQUALS': ('Operator',), 'LBRACKET': ('Punctuation',), 'LPAREN': ('Punctuation',), 'MINUS': ('Operator',), 'NAME': ('Text',), 'NEWLINE': ('Text',), 'NONE': ('Text',), 'NUMBER': ('Literal', 'Number'), 'PLUS': ('Operator',), 'RBRACKET': ('Punctuation',), 'REFERENCE': ('Name', 'Variable'), 'RPAREN': ('Punctuation',), 'STRING': ('Literal', 'String'), 'TIMES': ('Operator',), 'WHITESPACE': ('Text',)}
class finesse.script.highlighter.KatScriptSubstringPygmentsLexer(*args, **kwds)

Bases: RegexLexer

aliases = ['katscriptinpython']

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

flags = 16

Flags for compiling the regular expressions. Defaults to MULTILINE.

name = 'KatScriptInPython'

Full name of the lexer, in human-readable form

tokens = {'katscript': [('(.*?)(""")', <function bygroups.<locals>.callback>, '#pop')], 'root': [('(.+?""")([\\s\\n]*#kat)', <function bygroups.<locals>.callback>, 'katscript'), ('.+', <function using.<locals>.callback>)]}

At all time there is a stack of states. Initially, the stack contains a single state ‘root’. The top of the stack is called “the current state”.

Dict of {'state': [(regex, tokentype, new_state), ...], ...}

new_state can be omitted to signify no state transition. If new_state is a string, it is pushed on the stack. This ensure the new current state is new_state. If new_state is a tuple of strings, all of those strings are pushed on the stack and the current state will be the last element of the list. new_state can also be combined('state1', 'state2', ...) to signify a new, anonymous state combined from the rules of two or more existing ones. Furthermore, it can be ‘#pop’ to signify going back one step in the state stack, or ‘#push’ to push the current state on the stack again. Note that if you push while in a combined state, the combined state itself is pushed, and not only the state in which the rule is defined.

The tuple can also be replaced with include('state'), in which case the rules from the state named by the string are included in the current one.

finesse.script.legacy module

Finesse legacy (Finesse 2) kat-script parser.

class finesse.script.legacy.KatParser

Bases: object

Kat file lexer, parser and builder.

parse(text, model=None, **kwargs)

Parse kat code into a model.

Parameters

textstr

String containing the kat code to be parsed.

modelModel, optional

Model object to add components to. If not specified, a new model will be created.

ignored_blockslist, optional

A list of names of FTBLOCK sections in the kat code to leave out of the model; defaults to empty list.

Returns

Model

The constructed model.

Raises

KatParserError

If an error occurs during parsing or building.

parse_file(path, model=None, **kwargs)

Parse kat code from a file into a model.

Parameters

pathstr or io.FileIO

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.

modelModel, optional

Model object to add components to. If not specified, a new model will be created.

Other Parameters

**kwargs

Keyword parameters supported by parse().

Raises

KatParserError

If an error occurs during parsing or building.

exception finesse.script.legacy.KatParserError(errors, text, **kwargs)

Bases: FinesseException

Kat file parser error.

expected = {'FTblock': 'FTblock name', 'FTend': 'FTend name', 'ad\\s': 'ad name [n m] f node[*]', 'attr\\s': 'attr component parameter value', 'beam\\s': 'beam name [f] node[*]', 'bp\\s': 'bp name x/y parameter node', 'bs1\\s': 'bs1 name T L phi alpha node1 node2 node3 node4', 'bs2\\s': 'bs2 name R L phi alpha node1 node2 node3 node4', 'bs\\s': 'bs name R T phi alpha node1 node2 node3 node4', 'cav\\s': 'cav name component1 node component2 node', 'const\\s': 'const name value', 'dbs\\s': 'dbs name node1 node2 node3 node4', 'freq\\s': None, 'fsig\\s': ('fsig name component [type] f phase [amp]', 'fsig name f'), 'func\\s': 'func name = function-string', 'gauss*\\s': 'gauss* name component node q [qy]', 'gauss\\s': 'gauss name component node w0 z [wy0 zy]', 'gouy\\s': 'gouy name x/y space-list', 'isol\\s': 'isol name S [Loss] node1 node2 [node3]', 'l\\s': 'l name I f [phase] node', 'lambda\\s': 'lambda wavelength', 'lens\\s': 'lens name f node1 node2', 'lock\\s': 'lock name function/set gain accuracy [offset]', 'm1\\s': 'm1 name T L phi node1 node2', 'm2\\s': 'm2 name R L phi node1 node2', 'm\\s': 'm name R T phi node1 node2', 'maxtem\\s': 'maxtem order', 'mod\\s': 'mod name f midx order am/pm/yaw/pitch node1 node2', 'noxaxis': None, 'pd\\s': 'pd[n] name [f1 [phase1 [f2 [phase2 [...] ] ] ] ] node[*]', 'phase\\s': 'phase 0-7', 'put\\s': 'put component parameter function/set/axis', 'qnoised\\s': 'qnoised name num_demods f1 phase1 [f2 phase2 [...]] node[*]', 'qshot\\s': 'qshot name num_demods f1 phase1 [f2 phase2 [...]] node[*]', 'retrace': 'retrace [off|force]', 's\\s': 's name L [n] node1 node2', 'tem\\s': 'tem input n m factor phase', 'variable\\s': 'variable name value', 'x2axis\\s': 'x2axis component parameter lin/log min max steps', 'xaxis\\s': 'xaxis component parameter lin/log min max steps', 'yaxis\\s': 'yaxis [lin/log] abs:deg/db:deg/re:im/abs/db/deg'}
finesse.script.legacy.find_column(text, index)
finesse.script.legacy.get_const(consts, value)
finesse.script.legacy.get_model_element(model, element)
finesse.script.legacy.select_powerdetector(*args, **kwargs)
finesse.script.legacy.select_quantum_noisedetector(*args, **kwargs)

finesse.script.memoize module

Memoize wrappers for the parser.

Based on https://github.com/we-like-parsers/pegen/blob/main/story5/memo.py by Guido van Rossum.

Copyright (c) 2021 we-like-parsers

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

finesse.script.memoize.memoize(func)

Memoize a parsing method.

The functon must be a method on a class deriving from Parser. The method must have either no arguments or a single argument that is an int or str (the latter being the case for expect()). It must return either None or an object that is not modified (at least not while we’re parsing). We memoize positive and negative outcomes per input position. The function is expected to move the input position iff it returns a not- None value. The memo is structured as a dict of dict, the outer dict indexed by input position, the inner by function and arguments.

finesse.script.memoize.memoize_left_rec(func)

Memoize a left-recursive parsing method.

This is similar to @memoize but loops until no longer parse is obtained. Inspired by https://github.com/PhilippeSigaud/Pegged/wiki/Left-Recursion

finesse.script.parser module

Kat parser to convert tokens to productions.

This is a recursive descent parser, providing unlimited lookahead capabilities to allow arbitrary context-free grammars to be parsed. The implementation of memoization makes it a packrat parser which runs in linear time at the expense of potentially unlimited memory use. In practice memory use is limited by the simplicity of typical kat scripts (e.g. expressions don’t tend to have many subexpressions).

This is inspired by Python’s PEG parser, used as of 3.9. Some introductory information can be found in this series of blog posts.

Sean Leavey <sean.leavey@ligo.org>

class finesse.script.parser.KatParser

Bases: object

Kat script parser.

This uses so-called packrat parsing to reduce, via productions, tokens yielded from a token stream generated from an input file or string to KatScriptItem objects containing the associated tokens.

array(*args)
array_value(*args)
array_values(*args)
element(*args)
element_key_value_list(*args)
element_params(*args)
element_value_list(*args)
empty(*args)
expect_production(production, *args, **kwargs)
expect_token(*args)
expr(*args)
expr1(*args)
expr2(*args)
expr3(*args)
expr4(*args)
function(*args)
function_key_value_list(*args)
function_params(*args)
function_value_list(*args)
get_token()
invalid_array(*args)
invalid_expr4(*args)
invalid_script_line(*args)
key_value(*args)
loop(production, nonempty, *args, **kwargs)
mark()
maybe_trailing_comma(multiline)
maybe_whitespace(multiline, whitespace)

Expect zero or more whitespace if enabled, else return [].

negative_lookahead(token_type)
parse(string)

Parse the contents of string.

Parameters

stringstr

The string to parse kat script from.

Returns

KatScript

The parsed kat script.

parse_file(fobj)

Parse the contents of the specified file.

Parameters

fobjio.FileIO

The file object to parse kat script from. This should be opened in text mode.

Returns

KatScript

The parsed kat script.

peek_token()
positional_value(*args)
positive_lookahead(token_type)
reset(pos)
property script
script_line(*args)
script_line_empty(*args)
start()
statement(*args)
value(*args)

finesse.script.spec module

KatScript specification.

This defines supported KatScript syntax and maps it to Finesse Python classes via ItemAdapter objects.

class finesse.script.spec.FsigArgumentsMixin

Bases: object

arguments(**kwargs)
class finesse.script.spec.FsigDocumenter

Bases: FsigArgumentsMixin, CommandMethodDocumenter

argument_descriptions()

The types and descriptions for each argument as parsed from the docstring.

Returns

dict

Mapping of arguments to their type and docstrings as listed in the object’s docstring. Note that the arguments may not correspond to signature argument names; numpydoc allows arguments to share docstrings so some keys may be e.g. n, m.

class finesse.script.spec.FsigDumper

Bases: ItemDumper

class finesse.script.spec.FsigSetter

Bases: FsigArgumentsMixin, ItemSetter

class finesse.script.spec.GaussDumper

Bases: ItemDumper

Dumper for the Gauss component.

Gauss components accept many different forms of argument to define the beam parameter but only store these internally as q parameters. This dumper therefore tries to figure out how the parameters were defined by the user (either via Python or KatScript) and generates parameters based on that.

class finesse.script.spec.KatSpec

Bases: object

KatScript language specification.

This defines the available KatScript elements, commands, and analyses that the parser recognises. These directives are mapped by this object to adapter classes to convert between KatScript and Finesse objects.

Additional directives can be registered at runtime using register_element(), register_command(), and register_analysis(). These adapters will remain for the rest of the lifetime of the object.

Supported KatScript keywords, constants, operators, and functions are not modifiable by users.

This class should not normally be instantiated by user code; the shared instance in KATSPEC should instead be used.

binary_operators = {'*': <function MAKE_simplify_mul.<locals>.simplify_mul>, '**': <function MAKE_simplify_pow.<locals>.simplify_pow>, '+': <function MAKE_simplify_add.<locals>.simplify_add>, '-': <function MAKE_simplify_sub.<locals>.simplify_sub>, '/': <function MAKE_LOP_simplify_truediv.<locals>.simplify_truediv>, '//': <function <lambda>.<locals>.<lambda>>}
constants = {'c0': c, 'pi': π}
property directives

All top level parser directives.

Getter:

Returns a mapping of top level parser directive aliases to adapters.

Type:

ChainMap

expression_functions = {'abs': <function <lambda>>, 'arange': <function <lambda>>, 'arccos': <function <lambda>>, 'arcsin': <function <lambda>>, 'arctan': <function <lambda>>, 'arctan2': <function <lambda>>, 'conj': <function <lambda>>, 'cos': <function <lambda>>, 'deg2rad': <function <lambda>>, 'degrees': <function <lambda>>, 'dot': <function <lambda>>, 'exp': <function <lambda>>, 'geomspace': <function <lambda>>, 'imag': <function <lambda>>, 'jv': <function <lambda>>, 'linspace': <function <lambda>>, 'log': <function <lambda>>, 'log10': <function <lambda>>, 'logspace': <function <lambda>>, 'neg': <function <lambda>>, 'pos': <function <lambda>>, 'pow': <function <lambda>>, 'rad2deg': <function <lambda>>, 'radians': <function <lambda>>, 'real': <function <lambda>>, 'sin': <function <lambda>>, 'sqrt': <function <lambda>>, 'std': <function <lambda>>, 'sum': <function <lambda>>, 'tan': <function <lambda>>}
property function_directives

All top level function-style parser directives.

Getter:

Returns a mapping of top level function parser directive aliases to adapters.

Type:

ChainMap

get_element_class(name: str) type

Get the corresponding python class for a katscript model element.

Parameters

namestr

name of a katscript element

Returns

type

Python class for this element

Raises

ValueError

When the element can not be found

keywords = {'abcd', 'am', 'bandpass', 'bandstop', 'both', 'div', 'even', 'finesse', 'fsr', 'fwhm', 'g', 'gouy', 'highpass', 'l', 'length', 'lin', 'log', 'loss', 'lowpass', 'modesep', 'none', 'odd', 'off', 'pm', 'pole', 'q', 'rc', 'resolution', 's', 'single', 'stability', 'tau', 'w', 'w0', 'x', 'xsplit', 'y', 'ysplit', 'z', 'zr'}
register_analysis(adapter, **kwargs)

Add parser and generator support for an analysis.

Parameters

adapterItemAdapter

The analysis adapter.

Other Parameters

overwritebool, optional

Overwrite analyses with the same aliases, if present. If False and one of adapter’s aliases already exists, a KeyError is raised. Defaults to False.

register_command(adapter, **kwargs)

Add parser and generator support for a command.

Parameters

adapterItemAdapter

The command adapter.

Other Parameters

overwritebool, optional

Overwrite commands with the same aliases, if present. If False and one of adapter’s aliases already exists, a KeyError is raised. Defaults to False.

register_element(adapter, **kwargs)

Add parser and generator support for a model element such as a component or detector.

Parameters

adapterItemAdapter

The element adapter.

Other Parameters

overwritebool, optional

Overwrite elements with the same aliases, if present. If False and one of adapter’s aliases already exists, a KeyError is raised. Defaults to False.

property reserved_names

All reserved names.

This is primarily useful for tests.

Getter:

Returns the names reserved in the parser as special production types.

Type:

list

type_descriptor(_type, default=None)

Get a descriptor for a type that’s suitable for use in user feedback.

This allows something other than Python class names to be displayed to the user inside error messages.

Supports the same parameters as dict.get().

unary_operators = {'+': <function <lambda>>, '-': <function <lambda>>}
class finesse.script.spec.ModesDumper

Bases: SignatureArgumentMixin, ItemDumper

class finesse.script.spec.PhaseConfigDumper

Bases: SignatureArgumentMixin, ItemDumper

class finesse.script.spec.TEMDocumenter

Bases: CommandMethodDocumenter

argument_descriptions()

The types and descriptions for each argument as parsed from the docstring.

Returns

dict

Mapping of arguments to their type and docstrings as listed in the object’s docstring. Note that the arguments may not correspond to signature argument names; numpydoc allows arguments to share docstrings so some keys may be e.g. n, m.

arguments()
class finesse.script.spec.TEMDumper

Bases: SignatureArgumentMixin, ItemDumper

class finesse.script.spec.TEMSetter

Bases: CommandMethodSetter

class finesse.script.spec.VariableDumper

Bases: ItemDumper

Variable for finesse.components.general.Variable.

finesse.script.spec.add_name_to_other_names(name: str, kwargs: dict) dict

For ‘make_element’ and ‘make_analysis’, adds the name of the python class to the list of ‘other_names’, which get added in ‘ItemAdapter’ to the list of aliases. Allows ‘Xaxis’ to be recognized as ‘xaxis’ and ‘Beamsplitter’ as ‘beamsplitter’.

Parameters

cls_namestr

Name of the class

kwargsdict

kwargs meant to be passed to ItemAdapter

Returns

dict

kwargs with ‘other_names’ modified to include the class name.

finesse.script.spec.make_analysis(analysis_type, full_name, ref_args=None, **kwargs)

Create a standard analysis adapter.

Use this for analyses that follow the normal behaviour: they are of type Action, their constructor signature defines their attributes, and the attributes are available with the same name in the object.

finesse.script.spec.make_element(element_type, full_name, build_last=False, ref_args=None, **kwargs)

Create a standard element adapter.

Use this for elements that follow the normal behaviour: they are of type ModelElement, their constructor signature defines their attributes, and the attributes are available with the same name in the object.

finesse.script.tokenizer module

Tokenization for kat script.

This differs from a typical tokenizer in that it tokenizes whitespace and newline characters, which have important meanings in kat script and help maintain formatting in later model serialization.

Inspired by the Python standard library tokenize module and lex.py from David Beazley’s SLY (https://github.com/dabeaz/sly/).

Sean Leavey <sean.leavey@ligo.org>

class finesse.script.tokenizer.KatTokenizer

Bases: object

Kat script token generator.

Regular expressions define patterns to match prototypes. Prototypes are then either emitted as tokens as-is, or modified by callback methods defined in this class.

Parameters

graphKatGraph, optional

The parse graph to add parsed tokens to. Defaults to a new KatGraph.

on_LBRACKET(token)
on_LPAREN(token)
on_NEWLINE(token)
on_RBRACKET(token)
on_RPAREN(token)
tokenize(string)

Tokenize specified string.

Parameters

stringstr

The string to tokenize kat script from.

Yields

KatToken

The next token read from string.

tokenize_file(fobj)

Generate tokens from the given file.

Parameters

fobjio.FileIO

The file object to tokenize kat script from. This should be opened in text mode.

Yields

KatToken

The next token read from fobj.

finesse.script.tokens module

Regular expressions for matching tokens of different types in kat script.

Any new token types added here should be added to tokenizer.py and highlighter.py as well.

finesse.script.tokens.any(*choices)

Specify that there should be zero or more of the specified choices.

finesse.script.tokens.group(*choices)

Match any of the specified choices.

finesse.script.tokens.maybe(*choices)

Specify that there should be zero or one of the specified choices.

finesse.script.util module

Kat script utility functions.

finesse.script.util.duplicates(items, key=None)

Get duplicate keys and values in the 1D sequence items.

Parameters

itemssequence

The sequence to find duplicates in.

keycallable, optional

The key function to use for comparisons. If not specified, defaults to the identity function.

Returns

list

The duplicates in items. This is a sequence of tuples containing the result of the key function for each entry of items, where at least two such keys exist, and the original items that matched that key.

Examples

>>> [k for k, _ in duplicates("AAAABBCDAAB")]
["A", "B", "C", "D"]
>>> [list(g) for _, g in duplicates("AAAABBCDAAB")]
[["A", "A", "A", "A", "A", "A"], ["B", "B", "B"], ["C"], ["D"]]
finesse.script.util.index_ranges(intlist)

Create a sequence of range strings from a sequence of integers.

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

Parameters

intlistsequence

Integers to convert to range strings.

Yields

str

The next range string.

Examples

>>> list(index_ranges([1, 2, 4, 5, 6, 7, 9]))
["1-2", "4-7", "9"]
finesse.script.util.merge_attributes(attr1, attr2)

Perform a deep attribute dictionary merge.

This merges list and tuples in attr1 and attr2 into one dict. Values that are not lists or tuples result in an error. Items in attr1 appear before those in attr2 where they share the same key.

Parameters

attr1, attr2dict

The attribute dictionaries to merge.

Returns

dict

The merged attribute dictionary.

Raises

ValueError

If a dict value in attr1 or attr2 is not a list or tuple.

finesse.script.util.scriptsorted(items, reverse=False)

Sort container items by their script position.

Parameters

itemssequence of TokenContainer

The container items to sort.

reversebool, optional

Request the result in descending instead of ascending order.

Returns

list of TokenContainer

Container items sorted by line number then column.

Module contents

Parsing and unparsing of Finesse kat files and models.

finesse.script.parse(text, model=None, spec=None)

Parse KatScript into a model.

Parameters

textstr

The KatScript to parse.

modelModel, optional

The Finesse model to add the parsed objects to. Defaults to a new, empty model.

specKatSpec, optional

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

Returns

Model

The parsed model.

finesse.script.parse_file(path, model=None, spec=None)

Parse KatScript from a file into a model.

Parameters

pathstr or io.FileIO

The path or file object to read KatScript 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.

modelModel, optional

The Finesse model to add the parsed objects to. Defaults to a new, empty model.

specKatSpec, optional

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

Returns

Model

The parsed model.

finesse.script.parse_legacy(text, model=None, ignored_blocks=None)

Parse KatScript into a model.

Parameters

textstr

The KatScript to parse.

modelModel

The Finesse model to add the parsed objects to.

ignored_blockslist, optional

A list of names of FTBLOCK sections in the kat code to leave out of the model; defaults to empty list.

Returns

Model

The parsed model.

Raises

NotImplementedError

If model contains any non-default elements. Parsing into existing models is unsupported.

finesse.script.parse_legacy_file(path, model=None, ignored_blocks=None)

Parse KatScript from a file into a model.

Parameters

pathstr or io.FileIO

The path or file object to read KatScript 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.

modelModel

The Finesse model to add the parsed objects to.

ignored_blockslist, optional

A list of names of FTBLOCK sections in the kat code to leave out of the model; defaults to empty list.

Returns

Model

The parsed model.

Raises

NotImplementedError

If model contains any non-default elements. Parsing into existing models is unsupported.

finesse.script.syntax(query='', spec=None, verbose=False, elements=True, commands=True, analyses=True, keyword_arguments=True, exact=False, suggestions=True, **kwargs)

Query the KatScript syntax documentation for query.

Supports simple wildcard characters:

  • * matches 0 or more characters

  • ? matches any single character

  • [abc] matches any characters in abc

  • [!abc] matches any characters not in abc

If there is a . in query, everything before that is assumed to be a directive and everything after to be a parameter.

A * is added to the end of each query term, set exact to False to prevent this.

If no match is found some suggestions will be shown. Set suggestions to False to disable suggestions.

If query is an empty string all syntax documentation will be shown.

For more detailed help try finesse.help().

Parameters

querystr

The directive to retrieve syntax for.

specKatSpec, optional

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

verbosebool, default False

Show documentation for the directive.

elementsbool, default True

Whether to search for elements.

commandsbool, default True

Whether to search for commands.

analysesbool, default True

Whether to search for analyses.

keyword_argumentsbool, default True

Show keyword arguments where supported.

exactbool, default False

If True only documentation for an exact match will be shown.

suggestionsbool, default True

Whether to show suggestions if no match is found.

Other Parameters

kwargsdict, optional

Keyword arguments supported by ItemDocumenter.syntax().

Returns

str

The syntax for query.

finesse.script.unparse(item, warnings=True, **kwargs)

Serialise a Finesse object (such as a model) to KatScript.

Parameters

itemobject

A Finesse object (such as a Model) to generate KatScript for.

Returns

str

The generated KatScript.

finesse.script.unparse_file(path, item, **kwargs)

Serialise a model to KatScript in a file.

Parameters

pathstr

The kat file path to parse.

itemobject

A Finesse object (such as a Model) to generate KatScript for.

Returns

str

The generated KatScript.