spinn_utilities package

Subpackages

Submodules

spinn_utilities.abstract_base module

A trimmed down version of standard Python Abstract Base classes.

class spinn_utilities.abstract_base.AbstractBase(name, bases, namespace, **kwargs)[source]

Bases: type

Metaclass for defining Abstract Base Classes (AbstractBases).

Use this metaclass to create an AbstractBase. An AbstractBase can be subclassed directly, and then acts as a mix-in class.

This is a trimmed down version of ABC. Unlike ABC you can not register unrelated concrete classes.

Usage:

class C(object, metaclass=AbstractBase):
    @abstractmethod
    def my_abstract_method(self, ...):
        ...
spinn_utilities.abstract_base.abstractmethod(funcobj: T) T[source]

A decorator indicating abstract methods.

Requires that the metaclass is AbstractBase or derived from it. A class that has a metaclass derived from AbstractBase cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the normal ‘super’ call mechanisms.

Usage:

class C(object, metaclass=AbstractBase):
    @abstractmethod
    def my_abstract_method(self, ...):
        ...

spinn_utilities.abstract_context_manager module

class spinn_utilities.abstract_context_manager.AbstractContextManager[source]

Bases: object

Closeable class that supports being used as a simple context manager.

abstract close() None[source]

How to actually close the underlying resources.

spinn_utilities.bytestring_utils module

spinn_utilities.bytestring_utils.as_hex(byte_string: bytes, start: int | None = None, end: int | None = None) str[source]

Returns the byte string as string showing the hex values

Parameters:
  • byte_string (bytes) – data as a byte string

  • start (int) – the inclusive start of the slice to return. May be None

  • end (int) – the exclusive end of the slice to return. May be None

Returns:

Comma-separated hex values

Return type:

str

spinn_utilities.bytestring_utils.as_string(byte_string: bytes, start: int | None = None, end: int | None = None) str[source]

Returns the length and the hex values.

The length is always the full length irrespective of the start and end.

Parameters:
  • byte_string (bytes) – data as a byte string

  • start (int) – The inclusive start of the slice to convert to hexadecimal. May be None

  • end (int) – The exclusive end of the slice to convert to hexadecimal. May be None

Returns:

The length of the byte string and the comma separated hex values, as a descriptive string

Return type:

str

spinn_utilities.classproperty module

spinn_utilities.classproperty.classproperty(func)[source]

Defines a property at the class-level.

Usage:

class C(object):
    _my_property = "Value"

    @classproperty
    def my_property(cls):
        return cls._my_property

spinn_utilities.conf_loader module

spinn_utilities.conf_loader.install_cfg_and_error(filename: str, defaults: List[str], config_locations: List[str]) NoConfigFoundException[source]

Installs a local configuration file based on the templates and raises an exception.

This method is called when no user configuration file is found.

It will create a file in the users home directory based on the defaults. Then it prints a helpful message and throws an error with the same message.

Parameters:
  • filename (str) – Name under which to save the new configuration file

  • defaults (list(str)) – List of full paths to the default configuration files. Each of which must have an associated template file with exactly the same path plus .template.

  • config_locations (list(str)) – List of paths where the user configuration files were looked for. Only used for the message

Raises:

spinn_utilities.configs.NoConfigFoundException – Always raised

spinn_utilities.conf_loader.load_config(filename: str, defaults: List[str], config_parsers: Sequence[Tuple[str, Callable[[CamelCaseConfigParser], None]]] | Dict[str, Callable[[CamelCaseConfigParser], None]] = ()) CamelCaseConfigParser[source]

Load the configuration.

Parameters:
  • filename (str) – The base name of the configuration file(s). Should not include any path components.

  • defaults (list(str)) – The list of files to get default configurations from.

  • config_parsers (list(tuple(str, RawConfigParser))) – The parsers to parse the sections of the configuration file with, as a list of (section name, parser) or a dictionary from section name to parser; a configuration section will only be parsed if the section_name is found in the configuration files already loaded. The standard logging parser is appended to (a copy of) this.

Returns:

the fully-loaded and checked configuration

Return type:

RawConfigParser

spinn_utilities.conf_loader.logging_parser(config: CamelCaseConfigParser)[source]

