chimerax.core.commands: Application command line support

cli: Command line interface

This module provides a method for parsing text commands and calling the functions that implement them. First, commands are registered with a description of the arguments they take, and with a function that implements the command. Later, a Command instance is used to parse a command line, and optionally execute the command. Incomplete command lines are supported, so possible commands can be suggested.

In addition to registering command functions, there is a separate mechanism to support textual Command Aliases.

Text Commands

Synopsis:

command_name rv1 rv2 [ov1 [ov2]] [kn1 kv1] [kn2 kv2]

Text commands are composed of a command name, which can be multiple words, followed by required positional arguments, rvX, optional positional arguments, ovX, and keyword arguments with a value, knX kvX. Each argument has an associated Python argument name (for keyword arguments it is the keyword, knX). rvX, ovX, and kvX are the type-checked values. If the argument name is the same as a Python keyword, then an underscore appended to it to form the Python argument name. The names of the optional arguments are used to let them be given as keyword arguments as well. Multiple value arguments are separated by commas and the commas may be followed by whitespace. Depending on the type of an argument, e.g., a color name, whitespace can also appear within an argument value. Argument values may be quoted with double quotes. And in quoted text, Python’s textual escape sequences are recognized, e.g., \N{LATIN CAPITAL LETTER A WITH RING ABOVE} for the ångström sign, Å.

Words in the command name may be truncated and are automatically completed to the first registered command with the given prefix. Likewise for keyword arguments.

Keywords are case sensitive, and are expected to be all lowercase. Underscores are elided, but are documented as mixed case. For example, a bg_color keyword would be documented as bgColor.

Registering Commands

To add a command, register() the command name, a description of the arguments it takes, and the function to call that implements the command. Command registration can be partially delayed to avoid importing the command description and function until needed. See register() and delay_registration() for details.

The description is either an instance of the Command Description class, CmdDesc, or a tuple with the arguments to the initializer. The CmdDesc initializer takes tuples describing the required, optional, and keyword arguments. Each tuple contains tuples with the argument name and a type annotation (see below). Postconditions (see below) can be given too.

Command Functions

The command function arguments are expected to start with a session argument. The rest of the arguments are assembled as keyword arguments, as built from the command line and the command description. The initial session argument to a command function is not part of the command description.

Type Annotations

There are many standard type notations and they should be reused as much as possible:

Type Annotation
bool BoolArg
float FloatArg
int IntArg
str StringArg
tuple of 3 bool Bool3Arg
tuple of 3 float Float3Arg
tuple of 3 int Int3Arg
list of float FloatsArg
list of int IntsArg

There is one special annotation: RestOfLine that consumes the rest of the command line as text.

Annotations are used to parse text and convert it to the appropriate type. Annotations can be extended with various specializers:

Specializer Example
Bounded Bounded(FloatArg, 0.0, 100.0)
ListOf ListOf(FloatArg) a.k.a., FloatsArg
SetOf SetOf(IntArg)
TupleOf TupleOf(FloatArg, 3) a.k.a., Float3Arg
Or Or(FloatArg, StringArg) discouraged
EnumOf enumerated values

Creating Your Own Type Annotation

Annotations perform several functions: (1) to convert text to a value of the appropriate type, and (2) to give reasonable error messages.

See the Annotation documentation for details.

Example

Here is a simple example:

import from chimerax.core.commands import Command, CmdDesc, RestOfLine
import from chimerax.core import errors
@register("echo", CmdDesc(optional=[('text', RestOfLine)]))
def echo(session, text=''):
    print(text)
...
command = Command(session)
try:
    status = command.run(text)
    if status:
        print(status)
except errors.UserError as err:
    print(err, file=sys.stderr)

Command Aliases

Normally, command aliases are made with the alias command, but they can also be explicitly register with alias() and removed with remove_alias().

An alias definition uses $n to refer to passed in arguments. $1 may appear more than once. $$ is $.

To register a multiword alias, quote the command name.

