text
stringlengths
81
112k
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 ...
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 ...
Free the memory referred to by the file-like, any subsequent operations on this file-like or slices of it will fail. 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. """ # Free the memory ...
Perform a read using the machine controller. def _perform_read(self, addr, size): """Perform a read using the machine controller.""" return self._machine_controller.read(addr, size, self._x, self._y, 0)
Perform a write using the machine controller. def _perform_write(self, addr, data): """Perform a write using the machine controller.""" return self._machine_controller.write(addr, data, self._x, self._y, 0)
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. def _unpack_sdp_into_packet(packet, bytestring): """Unpack the...
Pack the data for the SCP packet. def packed_data(self): """Pack the data for the SCP packet.""" # 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'...
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. def hash64(key, seed): """ Wrapper around mmh3.hash64 to get us single 64-bit value. This also do...
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. def generate_hashfunctions(nbr_bits, nbr_slices): """Generate a set of hash functions. The core method is a 64-bit murmur3...
Return a dictionary containing the current context arguments. def get_context_arguments(self): """Return a dictionary containing the current context arguments.""" cargs = {} for context in self.__context_stack: cargs.update(context.context_arguments) return cargs
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::...
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...
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...
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 def _get_generality(key, mask): """Count the n...
Inspect all possible merges for the routing table and return the merge which would combine the greatest number of entries. Returns ------- :py:class:`~.Merge` def _get_best_merge(routing_table, aliases): """Inspect all possible merges for the routing table and return the merge which would comb...
Get possible sets of entries to merge. Yields ------ :py:class:`~.Merge` def _get_all_merges(routing_table): """Get possible sets of entries to merge. Yields ------ :py:class:`~.Merge` """ # Memorise entries that have been considered as part of a merge considered_entries = set...
Determine the index in the routing table where a new entry should be inserted. def _get_insertion_index(routing_table, generality): """Determine the index in the routing table where a new entry should be inserted. """ # We insert before blocks of equivalent generality, so decrement the given # ...
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 ...
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...
Prune the merge to avoid it covering up any entries which are below the merge insertion position. For example, in the (non-orthogonal) table:: 00001 -> N S 00011 -> N S 00100 -> N S 00X00 -> N S XX1XX -> 3 5 Merging the first four entries would generate the new key...
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 ...
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), ...}} ...
Locate pre-built packages in the _packages directory def find_packages(name, pkg_dir): """Locate pre-built packages in the _packages directory""" for c in (FileSystemPackageBuilder, ZipPackageBuilder, ExcelPackageBuilder): package_path, cache_path = c.make_package_path(pkg_dir, name) if packa...
The `mp new` command creates source package directories with a proper name, a `.gitignore` file, and optionally, example data, entries and code. Typical usage, for creating a new package with most of the example options, is :: mp new -o metatab.org -d tutorial -L -E -T "Quickstart Example Packa...
Initialize both bitarray. This BF contain two bit arrays instead of single one like a plain BF. bitarray is the main bit array where all the historical items are stored. It's the one used for the membership query. The second one, current_day_bitarray is the one used for creating the dai...
Initialize the period of BF. :period: datetime.datetime for setting the period explicity. def initialize_period(self, period=None): """Initialize the period of BF. :period: datetime.datetime for setting the period explicity. """ if not period: self.current_period =...
Progressively load the previous snapshot during the day. Loading all the snapshots at once can takes a substantial amount of time. This method, if called periodically during the day will progressively load those snapshots one by one. Because many workers are going to use this method at the same...
Restore the state of the BF using previous snapshots. :clean_old_snapshot: Delete the old snapshot on the disk (period < current - expiration) def restore_from_disk(self, clean_old_snapshot=False): """Restore the state of the BF using previous snapshots. :clean_old_snapshot: Delete the old sn...
Save the current state of the current day bitarray on disk. Save the internal representation (bitarray) into a binary file using this format: filename : name_expiration_2013-01-01.dat def save_snaphot(self): """Save the current state of the current day bitarray on disk. Save the i...
Blindly places vertices in sequential order onto chips in the machine. This algorithm sequentially places vertices onto chips in the order specified (or in an undefined order if not specified). This algorithm is essentially the simplest possible valid placement algorithm and is intended to form the bas...
Wrapper for core place-and-route tasks for the common case. This function takes a set of vertices and nets and produces placements, allocations, minimised routing tables and application loading information. .. note:: This function replaces the deprecated :py:func:`.wrapper` function and m...
Wrapper for core place-and-route tasks for the common case. At a high level this function essentially takes a set of vertices and nets and produces placements, memory allocations, routing tables and application loading information. .. warning:: This function is deprecated. New users should use...
Get the region word for the given chip co-ordinates. Parameters ---------- x : int x co-ordinate y : int y co-ordinate level : int Level of region to build. 0 is the most coarse and 3 is the finest. When 3 is used the specified region will ONLY select the given chip,...
Generate a reduced set of flood fill parameters. Parameters ---------- targets : {(x, y) : set([c, ...]), ...} For each used chip a set of core numbers onto which an application should be loaded. E.g., the output of :py:func:`~rig.place_and_route.util.build_application_map` when in...
Generate a set of ordered paired region and core mask representations. .. note:: The region and core masks are ordered such that ``(region << 32) | core_mask`` is monotonically increasing. Consequently region and core masks generated by this method can be used with SCAMP's ...
Add a new core to the region tree. Raises ------ ValueError If the co-ordinate is not contained within this part of the tree or the core number is out of range. Returns ------- bool True if the specified core is to be loaded to all su...
Transmit an SCP Packet to a specific board. Automatically determines the appropriate connection to use. See the arguments for :py:meth:`~rig.machine_control.scp_connection.SCPConnection` for details. Parameters ---------- cabinet : int frame : int ...
Determine the best connection to use to send an SCP packet and use it to transmit. See the arguments for :py:meth:`~rig.machine_control.scp_connection.SCPConnection` for details. def _send_scp(self, cabinet, frame, board, *args, **kwargs): """Determine the best connection to us...
Get the software version for a given BMP. Returns ------- :py:class:`.BMPInfo` Information about the software running on a BMP. def get_software_version(self, cabinet, frame, board): """Get the software version for a given BMP. Returns ------- :py:c...
Control power to the SpiNNaker chips and FPGAs on a board. Returns ------- state : bool True for power on, False for power off. board : int or iterable Specifies the board to control the power of. This may also be an iterable of multiple boards (in th...
Set or toggle the state of an LED. .. note:: At the time of writing, LED 7 is only set by the BMP on start-up to indicate that the watchdog timer reset the board. After this point, the LED is available for use by applications. Parameters ---------- l...
Read the value of an FPGA (SPI) register. See the SpI/O project's spinnaker_fpga design's `README`_ for a listing of FPGA registers. The SpI/O project can be found on GitHub at: https://github.com/SpiNNakerManchester/spio/ .. _README: https://github.com/SpiNNakerManchester/spio/\ ...
Write the value of an FPGA (SPI) register. See the SpI/O project's spinnaker_fpga design's `README`_ for a listing of FPGA registers. The SpI/O project can be found on GitHub at: https://github.com/SpiNNakerManchester/spio/ .. _README: https://github.com/SpiNNakerManchester/spio/\ ...
Read ADC data from the BMP including voltages and temperature. Returns ------- :py:class:`.ADCInfo` def read_adc(self, cabinet, frame, board): """Read ADC data from the BMP including voltages and temperature. Returns ------- :py:class:`.ADCInfo` """ ...
Return the resources after adding res_b's resources to res_a. Parameters ---------- res_a : dict Dictionary `{resource: value, ...}`. res_b : dict Dictionary `{resource: value, ...}`. Must be a (non-strict) subset of res_a. If A resource is not present in res_b, the value is pre...
Return the resources remaining after subtracting res_b's resources from res_a. Parameters ---------- res_a : dict Dictionary `{resource: value, ...}`. res_b : dict Dictionary `{resource: value, ...}`. Must be a (non-strict) subset of res_a. If A resource is not present in re...
Return the resources available after a specified ReserveResourceConstraint has been applied. Note: the caller is responsible for testing that the constraint is applicable to the core whose resources are being constrained. Note: this function does not pay attention to the specific position of the r...
Apply the changes implied by a reserve resource constraint to a machine model. def apply_reserve_resource_constraint(machine, constraint): """Apply the changes implied by a reserve resource constraint to a machine model.""" if constraint.location is None: # Compensate for globally reserved reso...
Modify a set of vertices_resources, nets and constraints to account for all SameChipConstraints. To allow placement algorithms to handle SameChipConstraints without any special cases, Vertices identified in a SameChipConstraint are merged into a new vertex whose vertices_resources are the sum total of ...
Given a set of placements containing the supplied :py:class:`MergedVertex`, remove the merged vertices replacing them with their constituent vertices (changing the placements inplace). def finalise_same_chip_constraints(substitutions, placements): """Given a set of placements containing the supplied :p...
Return the metatab document for the URL def doc(self): """Return the metatab document for the URL""" from metapack import MetapackDoc t = self.get_resource().get_target() return MetapackDoc(t, package_url=self.package_url)
Return a URL to a local copy of a resource, suitable for get_generator() def resolve_url(self, resource_name): """Return a URL to a local copy of a resource, suitable for get_generator()""" if self.target_format == 'csv' and self.target_file != DEFAULT_METATAB_FILE: # For CSV packages, nee...
Return the package URL associated with this metadata def package_url(self): """Return the package URL associated with this metadata""" if self.resource_file == DEFAULT_METATAB_FILE or self.target_format in ('txt','ipynb'): u = self.inner.clone().clear_fragment() u.path = dirnam...
Return a MetapackResourceUrl that includes a reference to the resource. Returns a MetapackResourceUrl, which will have a fragment def join_resource_name(self, v): """Return a MetapackResourceUrl that includes a reference to the resource. Returns a MetapackResourceUrl, which will have a fragment...
Return a URL to a local copy of a resource, suitable for get_generator() For Package URLS, resolution involves generating a URL to a data file from the package URL and the value of a resource. The resource value, the url, can be one of: - An absolute URL, with a web scheme - A relative...
Return the package URL associated with this metadata def package_url(self): """Return the package URL associated with this metadata""" return MetapackDocumentUrl(str(self.clear_fragment()), downloader=self._downloader).package_url
Return a search function for searching a directory of packages, which has an index.json file created by the `mp install file` command. This will only search the issued index; it will not return results for the source index def search_json_indexed_directory(directory): """Return a search functi...
Search for a url by returning the value from the first callback that returns a non-None value def search(self): """Search for a url by returning the value from the first callback that returns a non-None value""" for cb in SearchUrl.search_callbacks: try: v ...
Ensure all of the important directories in a source package exist def ensure_source_package_dir(nb_path, pkg_name): """Ensure all of the important directories in a source package exist""" pkg_path = join(dirname(nb_path), pkg_name) makedirs(join(pkg_path,'notebooks'),exist_ok=True) makedirs(join(pkg_...
Read a notebook and extract the metatab document. Only returns the first document def get_metatab_doc(nb_path): """Read a notebook and extract the metatab document. Only returns the first document""" from metatab.generate import CsvDataRowGenerator from metatab.rowgenerators import TextRowGenerator fr...
Return the package directory for a Notebook that has an embeded Metatab doc, *not* for notebooks that are part of a package def get_package_dir(nb_path): """Return the package directory for a Notebook that has an embeded Metatab doc, *not* for notebooks that are part of a package """ doc = get_metatab_...
Add schema entiries to a metatab doc from a dataframe def process_schema(doc, resource, df): """Add schema entiries to a metatab doc from a dataframe""" from rowgenerators import SourceError from requests.exceptions import ConnectionError from metapack.cli.core import extract_path_name, alt_col_name, ...
Boot a SpiNNaker machine of the given size. Parameters ---------- hostname : str Hostname or IP address of the SpiNNaker chip to use to boot the system. boot_port : int The port number to sent boot packets to. scamp_binary : filename or None Filename of the binary to boot th...
Create and transmit a packet to boot the machine. Parameters ---------- sock : :py:class:`~socket.socket` Connected socket to use to transmit the packet. cmd : int arg1 : int arg2 : int arg3 : int data : :py:class:`bytes` Optional data to include in the packet. def boot...
Produce a copy of this datastructure. def copy(self): """Produce a copy of this datastructure.""" return Machine( self.width, self.height, self.chip_resources, self.chip_resource_exceptions, self.dead_chips, self.dead_links)
Test whether the resources available in this machine description are a (non-strict) subset of those available in another machine. .. note:: This test being False does not imply that the this machine is a superset of the other machine; machines may have disjoint reso...
An iterator over the working links in the machine. Generates a series of (x, y, link) tuples. def iter_links(self): """An iterator over the working links in the machine. Generates a series of (x, y, link) tuples. """ for x in range(self.width): for y in range(self....
Test if a machine has wrap-around connections installed. Since the Machine object does not explicitly define whether a machine has wrap-around links they must be tested for directly. This test performs a "fuzzy" test on the number of wrap-around links which are working to determine if w...
Write a Metatab doc to a CSV file, and update the Modified time :param doc: :param mt_file: :return: def write_doc(doc : MetapackDoc, mt_file=None): """ Write a Metatab doc to a CSV file, and update the Modified time :param doc: :param mt_file: :return: """ from rowgenerators i...
Get descriptions and other properties from this, or upstream, packages, and add them to the schema. def update_resource_properties(r, orig_columns={}, force=False): """Get descriptions and other properties from this, or upstream, packages, and add them to the schema. """ added = [] schema_term = r.schema...
Return a configuration dict def get_config(): """Return a configuration dict""" from os import environ from os.path import expanduser from pathlib import Path import yaml def pexp(p): try: return Path(p).expanduser() except AttributeError: # python 3.4 ...
Locate the build CSV package, which will have distributions if it was generated as and S3 package def find_csv_packages(m, downloader): """Locate the build CSV package, which will have distributions if it was generated as and S3 package""" from metapack.package import CsvPackageBuilder pkg_dir =...
ProvisioningConfiguration. :param body: :type body: :class:`ContinuousDeploymentConfiguration <vsts_info_provider.models.ContinuousDeploymentConfiguration>` :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongs...
GetContinuousDeploymentOperation. :param provisioning_configuration_id: :type provisioning_configuration_id: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param...
Serialize EmailMessages to be passed as task argument. Pickle is used because serializing an EmailMessage to json can be a bit tricky and would probably break if Django modifies the structure of the object in the future. def serialize_email_messages(messages: List[EmailMessage]): """Serialize EmailMes...
Deserialize EmailMessages passed as task argument. def deserialize_email_messages(messages: List[str]): """Deserialize EmailMessages passed as task argument.""" return [ pickle.loads(zlib.decompress(base64.b64decode(m))) for m in messages ]
Update the count number using the estimation of the unset ratio def _estimate_count(self): """ Update the count number using the estimation of the unset ratio """ if self.estimate_z == 0: self.estimate_z = (1.0 / self.nbr_bits) self.estimate_z = min(self.estimate_z, 0.999999) ...
Decrement cell value if not zero This maintenance process need to executed each self.compute_refresh_time() def expiration_maintenance(self): """ Decrement cell value if not zero This maintenance process need to executed each self.compute_refresh_time() """ if self.cella...
Batched version of expiration_maintenance() def batched_expiration_maintenance_dev(self, elapsed_time): """ Batched version of expiration_maintenance() """ num_iterations = self.num_batched_maintenance(elapsed_time) for i in range(num_iterations): self.expiration_maintenance()
Batched version of expiration_maintenance() Cython version def batched_expiration_maintenance(self, elapsed_time): """ Batched version of expiration_maintenance() Cython version """ num_iterations = self.num_batched_maintenance(elapsed_time) self.refresh_head, no...
Compute the refresh period for the given expiration delay def compute_refresh_time(self): """ Compute the refresh period for the given expiration delay """ if self.z == 0: self.z = 1E-10 s = float(self.expiration) * (1.0/(self.nbr_bits)) * (1.0/(self.counter_init - 1 + (1.0/(self.z ...
input_source = InputSource(id='iclamp0', pynn_input='DCSource', parameters={'amplitude':0.002, 'start':100., 'stop':900.}) input_source = InputSource(id='poissonFiringSyn', neuroml2_input='poissonFiringSynapse', ...
Allocate resources to vertices on cores arbitrarily using a simple greedy algorithm. def allocate(vertices_resources, nets, machine, constraints, placements): """Allocate resources to vertices on cores arbitrarily using a simple greedy algorithm. """ allocation = {} # Globally reserved resourc...
Apply QoS rules on port for the first time. :param port: port object. :param qos_policy: the QoS policy to be applied on port. def create(self, port, qos_policy): """Apply QoS rules on port for the first time. :param port: port object. :param qos_policy: the QoS policy to be a...
Remove QoS rules from port. :param port: port object. :param qos_policy: the QoS policy to be removed from port. def delete(self, port, qos_policy=None): """Remove QoS rules from port. :param port: port object. :param qos_policy: the QoS policy to be removed from port. ...
Decorator to register a task function. :arg name: name of the task, used later to schedule jobs :arg queue: queue of the task, the default is used if not provided :arg max_retries: maximum number of retries, the default is used if not provided :arg periodicity: for periodic...
Register a task function. :arg func: a callable to be executed :arg name: name of the task, used later to schedule jobs :arg queue: queue of the task, the default is used if not provided :arg max_retries: maximum number of retries, the default is used if not provided ...
Schedule a job to be executed as soon as possible. :arg task: the task or its name to execute in the background :arg args: args to be passed to the task function :arg kwargs: kwargs to be passed to the task function This method can only be used once tasks have been attached to a ...
Schedule a job to be executed in the future. :arg task: the task or its name to execute in the background :arg at: Date at which the job should start. It is advised to pass a timezone aware datetime to lift any ambiguity. However if a timezone naive datetime if given, ...
Add a job to be executed ASAP to the batch. :arg task: the task or its name to execute in the background :arg args: args to be passed to the task function :arg kwargs: kwargs to be passed to the task function def schedule(self, task: Schedulable, *args, **kwargs): """Add a job to be ex...
Add a job to be executed in the future to the batch. :arg task: the task or its name to execute in the background :arg at: Date at which the job should start. It is advised to pass a timezone aware datetime to lift any ambiguity. However if a timezone naive datetime if...
For internal use. Unpack the version-related parts of an sver (aka CMD_VERSION) response. Parameters ---------- packet : :py:class:`~rig.machine_control.packets.SCPPacket` The packet recieved in response to the version command. Returns ------- software_name : string The nam...
Utility method for finding full path to a filename as string def _locate_file(f, base_dir): """ Utility method for finding full path to a filename as string """ if base_dir == None: return f file_name = os.path.join(base_dir, f) real = os.path.realpath(file_name) #print_v('- Located...
Generate the network model as described in NeuroMLlite in a specific handler, e.g. NeuroMLHandler, PyNNHandler, etc. def generate_network(nl_model, handler, seed=1234, always_include_props=False, include_connections=True, ...
Useful method for calling in main method after network and simulation are generated, to handle some standard export options like -jnml, -graph etc. def check_to_generate_or_run(argv, sim): """ Useful method for calling in main method after network and simulation are generated, to handle some standard...
Parse the NeuroMLlite description for cell, synapses and inputs described as PyNN elements (e.g. IF_cond_alpha, DCSource) and parameters, and convert these to the equivalent elements in a NeuroMLDocument def _extract_pynn_components_to_neuroml(nl_model, nml_doc=None): """ Parse the NeuroMLlite descri...
Generate and save NeuroML2 file (in either XML or HDF5 format) from the NeuroMLlite description def generate_neuroml2_from_network(nl_model, nml_file_name=None, print_summary=True, seed=1234, ...
Generate NEURON hoc/mod files from the NeuroML files which are marked as included in the NeuroMLlite description; also compiles the mod files def _generate_neuron_files_from_neuroml(network, verbose=False, dir_for_mod_files = None): """ Generate NEURON hoc/mod files from the NeuroML files which are marked...
Generates the network in the specified simulator and runs, if appropriate def generate_and_run(simulation, simulator, network=None, return_results=False, base_dir=None, target_dir=None, num...
Print a summary of the returned (voltage) traces and spike times def _print_result_info(traces, events): """ Print a summary of the returned (voltage) traces and spike times """ print_v('Returning %i traces:'%len(traces)) for r in sorted(traces.keys()): x = traces[r] print_v(' %s (...