text
stringlengths
81
112k
TODO: This implementation is very specific to a particular environment and project, and should be generalized. :param doc: :return: def yield_deps(doc): """ TODO: This implementation is very specific to a particular environment and project, and should be generalized. :param doc: :return: ""...
Wrap a URL string def wrap_url(s, l): """Wrap a URL string""" parts = s.split('/') if len(parts) == 1: return parts[0] else: i = 0 lines = [] for j in range(i, len(parts) + 1): tv = '/'.join(parts[i:j]) nv = '/'.join(parts[i:j + 1]) ...
Return the least signifiant bit O(N) in the worst case def _get_rho(self, w, arr): """ Return the least signifiant bit O(N) in the worst case """ lsb = 0 while not (w & arr[lsb]): lsb += 1 return lsb + 1
Adds a key to the HyperLogLog def add(self, uuid): """ Adds a key to the HyperLogLog """ if uuid: # Computing the hash try: x = hash64(uuid) except UnicodeEncodeError: x = hash64(uuid.encode('ascii', 'ignore')) # Finding th...
Returns the estimate of the cardinality def estimate(self): """ Returns the estimate of the cardinality """ E = self.alpha * float(self.m ** 2) / np.power(2.0, - self.M).sum() if E <= 2.5 * self.m: # Small range correction V = self.m - np.count_nonzero(self.M) ...
Base URL for resolving resource URLs def base_url(self): """Base URL for resolving resource URLs""" if self.doc.package_url: return self.doc.package_url return self.doc._ref
The execution context for rowprocessors and row-generating notebooks and functions. def env(self): """The execution context for rowprocessors and row-generating notebooks and functions. """ from copy import copy env = copy(self.doc.env) assert env is not None, 'Got a null execution co...
Return a URL that properly combines the base_url and a possibly relative resource url def _resolved_url(self): """Return a URL that properly combines the base_url and a possibly relative resource url""" if not self.url: return None u = parse_app_url(self.url) ...
Return the Table term for this resource, which is referenced either by the `table` property or the `schema` property def schema_term(self): """Return the Table term for this resource, which is referenced either by the `table` property or the `schema` property""" if not self.name: ...
Return the headers for the resource. Returns the AltName, if specified; if not, then the Name, and if that is empty, a name based on the column position. These headers are specifically applicable to the output table, and may not apply to the resource source. FOr those headers, use source_headers...
Returns the headers for the resource source. Specifically, does not include any header that is the EMPTY_SOURCE_HEADER value of _NONE_ def source_headers(self): """"Returns the headers for the resource source. Specifically, does not include any header that is the EMPTY_SOURCE_HEADER value of _N...
Return column information from the schema or from an upstreram package def columns(self): """Return column information from the schema or from an upstreram package""" try: # For resources that are metapack packages. r = self.expanded_url.resource.columns() return li...
Return column informatino only from this schema def schema_columns(self): """Return column informatino only from this schema""" t = self.schema_term columns = [] if t: for i, c in enumerate(t.children): if c.term_is("Table.Column"): p ...
Create a row processor from the schema, to convert the text values from the CSV into real types def row_processor_table(self, ignore_none=False): """Create a row processor from the schema, to convert the text values from the CSV into real types""" from rowgenerators.rowpipe import Table...
Like rowgenerator, but does not try to create a row processor table def raw_row_generator(self): """Like rowgenerator, but does not try to create a row processor table""" from rowgenerators import get_generator self.doc.set_sys_path() # Set sys path to package 'lib' dir in case of python func...
Get the header from the deinfed header rows, for use on references or resources where the schema has not been run def _get_header(self): """Get the header from the deinfed header rows, for use on references or resources where the schema has not been run""" try: header_lin...
Iterate over the resource in dict records def iterdict(self): """Iterate over the resource in dict records""" from collections import OrderedDict headers = None for row in self: if headers is None: headers = row continue yield ...
Iterate over the resource as row proxy objects, which allow acessing colums as attributes def iterrows(self): """Iterate over the resource as row proxy objects, which allow acessing colums as attributes""" row_proxy = None headers = None for row in self: if not headers...
Iterate over the resource as row proxy objects, which allow acessing colums as attributes. Like iterrows, but allows for setting a specific RowProxy class. def iterrowproxy(self, cls=RowProxy): """Iterate over the resource as row proxy objects, which allow acessing colums as attributes. Like iterrows, ...
Yield data structures built from the JSON header specifications in a table def iterstruct(self): """Yield data structures built from the JSON header specifications in a table""" from rowgenerators.rowpipe.json import add_to_struct json_headers = self.json_headers for row in islice(sel...
Yields the data structures from iterstruct as JSON strings def iterjson(self, *args, **kwargs): """Yields the data structures from iterstruct as JSON strings""" from rowgenerators.rowpipe.json import VTEncoder import json if 'cls' not in kwargs: kwargs['cls'] = VTEncoder ...
Yields the data structures from iterstruct as YAML strings def iteryaml(self, *args, **kwargs): """Yields the data structures from iterstruct as YAML strings""" from rowgenerators.rowpipe.json import VTEncoder import yaml if 'cls' not in kwargs: kwargs['cls'] = VTEncoder ...
Return a pandas datafrome from the resource def dataframe(self, dtype=False, parse_dates=True, *args, **kwargs): """Return a pandas datafrome from the resource""" import pandas as pd rg = self.row_generator t = self.resolved_url.get_resource().get_target() if t.target_forma...
Return a Geo dataframe def geoframe(self, *args, **kwargs): """Return a Geo dataframe""" from geopandas import GeoDataFrame import geopandas as gpd from shapely.geometry.polygon import BaseGeometry from shapely.wkt import loads gdf = None try: gdf =...
Construct args suitable for pandas read_csv :param dtype: If true, create a dtype type map. Otherwise, pass argument value to read_csv :param parse_dates: If true, create a list of date/time columns for the parse_dates argument of read_csv :param kwargs: :return: def _update_pandas_kwar...
Fetch the target and pass through to pandas.read_csv Don't provide the first argument of read_csv(); it is supplied internally. def read_csv(self, dtype=False, parse_dates=True, *args, **kwargs): """Fetch the target and pass through to pandas.read_csv Don't provide the first argument of read_...
Fetch the target and pass through to pandas.read_fwf. Don't provide the first argument of read_fwf(); it is supplied internally. def read_fwf(self, *args, **kwargs): """Fetch the target and pass through to pandas.read_fwf. Don't provide the first argument of read_fwf(); it is supplied interna...
Load the target, open it, and return the result from readlines() def readlines(self): """Load the target, open it, and return the result from readlines()""" t = self.resolved_url.get_resource().get_target() with open(t.fspath) as f: return f.readlines()
Return a PETL source object def petl(self, *args, **kwargs): """Return a PETL source object""" import petl t = self.resolved_url.get_resource().get_target() if t.target_format == 'txt': return petl.fromtext(str(t.fspath), *args, **kwargs) elif t.target_format == 'c...
Build the interpolation context from the schemas def context(self): """Build the interpolation context from the schemas""" # Can't use self.columns b/c of recursion with resolved_url t = self.schema_term if not t: return {} sql_columns = [] all_columns = ...
Get the local variables in the caller's frame. def caller_locals(): """Get the local variables in the caller's frame.""" import inspect frame = inspect.currentframe() try: return frame.f_back.f_back.f_locals finally: del frame
Like open_package(), but always open the source package def open_source_package(dr=None): """Like open_package(), but always open the source package""" if dr is None: dr = getcwd() for i, e in enumerate(walk_up(dr)): intr = set([DEFAULT_METATAB_FILE, LINES_METATAB_FILE, IPYNB_METATAB_FILE...
Try to open a package with the metatab_doc variable, which is set when a Notebook is run as a resource. If that does not exist, try the local _packages directory def open_package(locals=None, dr=None): """Try to open a package with the metatab_doc variable, which is set when a Notebook is run as a resource...
Rebuild the schema for a resource based on a dataframe def rebuild_schema(doc, r, df): """Rebuild the schema for a resource based on a dataframe""" import numpy as np # Re-get the resource in the doc, since it may be different. try: r = doc.resource(r.name) except AttributeError: #...
Rebuild the schema for a resource based on a dataframe and re-write the doc def rewrite_schema(r, df, doc=None): """Rebuild the schema for a resource based on a dataframe and re-write the doc""" from metapack.cli.core import write_doc if doc is None: doc = open_source_package() rebuild_schem...
Rebuild the schema for a resource based on a dataframe and re-write the doc, but only if running the notebook interactively, not while building def interactive_rewrite_schema(r, df, doc=None): """Rebuild the schema for a resource based on a dataframe and re-write the doc, but only if running the notebook i...
Yield tuples of dataframe variable name and the dataframe. Skips variables with names that start with an underscore def get_dataframes(): """Yield tuples of dataframe variable name and the dataframe. Skips variables with names that start with an underscore""" for k, v in caller_locals().items(): ...
Return the full path of the jupyter notebook. def get_notebook_path(): """ Return the full path of the jupyter notebook. """ kernel_id = re.search('kernel-(.*).json', ipykernel.connect.get_connection_file()).group(1) servers = list_running_servers() for ss in servers: ...
Get the path of a notebook, relative to the current soruce package def get_notebook_rel_path(pkg=None): """Get the path of a notebook, relative to the current soruce package""" pkg = pkg or open_source_package() pkg_path = str(pkg.package_url.fspath) nb_path = get_notebook_path() return nb_path.re...
Add a dataframe to a source package. Pass in either the name of the dataframe, or the dataframe. If the dataframeis passed it, the name will be the dataframe's variable name. The function will re-write the source package with the new resource. def add_dataframe(df, name, pkg=None, description=''): """Add a...
Decorator for IntEnum which re-writes the documentation string so that Sphinx enumerates all the enumeration values. This is a work-around for Sphinx autodoc's inability to properly document IntEnums. This decorator adds enumeration names and values to the 'Attributes' section of the docstring of ...
Decorator which adds the function signature of 'f' to the decorated function's docstring. Under Python 2, wrapping a function (even using functools.wraps) hides its signature to Sphinx's introspection tools so it is necessary to include the function signature in the docstring to enable Sphinx to render...
Run the method iff. the memory view hasn't been closed and the parent object has not been freed. def _if_not_closed(f): """Run the method iff. the memory view hasn't been closed and the parent object has not been freed.""" @add_signature_to_docstring(f) @functools.wraps(f) def f_(self, *args, *...
Run the method iff. the memory view hasn't been closed. def _if_not_freed(f): """Run the method iff. the memory view hasn't been closed.""" @add_signature_to_docstring(f) @functools.wraps(f) def f_(self, *args, **kwargs): if self._freed: raise OSError return f(self, *args, *...
Unpack a routing table entry read from a SpiNNaker machine. Parameters ---------- packet : :py:class:`bytes` Bytes containing a packed routing table. Returns ------- (:py:class:`~rig.routing_table.RoutingTableEntry`, app_id, core) or None Tuple containing the routing entry, the...
The maximum SCP data field length supported by the machine (bytes). def scp_data_length(self): """The maximum SCP data field length supported by the machine (bytes). """ # If not known, query the machine if self._scp_data_length is None: data = self.get_softw...
The coordinates (x, y) of the chip used to boot the machine. def root_chip(self): """The coordinates (x, y) of the chip used to boot the machine.""" # If not known, query the machine if self._root_chip is None: self._root_chip = self.get_software_version(255, 255, 0).position ...
Transmit an SCP Packet and return the response. This function is a thin wrapper around :py:meth:`rig.machine_control.scp_connection.SCPConnection.send_scp`. This function will attempt to use the SCP connection nearest the destination of the SCP command if multiple connections have been...
Get the appropriate connection for a chip. def _get_connection(self, x, y): """Get the appropriate connection for a chip.""" if (self._width is None or self._height is None or self._root_chip is None): return self.connections[None] else: # If possible, us...
Determine the best connection to use to send an SCP packet and use it to transmit. This internal version of the method is identical to send_scp except it has positional arguments for x, y and p. See the arguments for :py:meth:`~rig.machine_control.scp_connection.SCPConnection` ...
Boot a SpiNNaker machine. The system will be booted from the Ethernet connected chip whose hostname was given as the argument to the MachineController. With the default arguments this method will only boot systems which have not already been booted and will wait until machine is complet...
Attempt to discover all available Ethernet connections to a machine. After calling this method, :py:class:`.MachineController` will attempt to communicate via the Ethernet connection on the same board as the destination chip for all commands. If called multiple times, existing connecti...
Update the context to use the given application ID and stop the application when done. For example:: with cn.application(54): # All commands in this block will use app_id=54. # On leaving the block `cn.send_signal("stop", 54)` is # automatica...
Get the software version for a given SpiNNaker core. Returns ------- :py:class:`.CoreInfo` Information about the software running on a core. def get_software_version(self, x=255, y=255, processor=0): """Get the software version for a given SpiNNaker core. Returns ...
Get the IP address of a particular SpiNNaker chip's Ethernet link. Returns ------- str or None The IPv4 address (as a string) of the chip's Ethernet link or None if the chip does not have an Ethernet connection or the link is currently down. def get_ip_addre...
Write a bytestring to an address in memory. It is strongly encouraged to only read and write to blocks of memory allocated using :py:meth:`.sdram_alloc`. Additionally, :py:meth:`.sdram_alloc_as_filelike` can be used to safely wrap read/write access to memory with a file-like interface a...
Read a bytestring from an address in memory. Parameters ---------- address : int The address at which to start reading the data. length_bytes : int The number of bytes to read from memory. Large reads are transparently broken into multiple SCP read co...
Write a bytestring to an address in memory on a neigbouring chip. .. warning:: This function is intended for low-level debug use only and is not optimised for performance nor intended for more general use. This method instructs a monitor processor to send 'POKE' neares...
Read a bytestring from an address in memory on a neigbouring chip. .. warning:: This function is intended for low-level debug use only and is not optimised for performance nor intended for more general use. This method instructs a monitor processor to send 'PEEK' neare...
Read the value out of a struct maintained by SARK. This method is particularly useful for reading fields from the ``sv`` struct which, for example, holds information about system status. See ``sark.h`` for details. Parameters ---------- struct_name : string ...
Write a value into a struct. This method is particularly useful for writing values into the ``sv`` struct which contains some configuration data. See ``sark.h`` for details. Parameters ---------- struct_name : string Name of the struct to write to, e.g., `"...
Get the field and address for a VCPU struct field. def _get_vcpu_field_and_address(self, field_name, x, y, p): """Get the field and address for a VCPU struct field.""" vcpu_struct = self.structs[b"vcpu"] field = vcpu_struct[six.b(field_name)] address = (self.read_struct_field("sv", "vcp...
Read a value out of the VCPU struct for a specific core. Similar to :py:meth:`.read_struct_field` except this method accesses the individual VCPU struct for to each core and contains application runtime status. Parameters ---------- field_name : string Name ...
Write a value to the VCPU struct for a specific core. Parameters ---------- field_name : string Name of the field to write (e.g. `"user0"`) value : Value to write to this field. def write_vcpu_struct_field(self, field_name, value, x, y, p): """Write a va...
Get the status of a given core and the application executing on it. Returns ------- :py:class:`.ProcessorStatus` Representation of the current state of the processor. def get_processor_status(self, p, x, y): """Get the status of a given core and the application executing on...
Read the messages ``io_printf``'d into the ``IOBUF`` buffer on a specified core. See also: :py:meth:`.get_iobuf_bytes` which returns the undecoded raw bytes in the ``IOBUF``. Useful if the IOBUF contains non-text or non-UTF-8 encoded text. Returns ------- str ...
Read raw bytes ``io_printf``'d into the ``IOBUF`` buffer on a specified core. This may be useful when the data contained in the ``IOBUF`` is not UTF-8 encoded text. See also: :py:meth:`.get_iobuf` which returns a decoded string rather than raw bytes. Returns --...
Get the values of the router diagnostic counters. Returns ------- :py:class:`~.RouterDiagnostics` Description of the state of the counters. def get_router_diagnostics(self, x, y): """Get the values of the router diagnostic counters. Returns ------- ...
Set the value of an IPTag. Forward SDP packets with the specified IP tag sent by a SpiNNaker application to a given external IP address. A :ref:`tutorial example <scp-and-sdp-tutorial>` of the use of IP Tags to send and receive SDP packets to and from applications is also avail...
Get the value of an IPTag. Parameters ---------- iptag : int Index of the IPTag to get Returns ------- :py:class:`.IPTag` The IPTag returned from SpiNNaker. def iptag_get(self, iptag, x, y): """Get the value of an IPTag. Paramet...
Clear an IPTag. Parameters ---------- iptag : int Index of the IPTag to clear. def iptag_clear(self, iptag, x, y): """Clear an IPTag. Parameters ---------- iptag : int Index of the IPTag to clear. """ self._send_scp(x, y,...
Set or toggle the state of an LED. .. note:: By default, SARK takes control of LED 0 and so changes to this LED will not typically last long enough to be useful. Parameters ---------- led : int or iterable Number of the LED or an iterable of LEDs to ...
Fill a region of memory with the specified byte. Parameters ---------- data : int Data with which to fill memory. If `address` and `size` are word aligned then `data` is assumed to be a word; otherwise it is assumed to be a byte. Notes ----- ...
Allocate a region of SDRAM for an application. Requests SARK to allocate a block of SDRAM for an application and raises a :py:exc:`.SpiNNakerMemoryError` on failure. This allocation will be freed when the application is stopped. Parameters ---------- size : int ...
Like :py:meth:`.sdram_alloc` but returns a :py:class:`file-like object <.MemoryIO>` which allows safe reading and writing to the block that is allocated. Returns ------- :py:class:`.MemoryIO` File-like object which allows accessing the newly allocated region ...
Free an allocated block of memory in SDRAM. .. note:: All unfreed SDRAM allocations associated with an application are automatically freed when the 'stop' signal is sent (e.g. after leaving a :py:meth:`.application` block). As such, this method is only useful wh...
Get the next nearest neighbour ID. def _get_next_nn_id(self): """Get the next nearest neighbour ID.""" self._nn_id = self._nn_id + 1 if self._nn_id < 126 else 1 return self._nn_id * 2
Send a flood-fill start packet. The cores and regions that the application should be loaded to will be specified by a stream of flood-fill core select packets (FFCS). def _send_ffs(self, pid, n_blocks, fr): """Send a flood-fill start packet. The cores and regions that the application ...
Send a flood-fill core select packet. This packet was added in a patched SC&MP 1.34*. Each packet includes a region and a core mask; every core that is in the region ORs the core mask with a mask it stores locally. On receiving a flood-fill end (FFE) packet the application is loaded to ...
Send flood-fill data packets. def _send_ffd(self, pid, aplx_data, address): """Send flood-fill data packets.""" block = 0 pos = 0 aplx_size = len(aplx_data) while pos < aplx_size: # Get the next block of data, send and progress the block # counter and th...
Send a flood-fill end packet. The cores and regions that the application should be loaded to will have been specified by a stream of flood-fill core select packets (FFCS). def _send_ffe(self, pid, app_id, app_flags, fr): """Send a flood-fill end packet. The cores and regions t...
Unreliably flood-fill APLX to a set of application cores. .. note:: Most users should use the :py:meth:`.load_application` wrapper around this method which guarantees successful loading. This method can be called in either of the following ways:: flood_fill_aplx("...
Load an application to a set of application cores. This method guarantees that once it returns, all required cores will have been loaded. If this is not possible after a small number of attempts, a :py:exc:`.SpiNNakerLoadingError` will be raised. This method can be called in either of ...
Transmit a signal to applications. .. warning:: In current implementations of SARK, signals are highly likely to arrive but this is not guaranteed (especially when the system's network is heavily utilised). Users should treat this mechanism with caution. Future v...
Count the number of cores in a given state. .. warning:: In current implementations of SARK, signals (which are used to determine the state of cores) are highly likely to arrive but this is not guaranteed (especially when the system's network is heavily utilised)...
Block until the specified number of cores reach the specified state. This is a simple utility-wrapper around the :py:meth:`.count_cores_in_state` method which polls the machine until (at least) the supplied number of cores has reached the specified state. .. warning:: ...
Allocate space for an load multicast routing tables. The routing table entries will be removed automatically when the associated application is stopped. Parameters ---------- routing_tables : {(x, y): \ [:py:class:`~rig.routing_table.RoutingTableEntry`...
Allocate space for and load multicast routing table entries into the router of a SpiNNaker chip. .. note:: This method only loads routing table entries for a single chip. Most users should use :py:meth:`.load_routing_tables` which loads routing tables to multiple chi...
Dump the multicast routing table of a given chip. Returns ------- [(:py:class:`~rig.routing_table.RoutingTableEntry`, app_id, core) \ or None, ...] Ordered list of routing table entries with app_ids and core numbers. def get_routing_table_entries(self, x, y): ...
Clear the routing table entries associated with a given application. def clear_routing_table_entries(self, x, y, app_id): """Clear the routing table entries associated with a given application. """ # Construct the arguments arg1 = (app_id << 8) | consts.AllocOperations.free_rtr_by_app ...
Dump the contents of a chip's P2P routing table. This method can be indirectly used to get a list of functioning chips. .. note:: This method only returns the entries for chips within the bounds of the system. E.g. if booted with 8x8 only entries for these 8x8 chips...
Get general information about the resources available on a chip. Returns ------- :py:class:`.ChipInfo` A named tuple indicating the number of working cores, the states of all working cores, the set of working links and the size of the largest free block in SD...
Discover the integrity and resource availability of a whole SpiNNaker system. This command performs :py:meth:`.get_chip_info` on all working chips in the system returning an enhanced :py:class:`dict` (:py:class:`.SystemInfo`) containing a look-up from chip coordinate to :py:clas...
**Deprecated.** Probe the machine to discover which cores and links are working. .. warning:: This method has been deprecated in favour of :py:meth:`.get_system_info` for getting information about the general resources available in a SpiNNaker machine. This method ma...
Iterate over the coordinates of Ethernet connected chips. Yields ------ ((x, y), str) The coordinate and IP address of each Ethernet connected chip in the system. def ethernet_connected_chips(self): """Iterate over the coordinates of Ethernet connected chips. ...
Generate the coordinates of all dead chips. Yields ------ (x, y) The coordinate of a dead chip. def dead_chips(self): """Generate the coordinates of all dead chips. Yields ------ (x, y) The coordinate of a dead chip. """ ...
Generate the coordinates of all working links. Yields ------ (x, y, :py:class:`rig.links.Links`) A working link leaving a chip from the perspective of the chip. For example ``(0, 0, Links.north)`` would be the link going north from chip (0, 0) to chip (0, 1)....
Generate the coordinates of all dead links leaving working chips. Any link leading to a dead chip will also be included in the list of dead links. In non-torroidal SpiNNaker sysmtes (e.g. single SpiNN-5 boards), links on the periphery of the system will be marked as dead. Yields ...
Generate the set of all cores in the system. Yields ------ (x, y, p, :py:class:`~rig.machine_control.consts.AppState`) A core in the machine, and its state. Cores related to a specific chip are yielded consecutively in ascending order of core number. def cores(self): ...
Read a number of bytes from the memory. .. note:: Reads beyond the specified memory range will be truncated. .. note:: Produces a :py:exc:`.TruncationWarning` if fewer bytes are read than requested. These warnings can be converted into exceptions using :...