class Aggregate(annotation, min_size=None, max_size=None, name=None, url=None, prefix=None)

Bases: Annotation

Common class for collections of values.

Aggregate(annotation, constructor, add_to, min_size=None, max_size=None,
name=None, url=None) -> annotation
Parameters:
  • annotation – annotation for values in the collection.
  • min_size – minimum size of collection, default None.
  • max_size – maximum size of collection, default None.
  • name – optionally override name in error messages.
  • url – optionally give documentation URL.
  • prefix – optionally required prefix to aggregate.

This class is typically used via ListOf, SetOf, or TupleOf. The comma separator for aggregate values is handled by the Command class, so parsing is delegated to the underlying annotation.

Subclasses need to set the constructor attribute and replace the add_to method.

add_to(container, element)

Experimental API . Add to add an element to the container

Parameters:
  • container – the container to add elements to
  • element – the element to add to the container
Returns:

None for mutable containers, or a new container if immutable.

parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class Alias(text, *, user=False, registry=None)

Bases: object

alias a command

Returns a callable unnamed command alias.

Parameters:
  • text – parameterized command text
  • user – true if alias was generated by user

The text is scanned for $n, where n is the n-th argument, $* for the rest of the line, and $$ for a single $.

cmd_desc(**kw)

Experimental API . Return CmdDesc instance for alias

The CmdDesc keyword arguments other than ‘required’, ‘optional’, and ‘keyword’ can be used.

class Annotation(name=None, url=None, html_name=None)

Bases: object

Base class for all annotations

Each annotation should have the following attributes:

name

Set to textual description of the annotation, including the leading article, e.g., “an integer”.

inst_html_name(name=None)

Experimental API . Subclasses that are to be used as instances, should set their html_name method to be Annotation.inst_html_name

name = None

Experimental API . article name, e.g., “an integer”

static parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

url = None

Experimental API . URL for help information

exception AnnotationError(message, offset=None)

Bases: UserError, ValueError

Error, with optional offset, in annotation

class AttrNameArg(name=None, url=None, html_name=None)

Bases: StringArg

Annotation for a Python attribute name

static parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class AxisArg(name=None, url=None, html_name=None)

Bases: Annotation

Annotation for axis vector that can be 3 floats or “x”, or “y”, or “z” or two atoms.

static parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class BoolArg(name=None, url=None, html_name=None)

Bases: Annotation

Annotation for boolean literals

static parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class Bounded(annotation, min=None, max=None, name=None, url=None, html_name=None)

Bases: Annotation

Support bounded numerical values

Bounded(annotation, min=None, max=None, name=None, url=None) -> an Annotation

Parameters:
  • annotation – numerical annotation
  • min – optional lower bound
  • max – optional upper bound
  • name – optional explicit name for annotation
  • url – optionally give documentation URL.
parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class CenterArg(name=None, url=None, html_name=None)

Bases: Annotation

Annotation for a center point that can be 3 floats or objects.

static parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class CmdDesc(required=(), optional=(), keyword=(), postconditions=(), required_arguments=(), non_keyword=(), hidden=(), url=None, synopsis=None)

Bases: object

Describe command arguments.

Parameters:
  • required – required positional arguments sequence
  • optional – optional positional arguments sequence
  • keyword – keyword arguments sequence
  • required_arguments – sequence of argument names that must be given
  • non_keyword – sequence of optional arguments that cannot be keywords
  • hidden – sequence of keyword arguments that should be omitted from usage
  • url – URL to help page
  • synopsis – one line description

Each :param required:, :param optional:, :param keyword: sequence contains 2-tuples with the argument name and a type annotation. The command line parser uses the :param optional: argument names as additional keyword arguments. :param required_arguments: are for Python function arguments that don’t have default values, but should be given on the command line (typically keyword arguments, but could be used for syntactically optional arguments).

copy()

Experimental API . Return a copy suitable for use with another function.

class Command(session, *, registry=None)