Create the root logger with the given level.

Create filters based on logging levels

Note

You do not normally need to call this function; it is used automatically to parse Logging configuration sections.

spinn_utilities.config_holder module

spinn_utilities.config_holder.add_default_cfg(default: str)[source]

Adds an extra default configuration file to be read after earlier ones.

Parameters:

default (str) – Absolute path to the configuration file

spinn_utilities.config_holder.clear_cfg_files(unittest_mode: bool)[source]

Clears any previous set configurations and configuration files.

After this method add_default_cfg() and set_cfg_files() need to be called.

Parameters:

unittest_mode (bool) – Flag to put the holder into unit testing mode

spinn_utilities.config_holder.config_options(section: str) List[str][source]

Return a list of option names for the given section name.

Parameters:

section (str) – What section to list options for.

spinn_utilities.config_holder.get_config_bool(section: str, option: str) bool[source]

Get the Boolean value of a configuration option.

Parameters:
  • section (str) – What section to get the option from.

  • option (str) – What option to read.

Returns:

The option value.

Return type:

bool

Raises:

ConfigException – if the Value would be None

spinn_utilities.config_holder.get_config_bool_or_none(section, option) bool | None[source]

Get the Boolean value of a configuration option.

Parameters:
  • section (str) – What section to get the option from.

  • option (str) – What option to read.

Returns:

The option value.

Return type:

bool

Raises:

ConfigException – if the Value would be None

spinn_utilities.config_holder.get_config_float(section: str, option: str) float[source]

Get the float value of a configuration option.

Parameters:
  • section (str) – What section to get the option from.

  • option (str) – What option to read.

Returns:

The option value.

Return type:

float

Raises:

ConfigException – if the Value would be None

spinn_utilities.config_holder.get_config_float_or_none(section, option) float | None[source]

Get the float value of a configuration option.

Parameters:
  • section (str) – What section to get the option from.

  • option (str) – What option to read.

Returns:

The option value.

Return type:

float or None

spinn_utilities.config_holder.get_config_int(section: str, option: str) int[source]

Get the integer value of a configuration option.

Parameters:
  • section (str) – What section to get the option from.

  • option (str) – What option to read.

Returns:

The option value

Return type:

int

Raises:

ConfigException – if the Value would be None

spinn_utilities.config_holder.get_config_int_or_none(section, option) int | None[source]

Get the integer value of a configuration option.

Parameters:
  • section (str) – What section to get the option from.

  • option (str) – What option to read.

Returns:

The option value

Return type:

int or None

Raises:

ConfigException – if the Value would be None

spinn_utilities.config_holder.get_config_str(section, option) str[source]

Get the string value of a configuration option.

Parameters:
  • section (str) – What section to get the option from.

  • option (str) – What option to read.

Returns:

The option value

Return type:

str

Raises:

ConfigException – if the Value would be None

spinn_utilities.config_holder.get_config_str_list(section: str, option: str, token: str = ',') List[str][source]

Get the string value of a configuration option split into a list.

Parameters:
  • section (str) – What section to get the option from.

  • option (str) – What option to read.

  • token – The token to split the string into a list

Returns:

The list (possibly empty) of the option values

Return type:

list(str)

spinn_utilities.config_holder.get_config_str_or_none(section, option) str | None[source]

Get the string value of a configuration option.

Parameters:
  • section (str) – What section to get the option from.

  • option (str) – What option to read.

Returns:

The option value

Return type:

str or None

Raises:

ConfigException – if the Value would be None

spinn_utilities.config_holder.has_config_option(section: str, option: str) bool[source]

Check if the section has this configuration option.

Parameters:
  • section (str) – What section to check

  • option (str) – What option to check.

Return type:

bool

Returns:

True if and only if the option is defined. It may be None

spinn_utilities.config_holder.is_config_none(section, option) bool[source]

Check if the value of a configuration option would be considered None

Parameters:
  • section (str) – What section to get the option from.

  • option (str) – What option to read.

Returns:

True if and only if the value would be considered None

Return type:

bool

spinn_utilities.config_holder.load_config() CamelCaseConfigParser[source]

