code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
row_proxy = None
headers = None
for row in self:
if not headers:
headers = row
row_proxy = cls(headers)
continue
yield row_proxy.set_row(row) | def iterrowproxy(self, cls=RowProxy) | Iterate over the resource as row proxy objects, which allow acessing colums as attributes. Like iterrows,
but allows for setting a specific RowProxy class. | 5.098258 | 4.497931 | 1.133467 |
from rowgenerators.rowpipe.json import add_to_struct
json_headers = self.json_headers
for row in islice(self, 1, None): # islice skips header
d = {}
for pos, jh in json_headers:
add_to_struct(d, jh, row[pos])
yield d | def iterstruct(self) | Yield data structures built from the JSON header specifications in a table | 6.933846 | 6.359389 | 1.090332 |
from rowgenerators.rowpipe.json import VTEncoder
import json
if 'cls' not in kwargs:
kwargs['cls'] = VTEncoder
for s in self.iterstruct:
yield (json.dumps(s, *args, **kwargs)) | def iterjson(self, *args, **kwargs) | Yields the data structures from iterstruct as JSON strings | 7.766997 | 6.820627 | 1.138751 |
from rowgenerators.rowpipe.json import VTEncoder
import yaml
if 'cls' not in kwargs:
kwargs['cls'] = VTEncoder
for s in self.iterstruct:
yield (yaml.safe_dump(s)) | def iteryaml(self, *args, **kwargs) | Yields the data structures from iterstruct as YAML strings | 11.83791 | 8.845046 | 1.338366 |
import pandas as pd
rg = self.row_generator
t = self.resolved_url.get_resource().get_target()
if t.target_format == 'csv':
return self.read_csv(dtype, parse_dates, *args, **kwargs)
# Maybe generator has it's own Dataframe method()
try:
... | def dataframe(self, dtype=False, parse_dates=True, *args, **kwargs) | Return a pandas datafrome from the resource | 6.606765 | 6.45027 | 1.024262 |
from geopandas import GeoDataFrame
import geopandas as gpd
from shapely.geometry.polygon import BaseGeometry
from shapely.wkt import loads
gdf = None
try:
gdf = self.resolved_url.geoframe(*args, **kwargs)
except AttributeError:
p... | def geoframe(self, *args, **kwargs) | Return a Geo dataframe | 3.864427 | 3.838456 | 1.006766 |
from datetime import datetime, time, date
type_map = {
None: None,
'string': str,
'text': str,
'number': float,
'integer': int,
'datetime': datetime,
'time': time,
'date': date
}
... | def _update_pandas_kwargs(self, dtype=False, parse_dates=True, kwargs= {}) | 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: | 2.590586 | 2.512154 | 1.031221 |
import pandas
t = self.resolved_url.get_resource().get_target()
kwargs = self._update_pandas_kwargs(dtype, parse_dates, kwargs)
return pandas.read_csv(t.fspath, *args, **kwargs) | 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_csv(); it is supplied internally. | 5.480414 | 5.17218 | 1.059595 |
import pandas
t = self.resolved_url.get_resource().get_target()
return pandas.read_fwf(t.fspath, *args, **kwargs) | 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 internally. | 7.38996 | 7.020354 | 1.052648 |
t = self.resolved_url.get_resource().get_target()
with open(t.fspath) as f:
return f.readlines() | def readlines(self) | Load the target, open it, and return the result from readlines() | 10.39537 | 7.218054 | 1.44019 |
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 == 'csv':
return petl.fromcsv(str(t.fspath), *args, **kwargs)
else:
... | def petl(self, *args, **kwargs) | Return a PETL source object | 3.94751 | 3.939894 | 1.001933 |
# Can't use self.columns b/c of recursion with resolved_url
t = self.schema_term
if not t:
return {}
sql_columns = []
all_columns = []
for i, c in enumerate(t.children):
if c.term_is("Table.Column"):
p = c.all_props
... | def context(self) | Build the interpolation context from the schemas | 7.242232 | 6.678526 | 1.084406 |
import inspect
frame = inspect.currentframe()
try:
return frame.f_back.f_back.f_locals
finally:
del frame | def caller_locals() | Get the local variables in the caller's frame. | 2.654269 | 2.536541 | 1.046413 |
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]) & set(e[2])
if intr:
return op(join(e[0], list(intr)[0] ))
if i > 2:
break
return None | def open_source_package(dr=None) | Like open_package(), but always open the source package | 7.639082 | 7.434928 | 1.027459 |
if locals is None:
locals = caller_locals()
try:
# Running in a package build
return op(locals['metatab_doc'])
except KeyError:
# Running interactively in Jupyter
package_name = None
build_package_dir = None
source_package = None
if ... | 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. If that does not exist, try the local _packages directory | 5.00256 | 4.63724 | 1.078779 |
import numpy as np
# Re-get the resource in the doc, since it may be different.
try:
r = doc.resource(r.name)
except AttributeError:
# Maybe r is actually a resource name
r = doc.resource(r)
def alt_col_name(name, i):
import re
if not name:
... | def rebuild_schema(doc, r, df) | Rebuild the schema for a resource based on a dataframe | 3.024796 | 2.994507 | 1.010115 |
from metapack.cli.core import write_doc
if doc is None:
doc = open_source_package()
rebuild_schema(doc, r, df)
write_doc(doc, doc.ref) | def rewrite_schema(r, df, doc=None) | Rebuild the schema for a resource based on a dataframe and re-write the doc | 7.757361 | 7.217429 | 1.07481 |
if 'metatab_doc' in caller_locals():
return False
if doc is None:
doc = open_source_package()
rewrite_schema(r, df, doc)
return True | 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 interactively, not while building | 8.28759 | 8.766026 | 0.945422 |
for k, v in caller_locals().items():
if k.startswith('_'):
continue
if isinstance(v, pd.core.frame.DataFrame):
yield k, v | def get_dataframes() | Yield tuples of dataframe variable name and the dataframe. Skips variables with names that
start with an underscore | 4.567711 | 3.573991 | 1.278042 |
kernel_id = re.search('kernel-(.*).json',
ipykernel.connect.get_connection_file()).group(1)
servers = list_running_servers()
for ss in servers:
response = requests.get(urljoin(ss['url'], 'api/sessions'),
params={'token': ss.get('token', ... | def get_notebook_path() | Return the full path of the jupyter notebook. | 2.819246 | 2.684748 | 1.050097 |
pkg = pkg or open_source_package()
pkg_path = str(pkg.package_url.fspath)
nb_path = get_notebook_path()
return nb_path.replace(pkg_path, '').strip('/') | def get_notebook_rel_path(pkg=None) | Get the path of a notebook, relative to the current soruce package | 6.775414 | 5.562778 | 1.217991 |
from warnings import warn
from metapack.cli.core import alt_col_name, type_map
import numpy as np
if name is None or df is None:
warn("Did not find dataframe for reference '{}' ".format(ref))
return
pkg = pkg or open_source_package()
resource_ref = 'file:' + get_notebook_... | def add_dataframe(df, name, pkg=None, description='') | 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. | 4.534368 | 4.515804 | 1.004111 |
# The enum34 library (used for compatibility with Python < v3.4) rather
# oddly set its docstring to None rather than some senible but empty
# default...
if enum.__doc__ is None: # pragma: nocover
enum.__doc__ = ""
enum.__doc__ += ("\n\n"
"Attributes\n"
... | def add_int_enums_to_docstring(enum) | 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 ... | 7.433345 | 8.031138 | 0.925566 |
@add_signature_to_docstring(f)
@functools.wraps(f)
def f_(self, *args, **kwargs):
if self.closed or self._parent._freed:
raise OSError
return f(self, *args, **kwargs)
return f_ | def _if_not_closed(f) | Run the method iff. the memory view hasn't been closed and the parent
object has not been freed. | 3.817765 | 3.090984 | 1.235129 |
@add_signature_to_docstring(f)
@functools.wraps(f)
def f_(self, *args, **kwargs):
if self._freed:
raise OSError
return f(self, *args, **kwargs)
return f_ | def _if_not_freed(f) | Run the method iff. the memory view hasn't been closed. | 3.299746 | 3.144157 | 1.049485 |
# Unpack the routing table entry
_, free, route, key, mask = struct.unpack(consts.RTE_PACK_STRING, packed)
# If the top 8 bits of the route are set then this entry is not in use, so
# return None.
if route & 0xff000000 == 0xff000000:
return None
# Convert the routing table entry
... | def unpack_routing_table_entry(packed) | 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... | 5.057983 | 4.371109 | 1.15714 |
# If not known, query the machine
if self._scp_data_length is None:
data = self.get_software_version(255, 255, 0)
self._scp_data_length = data.buffer_size
return self._scp_data_length | def scp_data_length(self) | The maximum SCP data field length supported by the machine
(bytes). | 5.282055 | 4.604235 | 1.147217 |
# If not known, query the machine
if self._root_chip is None:
self._root_chip = self.get_software_version(255, 255, 0).position
return self._root_chip | def root_chip(self) | The coordinates (x, y) of the chip used to boot the machine. | 7.046575 | 5.345695 | 1.318177 |
# Retrieve contextual arguments from the keyword arguments. The
# context system ensures that these values are present.
x = kwargs.pop("x")
y = kwargs.pop("y")
p = kwargs.pop("p")
return self._send_scp(x, y, p, *args, **kwargs) | def send_scp(self, *args, **kwargs) | 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... | 5.624742 | 5.236239 | 1.074195 |
if (self._width is None or self._height is None or
self._root_chip is None):
return self.connections[None]
else:
# If possible, use the local Ethernet connected chip
eth_chip = spinn5_local_eth_coord(x, y, self._width, self._height,
... | def _get_connection(self, x, y) | Get the appropriate connection for a chip. | 7.376662 | 6.901634 | 1.068828 |
# Determine the size of packet we expect in return, this is usually the
# size that we are informed we should expect by SCAMP/SARK or else is
# the default.
if self._scp_data_length is None:
length = consts.SCP_SVER_RECEIVE_LENGTH_MAX
else:
length... | def _send_scp(self, x, y, p, *args, **kwargs) | 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` ... | 9.083452 | 9.317844 | 0.974845 |
working_chips = set(
(x, y)
for (x, y), route in iteritems(self.get_p2p_routing_table(x, y))
if route != consts.P2PTableEntry.none)
self._width = max(x for x, y in working_chips) + 1
self._height = max(y for x, y in working_chips) + 1
num_new... | def discover_connections(self, x=255, y=255) | 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... | 4.118138 | 3.930976 | 1.047612 |
# Get a new context and add a method that will be called before the
# context is removed from the stack.
context = self(app_id=app_id)
context.before_close(lambda: self.send_signal("stop"))
return context | def application(self, app_id) | 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... | 8.798152 | 7.216468 | 1.219177 |
sver = self._send_scp(x, y, processor, SCPCommands.sver)
# Format the result
# arg1 => p2p address, physical cpu, virtual cpu
p2p = sver.arg1 >> 16
p2p_address = (p2p >> 8, p2p & 0x00ff)
pcpu = (sver.arg1 >> 8) & 0xff
vcpu = sver.arg1 & 0xff
# a... | def get_software_version(self, x=255, y=255, processor=0) | Get the software version for a given SpiNNaker core.
Returns
-------
:py:class:`.CoreInfo`
Information about the software running on a core. | 5.390061 | 5.598309 | 0.962802 |
chip_info = self.get_chip_info(x=x, y=y)
return chip_info.ip_address if chip_info.ethernet_up else None | def get_ip_address(self, x, y) | 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. | 5.120358 | 4.410312 | 1.160997 |
# Call the SCPConnection to perform the write on our behalf
connection = self._get_connection(x, y)
return connection.write(self.scp_data_length, self.scp_window_size,
x, y, p, address, data) | def write(self, address, data, x, y, p=0) | 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... | 8.797468 | 11.719251 | 0.750685 |
# Call the SCPConnection to perform the read on our behalf
connection = self._get_connection(x, y)
return connection.read(self.scp_data_length, self.scp_window_size,
x, y, p, address, length_bytes) | def read(self, address, length_bytes, x, y, p=0) | 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... | 7.251748 | 8.608434 | 0.8424 |
if address % 4:
raise ValueError("Addresses must be word-aligned.")
if len(data) % 4:
raise ValueError("Data must be a whole number of words.")
length_bytes = len(data)
cur_byte = 0
# Write the requested data, one SCP packet worth at a time
... | def write_across_link(self, address, data, x, y, link) | 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... | 4.120938 | 3.569391 | 1.154521 |
if address % 4:
raise ValueError("Addresses must be word-aligned.")
if length_bytes % 4:
raise ValueError("Lengths must be multiples of words.")
# Prepare the buffer to receive the incoming data
data = bytearray(length_bytes)
mem = memoryview(dat... | def read_across_link(self, address, length_bytes, x, y, link) | 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... | 4.623962 | 4.213618 | 1.097385 |
# Look up the struct and field
field, address, pack_chars = \
self._get_struct_field_and_address(struct_name, field_name)
length = struct.calcsize(pack_chars)
# Perform the read
data = self.read(address, length, x, y, p)
# Unpack the data
un... | def read_struct_field(self, struct_name, field_name, x, y, p=0) | 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
... | 3.013055 | 3.47753 | 0.866435 |
# Look up the struct and field
field, address, pack_chars = \
self._get_struct_field_and_address(struct_name, field_name)
if field.length != 1:
assert len(values) == field.length
data = struct.pack(pack_chars, *values)
else:
data ... | def write_struct_field(self, struct_name, field_name, values, x, y, p=0) | 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., `"... | 3.352365 | 3.776784 | 0.887624 |
vcpu_struct = self.structs[b"vcpu"]
field = vcpu_struct[six.b(field_name)]
address = (self.read_struct_field("sv", "vcpu_base", x, y) +
vcpu_struct.size * p) + field.offset
pack_chars = b"<" + field.pack_chars
return field, address, pack_chars | def _get_vcpu_field_and_address(self, field_name, x, y, p) | Get the field and address for a VCPU struct field. | 7.156507 | 6.094967 | 1.174167 |
# Get the base address of the VCPU struct for this chip, then advance
# to get the correct VCPU struct for the requested core.
field, address, pack_chars = \
self._get_vcpu_field_and_address(field_name, x, y, p)
# Perform the read
length = struct.calcsize(pa... | def read_vcpu_struct_field(self, field_name, x, y, p) | 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 ... | 4.511823 | 4.710034 | 0.957917 |
field, address, pack_chars = \
self._get_vcpu_field_and_address(field_name, x, y, p)
# Pack the data
if b"s" in pack_chars:
data = struct.pack(pack_chars, value.encode('utf-8'))
elif field.length == 1:
data = struct.pack(pack_chars, value)
... | def write_vcpu_struct_field(self, field_name, value, x, y, p) | 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. | 4.07661 | 4.443552 | 0.917421 |
# Get the VCPU base
address = (self.read_struct_field("sv", "vcpu_base", x, y) +
self.structs[b"vcpu"].size * p)
# Get the VCPU data
data = self.read(address, self.structs[b"vcpu"].size, x, y)
# Build the kwargs that describe the current state
... | def get_processor_status(self, p, x, y) | 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. | 4.130883 | 4.133651 | 0.99933 |
return self.get_iobuf_bytes(p, x, y).decode("utf-8") | def get_iobuf(self, p, x, y) | 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
... | 4.792802 | 5.295527 | 0.905066 |
# The IOBUF data is stored in a linked-list of blocks of memory in
# SDRAM. The size of each block is given in SV
iobuf_size = self.read_struct_field("sv", "iobuf_size", x, y)
# The first block in the list is given in the core's VCPU field
address = self.read_vcpu_struc... | def get_iobuf_bytes(self, p, x, y) | 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
--... | 6.805472 | 6.923491 | 0.982954 |
# Read the block of memory
data = self.read(0xe1000300, 64, x=x, y=y)
# Convert to 16 ints, then process that as the appropriate tuple type
return RouterDiagnostics(*struct.unpack("<16I", data)) | def get_router_diagnostics(self, x, y) | Get the values of the router diagnostic counters.
Returns
-------
:py:class:`~.RouterDiagnostics`
Description of the state of the counters. | 11.174158 | 11.952653 | 0.934868 |
# Format the IP address
ip_addr = struct.pack('!4B',
*map(int, socket.gethostbyname(addr).split('.')))
self._send_scp(x, y, 0, SCPCommands.iptag,
int(consts.IPTagCommands.set) << 16 | iptag,
port, struct.unpack(... | def iptag_set(self, iptag, addr, port, x, y) | 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... | 6.882615 | 6.648129 | 1.035271 |
ack = self._send_scp(x, y, 0, SCPCommands.iptag,
int(consts.IPTagCommands.get) << 16 | iptag, 1,
expected_args=0)
return IPTag.from_bytestring(ack.data) | def iptag_get(self, iptag, x, y) | Get the value of an IPTag.
Parameters
----------
iptag : int
Index of the IPTag to get
Returns
-------
:py:class:`.IPTag`
The IPTag returned from SpiNNaker. | 11.71147 | 12.252403 | 0.955851 |
self._send_scp(x, y, 0, SCPCommands.iptag,
int(consts.IPTagCommands.clear) << 16 | iptag) | def iptag_clear(self, iptag, x, y) | Clear an IPTag.
Parameters
----------
iptag : int
Index of the IPTag to clear. | 14.372979 | 14.339831 | 1.002312 |
if isinstance(led, int):
leds = [led]
else:
leds = led
arg1 = sum(LEDAction.from_bool(action) << (led * 2) for led in leds)
self._send_scp(x, y, 0, SCPCommands.led, arg1=arg1, expected_args=0) | def set_led(self, led, action=None, x=Required, y=Required) | 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 ... | 5.959416 | 6.279582 | 0.949015 |
if size % 4 or address % 4:
# If neither the size nor the address are word aligned we have to
# use `write` as `sark_word_set` can only work with words.
# Convert the data into a string and then write:
data = struct.pack('<B', data) * size
sel... | def fill(self, address, data, size, x, y, p) | 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
-----
... | 7.447569 | 6.935524 | 1.073829 |
assert 0 <= tag < 256
# Construct arg1 (app_id << 8) | op code
arg1 = app_id << 8 | consts.AllocOperations.alloc_sdram
# Send the packet and retrieve the address
rv = self._send_scp(x, y, 0, SCPCommands.alloc_free, arg1, size, tag)
if rv.arg1 == 0: # Allocatio... | def sdram_alloc(self, size, tag=0, x=Required, y=Required,
app_id=Required, clear=False) | 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
... | 5.804784 | 5.895413 | 0.984627 |
# Perform the malloc
start_address = self.sdram_alloc(size, tag, x, y, app_id, clear)
return MemoryIO(self, x, y, start_address, start_address + size) | def sdram_alloc_as_filelike(self, size, tag=0, x=Required, y=Required,
app_id=Required, clear=False) | 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
... | 4.268919 | 5.794504 | 0.736719 |
self._send_scp(x, y, 0, SCPCommands.alloc_free,
consts.AllocOperations.free_sdram_by_ptr, ptr) | def sdram_free(self, ptr, x=Required, y=Required) | 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... | 17.916817 | 22.095413 | 0.810884 |
self._nn_id = self._nn_id + 1 if self._nn_id < 126 else 1
return self._nn_id * 2 | def _get_next_nn_id(self) | Get the next nearest neighbour ID. | 3.234399 | 2.963749 | 1.09132 |
sfr = fr | (1 << 31)
self._send_scp(
255, 255, 0, SCPCommands.nearest_neighbour_packet,
(NNCommands.flood_fill_start << 24) | (pid << 16) |
(n_blocks << 8), 0x0, sfr
) | def _send_ffs(self, pid, n_blocks, fr) | 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). | 8.242321 | 7.574573 | 1.088157 |
arg1 = (NNCommands.flood_fill_core_select << 24) | core_mask
arg2 = region
self._send_scp(255, 255, 0, SCPCommands.nearest_neighbour_packet,
arg1, arg2, fr) | def _send_ffcs(self, region, core_mask, fr) | 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 ... | 9.238564 | 9.539269 | 0.968477 |
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 the address
data = aplx_data[pos:pos + self.scp_data_length]
data_size = len(data)
... | def _send_ffd(self, pid, aplx_data, address) | Send flood-fill data packets. | 4.859833 | 4.536006 | 1.07139 |
arg1 = (NNCommands.flood_fill_end << 24) | pid
arg2 = (app_id << 24) | (app_flags << 18)
self._send_scp(255, 255, 0, SCPCommands.nearest_neighbour_packet,
arg1, arg2, fr) | def _send_ffe(self, pid, app_id, app_flags, fr) | 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). | 6.969743 | 6.936087 | 1.004852 |
# Coerce the arguments into a single form. If there are two arguments
# then assume that we have filename and a map of chips and cores;
# otherwise there should be ONE argument which is of the form of the
# return value of `build_application_map`.
application_map = {}
... | def flood_fill_aplx(self, *args, **kwargs) | 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("... | 6.242309 | 5.670983 | 1.100745 |
if isinstance(signal, str):
try:
signal = getattr(consts.AppSignal, signal)
except AttributeError:
# The signal name is not present in consts.AppSignal! The next
# test will throw an appropriate exception since no string can
... | def send_signal(self, signal, app_id) | 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... | 6.263838 | 5.590756 | 1.120392 |
if (isinstance(state, collections.Iterable) and
not isinstance(state, str)):
# If the state is iterable then call for each state and return the
# sum.
return sum(self.count_cores_in_state(s, app_id) for s in state)
if isinstance(state, str):
... | def count_cores_in_state(self, state, app_id) | 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)... | 6.260738 | 5.926109 | 1.056467 |
if timeout is not None:
timeout_time = time.time() + timeout
while True:
cur_count = self.count_cores_in_state(state, app_id)
if cur_count >= count:
break
# Stop if timeout elapsed
if timeout is not None and time.time... | def wait_for_cores_to_reach_state(self, state, count, app_id,
poll_interval=0.1, timeout=None) | 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::
... | 2.498162 | 2.65634 | 0.940453 |
for (x, y), table in iteritems(routing_tables):
self.load_routing_table_entries(table, x=x, y=y, app_id=app_id) | def load_routing_tables(self, routing_tables, app_id) | 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`... | 3.805665 | 3.65118 | 1.042311 |
count = len(entries)
# Try to allocate room for the entries
rv = self._send_scp(
x, y, 0, SCPCommands.alloc_free,
(app_id << 8) | consts.AllocOperations.alloc_rtr, count
)
rtr_base = rv.arg1 # Index of the first allocated entry, 0 if failed
... | def load_routing_table_entries(self, entries, x, y, app_id) | 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... | 5.750344 | 5.615007 | 1.024103 |
# Determine where to read from, perform the read
rtr_addr = self.read_struct_field("sv", "rtr_copy", x, y)
read_size = struct.calcsize(consts.RTE_PACK_STRING)
rtr_data = self.read(rtr_addr, consts.RTR_ENTRIES * read_size, x, y)
# Read each routing table entry in turn
... | def get_routing_table_entries(self, x, y) | 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. | 4.778625 | 5.104167 | 0.93622 |
# Construct the arguments
arg1 = (app_id << 8) | consts.AllocOperations.free_rtr_by_app
self._send_scp(x, y, 0, SCPCommands.alloc_free, arg1, 0x1) | def clear_routing_table_entries(self, x, y, app_id) | Clear the routing table entries associated with a given application. | 13.513309 | 17.284941 | 0.781797 |
table = {}
# Get the dimensions of the system
p2p_dims = self.read_struct_field("sv", "p2p_dims", x, y)
width = (p2p_dims >> 8) & 0xFF
height = (p2p_dims >> 0) & 0xFF
# Read out the P2P table data, one column at a time (note that eight
# entries are pac... | def get_p2p_routing_table(self, x, y) | 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... | 4.570764 | 4.347086 | 1.051455 |
info = self._send_scp(x, y, 0, SCPCommands.info, expected_args=3)
# Unpack values encoded in the argument fields
num_cores = info.arg1 & 0x1F
working_links = set(link for link in Links
if (info.arg1 >> (8 + link)) & 1)
largest_free_rtr_mc_blo... | def get_chip_info(self, x, y) | 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... | 3.973775 | 3.629551 | 1.094839 |
# A quick way of getting a list of working chips
p2p_tables = self.get_p2p_routing_table(x, y)
# Calculate the extent of the system
max_x = max(x_ for (x_, y_), r in iteritems(p2p_tables)
if r != consts.P2PTableEntry.none)
max_y = max(y_ for (x_, y_)... | def get_system_info(self, x=255, y=255) | 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... | 3.498044 | 3.406454 | 1.026887 |
warnings.warn(
"MachineController.get_machine() is deprecated, "
"see get_system_info().", DeprecationWarning)
from rig.place_and_route.utils import build_machine
system_info = self.get_system_info(x, y)
return build_machine(system_info) | def get_machine(self, x=255, y=255, default_num_cores=18) | **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... | 5.041358 | 3.768866 | 1.337632 |
for xy, chip_info in six.iteritems(self):
if chip_info.ethernet_up:
yield (xy, chip_info.ip_address) | def ethernet_connected_chips(self) | 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. | 7.088246 | 5.947476 | 1.191807 |
for x in range(self.width):
for y in range(self.height):
if (x, y) not in self:
yield (x, y) | def dead_chips(self) | Generate the coordinates of all dead chips.
Yields
------
(x, y)
The coordinate of a dead chip. | 3.459547 | 2.690719 | 1.285733 |
for (x, y), chip_info in iteritems(self):
for link in chip_info.working_links:
yield (x, y, link) | def links(self) | 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). | 7.764599 | 4.358191 | 1.781611 |
for (x, y), chip_info in iteritems(self):
for link in Links:
if link not in chip_info.working_links:
yield (x, y, link) | def dead_links(self) | 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
... | 8.474686 | 4.579165 | 1.850705 |
for (x, y), chip_info in iteritems(self):
for p, state in enumerate(chip_info.core_states):
yield (x, y, p, state) | def cores(self) | 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. | 7.095607 | 4.554035 | 1.558092 |
# If n_bytes is negative then calculate it as the number of bytes left
if n_bytes < 0:
n_bytes = self._end_address - self.address
# Determine how far to read, then read nothing beyond that point.
if self.address + n_bytes > self._end_address:
new_n_bytes... | def read(self, n_bytes=-1) | 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 :... | 3.483094 | 3.403433 | 1.023406 |
if self.address + len(bytes) > self._end_address:
n_bytes = self._end_address - self.address
warnings.warn("write truncated from {} to {} bytes".format(
len(bytes), n_bytes), TruncationWarning, stacklevel=3)
bytes = bytes[:n_bytes]
if len(by... | def write(self, bytes) | Write data to the memory.
.. note::
Writes beyond the specified memory range will be truncated and a
:py:exc:`.TruncationWarning` is produced. These warnings can be
converted into exceptions using :py:func:`warnings.simplefilter`::
>>> import warnings
... | 3.45973 | 3.253622 | 1.063347 |
if from_what == 0:
self._offset = n_bytes
elif from_what == 1:
self._offset += n_bytes
elif from_what == 2:
self._offset = (self._end_address - self._start_address) - n_bytes
else:
raise ValueError(
"from_what: can ... | def seek(self, n_bytes, from_what=os.SEEK_SET) | Seek to a new position in the memory region.
Parameters
----------
n_bytes : int
Number of bytes to seek.
from_what : int
As in the Python standard: `0` seeks from the start of the memory
region, `1` seeks from the current position and `2` seeks from ... | 2.38518 | 2.477331 | 0.962802 |
# Free the memory
self._machine_controller.sdram_free(self._start_address,
self._x, self._y)
# Mark as freed
self._freed = True | def free(self) | Free the memory referred to by the file-like, any subsequent
operations on this file-like or slices of it will fail. | 9.921305 | 9.499028 | 1.044455 |
return self._machine_controller.read(addr, size, self._x, self._y, 0) | def _perform_read(self, addr, size) | Perform a read using the machine controller. | 9.307394 | 6.032731 | 1.542816 |
return self._machine_controller.write(addr, data, self._x, self._y, 0) | def _perform_write(self, addr, data) | Perform a write using the machine controller. | 9.226348 | 6.294701 | 1.465733 |
# Extract the header and the data from the packet
packet.data = bytestring[10:] # Everything but the header
# Unpack the header
(flags, packet.tag, dest_cpu_port, src_cpu_port,
packet.dest_y, packet.dest_x,
packet.src_y, packet.src_x) = struct.unpack_from('<2x8B', bytestring)
packet... | def _unpack_sdp_into_packet(packet, bytestring) | Unpack the SDP header from a bytestring into a packet.
Parameters
----------
packet : :py:class:`.SDPPacket`
Packet into which to store the unpacked header.
bytestring : bytes
Bytes from which to unpack the header data. | 3.877301 | 3.935881 | 0.985116 |
# Pack the header
scp_header = struct.pack("<2H", self.cmd_rc, self.seq)
# Potential loop intentionally unrolled
if self.arg1 is not None:
scp_header += struct.pack('<I', self.arg1)
if self.arg2 is not None:
scp_header += struct.pack('<I', self.a... | def packed_data(self) | Pack the data for the SCP packet. | 3.420729 | 2.942431 | 1.162552 |
hash_val = mmh3.hash64(key, seed)[0]
return struct.unpack('>Q', struct.pack('q', hash_val))[0] | def hash64(key, seed) | Wrapper around mmh3.hash64 to get us single 64-bit value.
This also does the extra work of ensuring that we always treat the
returned values as big-endian unsigned long, like smhasher used to
do. | 3.451321 | 3.275135 | 1.053795 |
def _make_hashfuncs(key):
if isinstance(key, text_type):
key = key.encode('utf-8')
else:
key = str(key)
rval = []
current_hash = 0
for i in range(nbr_slices):
seed = current_hash
current_hash = hash64(key, seed)
... | def generate_hashfunctions(nbr_bits, nbr_slices) | Generate a set of hash functions.
The core method is a 64-bit murmur3 hash which has a good distribution.
Multiple hashes can be generate using the previous hash value as a seed. | 2.699502 | 2.735059 | 0.986999 |
cargs = {}
for context in self.__context_stack:
cargs.update(context.context_arguments)
return cargs | def get_context_arguments(self) | Return a dictionary containing the current context arguments. | 5.269995 | 3.767346 | 1.398861 |
def decorator(f):
# Extract any positional and positional-and-key-word arguments
# which may be set.
arg_names, varargs, keywords, defaults = inspect.getargspec(f)
# Sanity check: non-keyword-only arguments should't be present in
# the keywor... | def use_contextual_arguments(**kw_only_args_defaults) | Decorator function which allows the wrapped function to accept
arguments not specified in the call from the context.
Arguments whose default value is set to the Required sentinel must be
supplied either by the context or the caller and a TypeError is raised
if not.
.. warning::... | 4.03475 | 3.868413 | 1.042999 |
table, _ = ordered_covering(routing_table, target_length, no_raise=True)
return remove_default_routes(table, target_length) | def minimise(routing_table, target_length) | Reduce the size of a routing table by merging together entries where
possible and by removing any remaining default routes.
.. warning::
The input routing table *must* also include entries which could be
removed and replaced by default routing.
.. warning::
It is assumed that the... | 9.459656 | 12.459239 | 0.759248 |
# Copy the aliases dictionary
aliases = dict(aliases)
# Perform an initial sort of the routing table in order of increasing
# generality.
routing_table = sorted(
routing_table,
key=lambda entry: _get_generality(entry.key, entry.mask)
)
while target_length is None or le... | def ordered_covering(routing_table, target_length, aliases=dict(),
no_raise=False) | Reduce the size of a routing table by merging together entries where
possible.
.. warning::
The input routing table *must* also include entries which could be
removed and replaced by default routing.
.. warning::
It is assumed that the input routing table is not in any particular... | 3.757803 | 3.080081 | 1.220034 |
xs = (~key) & (~mask)
return sum(1 for i in range(32) if xs & (1 << i)) | def _get_generality(key, mask) | Count the number of Xs in the key-mask pair.
For example, there are 32 Xs in ``0x00000000/0x00000000``::
>>> _get_generality(0x0, 0x0)
32
And no Xs in ``0xffffffff/0xffffffff``::
>>> _get_generality(0xffffffff, 0xffffffff)
0 | 7.588128 | 8.069559 | 0.94034 |
# Create an empty merge to start with
best_merge = _Merge(routing_table)
best_goodness = 0
# Look through every merge, discarding those that are no better than the
# best we currently know about.
for merge in _get_all_merges(routing_table):
# If the merge isn't sufficiently good ig... | def _get_best_merge(routing_table, aliases) | Inspect all possible merges for the routing table and return the merge
which would combine the greatest number of entries.
Returns
-------
:py:class:`~.Merge` | 5.37812 | 5.462945 | 0.984473 |
# Memorise entries that have been considered as part of a merge
considered_entries = set()
for i, entry in enumerate(routing_table):
# If we've already considered this entry then skip
if i in considered_entries:
continue
# Construct a merge by including other routi... | def _get_all_merges(routing_table) | Get possible sets of entries to merge.
Yields
------
:py:class:`~.Merge` | 4.470346 | 4.514745 | 0.990166 |
# We insert before blocks of equivalent generality, so decrement the given
# generality.
generality -= 1
# Wrapper for _get_generality which accepts a routing entry
def gg(entry):
return _get_generality(entry.key, entry.mask)
# Perform a binary search through the routing table
... | def _get_insertion_index(routing_table, generality) | Determine the index in the routing table where a new entry should be
inserted. | 4.116753 | 3.986287 | 1.032729 |
# Perform the down-check
merge = _refine_downcheck(merge, aliases, min_goodness)
# If the merge is still sufficiently good then continue to refine it.
if merge.goodness > min_goodness:
# Perform the up-check
merge, changed = _refine_upcheck(merge, min_goodness)
if changed ... | def _refine_merge(merge, aliases, min_goodness) | Remove entries from a merge to generate a valid merge which may be
applied to the routing table.
Parameters
----------
merge : :py:class:`~.Merge`
Initial merge to refine.
aliases : {(key, mask): {(key, mask), ...}, ...}
Map of key-mask pairs to the sets of key-mask pairs that they ... | 4.120466 | 4.063068 | 1.014127 |
# Remove any entries which would be covered by entries above the merge
# position.
changed = False
for i in sorted(merge.entries, reverse=True):
# Get all the entries that are between the entry we're looking at the
# insertion index of the proposed merged index. If this entry would ... | def _refine_upcheck(merge, min_goodness) | Remove from the merge any entries which would be covered by entries
between their current position and the merge insertion position.
For example, the third entry of::
0011 -> N
0100 -> N
1000 -> N
X000 -> NE
Cannot be merged with the first two entries because that would ge... | 5.828152 | 4.863371 | 1.198377 |
# For every entry in the table below the insertion index see which keys
# and masks would overlap with the key and mask of the merged entry.
for entry in merge.routing_table[merge.insertion_index:]:
key_mask = (entry.key, entry.mask)
keys_masks = aliases.get(key_mask, [key_mask])
... | def _get_covered_keys_and_masks(merge, aliases) | Get keys and masks which would be covered by the entry resulting from
the merge.
Parameters
----------
aliases : {(key, mask): {(key, mask), ...}, ...}
Map of key-mask pairs to the sets of key-mask pairs that they actually
represent.
Yields
------
(key, mask)
Pairs ... | 5.922349 | 5.179042 | 1.143522 |
# Create a new routing table of the correct size
new_size = len(self.routing_table) - len(self.entries) + 1
new_table = [None for _ in range(new_size)]
# Create a copy of the aliases dictionary
aliases = dict(aliases)
# Get the new entry
new_entry = Rou... | def apply(self, aliases) | Apply the merge to the routing table it is defined against and get a
new routing table and alias dictionary.
Returns
-------
[:py:class:`~rig.routing_table.RoutingTableEntry`, ...]
A new routing table which may be minimised further.
{(key, mask): {(key, mask), ...}}
... | 3.513086 | 3.149493 | 1.115445 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.