Bases: object

Keep track of (partially) typed command with possible completions

Parameters:session – the session to run the command in (may be None for testing)
run(text, *, log=True, _used_aliases=None)

Experimental API . Parse and execute commands in the text

Parameters:
  • text – The text to be parsed.
  • log – True (default) if commands are logged.

There are a couple side effects:

  • The automatically completed text is put in self.current_text.
  • Possible completions are in self.completions.
  • The prefix of the completions is in self.completion_prefix.
class CoordSysArg(name=None, url=None, html_name=None)

Bases: ModelArg

Annotation for coordinate system for AxisArg and CenterArg when specified as tuples of numbers. Coordinate system is specified as a Model specifier.

classmethod parse(text, session)

Experimental API . Parse text and return an atomspec parse tree

class DottedTupleOf(annotation, min_size=None, max_size=None, name=None, url=None, prefix=None)

Bases: Aggregate

Annotation for dot-separated lists of a single type

DottedListOf(annotation, min_size=None, max_size=None) -> annotation

add_to(container, value)

Experimental API . Add to add an element to the container

Parameters:
  • container – the container to add elements to
  • element – the element to add to the container
Returns:

None for mutable containers, or a new container if immutable.

constructor

alias of builtins.tuple

class DynamicEnum(values_func, name=None, url=None, html_name=None)

Bases: Annotation

Enumerated type where enumeration values computed from a function.

parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class EmptyArg(name=None, url=None, html_name=None)

Bases: Annotation

Annotation for optionally missing ‘required’ argument

static parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class EnumOf(values, ids=None, abbreviations=None, name=None, url=None)

Bases: Annotation

Support enumerated types

EnumOf(values, ids=None, name=None, url=None) -> an Annotation

Parameters:
  • values – iterable of values
  • ids – optional iterable of identifiers
  • abbreviations – if not None, then override allow_truncated
  • name – optional explicit name for annotation
  • url – optionally give documentation URL.

If the ids are given, then there must be one for each and every value, otherwise the values are used as the identifiers. The identifiers must all be strings.

parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class FileNameArg(name=None, url=None, html_name=None)

Bases: Annotation

Base class for Open/SaveFileNameArg

classmethod parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class FloatArg(name=None, url=None, html_name=None)

Bases: Annotation

Annotation for floating point literals

static parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class IntArg(name=None, url=None, html_name=None)

Bases: Annotation

Annotation for integer literals

static parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class Limited(arg_name, min=None, max=None)

Bases: Postcondition

Bounded numerical values postcondition

Limited(name, min=None, max=None) -> Postcondition

Parameters:
  • arg_name – name of argument to check
  • min – optional inclusive lower bound
  • max – optional inclusive upper bound

If possible, use the Bounded annotation because the location of the error is the beginning of the argument, not the end of the line.

check(kw_args)

Experimental API . Assert arguments match postcondition

Parameters:kw_args – dictionary of arguments that will be passed to command callback function.
Returns:True if arguments are consistent
error_message()

Experimental API . Appropriate error message if check fails.

Returns:error message
class ListOf(annotation, min_size=None, max_size=None, name=None, url=None, prefix=None)

Bases: Aggregate

Annotation for lists of a single type

ListOf(annotation, min_size=None, max_size=None) -> annotation

add_to(container, value)

Experimental API . Add to add an element to the container

Parameters:
  • container – the container to add elements to
  • element – the element to add to the container
Returns:

None for mutable containers, or a new container if immutable.

constructor

alias of builtins.list

class ModelArg(name=None, url=None, html_name=None)

Bases: AtomSpecArg

Parse command model specifier

classmethod parse(text, session)

Experimental API . Parse text and return an atomspec parse tree

class ModelsArg(name=None, url=None, html_name=None)

Bases: AtomSpecArg

Parse command models specifier

classmethod parse(text, session)

Experimental API . Parse text and return an atomspec parse tree

class NoArg(name=None, url=None, html_name=None)

