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:
objectA set of analysis parameters and metadata.
- adapter: ItemAdapter
- 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
- adapter
ItemAdapter The adapter corresponding to this getter.
- analysis
Action The action to dump.
Yields
AnalysisDumpObject containing a mapping of keyword argument names to
ArgumentDumpobjects and whether they are all default values.
- adapter
- class finesse.script.adapter.AnalysisFactory(*, item_type)
Bases:
ItemFactory
- class finesse.script.adapter.AnalysisSetter(*, item_type, **kwargs)
- 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:
objectA generic instruction argument.
This is similar but not identical to
inspect.Parameter. Arguments in the Finesse sense are more general thaninspect.Parametersince 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
- 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:
ArgumentA 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.
- value
alias of
_empty
- class finesse.script.adapter.ArgumentType(*values)
Bases:
EnumSignature argument types.
While we just copy those defined by
inspect, note that the definitions here are more abstract than those ofinspect: 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:
ArgumentA concrete argument originating from a call to a setter.
This is the same as
Argumentexcept 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.
- class finesse.script.adapter.CommandDump(adapter: ItemAdapter, parameters: List[ArgumentDump] | List[List[ArgumentDump]], is_default: bool)
Bases:
objectA set of command parameters and metadata.
- adapter: ItemAdapter
- 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)
- class finesse.script.adapter.CommandPropertyDocumenter(*, item_type, **kwargs)
Bases:
CommandMethodDocumenter
- class finesse.script.adapter.CommandPropertyDumper(*, item_type, default=<class 'finesse.script.adapter._empty'>, **kwargs)
- 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:
objectA set of element parameters and metadata.
- adapter: ItemAdapter
- element: ModelElement
- parameters: List[ArgumentDump] | List[List[ArgumentDump]]
- class finesse.script.adapter.ElementDumper(*, item_type, **kwargs)
- class finesse.script.adapter.ElementFactory(last=False, **kwargs)
Bases:
ItemFactory
- class finesse.script.adapter.ElementSetter(*, item_type, **kwargs)
- 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:
objectAdapter 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
Laserfrom a laser l1 … instruction), to add it to aModel(or in the case of commands, set some model attribute), to dump that Python object back to script, and to generate documentation.Parameters
- full_name
str The instruction’s unabbreviated name. This must be alphanumeric and can contain underscores but no spaces.
- short_name
str, 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.
- getter
ItemDumper, optional Object handling the retrieval of parameters from the Python object corresponding to this instruction.
- factory
ItemFactory, optional Object handling the creation of the Python object corresponding to this instruction.
- setter
ItemSetter, optional Object handling the setting of parameters in the Python object corresponding to this instruction’s parameters.
- documenter
ItemDocumenter Object handling the retrieval of docstrings and syntax suggestions for the instruction.
- singular
bool, optional Flag indicating that this instruction can be defined only once per script. Defaults to False.
- build_last
bool, 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.
- full_name
- 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:
objectRoot class for all dumper, setter, factory and documenter objects.
- class finesse.script.adapter.ItemSetter(*, item_type)
Bases:
ItemHandler- bind_argument(name_or_index)
Return a bound argument object for name.
Parameters
Returns
BoundArgumentThe argument metadata corresponding to name_or_index.
- keyword_args(only=False)
The non-positional-only arguments of the call signature.
Parameters
- only
bool, optional Only include keyword-only arguments; defaults to False.
Returns
dictThe call object’s keyword parameters.
- only
- positional_args(only=False, keyword_defaults=True)
The non-keyword-only arguments of the call signature.
Parameters
Returns
dictThe 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.
- argument
BoundArgument 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
dictMapping 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:
objectMixin 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:
SignatureArgumentMixinMixin 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
ArgumentDumpobjects 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:
objectKat model compiler.
- compile(string, **kwargs)
Compile the contents of string.
Parameters
- string
str The string to compile kat script from.
Other Parameters
- kwargs
Keyword arguments supported by
compile_file().
Returns
ModelThe model compiled from reading string.
- string
- compile_file(fobj, model=None, resolve=True, build=True)
Compile the contents of the specified file.
Parameters
- fobj
io.FileIO The file object to compile kat script from. This should be opened in text mode.
- model
Model, optional An existing model to compile the contents of fobj into. If not specified, a new, empty model is created.
- resolve
bool, 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.
- build
bool, 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
Modelor NoneIf resolve and build are True, the model compiled from reading fobj; None otherwise.
Raises
KatSyntaxErrorIf a syntax error is present in the contents of fobj.
- fobj
- property script
- exception finesse.script.compiler.KatCycleError(script, cyclic_nodes)
Bases:
KatScriptErrorCyclic parameters.
- exception finesse.script.compiler.KatDirectiveBuildError(error, directive, script, statement_node, adapter, graph, spec)
Bases:
KatDirectiveErrorError 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:
KatScriptErrorError compiling a directive (either resolving or building).
- exception finesse.script.compiler.KatIncorrectFormError(user_directive_token, script, spec)
Bases:
KatSyntaxErrorError 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:
KatScriptErrorError during the building of a directive parameter.
finesse.script.containers module
Token and production containers for use in the tokenizer and parser.
- class finesse.script.containers.Addressable
Bases:
objectMixin defining interface to retrieve strings containing script lines.
- 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
- bounds
KatBounds, optional Bounds within which to retrieve script. Defaults to the whole script.
Returns
strThe script.
- bounds
- script_lines(bounds)
The script within bounds by line.
Parameters
- bounds
KatBounds The bounds to retrieve script between.
Returns
listLines 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.
- bounds
- 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:
TokenContainerMixin for containers that contain arguments.
- arguments: List[TokenContainer]
- class finesse.script.containers.BaseCustomToken(lineno: int, start_index: int, stop_index: int, type: str, raw_value: Any)
Bases:
KatTokenA custom token.
- class finesse.script.containers.ExtraTokenContainer(extra: List[KatToken])
Bases:
TokenContainerMixin for containers that contain extra tokens.
- class finesse.script.containers.KatArray(extra: List[KatToken], arguments: List[TokenContainer])
Bases:
ArgumentContainer,ExtraTokenContainer,TokenContainerRepresents a kat script array.
- class finesse.script.containers.KatBooleanToken(lineno: int, start_index: int, stop_index: int, type: str, raw_value: Any)
Bases:
BaseCustomTokenA boolean token.
- property value
- class finesse.script.containers.KatBounds(start: KatCoordinate, stop: KatCoordinate)
Bases:
objectKat 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
boolTrue if empty, False otherwise.
- lcontract(newstart)
Contract start boundary.
Parameters
- newstart
KatCoordinate The new start coordinate.
Returns
KatBoundsThe contracted bounds.
Raises
- ValueError
If newstart is not >= current start coordinate.
- newstart
- lexpand(newstart)
Expand start boundary.
Parameters
- newstart
KatCoordinate The new start coordinate.
Returns
KatBoundsThe expanded bounds.
Raises
- ValueError
If newstart is not <= current start coordinate.
- newstart
- rcontract(newstop)
Contract stop boundary.
Parameters
- newstop
KatCoordinate The new stop coordinate.
Returns
KatBoundsThe contracted bounds.
Raises
- ValueError
If newstop is not <= current stop coordinate.
- newstop
- rexpand(newstop)
Expand stop boundary.
Parameters
- newstop
KatCoordinate The new stop coordinate.
Returns
KatBoundsThe expanded bounds.
Raises
- ValueError
If newstop is not >= current stop coordinate.
- newstop
- start: KatCoordinate
- stop: KatCoordinate
- class finesse.script.containers.KatCoordinate(lineno: int, index: int)
Bases:
objectKat script file coordinate supporting comparison operations.
- class finesse.script.containers.KatElement(directive: KatToken, extra: List[KatToken], arguments: List[TokenContainer], name: KatToken)
Bases:
ArgumentContainer,ExtraTokenContainer,KatScriptItemRepresents 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.
- property node_name
- property tokens
Tokens contained in the container.
- property unique_name_token
- class finesse.script.containers.KatExpression(extra: List[KatToken], arguments: List[TokenContainer], operator: KatToken)
Bases:
ArgumentContainer,ExtraTokenContainer,TokenContainerRepresents a kat script expression.
- property lhs
- property rhs
- class finesse.script.containers.KatFile(text: str)
Bases:
AddressableContainer with kat script lines (no concrete tokens).
- class finesse.script.containers.KatFixMeToken(lineno: int, start_index: int, stop_index: int, type: str, raw_value: Any)
Bases:
BaseCustomTokenA “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,KatScriptItemRepresents 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,TokenContainerRepresents 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:
TokenContainerRepresents a kat argument containing a key, value and ‘=’.
- property tokens
Tokens contained in the container.
- value: KatToken | KatFunction | KatExpression | KatGroupedExpression | KatArray
- class finesse.script.containers.KatMetaToken(lineno: int, start_index: int, stop_index: int, type: str)
Bases:
TokenMixinA token that may not map to a real token.
Meta tokens are employed by
KatTokenizerwhen 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:
BaseCustomTokenA null token.
- property value
- class finesse.script.containers.KatNumberToken(lineno: int, start_index: int, stop_index: int, type: str, raw_value: Any)
Bases:
BaseCustomTokenA number token.
- SI_NUMBER_PATTERN = re.compile('.*[pnumkMGT]$')
- property value
- class finesse.script.containers.KatNumericalArray(extra: List[KatToken], arguments: List[TokenContainer])
Bases:
KatArrayRepresents 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,TokenContainerRepresents a kat script.
- class finesse.script.containers.KatScriptItem(directive: KatToken)
Bases:
TokenContainerRepresents a top level kat script item.
- 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.
- abstract property unique_name_token
- class finesse.script.containers.KatStringToken(lineno: int, start_index: int, stop_index: int, type: str, raw_value: Any)
Bases:
BaseCustomTokenA string token.
- property value
- class finesse.script.containers.KatToken(lineno: int, start_index: int, stop_index: int, type: str, raw_value: Any)
Bases:
TokenMixinA real token with the corresponding text’s location, type and value.
- property display_value
- to_meta()
Convert token to a meta token.
Returns
KatMetaTokenThe current token, as a meta token.
- to_new_position(start)
Copy token, updating its start (and stop) position.
Parameters
- start
KatCoordinate The token’s new start position.
Returns
KatTokenNew copy of self, with updated start position.
- start
- property value
- class finesse.script.containers.KatWhitespaceToken(lineno: int, start_index: int, stop_index: int, type: str, raw_value: Any)
Bases:
BaseCustomTokenA whitespace token.
- property display_value
- class finesse.script.containers.TokenContainer
Bases:
AddressableContainer with concrete token instances.
- property first_token
First container token by coordinate.
- Getter:
first
KatTokenwithin this container.
- property last_token
Last container token by coordinate.
- Getter:
last
KatTokenwithin this container.
- property sorted_tokens
Tokens contained in the container, in ascending coordinate order.
- class finesse.script.containers.TokenMixin(lineno: int, start_index: int, stop_index: int, type: str)
Bases:
TokenContainerA class that provides functionality shared by
KatMetaTokenandKatToken.Injected this way to prevent
KatTokeninheriting fromKatMetaToken, which would be confusing since they are both tokens, but one represent real tokens while the other does not.- property tokens
Tokens contained in the container.
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:
KatSyntaxErrorError for when an element name or function ‘(’ is missing.
- exception finesse.script.exceptions.KatParsingError(message, **kwargs)
Bases:
FinesseExceptionAn 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:
UserWarningWarns 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:
UserWarningA warning during the parsing, indicating that exceptions might occur later.
- exception finesse.script.exceptions.KatScriptError(error, container, error_items, syntax=None)
Bases:
KatParsingErrorDetailed kat script error.
Parameters
- errorstr or
Exception The error or error message.
- container
Addressable 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
Addressableobjects 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.- syntax
str, 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
- property error_lines
- items_to_linemarkers(items)
- message()
- rubric()
- errorstr or
- exception finesse.script.exceptions.KatSyntaxError(message, script, token)
Bases:
KatScriptErrorError with kat syntax.
finesse.script.generator module
Kat script generator.
- class finesse.script.generator.CommandContainer(adapter, params)
Bases:
objectContainer for top level commands, used by the generator.
- class finesse.script.generator.ElementContainer(element)
Bases:
objectContainer for top level model elements, used by the generator.
- class finesse.script.generator.KatUnbuilder(show_warnings=True, spec=None)
Bases:
objectModel to KatScript converter.
This class defines single-dispatch methods to recursively fill Finesse objects into a
KatGraph. The graph is then serialised to KatScript viaKatUnfiller.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
Modeltounbuild()orunbuild_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
Parameterobjects. 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
- fobj
io.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
Modelbut can be any Finesse object.- ref_graph
KatGraph, 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_node
str, 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
ValueErroris raised.- directive_defaults
bool, 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_defaults
bool, 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_keywords
bool, 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.
- fobj
- class finesse.script.generator.KatUnfiller
Bases:
objectKatGraph to kat script.
- production(node, graph)
- unfill(node, graph)
- unfill_file(fobj, node, graph)
finesse.script.graph module
Graph represening a parsed kat script file.
- class finesse.script.graph.KatGraph(*args, backend=None, **kwargs)
Bases:
DiGraphKat 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
BoundArgumentThe 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 whereindexis 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_statecan be omitted to signify no state transition. Ifnew_stateis a string, it is pushed on the stack. This ensure the new current state isnew_state. Ifnew_stateis 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_statecan also becombined('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:
objectKat 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.
- model
Model, optional Model object to add components to. If not specified, a new model will be created.
- ignored_blockslist, optional
A list of names of
FTBLOCKsections in the kat code to leave out of the model; defaults to empty list.
Returns
ModelThe constructed model.
Raises
KatParserErrorIf 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.
- model
Model, 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
KatParserErrorIf an error occurs during parsing or building.
- pathstr or
- exception finesse.script.legacy.KatParserError(errors, text, **kwargs)
Bases:
FinesseExceptionKat 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:
objectKat 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
KatScriptItemobjects containing the associatedtokens.- 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
- string
str The string to parse kat script from.
Returns
KatScriptThe parsed kat script.
- string
- parse_file(fobj)
Parse the contents of the specified file.
Parameters
- fobj
io.FileIO The file object to parse kat script from. This should be opened in text mode.
Returns
KatScriptThe parsed kat script.
- fobj
- 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.FsigDocumenter
Bases:
FsigArgumentsMixin,CommandMethodDocumenter- argument_descriptions()
The types and descriptions for each argument as parsed from the docstring.
Returns
dictMapping 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:
ItemDumperDumper for the
Gausscomponent.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:
objectKatScript 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(), andregister_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
KATSPECshould 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.
- 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.
- 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
- adapter
ItemAdapter 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
KeyErroris raised. Defaults to False.
- adapter
- register_command(adapter, **kwargs)
Add parser and generator support for a command.
Parameters
- adapter
ItemAdapter 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
KeyErroris raised. Defaults to False.
- adapter
- register_element(adapter, **kwargs)
Add parser and generator support for a model element such as a component or detector.
Parameters
- adapter
ItemAdapter 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
KeyErroris raised. Defaults to False.
- adapter
- 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:
- 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
dictMapping 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:
ItemDumperVariable 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:
objectKat 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
- on_LBRACKET(token)
- on_LPAREN(token)
- on_NEWLINE(token)
- on_RBRACKET(token)
- on_RPAREN(token)
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.
- itemssequence of
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
Returns
ModelThe 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.
- model
Model, optional The Finesse model to add the parsed objects to. Defaults to a new, empty model.
- spec
KatSpec, optional The language specification to use. Defaults to the shared
KatSpecinstance.
Returns
ModelThe parsed model.
- pathstr or
- finesse.script.parse_legacy(text, model=None, ignored_blocks=None)
Parse KatScript into a model.
Parameters
- textstr
The KatScript to parse.
- model
Model The Finesse model to add the parsed objects to.
- ignored_blockslist, optional
A list of names of
FTBLOCKsections in the kat code to leave out of the model; defaults to empty list.
Returns
ModelThe 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.
- model
Model The Finesse model to add the parsed objects to.
- ignored_blockslist, optional
A list of names of
FTBLOCKsections in the kat code to leave out of the model; defaults to empty list.
Returns
ModelThe parsed model.
Raises
- NotImplementedError
If model contains any non-default elements. Parsing into existing models is unsupported.
- pathstr or
- 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.
- spec
KatSpec, optional The language specification to use. Defaults to the shared
KatSpecinstance.- 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.