Reads in all the configuration files, resetting all values.

Raises:

ConfigException – If called before setting defaults

spinn_utilities.config_holder.run_config_checks(directories: str | Collection[str], *, exceptions: str | Collection[str] = (), repeaters: Collection[str] | None = ())[source]

Master test.

Parameters:
  • module

  • exceptions

  • repeaters

Raises:

ConfigException – If an incorrect directory passed in

spinn_utilities.config_holder.set_cfg_files(config_file: str, default: str)[source]

Adds the configuration files to be loaded.

Parameters:
  • config_file (str) – The base name of the configuration file(s). Should not include any path components.

  • default (str) – Full path to the extra file to get default configurations from.

spinn_utilities.config_holder.set_config(section: str, option: str, value: str | None)[source]

Sets the value of a configuration option.

This method should only be called by the simulator or by unit tests.

Parameters:
  • section (str) – What section to set the option in.

  • option (str) – What option to set.

  • value (object) – Value to set option to

Raises:

ConfigException – If called unexpectedly

spinn_utilities.config_setup module

spinn_utilities.config_setup.add_spinn_utilities_cfg() None[source]

Loads the default config values for spinn_utilities

spinn_utilities.config_setup.unittest_setup() None[source]

Resets the configurations so only the local default configuration is included.

Note

This file should only be called from SpiNNUtils/unittests

Parameters:

unittest_mode – Flag to indicate in unit tests

spinn_utilities.exceptions module

exception spinn_utilities.exceptions.ConfigException[source]

Bases: SpiNNUtilsException

Raised when reading or setting configurations went wrong.

exception spinn_utilities.exceptions.DataNotMocked(data)[source]

Bases: DataNotYetAvialable

Raised when trying to get data before a mocked simulator has created it.

exception spinn_utilities.exceptions.DataNotYetAvialable(data)[source]

Bases: SpiNNUtilsException

Raised when trying to get data before simulator has created it.

exception spinn_utilities.exceptions.IllegalWriterException[source]

Bases: SpiNNUtilsException

Raised when trying to create a writer other than setup or Mock.

exception spinn_utilities.exceptions.InvalidDirectory(name, value)[source]

Bases: SpiNNUtilsException

Raised when trying to set an invalid directory.

exception spinn_utilities.exceptions.NotSetupException(data)[source]

Bases: SpiNNUtilsException

Raised when trying to get data before simulator has been setup.

exception spinn_utilities.exceptions.ShutdownException(data)[source]

Bases: SpiNNUtilsException

Raised when trying to get simulator data after it has been shut down.

exception spinn_utilities.exceptions.SimulatorNotRunException[source]

Bases: SpiNNUtilsException

Raised when trying to reset or stop before starting.

exception spinn_utilities.exceptions.SimulatorNotSetupException[source]

Bases: SpiNNUtilsException

Raised when trying to get simulator before it has been setup.

exception spinn_utilities.exceptions.SimulatorRunningException[source]

Bases: SpiNNUtilsException

Raised when trying an action that should not happen while the simulator is running.

exception spinn_utilities.exceptions.SimulatorShutdownException[source]

Bases: SpiNNUtilsException

Raised when trying to get simulator after it has been shut down.

exception spinn_utilities.exceptions.SpiNNUtilsException[source]

Bases: Exception

Superclass of all exceptions from the SpiNNUtils module.

exception spinn_utilities.exceptions.UnexpectedCException[source]

Bases: SpiNNUtilsException

Raised when the converter (which replaces log messages) found a pattern it did not expect and cannot handle.

exception spinn_utilities.exceptions.UnexpectedStateChange[source]

Bases: SpiNNUtilsException

Raised when trying to change the state in an unexpected way.

spinn_utilities.executable_finder module

class spinn_utilities.executable_finder.ExecutableFinder[source]

Bases: object

Manages a set of folders in which to search for binaries, and allows for binaries to be discovered within this path.

add_path(path: str) None[source]

Adds a path to the set of folders to be searched. The path is added to the end of the list, so it is searched after all the paths currently in the list.

Parameters:

path (str) – The path to add

property binary_paths: str

The set of folders to search for binaries, as a printable colon-separated string.