Bases: Annotation

Annotation for keyword whose presence indicates True

static parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class NoneArg(name=None, url=None, html_name=None)

Bases: Annotation

Annotation for ‘none’ (typically used with Or)

static parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class ObjectsArg(name=None, url=None, html_name=None)

Bases: AtomSpecArg

Parse command objects specifier

classmethod parse(text, session)

Experimental API . Parse text and return an atomspec parse tree

class OpenFileNameArg(name=None, url=None, html_name=None)

Bases: FileNameArg

Annotation for a file to open

classmethod parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class OpenFolderNameArg(name=None, url=None, html_name=None)

Bases: FileNameArg

Annotation for a folder to open from

classmethod parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class Or(*annotations, name=None, url=None, html_name=None)

Bases: Annotation

Support two or more alternative annotations

Or(annotation, annotation [, annotation]*, name=None, url=None) -> an Annotation

Parameters:
  • name – optional explicit name for annotation
  • url – optionally give documentation URL.
parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class PasswordArg(name=None, url=None, html_name=None)

Bases: StringArg

Annotation for a password (should not be echoed to log)

static parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class PlaceArg(name=None, url=None, html_name=None)

Bases: Annotation

Annotation for positioning matrix as 12 floats defining a 3 row, 4 column matrix where the first 3 columns are x,y,z coordinate axes, and the last column is the origin.

static parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class Postcondition

Bases: object

Base class for postconditions

check(kw_args)

Experimental API . Assert arguments match postcondition

Parameters:kw_args – dictionary of arguments that will be passed to command callback function.
Returns:True if arguments are consistent
error_message()

Experimental API . Appropriate error message if check fails.

Returns:error message
class RepeatOf(annotation)

Bases: Annotation

Annotation for keyword options that can occur multiple times.

RepeatOf(annotation) -> annotation

Option values are put in list even if option occurs only once.

class RestOfLine(name=None, url=None, html_name=None)

Bases: Annotation

Return the rest of the line up to a semicolon

static parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class SameSize(name1, name2)

Bases: Postcondition

Postcondition check for same size arguments

SameSize(name1, name2) -> a SameSize object

Parameters:
  • name1 – name of first argument to check
  • name2 – name of second argument to check
check(kw_args)

Experimental API . Assert arguments match postcondition

Parameters:kw_args – dictionary of arguments that will be passed to command callback function.
Returns:True if arguments are consistent
error_message()

Experimental API . Appropriate error message if check fails.

Returns:error message
class SaveFileNameArg(name=None, url=None, html_name=None)

Bases: FileNameArg

Annotation for a file to save

classmethod parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class SaveFolderNameArg(name=None, url=None, html_name=None)

Bases: FileNameArg

Annotation for a folder to save to

classmethod parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class SetOf(annotation, min_size=None, max_size=None, name=None, url=None, prefix=None)

Bases: Aggregate

Annotation for sets of a single type

SetOf(annotation, min_size=None, max_size=None) -> annotation

add_to(container, value)

Experimental API . Add to add an element to the container

Parameters:
  • container – the container to add elements to
  • element – the element to add to the container
Returns:

None for mutable containers, or a new container if immutable.

constructor

alias of builtins.set

class StringArg(name=None, url=None, html_name=None)

Bases: Annotation

Annotation for text (a word or quoted)

static parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

class SurfaceArg(name=None, url=None, html_name=None)

Bases: SurfacesArg

Parse command surfaces specifier

classmethod parse(text, session)

Experimental API . Parse text and return an atomspec parse tree

class SurfacesArg(name=None, url=None, html_name=None)

Bases: ModelsArg

Parse command surfaces specifier

classmethod parse(text, session)

Experimental API . Parse text and return an atomspec parse tree

class TopModelsArg(name=None, url=None, html_name=None)

Bases: AtomSpecArg

Parse command models specifier

classmethod parse(text, session)

Experimental API . Parse text and return an atomspec parse tree

class TupleOf(annotation, size, name=None, url=None)

Bases: Aggregate

Annotation for tuples of a single type

TupleOf(annotation, size) -> annotation

add_to(container, value)

Experimental API . Add to add an element to the container

Parameters:
  • container – the container to add elements to
  • element – the element to add to the container
Returns:

None for mutable containers, or a new container if immutable.

constructor

alias of builtins.tuple

class WholeRestOfLine(name=None, url=None, html_name=None)

Bases: Annotation

Return the whole rest of the line including semicolons

static parse(text, session)

Experimental API . Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

add_keyword_arguments(name, kw_info, *, registry=None)

Experimental API . Make known additional keyword argument(s) for a command

Parameters:
  • name – the name of the command (must not be an alias)
  • kw_info – { keyword: annotation }
command_function(name, no_aliases=False, *, registry=None)

Experimental API . Return callable for given command name

Parameters:
  • name – the name of the command
  • no_aliases – True if aliases should not be considered.
Returns:

the callable that implements the command

command_url(name, no_aliases=False, *, registry=None)

Experimental API . Return help URL for given command name

Parameters:
  • name – the name of the command
  • no_aliases – True if aliases should not be considered.
Returns:

the URL registered with the command

commas(text_seq, conjunction=' or')

Experimental API . Return comma separated list of words

Parameters:
  • text_seq – a sequence of text strings
  • conjunction – a word with a leading space
create_alias(name, text, *, user=False, logger=None, url=None, registry=None)

Experimental API . Create command alias

Parameters:
  • name – name of the alias
  • text – text of the alias
  • user – boolean, true if user created alias
  • logger – optional logger
delay_registration(name, proxy_function, logger=None)

Experimental API . delay registering a named command until needed

Parameters:
  • proxy_function – the function to call if command is used
  • logger – optional logger

The proxy function should explicitly reregister the command or register subcommands and return nothing.

Example:

from chimerax.core.commands import cli

def lazy_reg():
    import module
    cli.register('cmd subcmd1', module.subcmd1_desc, module.subcmd1)
    cli.register('cmd subcmd2', module.subcmd2_desc, module.subcmd2)

cli.delay_registration('cmd', lazy_reg)
deregister(name, *, is_user_alias=False, registry=None)

Experimental API . Remove existing command and subcommands

Parameters:name – the name of the command

If the command was an alias, the previous version is restored

discard_article(text)

Experimental API . remove leading article from text

dq_repr(obj)

Experimental API . Like repr, but use double quotes

expand_alias(name, *, registry=None)

Experimental API . Return text of named alias

Parameters:name – name of the alias
html_usage(name, no_aliases=False, show_subcommands=5, expand_alias=True, show_hidden=False, *, registry=None)

Experimental API . Return usage string in HTML for given command name

Parameters:
  • name – the name of the command
  • no_aliases – True if aliases should not be considered.
  • show_subcommands – number of subcommands that should be shown.
  • show_hidden – True if hidden keywords should be shown.
Returns:

a HTML usage string for the command

is_python_keyword()

Experimental API . x.__contains__(y) <==> y in x.

list_aliases(all=False, logger=None)

Experimental API . List all aliases

Parameters:all – if True, then only list all aliases, not just user ones

Return in depth-first order.

next_token(text, *, no_raise=False)

Experimental API . Extract next token from given text.

Parameters:text – text to parse without leading whitespace
Returns:a 3-tuple of first argument in text, the actual text used, and the rest of the text.

Tokens may be quoted, in which case the text between the quotes is returned.

ordinal(i)

Experimental API . Return ordinal number name of number

plural_form(seq, word, plural=None)

Experimental API . Return plural of word based on length of sequence

Parameters:
  • seq – a sequence of objects
  • word – word to form the plural of
  • plural – optional explicit plural of word, otherwise best guess
plural_of(word)

Experimental API . Return best guess of the American English plural of the word

Parameters:word – the word to form the plural version