Return type:

str

check_logs() None[source]

Compares the aplx files used against the ones available for use

Reports the aplx files never used.

clear_logs() None[source]

Deletes log files from previous runs

get_executable_path(executable_name: str) str[source]

Finds an executable within the set of folders. The set of folders is searched sequentially and the first match is returned.

Parameters:

executable_name (str) – The name of the executable to find

Returns:

The full path of the discovered executable

Return type:

str

Raises:

KeyError – If no executable was found in the set of folders

get_executable_paths(executable_names: str) List[str][source]

Finds each executables within the set of folders.

The names are assumed to be comma separated The set of folders is searched sequentially and the first match for each name is returned.

Names not found are ignored and not added to the list.

Parameters:

executable_names (str) – The name of the executable to find. Assumed to be comma separated.

Returns:

The full path of the discovered executable, or None if no executable was found in the set of folders

Return type:

list(str)

spinn_utilities.find_max_success module

spinn_utilities.find_max_success.find_max_success(max_possible: int, check: Callable[[int], bool]) int[source]

Finds the maximum value that will pass the check

Parameters:
  • max_possible (int) – The maximum value that should be tested.

  • check (Callable[[int], bool]) – A Boolean function that given an int value returns True for every value up and including the cut-off and False for every value greater than the cut-off

Returns:

The highest value that returns true for the check but is not more than the max_possible

spinn_utilities.find_max_success.search_for_max_success(best_success: int, min_fail: int, check: Callable[[int], bool]) int[source]

Finds the maximum value in the range that pass the check

Parameters:
  • best_success (int) – A minimum value that needs not be tested because it is either known to succeed or is a flag for total failure. Can be negative

  • min_fail (int) – A maximum value that needs not be tested because it is either known to fail or one more than the maximum interesting value but must be greater than best_success but may also be negative

  • check (Callable[[int], bool]) – A Boolean function that given an int value returns True for every value up and including the cut-off and False for every value greater than the cut-off

Returns:

The highest value that returns true in the range between best_success and min_fail (both exclusive ends) or best_success if the whole range fails or is empty.

spinn_utilities.helpful_functions module

spinn_utilities.helpful_functions.gcd(numbers: Sequence[int], /) int[source]
spinn_utilities.helpful_functions.gcd(number: int, /, *numbers: int) int

Greatest common divisor of 1 or more integers.

GIGO: If any of the values are anything except positive int values this function will either produce incorrect results or raise an exception.

Parameters:

numbers – The positive integers to get the GCD for. This can be one or more int values or a singleton which is an iterator (not empty) of ints.

Returns:

the GCD

Return type:

int

Raises:
  • TypeError – If any value cannot be interpreted as an integer or if no values are provided

  • ZeroDivisionError – May be raised if one of the values is zero

spinn_utilities.helpful_functions.is_singleton(value: Any) TypeGuard[bool | int | float][source]

Tests whether the value is a singleton.

Singleton types are strings and any other class that can not be iterated.

Strings are considered singleton as only rarely will someone use a string to represent an iterable of characters.

spinn_utilities.helpful_functions.lcm(numbers: Sequence[int], /) int[source]
spinn_utilities.helpful_functions.lcm(number: int, /, *numbers: int) int

Lowest common multiple of 0, 1 or more integers.

GIGO: If any of the values are anything except positive int values this function will either produce incorrect results or raise an exception.

Parameters:

numbers – The Positive integers to get the Lowest common multiple for. This can be zero, one or more int values or a singleton which is an iterator (possibly empty) of ints.

Returns:

the Lowest common multiple, or 1 if numbers is empty or an empty iterator

Return type:

int

Raises:

spinn_utilities.index_is_value module

class spinn_utilities.index_is_value.IndexIsValue[source]

Bases: object

Tiny support class that implements object[x] by just returning x itself.

Used for where you want a range from 1 to N but you don’t know N.

Clearly, operations that assume a finite list are not supported.

spinn_utilities.log module

class spinn_utilities.log.ConfiguredFilter(conf)[source]

Bases: object

Allow a parent logger to filter a child logger.

filter(record)[source]

Get the level for the deepest parent, and filter appropriately.