The guess is rudimentary, e.g., it does not handle changing “leaf” to “leaves”. So in general, use the plural_form() function and explicitly give the plural.

quote_if_necessary(s)

Experimental API . quote a string

So :py:func`next_token` treats it like a single value

register(name, cmd_desc=(), function=None, *, logger=None, registry=None)

Experimental API . register function that implements command

Parameters:
  • name – the name of the command and may include spaces.
  • cmd_desc – information about the command, either an instance of CmdDesc, or the tuple with CmdDesc parameters.
  • function – the callback function.
  • logger – optional logger

If the function is None, then it assumed that register() is being used as a decorator.

registry is a RegisteredCommandInfo instance and is only used if you want your own separate registry of commands, to be parsed/executed on text you provide. One usage scenario is a set of “subcommands” organized under an “umbrella” command, e.g.:

sequence viewer <viewer-id> command-to-viewer

The ‘command-to-viewer’ commands could have their own separate registry.

To delay introspecting the function until it is actually used, register using the delay_registration() function.

registered_commands(multiword=False, _start=None)

Experimental API . Return a sorted list of the currently registered commands

remove_alias(name=None, user=False, logger=None, *, registry=None)

Experimental API . Remove command alias

Parameters:
  • name – name of the alias
  • user – boolean, true if user created alias

If no name is given, then all user generated aliases are removed.

unescape(text)

Experimental API . Replace backslash escape sequences with actual character.

Parameters:text – the input text
Returns:the processed text

Follows Python’s string literal syntax for escape sequences.

unescape_with_index_map(text)

Experimental API . Replace backslash escape sequences with actual character.

Parameters:text – the input text
Returns:the processed text and index map from processed to input text

Follows Python’s string literal syntax for escape sequences.

usage(name, no_aliases=False, show_subcommands=5, expand_alias=True, show_hidden=False, *, registry=None)

Experimental API . Return usage string for given command name

Parameters:
  • name – the name of the command
  • no_aliases – True if aliases should not be considered.
  • show_subcommands – number of subcommands that should be shown.
  • show_hidden – True if hidden keywords should be shown.
Returns:

a usage string for the command

atomspec: atom specifier cli annotation and evaluation

The ‘atomspec’ module provides two classes:

  • AtomSpecArg : command line argument annotation class.
  • AtomSpec : atom specifier class.

AtomSpecArg is a cli type annotation and is used to describe an argument of a function that is registered with the cli module. When the registered function is called, the argument corresponding to the AtomSpecArg is an instance of AtomSpec, which contains a parsed version of the input atom specifier. The model elements (atoms, bonds, models, etc) that match an AtomSpec may be found by calling the ‘evaluate’ method which returns an instance of Objects. Each type of model elements may be accessed as an attribute of the Objects instance.

Selectors

A (name, function) pair may be registered as a ‘selector’ in an atom specifier. The selectors may either be global (e.g., chemical groups) or session-specific (e.g., active site). The selector name may appear wherever a model, residue or atom string does. The selector function is called when the atom specifier is evaluated and is expected to fill in an Objects instance.

Example

Here is an example of a function that may be registered with cli:

from chimerax.core.commands import cli, atomspec

def move(session, by, modelspec=None):
    if modelspec is None:
        modelspec = atomspec.everything(session)
    spec = modelspec.evaluate(session)
    import numpy
    by_vector = numpy.array(by)
    from chimerax.core.geometry import place
    translation = place.translation(by_vector)
    for m in spec.models:
        m.position = translation * m.position
move_desc = cli.CmdDesc(required=[("by", cli.Float3Arg)],
                        optional=[("modelspec", atomspec.AtomSpecArg)])

Notes

AtomSpecArg arguments should always be optional because not providing an atom specifier is the same as choosing all atoms.

class AtomSpec(operator, left_spec, right_spec)

Bases: object

AtomSpec instances store and evaluate atom specifiers.

An AtomSpec instance, returned by AtomSpecArg arguments in cli command functions, keeps track of an atom specifier. When evaluated, the model elements that match the specifier are returned.

evaluate(session, models=None, **kw)

Experimental API . Return results of evaluating atom specifier for given models.

Parameters:
session : chimerax.core.session.Session instance

The session in which to evaluate atom specifier.

models : list of chimerax.core.models.Model instances

Defaults to None, which uses all models in ‘session’.

**kw : keyword arguments

If ‘models’ is None, ‘kw’ is passed through to call to ‘session.models.list’ to generate the model list.

Returns:
Objects instance

Instance containing data (atoms, bonds, etc) that match this atom specifier.

class AtomSpecArg(name=None, url=None, html_name=None)

Bases: Annotation

Command line type annotation for atom specifiers.

See cli documentation for details on type annotations.

classmethod parse(text, session)

Experimental API . Parse text and return an atomspec parse tree

all_objects(session)

Experimental API . Return Objects that matches everything.

deregister_selector(name, logger)

Experimental API . Deregister a name as an atom specifier selector.

Parameters:
name : str

Previously registered selector name.

logger : instance of chimerax.core.logger.Logger

Current logger.

Raises:
KeyError

If name is not registered.

everything(session)

Experimental API . Return AtomSpec that matches everything.

Parameters:
session : instance of chimerax.core.session.Session

Session in which the name may be used. If None, name is global.

Returns:
AtomSpec instance

An AtomSpec instance that matches everything in session.

get_selector(name)

Experimental API . Return value associated with registered selector name.

Parameters:
name : str

Previously registered selector name.

Returns:
Callable object, Objects instance, or None.

Callable object if name was registered; None, if not.

get_selector_description(name, session)

Experimental API . Return description for selector.

Parameters:
session : instance of chimerax.core.session.Session

Session in which the name may be used. If None, name is global.

name : str

Previously registered selector name.

Returns:
string

Description of selector. Registered description is used when available; otherwise, description is generated from the selector value.

is_selector_atomic(name)

Experimental API . Return whether selector may select any atoms.

Parameters:
name : str

Previously registered selector name.

Returns:
Boolean

Whether selector name may select any atoms.

is_selector_user_defined(name)

Experimental API . Return whether selector name is user-defined.

Parameters:
name : str

Previously registered selector name.

Returns:
Boolean

Whether selector name is user-defined.

list_selectors()

Experimental API . Return a list of all registered selector names.

Returns:
iterator yielding str

Iterator that yields registered selector names.

register_selector(name, value, logger, *, user=False, desc=None, atomic=True)

Experimental API . Register a (name, value) pair as an atom specifier selector.

Parameters:
name : str

Selector name, preferably without whitespace.

value : callable object or instance of Objects

Selector value. If a callable object, called as ‘value(session, models, results)’ where ‘models’ are chimerax.core.models.Model instances and ‘results’ is an Objects instance; the callable is expected to add selected items to ‘results’. If an Objects instance, items in value are merged with already selected items.

logger : instance of chimerax.core.logger.Logger

Current logger.

user : boolean

Boolean value indicating whether name is considered user-defined or not.

desc : string

Selector description. Returned by get_selector_description(). If not supplied, a generic description will be generated.

atomic : boolean

Boolean value indicating atoms may be selected using selector. Non-atomic selectors will not appear in Basic Actions tool.

run(session, text, *, log=True, downgrade_errors=False)

Experimental API . execute a textual command

Parameters:
text : string

The text of the command to execute.

log : bool

Print the command text to the reply log.

downgrade_errors : bool

True if errors in the command should be logged as informational.

runscript(session, text, *, log=True, downgrade_errors=False)

Experimental API . execute a Python script with arguments

Parameters:
text : string

The text of the command to execute.

log : bool

Print the command text to the reply log.

downgrade_errors : bool

True if errors in the command should be logged as informational.

register_core_commands(session)

Experimental API . Register core commands