class spinn_utilities.log.ConfiguredFormatter(conf)[source]

Bases: Formatter

Defines the logging format for the SpiNNaker host software.

Initialize the formatter with specified format strings.

Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.

Use a style parameter of ‘%’, ‘{’ or ‘$’ to specify that you want to use one of %-formatting, str.format() ({}) formatting or string.Template formatting in your format string.

Changed in version 3.2: Added the style parameter.

static construct_logging_parents(conf)[source]

Create a dictionary of module names and logging levels.

static deepest_parent(parents, child)[source]

Greediest match between child and parent.

static level_of_deepest_parent(parents, child)[source]

The logging level of the greediest match between child and parent.

class spinn_utilities.log.FormatAdapter(logger: Logger, extra=None)[source]

Bases: LoggerAdapter

An adaptor for logging with messages that uses Python format strings.

Example:

log = FormatAdapter(logging.getLogger(__name__))
log.info("this message has {} inside {}", 123, 'itself')
# --> INFO: this message has 123 inside itself

Initialize the adapter with a logger and a dict-like object which provides contextual information. This constructor signature allows easy stacking of LoggerAdapters, if so desired.

You can effectively pass keyword arguments as shown in the following example:

adapter = LoggerAdapter(someLogger, dict(p1=v1, p2=”v2”))

classmethod atexit_handler() None[source]

Adds code to print out high level log messages python run ends

log(level: int, msg: object, *args, **kwargs)[source]

Delegate a log call to the underlying logger, applying appropriate transformations to allow the log message to be written using Python format string, rather than via %-substitutions.

process(msg: object, kwargs: Any) Tuple[object, dict][source]

Process the logging message and keyword arguments passed in to a logging call to insert contextual information. You can either manipulate the message itself, the keyword arguments or both. Return the message and kwargs modified (or not) to suit your needs.

classmethod set_kill_level(level: int | None = None)[source]

Allow system to change the level at which a log is changed to an Exception.

Note

This is a static method; it affects all log messages.

Parameters:

level (int) – The level to set. The values in logging are recommended.

classmethod set_log_store(log_store: LogStore | None)[source]

Sets a Object to write the log messages to :param LogStore log_store:

exception spinn_utilities.log.LogLevelTooHighException[source]

Bases: Exception

An Exception throw when the System tries to log at a level where an Exception is a better option.

spinn_utilities.log_store module

class spinn_utilities.log_store.LogStore[source]

Bases: object

API supported by classes that can store logs for later retrieval.

abstract get_location() str[source]

Retrieves the location of the log store.

Return type:

str

abstract retreive_log_messages(min_level: int = 0) List[Tuple[int, str]][source]

Retrieves all log messages at or above the min_level.

Parameters:

min_level (int) – Constraint on the minimum logging level to retrieve.

Returns:

A list of messages that satisfy the constraint.

Return type:

list(tuple(int, str))

abstract store_log(level: int, message: str, timestamp: datetime | None = None)[source]

Writes the log message for later retrieval.

Parameters:
  • level (int) – The logging level.

  • message (str) – The logged message.

  • timestamp (datetime or None) – The time-stamp of the message.

spinn_utilities.logger_utils module

spinn_utilities.logger_utils.error_once(logger, msg)[source]

Write an error message to the given logger where that message should only be written to the logger once.

Parameters:
  • logger – The logger to write to.

  • msg

    The message to write.

    Note

    This must be a substitution-free message.

spinn_utilities.logger_utils.reset()[source]

Clear the store of what messages have already been seen.

Note

Only normally needed by test code.

spinn_utilities.logger_utils.warn_once(logger, msg)[source]

Write a warning message to the given logger where that message should only be written to the logger once.

Parameters:
  • logger – The logger to write to.

  • msg

    The message to write.

    Note

    This must be a substitution-free message.

spinn_utilities.ordered_set module

class spinn_utilities.ordered_set.OrderedSet(iterable: Iterable[T] | None = None)[source]

Bases: MutableSet, Generic[T]

A set like Object where peek, pop and iterate are in insert order

add(value: T)[source]

Add an element.

discard(value: T)[source]

Remove an element. Do not raise an exception if absent.

peek(last: bool = True) T[source]

Retrieve the first element from the set without removing it :param last: :return:

pop(last: bool = True) T[source]

Return the popped value. Raise KeyError if empty.

update(iterable: Iterable[T])[source]

Updates the set by adding each item in order

Parameters:

iterable

spinn_utilities.overrides module

class spinn_utilities.overrides.overrides(super_class_method, *, extend_doc: bool = True, additional_arguments: Iterable[str] | None = None, extend_defaults: bool = False, adds_typing: bool = False)[source]

Bases: object

A decorator for indicating that a method overrides another method in a superclass. This checks that the method does actually exist, copies the doc-string for the method, and enforces that the method overridden is specified, making maintenance easier.

Parameters:
  • super_class_method – The method to override in the superclass

  • extend_doc (bool) – True the method doc string should be appended to the super-method doc string, False if the documentation should be set to the super-method doc string only if there isn’t a doc string already

  • additional_arguments (iterable(str)) – Additional arguments taken by the subclass method over the superclass method, e.g., that are to be injected

  • extend_defaults (bool) – Whether the subclass may specify extra defaults for the parameters

  • adds_typing – Allows more typing (of non additional) than in the subclass. Should only be used for built in super classes

classmethod check_types()[source]

If called will trigger check that all parameters are checked.

Used for testing, to avoid users being affected by the strict checks

spinn_utilities.package_loader module

spinn_utilities.package_loader.all_modules(directory, prefix, remove_pyc_files=False)[source]

List all the python files found in this directory giving then the prefix.

Any file that ends in either .py or .pyc is assume a python module and added to the result set.

Parameters:
  • directory (str) – path to check for python files

  • prefix (str) – package prefix top add to the file name

Returns:

set of python package names

Return type:

set(str)

spinn_utilities.package_loader.load_module(name, remove_pyc_files=False, exclusions=None, gather_errors=True)[source]

Loads this modules and all its children.

Parameters:
  • name (str) – name of the modules

  • remove_pyc_files (bool) – True if .pyc files should be deleted

  • exclusions (list(str)) – a list of modules to exclude

  • gather_errors (bool) – True if errors should be gathered, False to report on first error

Returns:

None

spinn_utilities.package_loader.load_modules(directory, prefix, remove_pyc_files=False, exclusions=None, gather_errors=True)[source]

Loads all the python files found in this directory, giving them the specified prefix.

Any file that ends in either .py or .pyc is assume a python module and added to the result set.

Parameters:
  • directory (str) – path to check for python files

  • prefix (str) – package prefix top add to the file name

  • remove_pyc_files (bool) – True if .pyc files should be deleted

  • exclusions (list(str)) – a list of modules to exclude

  • gather_errors (bool) – True if errors should be gathered, False to report on first error

Returns:

None

spinn_utilities.ping module

class spinn_utilities.ping.Ping[source]

Bases: object

Platform-independent ping support.

static host_is_reachable(ip_address)[source]

Test if a host is unreachable via ICMP ECHO.

Note

This information may be cached in various ways. Transient failures are not necessarily detected or recovered from.

Parameters:

ip_address (str) – The IP address to ping. Hostnames can be used, but are not recommended.

Return type:

bool

static ping(ip_address)[source]

Send a ping (ICMP ECHO request) to the given host. SpiNNaker boards support ICMP ECHO when booted.

Parameters:

ip_address (str) – The IP address to ping. Hostnames can be used, but are not recommended.

Returns:

return code of subprocess; 0 for success, anything else for failure

Return type:

int

unreachable: Set[str] = {}

The unreachable host cache.

spinn_utilities.progress_bar module

class spinn_utilities.progress_bar.DummyProgressBar(*args, **kwargs)[source]

Bases: ProgressBar

This is a dummy version of the progress bar that just stubs out the internal printing operations with code that does nothing. It otherwise fails in exactly the same way.

class spinn_utilities.progress_bar.ProgressBar(*args, **kwargs)[source]

Bases: object

Progress bar for telling the user where a task is up to.

MAX_LENGTH_IN_CHARS = 60
TOO_MANY_ERROR = 'Too many update steps in progress bar! This may be a sign that something else has gone wrong!'
end()[source]

Close the progress bar, updating whatever is left if needed.

over(collection: Iterable[T], finish_at_end: bool = True) Iterable[T][source]

Simple wrapper for the cases where the progress bar is being used to show progress through the iteration over a single collection. The progress bar should have been initialised to the size of the collection being iterated over.

Parameters:
  • collection (Iterable) – The base collection (any iterable) being iterated over

  • finish_at_end (bool) – Flag to say if the bar should finish at the end of the collection

Returns:

An iterable. Expected to be directly used in a for.

Return type:

Iterable

update(amount_to_add=1)[source]

Update the progress bar by a given amount.

Parameters:

amount_to_add

spinn_utilities.require_subclass module

spinn_utilities.require_subclass.require_subclass(required_class)[source]

Decorator that arranges for subclasses of the decorated class to require that they are also subclasses of the given class.

Usage example:

@require_subclass(AbstractVertex)
class AbstractVirtual(object):
    ...
Parameters:

required_class (type) – The class that the subclass of the decorated class must be an instance of (if that subclass is concrete).

spinn_utilities.safe_eval module

class spinn_utilities.safe_eval.SafeEval(*args, **kwargs)[source]

Bases: object

This provides expression evaluation capabilities while allowing the set of symbols exposed to the expression to be strictly controlled.

Sample of use:

>>> import math
>>> def evil_func(x):
...    print("Hello World!")
...    return x/0.0
...
>>> eval_safely = SafeEval(math)
>>> eval_safely.eval("math.sqrt(x)", x=1.23)
1.1090536506409416
>>> eval_safely.eval("evil_func(1.23)")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../safe_eval.py", line 62, in eval
    return eval(expression, self._environment, kwargs)
  File "<string>", line 1, in <module>
NameError: name 'evil_func' is not defined

Warning

This is not guaranteed to be safe under all circumstances. It is not designed to be a fully secured interface; it just discourages abuse.

Parameters:
  • args

    The symbols to use to populate the global reference table.

    Note

    All of these symbols must support the __name__ property, but that includes any function, method of an object, or module. If you want to make an object available by anything other than its inherent name, define it in the eval() call.

  • kwargs – Define the symbols with explicit names. Needed because some symbols (e.g., constants in numpy) do not have names that we can otherwise look up easily.

eval(expression, **kwargs)[source]

Evaluate an expression and return the result.

Parameters:
  • expression (str) – The expression to evaluate

  • kwargs – The extra symbol bindings to use for this evaluation. This is useful for passing in particular parameters to an individual evaluation run.

Returns:

The expression result, the type of which will depend on the expression itself and the operations exposed to it.

spinn_utilities.socket_address module

class spinn_utilities.socket_address.SocketAddress(notify_host_name: str | None = None, notify_port_no: int | None = None, listen_port: int | None = None)[source]

Bases: object

Data holder for a socket interface for notification protocol.

Parameters:
  • notify_host_name (str or None) – Host to talk to tell that the database (and application) is ready.

  • notify_port_no (int or None) – Port to talk to tell that the database (and application) is ready.

  • listen_port (int or None) – Port on which to listen for an acknowledgement that the simulation should start.

property listen_port: int | None

The port to listen to for responses.

property notify_host_name: str

The host name or IP address to send a notification message to.

property notify_port_no: int

The UDP port number to send a notification message to.

spinn_utilities.timer module

class spinn_utilities.timer.Timer[source]

Bases: object

A timer used for performance measurements.

Recommended usage:

with Timer() as timer:
    ... do stuff that takes time ...

elapsed_time = timer.measured_interval

or alternatively:

timer = Timer()
timer.start_timing()
... do stuff that takes time ...
elapsed_time = timer.take_sample()

Mixing these two styles is not recommended.

property measured_interval: timedelta | None

Get how long elapsed during the measured section.

Return type:

datetime.timedelta

start_timing() None[source]

Start the timing. Use take_sample() to get the end.

take_sample() timedelta[source]

Describes how long has elapsed since the instance that the start_timing() method was last called.

Return type:

datetime.timedelta

Module contents