repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_code_tokens
sequencelengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
sequencelengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
UCSBarchlab/PyRTL | pyrtl/core.py | _get_useful_callpoint_name | def _get_useful_callpoint_name():
""" Attempts to find the lowest user-level call into the pyrtl module
:return (string, int) or None: the file name and line number respectively
This function walks back the current frame stack attempting to find the
first frame that is not part of the pyrtl module. The filename (stripped
of path and .py extention) and line number of that call are returned.
This point should be the point where the user-level code is making the
call to some pyrtl intrisic (for example, calling "mux"). If the
attempt to find the callpoint fails for any reason, None is returned.
"""
if not _setting_slower_but_more_descriptive_tmps:
return None
import inspect
loc = None
frame_stack = inspect.stack()
try:
for frame in frame_stack:
modname = inspect.getmodule(frame[0]).__name__
if not modname.startswith('pyrtl.'):
full_filename = frame[0].f_code.co_filename
filename = full_filename.split('/')[-1].rstrip('.py')
lineno = frame[0].f_lineno
loc = (filename, lineno)
break
except:
loc = None
finally:
del frame_stack
return loc | python | def _get_useful_callpoint_name():
""" Attempts to find the lowest user-level call into the pyrtl module
:return (string, int) or None: the file name and line number respectively
This function walks back the current frame stack attempting to find the
first frame that is not part of the pyrtl module. The filename (stripped
of path and .py extention) and line number of that call are returned.
This point should be the point where the user-level code is making the
call to some pyrtl intrisic (for example, calling "mux"). If the
attempt to find the callpoint fails for any reason, None is returned.
"""
if not _setting_slower_but_more_descriptive_tmps:
return None
import inspect
loc = None
frame_stack = inspect.stack()
try:
for frame in frame_stack:
modname = inspect.getmodule(frame[0]).__name__
if not modname.startswith('pyrtl.'):
full_filename = frame[0].f_code.co_filename
filename = full_filename.split('/')[-1].rstrip('.py')
lineno = frame[0].f_lineno
loc = (filename, lineno)
break
except:
loc = None
finally:
del frame_stack
return loc | [
"def",
"_get_useful_callpoint_name",
"(",
")",
":",
"if",
"not",
"_setting_slower_but_more_descriptive_tmps",
":",
"return",
"None",
"import",
"inspect",
"loc",
"=",
"None",
"frame_stack",
"=",
"inspect",
".",
"stack",
"(",
")",
"try",
":",
"for",
"frame",
"in",
"frame_stack",
":",
"modname",
"=",
"inspect",
".",
"getmodule",
"(",
"frame",
"[",
"0",
"]",
")",
".",
"__name__",
"if",
"not",
"modname",
".",
"startswith",
"(",
"'pyrtl.'",
")",
":",
"full_filename",
"=",
"frame",
"[",
"0",
"]",
".",
"f_code",
".",
"co_filename",
"filename",
"=",
"full_filename",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
".",
"rstrip",
"(",
"'.py'",
")",
"lineno",
"=",
"frame",
"[",
"0",
"]",
".",
"f_lineno",
"loc",
"=",
"(",
"filename",
",",
"lineno",
")",
"break",
"except",
":",
"loc",
"=",
"None",
"finally",
":",
"del",
"frame_stack",
"return",
"loc"
] | Attempts to find the lowest user-level call into the pyrtl module
:return (string, int) or None: the file name and line number respectively
This function walks back the current frame stack attempting to find the
first frame that is not part of the pyrtl module. The filename (stripped
of path and .py extention) and line number of that call are returned.
This point should be the point where the user-level code is making the
call to some pyrtl intrisic (for example, calling "mux"). If the
attempt to find the callpoint fails for any reason, None is returned. | [
"Attempts",
"to",
"find",
"the",
"lowest",
"user",
"-",
"level",
"call",
"into",
"the",
"pyrtl",
"module",
":",
"return",
"(",
"string",
"int",
")",
"or",
"None",
":",
"the",
"file",
"name",
"and",
"line",
"number",
"respectively"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/core.py#L614-L644 |
UCSBarchlab/PyRTL | pyrtl/core.py | set_debug_mode | def set_debug_mode(debug=True):
""" Set the global debug mode. """
global debug_mode
global _setting_keep_wirevector_call_stack
global _setting_slower_but_more_descriptive_tmps
debug_mode = debug
_setting_keep_wirevector_call_stack = debug
_setting_slower_but_more_descriptive_tmps = debug | python | def set_debug_mode(debug=True):
""" Set the global debug mode. """
global debug_mode
global _setting_keep_wirevector_call_stack
global _setting_slower_but_more_descriptive_tmps
debug_mode = debug
_setting_keep_wirevector_call_stack = debug
_setting_slower_but_more_descriptive_tmps = debug | [
"def",
"set_debug_mode",
"(",
"debug",
"=",
"True",
")",
":",
"global",
"debug_mode",
"global",
"_setting_keep_wirevector_call_stack",
"global",
"_setting_slower_but_more_descriptive_tmps",
"debug_mode",
"=",
"debug",
"_setting_keep_wirevector_call_stack",
"=",
"debug",
"_setting_slower_but_more_descriptive_tmps",
"=",
"debug"
] | Set the global debug mode. | [
"Set",
"the",
"global",
"debug",
"mode",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/core.py#L699-L706 |
UCSBarchlab/PyRTL | pyrtl/core.py | Block.add_wirevector | def add_wirevector(self, wirevector):
""" Add a wirevector object to the block."""
self.sanity_check_wirevector(wirevector)
self.wirevector_set.add(wirevector)
self.wirevector_by_name[wirevector.name] = wirevector | python | def add_wirevector(self, wirevector):
""" Add a wirevector object to the block."""
self.sanity_check_wirevector(wirevector)
self.wirevector_set.add(wirevector)
self.wirevector_by_name[wirevector.name] = wirevector | [
"def",
"add_wirevector",
"(",
"self",
",",
"wirevector",
")",
":",
"self",
".",
"sanity_check_wirevector",
"(",
"wirevector",
")",
"self",
".",
"wirevector_set",
".",
"add",
"(",
"wirevector",
")",
"self",
".",
"wirevector_by_name",
"[",
"wirevector",
".",
"name",
"]",
"=",
"wirevector"
] | Add a wirevector object to the block. | [
"Add",
"a",
"wirevector",
"object",
"to",
"the",
"block",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/core.py#L224-L228 |
UCSBarchlab/PyRTL | pyrtl/core.py | Block.remove_wirevector | def remove_wirevector(self, wirevector):
""" Remove a wirevector object to the block."""
self.wirevector_set.remove(wirevector)
del self.wirevector_by_name[wirevector.name] | python | def remove_wirevector(self, wirevector):
""" Remove a wirevector object to the block."""
self.wirevector_set.remove(wirevector)
del self.wirevector_by_name[wirevector.name] | [
"def",
"remove_wirevector",
"(",
"self",
",",
"wirevector",
")",
":",
"self",
".",
"wirevector_set",
".",
"remove",
"(",
"wirevector",
")",
"del",
"self",
".",
"wirevector_by_name",
"[",
"wirevector",
".",
"name",
"]"
] | Remove a wirevector object to the block. | [
"Remove",
"a",
"wirevector",
"object",
"to",
"the",
"block",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/core.py#L230-L233 |
UCSBarchlab/PyRTL | pyrtl/core.py | Block.add_net | def add_net(self, net):
""" Add a net to the logic of the block.
The passed net, which must be of type LogicNet, is checked and then
added to the block. No wires are added by this member, they must be
added seperately with add_wirevector."""
self.sanity_check_net(net)
self.logic.add(net) | python | def add_net(self, net):
""" Add a net to the logic of the block.
The passed net, which must be of type LogicNet, is checked and then
added to the block. No wires are added by this member, they must be
added seperately with add_wirevector."""
self.sanity_check_net(net)
self.logic.add(net) | [
"def",
"add_net",
"(",
"self",
",",
"net",
")",
":",
"self",
".",
"sanity_check_net",
"(",
"net",
")",
"self",
".",
"logic",
".",
"add",
"(",
"net",
")"
] | Add a net to the logic of the block.
The passed net, which must be of type LogicNet, is checked and then
added to the block. No wires are added by this member, they must be
added seperately with add_wirevector. | [
"Add",
"a",
"net",
"to",
"the",
"logic",
"of",
"the",
"block",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/core.py#L235-L243 |
UCSBarchlab/PyRTL | pyrtl/core.py | Block.wirevector_subset | def wirevector_subset(self, cls=None, exclude=tuple()):
"""Return set of wirevectors, filtered by the type or tuple of types provided as cls.
If no cls is specified, the full set of wirevectors associated with the Block are
returned. If cls is a single type, or a tuple of types, only those wirevectors of
the matching types will be returned. This is helpful for getting all inputs, outputs,
or registers of a block for example."""
if cls is None:
initial_set = self.wirevector_set
else:
initial_set = (x for x in self.wirevector_set if isinstance(x, cls))
if exclude == tuple():
return set(initial_set)
else:
return set(x for x in initial_set if not isinstance(x, exclude)) | python | def wirevector_subset(self, cls=None, exclude=tuple()):
"""Return set of wirevectors, filtered by the type or tuple of types provided as cls.
If no cls is specified, the full set of wirevectors associated with the Block are
returned. If cls is a single type, or a tuple of types, only those wirevectors of
the matching types will be returned. This is helpful for getting all inputs, outputs,
or registers of a block for example."""
if cls is None:
initial_set = self.wirevector_set
else:
initial_set = (x for x in self.wirevector_set if isinstance(x, cls))
if exclude == tuple():
return set(initial_set)
else:
return set(x for x in initial_set if not isinstance(x, exclude)) | [
"def",
"wirevector_subset",
"(",
"self",
",",
"cls",
"=",
"None",
",",
"exclude",
"=",
"tuple",
"(",
")",
")",
":",
"if",
"cls",
"is",
"None",
":",
"initial_set",
"=",
"self",
".",
"wirevector_set",
"else",
":",
"initial_set",
"=",
"(",
"x",
"for",
"x",
"in",
"self",
".",
"wirevector_set",
"if",
"isinstance",
"(",
"x",
",",
"cls",
")",
")",
"if",
"exclude",
"==",
"tuple",
"(",
")",
":",
"return",
"set",
"(",
"initial_set",
")",
"else",
":",
"return",
"set",
"(",
"x",
"for",
"x",
"in",
"initial_set",
"if",
"not",
"isinstance",
"(",
"x",
",",
"exclude",
")",
")"
] | Return set of wirevectors, filtered by the type or tuple of types provided as cls.
If no cls is specified, the full set of wirevectors associated with the Block are
returned. If cls is a single type, or a tuple of types, only those wirevectors of
the matching types will be returned. This is helpful for getting all inputs, outputs,
or registers of a block for example. | [
"Return",
"set",
"of",
"wirevectors",
"filtered",
"by",
"the",
"type",
"or",
"tuple",
"of",
"types",
"provided",
"as",
"cls",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/core.py#L245-L259 |
UCSBarchlab/PyRTL | pyrtl/core.py | Block.logic_subset | def logic_subset(self, op=None):
"""Return set of logicnets, filtered by the type(s) of logic op provided as op.
If no op is specified, the full set of logicnets associated with the Block are
returned. This is helpful for getting all memories of a block for example."""
if op is None:
return self.logic
else:
return set(x for x in self.logic if x.op in op) | python | def logic_subset(self, op=None):
"""Return set of logicnets, filtered by the type(s) of logic op provided as op.
If no op is specified, the full set of logicnets associated with the Block are
returned. This is helpful for getting all memories of a block for example."""
if op is None:
return self.logic
else:
return set(x for x in self.logic if x.op in op) | [
"def",
"logic_subset",
"(",
"self",
",",
"op",
"=",
"None",
")",
":",
"if",
"op",
"is",
"None",
":",
"return",
"self",
".",
"logic",
"else",
":",
"return",
"set",
"(",
"x",
"for",
"x",
"in",
"self",
".",
"logic",
"if",
"x",
".",
"op",
"in",
"op",
")"
] | Return set of logicnets, filtered by the type(s) of logic op provided as op.
If no op is specified, the full set of logicnets associated with the Block are
returned. This is helpful for getting all memories of a block for example. | [
"Return",
"set",
"of",
"logicnets",
"filtered",
"by",
"the",
"type",
"(",
"s",
")",
"of",
"logic",
"op",
"provided",
"as",
"op",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/core.py#L261-L269 |
UCSBarchlab/PyRTL | pyrtl/core.py | Block.get_wirevector_by_name | def get_wirevector_by_name(self, name, strict=False):
"""Return the wirevector matching name.
By fallthrough, if a matching wirevector cannot be found the value None is
returned. However, if the argument strict is set to True, then this will
instead throw a PyrtlError when no match is found."""
if name in self.wirevector_by_name:
return self.wirevector_by_name[name]
elif strict:
raise PyrtlError('error, block does not have a wirevector named %s' % name)
else:
return None | python | def get_wirevector_by_name(self, name, strict=False):
"""Return the wirevector matching name.
By fallthrough, if a matching wirevector cannot be found the value None is
returned. However, if the argument strict is set to True, then this will
instead throw a PyrtlError when no match is found."""
if name in self.wirevector_by_name:
return self.wirevector_by_name[name]
elif strict:
raise PyrtlError('error, block does not have a wirevector named %s' % name)
else:
return None | [
"def",
"get_wirevector_by_name",
"(",
"self",
",",
"name",
",",
"strict",
"=",
"False",
")",
":",
"if",
"name",
"in",
"self",
".",
"wirevector_by_name",
":",
"return",
"self",
".",
"wirevector_by_name",
"[",
"name",
"]",
"elif",
"strict",
":",
"raise",
"PyrtlError",
"(",
"'error, block does not have a wirevector named %s'",
"%",
"name",
")",
"else",
":",
"return",
"None"
] | Return the wirevector matching name.
By fallthrough, if a matching wirevector cannot be found the value None is
returned. However, if the argument strict is set to True, then this will
instead throw a PyrtlError when no match is found. | [
"Return",
"the",
"wirevector",
"matching",
"name",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/core.py#L271-L282 |
UCSBarchlab/PyRTL | pyrtl/core.py | Block.net_connections | def net_connections(self, include_virtual_nodes=False):
""" Returns a representation of the current block useful for creating a graph.
:param include_virtual_nodes: if enabled, the wire itself will be used to
signal an external source or sink (such as the source for an Input net).
If disabled, these nodes will be excluded from the adjacency dictionaries
:return wire_src_dict, wire_sink_dict
Returns two dictionaries: one that map WireVectors to the logic
nets that creates their signal and one that maps WireVectors to
a list of logic nets that use the signal
These dictionaries make the creation of a graph much easier, as
well as facilitate other places in which one would need wire source
and wire sink information
Look at input_output.net_graph for one such graph that uses the information
from this function
"""
src_list = {}
dst_list = {}
def add_wire_src(edge, node):
if edge in src_list:
raise PyrtlError('Wire "{}" has multiple drivers (check for multiple assignments '
'with "<<=" or accidental mixing of "|=" and "<<=")'.format(edge))
src_list[edge] = node
def add_wire_dst(edge, node):
if edge in dst_list:
# if node in dst_list[edge]:
# raise PyrtlError("The net already exists in the graph")
dst_list[edge].append(node)
else:
dst_list[edge] = [node]
if include_virtual_nodes:
from .wire import Input, Output, Const
for wire in self.wirevector_subset((Input, Const)):
add_wire_src(wire, wire)
for wire in self.wirevector_subset(Output):
add_wire_dst(wire, wire)
for net in self.logic:
for arg in set(net.args): # prevents unexpected duplicates when doing b <<= a & a
add_wire_dst(arg, net)
for dest in net.dests:
add_wire_src(dest, net)
return src_list, dst_list | python | def net_connections(self, include_virtual_nodes=False):
""" Returns a representation of the current block useful for creating a graph.
:param include_virtual_nodes: if enabled, the wire itself will be used to
signal an external source or sink (such as the source for an Input net).
If disabled, these nodes will be excluded from the adjacency dictionaries
:return wire_src_dict, wire_sink_dict
Returns two dictionaries: one that map WireVectors to the logic
nets that creates their signal and one that maps WireVectors to
a list of logic nets that use the signal
These dictionaries make the creation of a graph much easier, as
well as facilitate other places in which one would need wire source
and wire sink information
Look at input_output.net_graph for one such graph that uses the information
from this function
"""
src_list = {}
dst_list = {}
def add_wire_src(edge, node):
if edge in src_list:
raise PyrtlError('Wire "{}" has multiple drivers (check for multiple assignments '
'with "<<=" or accidental mixing of "|=" and "<<=")'.format(edge))
src_list[edge] = node
def add_wire_dst(edge, node):
if edge in dst_list:
# if node in dst_list[edge]:
# raise PyrtlError("The net already exists in the graph")
dst_list[edge].append(node)
else:
dst_list[edge] = [node]
if include_virtual_nodes:
from .wire import Input, Output, Const
for wire in self.wirevector_subset((Input, Const)):
add_wire_src(wire, wire)
for wire in self.wirevector_subset(Output):
add_wire_dst(wire, wire)
for net in self.logic:
for arg in set(net.args): # prevents unexpected duplicates when doing b <<= a & a
add_wire_dst(arg, net)
for dest in net.dests:
add_wire_src(dest, net)
return src_list, dst_list | [
"def",
"net_connections",
"(",
"self",
",",
"include_virtual_nodes",
"=",
"False",
")",
":",
"src_list",
"=",
"{",
"}",
"dst_list",
"=",
"{",
"}",
"def",
"add_wire_src",
"(",
"edge",
",",
"node",
")",
":",
"if",
"edge",
"in",
"src_list",
":",
"raise",
"PyrtlError",
"(",
"'Wire \"{}\" has multiple drivers (check for multiple assignments '",
"'with \"<<=\" or accidental mixing of \"|=\" and \"<<=\")'",
".",
"format",
"(",
"edge",
")",
")",
"src_list",
"[",
"edge",
"]",
"=",
"node",
"def",
"add_wire_dst",
"(",
"edge",
",",
"node",
")",
":",
"if",
"edge",
"in",
"dst_list",
":",
"# if node in dst_list[edge]:",
"# raise PyrtlError(\"The net already exists in the graph\")",
"dst_list",
"[",
"edge",
"]",
".",
"append",
"(",
"node",
")",
"else",
":",
"dst_list",
"[",
"edge",
"]",
"=",
"[",
"node",
"]",
"if",
"include_virtual_nodes",
":",
"from",
".",
"wire",
"import",
"Input",
",",
"Output",
",",
"Const",
"for",
"wire",
"in",
"self",
".",
"wirevector_subset",
"(",
"(",
"Input",
",",
"Const",
")",
")",
":",
"add_wire_src",
"(",
"wire",
",",
"wire",
")",
"for",
"wire",
"in",
"self",
".",
"wirevector_subset",
"(",
"Output",
")",
":",
"add_wire_dst",
"(",
"wire",
",",
"wire",
")",
"for",
"net",
"in",
"self",
".",
"logic",
":",
"for",
"arg",
"in",
"set",
"(",
"net",
".",
"args",
")",
":",
"# prevents unexpected duplicates when doing b <<= a & a",
"add_wire_dst",
"(",
"arg",
",",
"net",
")",
"for",
"dest",
"in",
"net",
".",
"dests",
":",
"add_wire_src",
"(",
"dest",
",",
"net",
")",
"return",
"src_list",
",",
"dst_list"
] | Returns a representation of the current block useful for creating a graph.
:param include_virtual_nodes: if enabled, the wire itself will be used to
signal an external source or sink (such as the source for an Input net).
If disabled, these nodes will be excluded from the adjacency dictionaries
:return wire_src_dict, wire_sink_dict
Returns two dictionaries: one that map WireVectors to the logic
nets that creates their signal and one that maps WireVectors to
a list of logic nets that use the signal
These dictionaries make the creation of a graph much easier, as
well as facilitate other places in which one would need wire source
and wire sink information
Look at input_output.net_graph for one such graph that uses the information
from this function | [
"Returns",
"a",
"representation",
"of",
"the",
"current",
"block",
"useful",
"for",
"creating",
"a",
"graph",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/core.py#L284-L332 |
UCSBarchlab/PyRTL | pyrtl/core.py | Block.sanity_check | def sanity_check(self):
""" Check block and throw PyrtlError or PyrtlInternalError if there is an issue.
Should not modify anything, only check data structures to make sure they have been
built according to the assumptions stated in the Block comments."""
# TODO: check that the wirevector_by_name is sane
from .wire import Input, Const, Output
from .helperfuncs import get_stack, get_stacks
# check for valid LogicNets (and wires)
for net in self.logic:
self.sanity_check_net(net)
for w in self.wirevector_subset():
if w.bitwidth is None:
raise PyrtlError(
'error, missing bitwidth for WireVector "%s" \n\n %s' % (w.name, get_stack(w)))
# check for unique names
wirevector_names_set = set(x.name for x in self.wirevector_set)
if len(self.wirevector_set) != len(wirevector_names_set):
wirevector_names_list = [x.name for x in self.wirevector_set]
for w in wirevector_names_set:
wirevector_names_list.remove(w)
raise PyrtlError('Duplicate wire names found for the following '
'different signals: %s' % repr(wirevector_names_list))
# check for dead input wires (not connected to anything)
all_input_and_consts = self.wirevector_subset((Input, Const))
# The following line also checks for duplicate wire drivers
wire_src_dict, wire_dst_dict = self.net_connections()
dest_set = set(wire_src_dict.keys())
arg_set = set(wire_dst_dict.keys())
full_set = dest_set | arg_set
connected_minus_allwires = full_set.difference(self.wirevector_set)
if len(connected_minus_allwires) > 0:
bad_wire_names = '\n '.join(str(x) for x in connected_minus_allwires)
raise PyrtlError('Unknown wires found in net:\n %s \n\n %s' % (bad_wire_names,
get_stacks(*connected_minus_allwires)))
allwires_minus_connected = self.wirevector_set.difference(full_set)
allwires_minus_connected = allwires_minus_connected.difference(all_input_and_consts)
# ^ allow inputs and consts to be unconnected
if len(allwires_minus_connected) > 0:
bad_wire_names = '\n '.join(str(x) for x in allwires_minus_connected)
raise PyrtlError('Wires declared but not connected:\n %s \n\n %s' % (bad_wire_names,
get_stacks(*allwires_minus_connected)))
# Check for wires that are inputs to a logicNet, but are not block inputs and are never
# driven.
ins = arg_set.difference(dest_set)
undriven = ins.difference(all_input_and_consts)
if len(undriven) > 0:
raise PyrtlError('Wires used but never driven: %s \n\n %s' %
([w.name for w in undriven], get_stacks(*undriven)))
# Check for async memories not specified as such
self.sanity_check_memory_sync(wire_src_dict)
if debug_mode:
# Check for wires that are destinations of a logicNet, but are not outputs and are never
# used as args.
outs = dest_set.difference(arg_set)
unused = outs.difference(self.wirevector_subset(Output))
if len(unused) > 0:
names = [w.name for w in unused]
print('Warning: Wires driven but never used { %s } ' % names)
print(get_stacks(*unused)) | python | def sanity_check(self):
""" Check block and throw PyrtlError or PyrtlInternalError if there is an issue.
Should not modify anything, only check data structures to make sure they have been
built according to the assumptions stated in the Block comments."""
# TODO: check that the wirevector_by_name is sane
from .wire import Input, Const, Output
from .helperfuncs import get_stack, get_stacks
# check for valid LogicNets (and wires)
for net in self.logic:
self.sanity_check_net(net)
for w in self.wirevector_subset():
if w.bitwidth is None:
raise PyrtlError(
'error, missing bitwidth for WireVector "%s" \n\n %s' % (w.name, get_stack(w)))
# check for unique names
wirevector_names_set = set(x.name for x in self.wirevector_set)
if len(self.wirevector_set) != len(wirevector_names_set):
wirevector_names_list = [x.name for x in self.wirevector_set]
for w in wirevector_names_set:
wirevector_names_list.remove(w)
raise PyrtlError('Duplicate wire names found for the following '
'different signals: %s' % repr(wirevector_names_list))
# check for dead input wires (not connected to anything)
all_input_and_consts = self.wirevector_subset((Input, Const))
# The following line also checks for duplicate wire drivers
wire_src_dict, wire_dst_dict = self.net_connections()
dest_set = set(wire_src_dict.keys())
arg_set = set(wire_dst_dict.keys())
full_set = dest_set | arg_set
connected_minus_allwires = full_set.difference(self.wirevector_set)
if len(connected_minus_allwires) > 0:
bad_wire_names = '\n '.join(str(x) for x in connected_minus_allwires)
raise PyrtlError('Unknown wires found in net:\n %s \n\n %s' % (bad_wire_names,
get_stacks(*connected_minus_allwires)))
allwires_minus_connected = self.wirevector_set.difference(full_set)
allwires_minus_connected = allwires_minus_connected.difference(all_input_and_consts)
# ^ allow inputs and consts to be unconnected
if len(allwires_minus_connected) > 0:
bad_wire_names = '\n '.join(str(x) for x in allwires_minus_connected)
raise PyrtlError('Wires declared but not connected:\n %s \n\n %s' % (bad_wire_names,
get_stacks(*allwires_minus_connected)))
# Check for wires that are inputs to a logicNet, but are not block inputs and are never
# driven.
ins = arg_set.difference(dest_set)
undriven = ins.difference(all_input_and_consts)
if len(undriven) > 0:
raise PyrtlError('Wires used but never driven: %s \n\n %s' %
([w.name for w in undriven], get_stacks(*undriven)))
# Check for async memories not specified as such
self.sanity_check_memory_sync(wire_src_dict)
if debug_mode:
# Check for wires that are destinations of a logicNet, but are not outputs and are never
# used as args.
outs = dest_set.difference(arg_set)
unused = outs.difference(self.wirevector_subset(Output))
if len(unused) > 0:
names = [w.name for w in unused]
print('Warning: Wires driven but never used { %s } ' % names)
print(get_stacks(*unused)) | [
"def",
"sanity_check",
"(",
"self",
")",
":",
"# TODO: check that the wirevector_by_name is sane",
"from",
".",
"wire",
"import",
"Input",
",",
"Const",
",",
"Output",
"from",
".",
"helperfuncs",
"import",
"get_stack",
",",
"get_stacks",
"# check for valid LogicNets (and wires)",
"for",
"net",
"in",
"self",
".",
"logic",
":",
"self",
".",
"sanity_check_net",
"(",
"net",
")",
"for",
"w",
"in",
"self",
".",
"wirevector_subset",
"(",
")",
":",
"if",
"w",
".",
"bitwidth",
"is",
"None",
":",
"raise",
"PyrtlError",
"(",
"'error, missing bitwidth for WireVector \"%s\" \\n\\n %s'",
"%",
"(",
"w",
".",
"name",
",",
"get_stack",
"(",
"w",
")",
")",
")",
"# check for unique names",
"wirevector_names_set",
"=",
"set",
"(",
"x",
".",
"name",
"for",
"x",
"in",
"self",
".",
"wirevector_set",
")",
"if",
"len",
"(",
"self",
".",
"wirevector_set",
")",
"!=",
"len",
"(",
"wirevector_names_set",
")",
":",
"wirevector_names_list",
"=",
"[",
"x",
".",
"name",
"for",
"x",
"in",
"self",
".",
"wirevector_set",
"]",
"for",
"w",
"in",
"wirevector_names_set",
":",
"wirevector_names_list",
".",
"remove",
"(",
"w",
")",
"raise",
"PyrtlError",
"(",
"'Duplicate wire names found for the following '",
"'different signals: %s'",
"%",
"repr",
"(",
"wirevector_names_list",
")",
")",
"# check for dead input wires (not connected to anything)",
"all_input_and_consts",
"=",
"self",
".",
"wirevector_subset",
"(",
"(",
"Input",
",",
"Const",
")",
")",
"# The following line also checks for duplicate wire drivers",
"wire_src_dict",
",",
"wire_dst_dict",
"=",
"self",
".",
"net_connections",
"(",
")",
"dest_set",
"=",
"set",
"(",
"wire_src_dict",
".",
"keys",
"(",
")",
")",
"arg_set",
"=",
"set",
"(",
"wire_dst_dict",
".",
"keys",
"(",
")",
")",
"full_set",
"=",
"dest_set",
"|",
"arg_set",
"connected_minus_allwires",
"=",
"full_set",
".",
"difference",
"(",
"self",
".",
"wirevector_set",
")",
"if",
"len",
"(",
"connected_minus_allwires",
")",
">",
"0",
":",
"bad_wire_names",
"=",
"'\\n '",
".",
"join",
"(",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"connected_minus_allwires",
")",
"raise",
"PyrtlError",
"(",
"'Unknown wires found in net:\\n %s \\n\\n %s'",
"%",
"(",
"bad_wire_names",
",",
"get_stacks",
"(",
"*",
"connected_minus_allwires",
")",
")",
")",
"allwires_minus_connected",
"=",
"self",
".",
"wirevector_set",
".",
"difference",
"(",
"full_set",
")",
"allwires_minus_connected",
"=",
"allwires_minus_connected",
".",
"difference",
"(",
"all_input_and_consts",
")",
"# ^ allow inputs and consts to be unconnected",
"if",
"len",
"(",
"allwires_minus_connected",
")",
">",
"0",
":",
"bad_wire_names",
"=",
"'\\n '",
".",
"join",
"(",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"allwires_minus_connected",
")",
"raise",
"PyrtlError",
"(",
"'Wires declared but not connected:\\n %s \\n\\n %s'",
"%",
"(",
"bad_wire_names",
",",
"get_stacks",
"(",
"*",
"allwires_minus_connected",
")",
")",
")",
"# Check for wires that are inputs to a logicNet, but are not block inputs and are never",
"# driven.",
"ins",
"=",
"arg_set",
".",
"difference",
"(",
"dest_set",
")",
"undriven",
"=",
"ins",
".",
"difference",
"(",
"all_input_and_consts",
")",
"if",
"len",
"(",
"undriven",
")",
">",
"0",
":",
"raise",
"PyrtlError",
"(",
"'Wires used but never driven: %s \\n\\n %s'",
"%",
"(",
"[",
"w",
".",
"name",
"for",
"w",
"in",
"undriven",
"]",
",",
"get_stacks",
"(",
"*",
"undriven",
")",
")",
")",
"# Check for async memories not specified as such",
"self",
".",
"sanity_check_memory_sync",
"(",
"wire_src_dict",
")",
"if",
"debug_mode",
":",
"# Check for wires that are destinations of a logicNet, but are not outputs and are never",
"# used as args.",
"outs",
"=",
"dest_set",
".",
"difference",
"(",
"arg_set",
")",
"unused",
"=",
"outs",
".",
"difference",
"(",
"self",
".",
"wirevector_subset",
"(",
"Output",
")",
")",
"if",
"len",
"(",
"unused",
")",
">",
"0",
":",
"names",
"=",
"[",
"w",
".",
"name",
"for",
"w",
"in",
"unused",
"]",
"print",
"(",
"'Warning: Wires driven but never used { %s } '",
"%",
"names",
")",
"print",
"(",
"get_stacks",
"(",
"*",
"unused",
")",
")"
] | Check block and throw PyrtlError or PyrtlInternalError if there is an issue.
Should not modify anything, only check data structures to make sure they have been
built according to the assumptions stated in the Block comments. | [
"Check",
"block",
"and",
"throw",
"PyrtlError",
"or",
"PyrtlInternalError",
"if",
"there",
"is",
"an",
"issue",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/core.py#L373-L441 |
UCSBarchlab/PyRTL | pyrtl/core.py | Block.sanity_check_memory_sync | def sanity_check_memory_sync(self, wire_src_dict=None):
""" Check that all memories are synchronous unless explicitly specified as async.
While the semantics of 'm' memories reads is asynchronous, if you want your design
to use a block ram (on an FPGA or otherwise) you want to make sure the index is
available at the beginning of the clock edge. This check will walk the logic structure
and throw an error on any memory if finds that has an index that is not ready at the
beginning of the cycle.
"""
sync_mems = set(m for m in self.logic_subset('m') if not m.op_param[1].asynchronous)
if not len(sync_mems):
return # nothing to check here
if wire_src_dict is None:
wire_src_dict, wdd = self.net_connections()
from .wire import Input, Const
sync_src = 'r'
sync_prop = 'wcs'
for net in sync_mems:
wires_to_check = list(net.args)
while len(wires_to_check):
wire = wires_to_check.pop()
if isinstance(wire, (Input, Const)):
continue
src_net = wire_src_dict[wire]
if src_net.op == sync_src:
continue
elif src_net.op in sync_prop:
wires_to_check.extend(src_net.args)
else:
raise PyrtlError(
'memory "%s" is not specified as asynchronous but has an index '
'"%s" that is not ready at the start of the cycle due to net "%s"'
% (net.op_param[1].name, net.args[0].name, str(src_net))) | python | def sanity_check_memory_sync(self, wire_src_dict=None):
""" Check that all memories are synchronous unless explicitly specified as async.
While the semantics of 'm' memories reads is asynchronous, if you want your design
to use a block ram (on an FPGA or otherwise) you want to make sure the index is
available at the beginning of the clock edge. This check will walk the logic structure
and throw an error on any memory if finds that has an index that is not ready at the
beginning of the cycle.
"""
sync_mems = set(m for m in self.logic_subset('m') if not m.op_param[1].asynchronous)
if not len(sync_mems):
return # nothing to check here
if wire_src_dict is None:
wire_src_dict, wdd = self.net_connections()
from .wire import Input, Const
sync_src = 'r'
sync_prop = 'wcs'
for net in sync_mems:
wires_to_check = list(net.args)
while len(wires_to_check):
wire = wires_to_check.pop()
if isinstance(wire, (Input, Const)):
continue
src_net = wire_src_dict[wire]
if src_net.op == sync_src:
continue
elif src_net.op in sync_prop:
wires_to_check.extend(src_net.args)
else:
raise PyrtlError(
'memory "%s" is not specified as asynchronous but has an index '
'"%s" that is not ready at the start of the cycle due to net "%s"'
% (net.op_param[1].name, net.args[0].name, str(src_net))) | [
"def",
"sanity_check_memory_sync",
"(",
"self",
",",
"wire_src_dict",
"=",
"None",
")",
":",
"sync_mems",
"=",
"set",
"(",
"m",
"for",
"m",
"in",
"self",
".",
"logic_subset",
"(",
"'m'",
")",
"if",
"not",
"m",
".",
"op_param",
"[",
"1",
"]",
".",
"asynchronous",
")",
"if",
"not",
"len",
"(",
"sync_mems",
")",
":",
"return",
"# nothing to check here",
"if",
"wire_src_dict",
"is",
"None",
":",
"wire_src_dict",
",",
"wdd",
"=",
"self",
".",
"net_connections",
"(",
")",
"from",
".",
"wire",
"import",
"Input",
",",
"Const",
"sync_src",
"=",
"'r'",
"sync_prop",
"=",
"'wcs'",
"for",
"net",
"in",
"sync_mems",
":",
"wires_to_check",
"=",
"list",
"(",
"net",
".",
"args",
")",
"while",
"len",
"(",
"wires_to_check",
")",
":",
"wire",
"=",
"wires_to_check",
".",
"pop",
"(",
")",
"if",
"isinstance",
"(",
"wire",
",",
"(",
"Input",
",",
"Const",
")",
")",
":",
"continue",
"src_net",
"=",
"wire_src_dict",
"[",
"wire",
"]",
"if",
"src_net",
".",
"op",
"==",
"sync_src",
":",
"continue",
"elif",
"src_net",
".",
"op",
"in",
"sync_prop",
":",
"wires_to_check",
".",
"extend",
"(",
"src_net",
".",
"args",
")",
"else",
":",
"raise",
"PyrtlError",
"(",
"'memory \"%s\" is not specified as asynchronous but has an index '",
"'\"%s\" that is not ready at the start of the cycle due to net \"%s\"'",
"%",
"(",
"net",
".",
"op_param",
"[",
"1",
"]",
".",
"name",
",",
"net",
".",
"args",
"[",
"0",
"]",
".",
"name",
",",
"str",
"(",
"src_net",
")",
")",
")"
] | Check that all memories are synchronous unless explicitly specified as async.
While the semantics of 'm' memories reads is asynchronous, if you want your design
to use a block ram (on an FPGA or otherwise) you want to make sure the index is
available at the beginning of the clock edge. This check will walk the logic structure
and throw an error on any memory if finds that has an index that is not ready at the
beginning of the cycle. | [
"Check",
"that",
"all",
"memories",
"are",
"synchronous",
"unless",
"explicitly",
"specified",
"as",
"async",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/core.py#L443-L477 |
UCSBarchlab/PyRTL | pyrtl/core.py | Block.sanity_check_wirevector | def sanity_check_wirevector(self, w):
""" Check that w is a valid wirevector type. """
from .wire import WireVector
if not isinstance(w, WireVector):
raise PyrtlError(
'error attempting to pass an input of type "%s" '
'instead of WireVector' % type(w)) | python | def sanity_check_wirevector(self, w):
""" Check that w is a valid wirevector type. """
from .wire import WireVector
if not isinstance(w, WireVector):
raise PyrtlError(
'error attempting to pass an input of type "%s" '
'instead of WireVector' % type(w)) | [
"def",
"sanity_check_wirevector",
"(",
"self",
",",
"w",
")",
":",
"from",
".",
"wire",
"import",
"WireVector",
"if",
"not",
"isinstance",
"(",
"w",
",",
"WireVector",
")",
":",
"raise",
"PyrtlError",
"(",
"'error attempting to pass an input of type \"%s\" '",
"'instead of WireVector'",
"%",
"type",
"(",
"w",
")",
")"
] | Check that w is a valid wirevector type. | [
"Check",
"that",
"w",
"is",
"a",
"valid",
"wirevector",
"type",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/core.py#L479-L485 |
UCSBarchlab/PyRTL | pyrtl/core.py | Block.sanity_check_net | def sanity_check_net(self, net):
""" Check that net is a valid LogicNet. """
from .wire import Input, Output, Const
from .memory import _MemReadBase
# general sanity checks that apply to all operations
if not isinstance(net, LogicNet):
raise PyrtlInternalError('error, net must be of type LogicNet')
if not isinstance(net.args, tuple):
raise PyrtlInternalError('error, LogicNet args must be tuple')
if not isinstance(net.dests, tuple):
raise PyrtlInternalError('error, LogicNet dests must be tuple')
for w in net.args + net.dests:
self.sanity_check_wirevector(w)
if w._block is not self:
raise PyrtlInternalError('error, net references different block')
if w not in self.wirevector_set:
raise PyrtlInternalError('error, net with unknown source "%s"' % w.name)
# checks that input and output wirevectors are not misused
for w in net.dests:
if isinstance(w, (Input, Const)):
raise PyrtlInternalError('error, Inputs, Consts cannot be destinations to a net')
for w in net.args:
if isinstance(w, Output):
raise PyrtlInternalError('error, Outputs cannot be arguments for a net')
if net.op not in self.legal_ops:
raise PyrtlInternalError('error, net op "%s" not from acceptable set %s' %
(net.op, self.legal_ops))
# operation specific checks on arguments
if net.op in 'w~rsm' and len(net.args) != 1:
raise PyrtlInternalError('error, op only allowed 1 argument')
if net.op in '&|^n+-*<>=' and len(net.args) != 2:
raise PyrtlInternalError('error, op only allowed 2 arguments')
if net.op == 'x':
if len(net.args) != 3:
raise PyrtlInternalError('error, op only allowed 3 arguments')
if net.args[1].bitwidth != net.args[2].bitwidth:
raise PyrtlInternalError('error, args have mismatched bitwidths')
if net.args[0].bitwidth != 1:
raise PyrtlInternalError('error, mux select must be a single bit')
if net.op == '@' and len(net.args) != 3:
raise PyrtlInternalError('error, op only allowed 3 arguments')
if net.op in '&|^n+-*<>=' and net.args[0].bitwidth != net.args[1].bitwidth:
raise PyrtlInternalError('error, args have mismatched bitwidths')
if net.op in 'm@' and net.args[0].bitwidth != net.op_param[1].addrwidth:
raise PyrtlInternalError('error, mem addrwidth mismatch')
if net.op == '@' and net.args[1].bitwidth != net.op_param[1].bitwidth:
raise PyrtlInternalError('error, mem bitwidth mismatch')
if net.op == '@' and net.args[2].bitwidth != 1:
raise PyrtlInternalError('error, mem write enable must be 1 bit')
# operation specific checks on op_params
if net.op in 'w~&|^n+-*<>=xcr' and net.op_param is not None:
raise PyrtlInternalError('error, op_param should be None')
if net.op == 's':
if not isinstance(net.op_param, tuple):
raise PyrtlInternalError('error, select op requires tuple op_param')
for p in net.op_param:
if not isinstance(p, int):
raise PyrtlInternalError('error, select op_param requires ints')
if p < 0 or p >= net.args[0].bitwidth:
raise PyrtlInternalError('error, op_param out of bounds')
if net.op in 'm@':
if not isinstance(net.op_param, tuple):
raise PyrtlInternalError('error, mem op requires tuple op_param')
if len(net.op_param) != 2:
raise PyrtlInternalError('error, mem op requires 2 op_params in tuple')
if not isinstance(net.op_param[0], int):
raise PyrtlInternalError('error, mem op requires first operand as int')
if not isinstance(net.op_param[1], _MemReadBase):
raise PyrtlInternalError('error, mem op requires second operand of a memory type')
# check destination validity
if net.op in 'w~&|^nr' and net.dests[0].bitwidth > net.args[0].bitwidth:
raise PyrtlInternalError('error, upper bits of destination unassigned')
if net.op in '<>=' and net.dests[0].bitwidth != 1:
raise PyrtlInternalError('error, destination should be of bitwidth=1')
if net.op in '+-' and net.dests[0].bitwidth > net.args[0].bitwidth + 1:
raise PyrtlInternalError('error, upper bits of destination unassigned')
if net.op == '*' and net.dests[0].bitwidth > 2 * net.args[0].bitwidth:
raise PyrtlInternalError('error, upper bits of destination unassigned')
if net.op == 'x' and net.dests[0].bitwidth > net.args[1].bitwidth:
raise PyrtlInternalError('error, upper bits of mux output undefined')
if net.op == 'c' and net.dests[0].bitwidth > sum(x.bitwidth for x in net.args):
raise PyrtlInternalError('error, upper bits of concat output undefined')
if net.op == 's' and net.dests[0].bitwidth > len(net.op_param):
raise PyrtlInternalError('error, upper bits of select output undefined')
if net.op == 'm' and net.dests[0].bitwidth != net.op_param[1].bitwidth:
raise PyrtlInternalError('error, mem read dest bitwidth mismatch')
if net.op == '@' and net.dests != ():
raise PyrtlInternalError('error, mem write dest should be empty tuple') | python | def sanity_check_net(self, net):
""" Check that net is a valid LogicNet. """
from .wire import Input, Output, Const
from .memory import _MemReadBase
# general sanity checks that apply to all operations
if not isinstance(net, LogicNet):
raise PyrtlInternalError('error, net must be of type LogicNet')
if not isinstance(net.args, tuple):
raise PyrtlInternalError('error, LogicNet args must be tuple')
if not isinstance(net.dests, tuple):
raise PyrtlInternalError('error, LogicNet dests must be tuple')
for w in net.args + net.dests:
self.sanity_check_wirevector(w)
if w._block is not self:
raise PyrtlInternalError('error, net references different block')
if w not in self.wirevector_set:
raise PyrtlInternalError('error, net with unknown source "%s"' % w.name)
# checks that input and output wirevectors are not misused
for w in net.dests:
if isinstance(w, (Input, Const)):
raise PyrtlInternalError('error, Inputs, Consts cannot be destinations to a net')
for w in net.args:
if isinstance(w, Output):
raise PyrtlInternalError('error, Outputs cannot be arguments for a net')
if net.op not in self.legal_ops:
raise PyrtlInternalError('error, net op "%s" not from acceptable set %s' %
(net.op, self.legal_ops))
# operation specific checks on arguments
if net.op in 'w~rsm' and len(net.args) != 1:
raise PyrtlInternalError('error, op only allowed 1 argument')
if net.op in '&|^n+-*<>=' and len(net.args) != 2:
raise PyrtlInternalError('error, op only allowed 2 arguments')
if net.op == 'x':
if len(net.args) != 3:
raise PyrtlInternalError('error, op only allowed 3 arguments')
if net.args[1].bitwidth != net.args[2].bitwidth:
raise PyrtlInternalError('error, args have mismatched bitwidths')
if net.args[0].bitwidth != 1:
raise PyrtlInternalError('error, mux select must be a single bit')
if net.op == '@' and len(net.args) != 3:
raise PyrtlInternalError('error, op only allowed 3 arguments')
if net.op in '&|^n+-*<>=' and net.args[0].bitwidth != net.args[1].bitwidth:
raise PyrtlInternalError('error, args have mismatched bitwidths')
if net.op in 'm@' and net.args[0].bitwidth != net.op_param[1].addrwidth:
raise PyrtlInternalError('error, mem addrwidth mismatch')
if net.op == '@' and net.args[1].bitwidth != net.op_param[1].bitwidth:
raise PyrtlInternalError('error, mem bitwidth mismatch')
if net.op == '@' and net.args[2].bitwidth != 1:
raise PyrtlInternalError('error, mem write enable must be 1 bit')
# operation specific checks on op_params
if net.op in 'w~&|^n+-*<>=xcr' and net.op_param is not None:
raise PyrtlInternalError('error, op_param should be None')
if net.op == 's':
if not isinstance(net.op_param, tuple):
raise PyrtlInternalError('error, select op requires tuple op_param')
for p in net.op_param:
if not isinstance(p, int):
raise PyrtlInternalError('error, select op_param requires ints')
if p < 0 or p >= net.args[0].bitwidth:
raise PyrtlInternalError('error, op_param out of bounds')
if net.op in 'm@':
if not isinstance(net.op_param, tuple):
raise PyrtlInternalError('error, mem op requires tuple op_param')
if len(net.op_param) != 2:
raise PyrtlInternalError('error, mem op requires 2 op_params in tuple')
if not isinstance(net.op_param[0], int):
raise PyrtlInternalError('error, mem op requires first operand as int')
if not isinstance(net.op_param[1], _MemReadBase):
raise PyrtlInternalError('error, mem op requires second operand of a memory type')
# check destination validity
if net.op in 'w~&|^nr' and net.dests[0].bitwidth > net.args[0].bitwidth:
raise PyrtlInternalError('error, upper bits of destination unassigned')
if net.op in '<>=' and net.dests[0].bitwidth != 1:
raise PyrtlInternalError('error, destination should be of bitwidth=1')
if net.op in '+-' and net.dests[0].bitwidth > net.args[0].bitwidth + 1:
raise PyrtlInternalError('error, upper bits of destination unassigned')
if net.op == '*' and net.dests[0].bitwidth > 2 * net.args[0].bitwidth:
raise PyrtlInternalError('error, upper bits of destination unassigned')
if net.op == 'x' and net.dests[0].bitwidth > net.args[1].bitwidth:
raise PyrtlInternalError('error, upper bits of mux output undefined')
if net.op == 'c' and net.dests[0].bitwidth > sum(x.bitwidth for x in net.args):
raise PyrtlInternalError('error, upper bits of concat output undefined')
if net.op == 's' and net.dests[0].bitwidth > len(net.op_param):
raise PyrtlInternalError('error, upper bits of select output undefined')
if net.op == 'm' and net.dests[0].bitwidth != net.op_param[1].bitwidth:
raise PyrtlInternalError('error, mem read dest bitwidth mismatch')
if net.op == '@' and net.dests != ():
raise PyrtlInternalError('error, mem write dest should be empty tuple') | [
"def",
"sanity_check_net",
"(",
"self",
",",
"net",
")",
":",
"from",
".",
"wire",
"import",
"Input",
",",
"Output",
",",
"Const",
"from",
".",
"memory",
"import",
"_MemReadBase",
"# general sanity checks that apply to all operations",
"if",
"not",
"isinstance",
"(",
"net",
",",
"LogicNet",
")",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, net must be of type LogicNet'",
")",
"if",
"not",
"isinstance",
"(",
"net",
".",
"args",
",",
"tuple",
")",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, LogicNet args must be tuple'",
")",
"if",
"not",
"isinstance",
"(",
"net",
".",
"dests",
",",
"tuple",
")",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, LogicNet dests must be tuple'",
")",
"for",
"w",
"in",
"net",
".",
"args",
"+",
"net",
".",
"dests",
":",
"self",
".",
"sanity_check_wirevector",
"(",
"w",
")",
"if",
"w",
".",
"_block",
"is",
"not",
"self",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, net references different block'",
")",
"if",
"w",
"not",
"in",
"self",
".",
"wirevector_set",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, net with unknown source \"%s\"'",
"%",
"w",
".",
"name",
")",
"# checks that input and output wirevectors are not misused",
"for",
"w",
"in",
"net",
".",
"dests",
":",
"if",
"isinstance",
"(",
"w",
",",
"(",
"Input",
",",
"Const",
")",
")",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, Inputs, Consts cannot be destinations to a net'",
")",
"for",
"w",
"in",
"net",
".",
"args",
":",
"if",
"isinstance",
"(",
"w",
",",
"Output",
")",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, Outputs cannot be arguments for a net'",
")",
"if",
"net",
".",
"op",
"not",
"in",
"self",
".",
"legal_ops",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, net op \"%s\" not from acceptable set %s'",
"%",
"(",
"net",
".",
"op",
",",
"self",
".",
"legal_ops",
")",
")",
"# operation specific checks on arguments",
"if",
"net",
".",
"op",
"in",
"'w~rsm'",
"and",
"len",
"(",
"net",
".",
"args",
")",
"!=",
"1",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, op only allowed 1 argument'",
")",
"if",
"net",
".",
"op",
"in",
"'&|^n+-*<>='",
"and",
"len",
"(",
"net",
".",
"args",
")",
"!=",
"2",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, op only allowed 2 arguments'",
")",
"if",
"net",
".",
"op",
"==",
"'x'",
":",
"if",
"len",
"(",
"net",
".",
"args",
")",
"!=",
"3",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, op only allowed 3 arguments'",
")",
"if",
"net",
".",
"args",
"[",
"1",
"]",
".",
"bitwidth",
"!=",
"net",
".",
"args",
"[",
"2",
"]",
".",
"bitwidth",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, args have mismatched bitwidths'",
")",
"if",
"net",
".",
"args",
"[",
"0",
"]",
".",
"bitwidth",
"!=",
"1",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, mux select must be a single bit'",
")",
"if",
"net",
".",
"op",
"==",
"'@'",
"and",
"len",
"(",
"net",
".",
"args",
")",
"!=",
"3",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, op only allowed 3 arguments'",
")",
"if",
"net",
".",
"op",
"in",
"'&|^n+-*<>='",
"and",
"net",
".",
"args",
"[",
"0",
"]",
".",
"bitwidth",
"!=",
"net",
".",
"args",
"[",
"1",
"]",
".",
"bitwidth",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, args have mismatched bitwidths'",
")",
"if",
"net",
".",
"op",
"in",
"'m@'",
"and",
"net",
".",
"args",
"[",
"0",
"]",
".",
"bitwidth",
"!=",
"net",
".",
"op_param",
"[",
"1",
"]",
".",
"addrwidth",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, mem addrwidth mismatch'",
")",
"if",
"net",
".",
"op",
"==",
"'@'",
"and",
"net",
".",
"args",
"[",
"1",
"]",
".",
"bitwidth",
"!=",
"net",
".",
"op_param",
"[",
"1",
"]",
".",
"bitwidth",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, mem bitwidth mismatch'",
")",
"if",
"net",
".",
"op",
"==",
"'@'",
"and",
"net",
".",
"args",
"[",
"2",
"]",
".",
"bitwidth",
"!=",
"1",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, mem write enable must be 1 bit'",
")",
"# operation specific checks on op_params",
"if",
"net",
".",
"op",
"in",
"'w~&|^n+-*<>=xcr'",
"and",
"net",
".",
"op_param",
"is",
"not",
"None",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, op_param should be None'",
")",
"if",
"net",
".",
"op",
"==",
"'s'",
":",
"if",
"not",
"isinstance",
"(",
"net",
".",
"op_param",
",",
"tuple",
")",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, select op requires tuple op_param'",
")",
"for",
"p",
"in",
"net",
".",
"op_param",
":",
"if",
"not",
"isinstance",
"(",
"p",
",",
"int",
")",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, select op_param requires ints'",
")",
"if",
"p",
"<",
"0",
"or",
"p",
">=",
"net",
".",
"args",
"[",
"0",
"]",
".",
"bitwidth",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, op_param out of bounds'",
")",
"if",
"net",
".",
"op",
"in",
"'m@'",
":",
"if",
"not",
"isinstance",
"(",
"net",
".",
"op_param",
",",
"tuple",
")",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, mem op requires tuple op_param'",
")",
"if",
"len",
"(",
"net",
".",
"op_param",
")",
"!=",
"2",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, mem op requires 2 op_params in tuple'",
")",
"if",
"not",
"isinstance",
"(",
"net",
".",
"op_param",
"[",
"0",
"]",
",",
"int",
")",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, mem op requires first operand as int'",
")",
"if",
"not",
"isinstance",
"(",
"net",
".",
"op_param",
"[",
"1",
"]",
",",
"_MemReadBase",
")",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, mem op requires second operand of a memory type'",
")",
"# check destination validity",
"if",
"net",
".",
"op",
"in",
"'w~&|^nr'",
"and",
"net",
".",
"dests",
"[",
"0",
"]",
".",
"bitwidth",
">",
"net",
".",
"args",
"[",
"0",
"]",
".",
"bitwidth",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, upper bits of destination unassigned'",
")",
"if",
"net",
".",
"op",
"in",
"'<>='",
"and",
"net",
".",
"dests",
"[",
"0",
"]",
".",
"bitwidth",
"!=",
"1",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, destination should be of bitwidth=1'",
")",
"if",
"net",
".",
"op",
"in",
"'+-'",
"and",
"net",
".",
"dests",
"[",
"0",
"]",
".",
"bitwidth",
">",
"net",
".",
"args",
"[",
"0",
"]",
".",
"bitwidth",
"+",
"1",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, upper bits of destination unassigned'",
")",
"if",
"net",
".",
"op",
"==",
"'*'",
"and",
"net",
".",
"dests",
"[",
"0",
"]",
".",
"bitwidth",
">",
"2",
"*",
"net",
".",
"args",
"[",
"0",
"]",
".",
"bitwidth",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, upper bits of destination unassigned'",
")",
"if",
"net",
".",
"op",
"==",
"'x'",
"and",
"net",
".",
"dests",
"[",
"0",
"]",
".",
"bitwidth",
">",
"net",
".",
"args",
"[",
"1",
"]",
".",
"bitwidth",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, upper bits of mux output undefined'",
")",
"if",
"net",
".",
"op",
"==",
"'c'",
"and",
"net",
".",
"dests",
"[",
"0",
"]",
".",
"bitwidth",
">",
"sum",
"(",
"x",
".",
"bitwidth",
"for",
"x",
"in",
"net",
".",
"args",
")",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, upper bits of concat output undefined'",
")",
"if",
"net",
".",
"op",
"==",
"'s'",
"and",
"net",
".",
"dests",
"[",
"0",
"]",
".",
"bitwidth",
">",
"len",
"(",
"net",
".",
"op_param",
")",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, upper bits of select output undefined'",
")",
"if",
"net",
".",
"op",
"==",
"'m'",
"and",
"net",
".",
"dests",
"[",
"0",
"]",
".",
"bitwidth",
"!=",
"net",
".",
"op_param",
"[",
"1",
"]",
".",
"bitwidth",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, mem read dest bitwidth mismatch'",
")",
"if",
"net",
".",
"op",
"==",
"'@'",
"and",
"net",
".",
"dests",
"!=",
"(",
")",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, mem write dest should be empty tuple'",
")"
] | Check that net is a valid LogicNet. | [
"Check",
"that",
"net",
"is",
"a",
"valid",
"LogicNet",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/core.py#L487-L580 |
UCSBarchlab/PyRTL | pyrtl/core.py | _NameSanitizer.make_valid_string | def make_valid_string(self, string=''):
""" Inputting a value for the first time """
if not self.is_valid_str(string):
if string in self.val_map and not self.allow_dups:
raise IndexError("Value {} has already been given to the sanitizer".format(string))
internal_name = super(_NameSanitizer, self).make_valid_string()
self.val_map[string] = internal_name
return internal_name
else:
if self.map_valid:
self.val_map[string] = string
return string | python | def make_valid_string(self, string=''):
""" Inputting a value for the first time """
if not self.is_valid_str(string):
if string in self.val_map and not self.allow_dups:
raise IndexError("Value {} has already been given to the sanitizer".format(string))
internal_name = super(_NameSanitizer, self).make_valid_string()
self.val_map[string] = internal_name
return internal_name
else:
if self.map_valid:
self.val_map[string] = string
return string | [
"def",
"make_valid_string",
"(",
"self",
",",
"string",
"=",
"''",
")",
":",
"if",
"not",
"self",
".",
"is_valid_str",
"(",
"string",
")",
":",
"if",
"string",
"in",
"self",
".",
"val_map",
"and",
"not",
"self",
".",
"allow_dups",
":",
"raise",
"IndexError",
"(",
"\"Value {} has already been given to the sanitizer\"",
".",
"format",
"(",
"string",
")",
")",
"internal_name",
"=",
"super",
"(",
"_NameSanitizer",
",",
"self",
")",
".",
"make_valid_string",
"(",
")",
"self",
".",
"val_map",
"[",
"string",
"]",
"=",
"internal_name",
"return",
"internal_name",
"else",
":",
"if",
"self",
".",
"map_valid",
":",
"self",
".",
"val_map",
"[",
"string",
"]",
"=",
"string",
"return",
"string"
] | Inputting a value for the first time | [
"Inputting",
"a",
"value",
"for",
"the",
"first",
"time"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/core.py#L759-L770 |
UCSBarchlab/PyRTL | pyrtl/rtllib/libutils.py | str_to_int_array | def str_to_int_array(string, base=16):
"""
Converts a string to an array of integer values according to the
base specified (int numbers must be whitespace delimited).\n
Example: "13 a3 3c" => [0x13, 0xa3, 0x3c]
:return: [int]
"""
int_strings = string.split()
return [int(int_str, base) for int_str in int_strings] | python | def str_to_int_array(string, base=16):
"""
Converts a string to an array of integer values according to the
base specified (int numbers must be whitespace delimited).\n
Example: "13 a3 3c" => [0x13, 0xa3, 0x3c]
:return: [int]
"""
int_strings = string.split()
return [int(int_str, base) for int_str in int_strings] | [
"def",
"str_to_int_array",
"(",
"string",
",",
"base",
"=",
"16",
")",
":",
"int_strings",
"=",
"string",
".",
"split",
"(",
")",
"return",
"[",
"int",
"(",
"int_str",
",",
"base",
")",
"for",
"int_str",
"in",
"int_strings",
"]"
] | Converts a string to an array of integer values according to the
base specified (int numbers must be whitespace delimited).\n
Example: "13 a3 3c" => [0x13, 0xa3, 0x3c]
:return: [int] | [
"Converts",
"a",
"string",
"to",
"an",
"array",
"of",
"integer",
"values",
"according",
"to",
"the",
"base",
"specified",
"(",
"int",
"numbers",
"must",
"be",
"whitespace",
"delimited",
")",
".",
"\\",
"n",
"Example",
":",
"13",
"a3",
"3c",
"=",
">",
"[",
"0x13",
"0xa3",
"0x3c",
"]"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/libutils.py#L23-L33 |
UCSBarchlab/PyRTL | pyrtl/rtllib/libutils.py | twos_comp_repr | def twos_comp_repr(val, bitwidth):
"""
Converts a value to it's two's-complement (positive) integer representation using a
given bitwidth (only converts the value if it is negative).
For use with Simulation.step() etc. in passing negative numbers, which it does not accept
"""
correctbw = abs(val).bit_length() + 1
if bitwidth < correctbw:
raise pyrtl.PyrtlError("please choose a larger target bitwidth")
if val >= 0:
return val
else:
return (~abs(val) & (2**bitwidth-1)) + 1 | python | def twos_comp_repr(val, bitwidth):
"""
Converts a value to it's two's-complement (positive) integer representation using a
given bitwidth (only converts the value if it is negative).
For use with Simulation.step() etc. in passing negative numbers, which it does not accept
"""
correctbw = abs(val).bit_length() + 1
if bitwidth < correctbw:
raise pyrtl.PyrtlError("please choose a larger target bitwidth")
if val >= 0:
return val
else:
return (~abs(val) & (2**bitwidth-1)) + 1 | [
"def",
"twos_comp_repr",
"(",
"val",
",",
"bitwidth",
")",
":",
"correctbw",
"=",
"abs",
"(",
"val",
")",
".",
"bit_length",
"(",
")",
"+",
"1",
"if",
"bitwidth",
"<",
"correctbw",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"please choose a larger target bitwidth\"",
")",
"if",
"val",
">=",
"0",
":",
"return",
"val",
"else",
":",
"return",
"(",
"~",
"abs",
"(",
"val",
")",
"&",
"(",
"2",
"**",
"bitwidth",
"-",
"1",
")",
")",
"+",
"1"
] | Converts a value to it's two's-complement (positive) integer representation using a
given bitwidth (only converts the value if it is negative).
For use with Simulation.step() etc. in passing negative numbers, which it does not accept | [
"Converts",
"a",
"value",
"to",
"it",
"s",
"two",
"s",
"-",
"complement",
"(",
"positive",
")",
"integer",
"representation",
"using",
"a",
"given",
"bitwidth",
"(",
"only",
"converts",
"the",
"value",
"if",
"it",
"is",
"negative",
")",
".",
"For",
"use",
"with",
"Simulation",
".",
"step",
"()",
"etc",
".",
"in",
"passing",
"negative",
"numbers",
"which",
"it",
"does",
"not",
"accept"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/libutils.py#L36-L48 |
UCSBarchlab/PyRTL | pyrtl/rtllib/libutils.py | rev_twos_comp_repr | def rev_twos_comp_repr(val, bitwidth):
"""
Takes a two's-complement represented value and
converts it to a signed integer based on the provided bitwidth.
For use with Simulation.inspect() etc. when expecting negative numbers,
which it does not recognize
"""
valbl = val.bit_length()
if bitwidth < val.bit_length() or val == 2**(bitwidth-1):
raise pyrtl.PyrtlError("please choose a larger target bitwidth")
if bitwidth == valbl: # MSB is a 1, value is negative
return -((~val & (2**bitwidth-1)) + 1) # flip the bits, add one, and make negative
else:
return val | python | def rev_twos_comp_repr(val, bitwidth):
"""
Takes a two's-complement represented value and
converts it to a signed integer based on the provided bitwidth.
For use with Simulation.inspect() etc. when expecting negative numbers,
which it does not recognize
"""
valbl = val.bit_length()
if bitwidth < val.bit_length() or val == 2**(bitwidth-1):
raise pyrtl.PyrtlError("please choose a larger target bitwidth")
if bitwidth == valbl: # MSB is a 1, value is negative
return -((~val & (2**bitwidth-1)) + 1) # flip the bits, add one, and make negative
else:
return val | [
"def",
"rev_twos_comp_repr",
"(",
"val",
",",
"bitwidth",
")",
":",
"valbl",
"=",
"val",
".",
"bit_length",
"(",
")",
"if",
"bitwidth",
"<",
"val",
".",
"bit_length",
"(",
")",
"or",
"val",
"==",
"2",
"**",
"(",
"bitwidth",
"-",
"1",
")",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"please choose a larger target bitwidth\"",
")",
"if",
"bitwidth",
"==",
"valbl",
":",
"# MSB is a 1, value is negative",
"return",
"-",
"(",
"(",
"~",
"val",
"&",
"(",
"2",
"**",
"bitwidth",
"-",
"1",
")",
")",
"+",
"1",
")",
"# flip the bits, add one, and make negative",
"else",
":",
"return",
"val"
] | Takes a two's-complement represented value and
converts it to a signed integer based on the provided bitwidth.
For use with Simulation.inspect() etc. when expecting negative numbers,
which it does not recognize | [
"Takes",
"a",
"two",
"s",
"-",
"complement",
"represented",
"value",
"and",
"converts",
"it",
"to",
"a",
"signed",
"integer",
"based",
"on",
"the",
"provided",
"bitwidth",
".",
"For",
"use",
"with",
"Simulation",
".",
"inspect",
"()",
"etc",
".",
"when",
"expecting",
"negative",
"numbers",
"which",
"it",
"does",
"not",
"recognize"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/libutils.py#L51-L64 |
UCSBarchlab/PyRTL | pyrtl/rtllib/libutils.py | _shifted_reg_next | def _shifted_reg_next(reg, direct, num=1):
"""
Creates a shifted 'next' property for shifted (left or right) register.\n
Use: `myReg.next = shifted_reg_next(myReg, 'l', 4)`
:param string direct: direction of shift, either 'l' or 'r'
:param int num: number of shifts
:return: Register containing reg's (shifted) next state
"""
if direct == 'l':
if num >= len(reg):
return 0
else:
return pyrtl.concat(reg, pyrtl.Const(0, num))
elif direct == 'r':
if num >= len(reg):
return 0
else:
return reg[num:]
else:
raise pyrtl.PyrtlError("direction must be specified with 'direct'"
"parameter as either 'l' or 'r'") | python | def _shifted_reg_next(reg, direct, num=1):
"""
Creates a shifted 'next' property for shifted (left or right) register.\n
Use: `myReg.next = shifted_reg_next(myReg, 'l', 4)`
:param string direct: direction of shift, either 'l' or 'r'
:param int num: number of shifts
:return: Register containing reg's (shifted) next state
"""
if direct == 'l':
if num >= len(reg):
return 0
else:
return pyrtl.concat(reg, pyrtl.Const(0, num))
elif direct == 'r':
if num >= len(reg):
return 0
else:
return reg[num:]
else:
raise pyrtl.PyrtlError("direction must be specified with 'direct'"
"parameter as either 'l' or 'r'") | [
"def",
"_shifted_reg_next",
"(",
"reg",
",",
"direct",
",",
"num",
"=",
"1",
")",
":",
"if",
"direct",
"==",
"'l'",
":",
"if",
"num",
">=",
"len",
"(",
"reg",
")",
":",
"return",
"0",
"else",
":",
"return",
"pyrtl",
".",
"concat",
"(",
"reg",
",",
"pyrtl",
".",
"Const",
"(",
"0",
",",
"num",
")",
")",
"elif",
"direct",
"==",
"'r'",
":",
"if",
"num",
">=",
"len",
"(",
"reg",
")",
":",
"return",
"0",
"else",
":",
"return",
"reg",
"[",
"num",
":",
"]",
"else",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"direction must be specified with 'direct'\"",
"\"parameter as either 'l' or 'r'\"",
")"
] | Creates a shifted 'next' property for shifted (left or right) register.\n
Use: `myReg.next = shifted_reg_next(myReg, 'l', 4)`
:param string direct: direction of shift, either 'l' or 'r'
:param int num: number of shifts
:return: Register containing reg's (shifted) next state | [
"Creates",
"a",
"shifted",
"next",
"property",
"for",
"shifted",
"(",
"left",
"or",
"right",
")",
"register",
".",
"\\",
"n",
"Use",
":",
"myReg",
".",
"next",
"=",
"shifted_reg_next",
"(",
"myReg",
"l",
"4",
")"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/libutils.py#L67-L88 |
UCSBarchlab/PyRTL | pyrtl/passes.py | optimize | def optimize(update_working_block=True, block=None, skip_sanity_check=False):
"""
Return an optimized version of a synthesized hardware block.
:param Boolean update_working_block: Don't copy the block and optimize the
new block
:param Block block: the block to optimize (defaults to working block)
Note:
optimize works on all hardware designs, both synthesized and non synthesized
"""
block = working_block(block)
if not update_working_block:
block = copy_block(block)
with set_working_block(block, no_sanity_check=True):
if (not skip_sanity_check) or debug_mode:
block.sanity_check()
_remove_wire_nets(block)
constant_propagation(block, True)
_remove_unlistened_nets(block)
common_subexp_elimination(block)
if (not skip_sanity_check) or debug_mode:
block.sanity_check()
return block | python | def optimize(update_working_block=True, block=None, skip_sanity_check=False):
"""
Return an optimized version of a synthesized hardware block.
:param Boolean update_working_block: Don't copy the block and optimize the
new block
:param Block block: the block to optimize (defaults to working block)
Note:
optimize works on all hardware designs, both synthesized and non synthesized
"""
block = working_block(block)
if not update_working_block:
block = copy_block(block)
with set_working_block(block, no_sanity_check=True):
if (not skip_sanity_check) or debug_mode:
block.sanity_check()
_remove_wire_nets(block)
constant_propagation(block, True)
_remove_unlistened_nets(block)
common_subexp_elimination(block)
if (not skip_sanity_check) or debug_mode:
block.sanity_check()
return block | [
"def",
"optimize",
"(",
"update_working_block",
"=",
"True",
",",
"block",
"=",
"None",
",",
"skip_sanity_check",
"=",
"False",
")",
":",
"block",
"=",
"working_block",
"(",
"block",
")",
"if",
"not",
"update_working_block",
":",
"block",
"=",
"copy_block",
"(",
"block",
")",
"with",
"set_working_block",
"(",
"block",
",",
"no_sanity_check",
"=",
"True",
")",
":",
"if",
"(",
"not",
"skip_sanity_check",
")",
"or",
"debug_mode",
":",
"block",
".",
"sanity_check",
"(",
")",
"_remove_wire_nets",
"(",
"block",
")",
"constant_propagation",
"(",
"block",
",",
"True",
")",
"_remove_unlistened_nets",
"(",
"block",
")",
"common_subexp_elimination",
"(",
"block",
")",
"if",
"(",
"not",
"skip_sanity_check",
")",
"or",
"debug_mode",
":",
"block",
".",
"sanity_check",
"(",
")",
"return",
"block"
] | Return an optimized version of a synthesized hardware block.
:param Boolean update_working_block: Don't copy the block and optimize the
new block
:param Block block: the block to optimize (defaults to working block)
Note:
optimize works on all hardware designs, both synthesized and non synthesized | [
"Return",
"an",
"optimized",
"version",
"of",
"a",
"synthesized",
"hardware",
"block",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/passes.py#L28-L52 |
UCSBarchlab/PyRTL | pyrtl/passes.py | _remove_wire_nets | def _remove_wire_nets(block):
""" Remove all wire nodes from the block. """
wire_src_dict = _ProducerList()
wire_removal_set = set() # set of all wirevectors to be removed
# one pass to build the map of value producers and
# all of the nets and wires to be removed
for net in block.logic:
if net.op == 'w':
wire_src_dict[net.dests[0]] = net.args[0]
if not isinstance(net.dests[0], Output):
wire_removal_set.add(net.dests[0])
# second full pass to create the new logic without the wire nets
new_logic = set()
for net in block.logic:
if net.op != 'w' or isinstance(net.dests[0], Output):
new_args = tuple(wire_src_dict.find_producer(x) for x in net.args)
new_net = LogicNet(net.op, net.op_param, new_args, net.dests)
new_logic.add(new_net)
# now update the block with the new logic and remove wirevectors
block.logic = new_logic
for dead_wirevector in wire_removal_set:
del block.wirevector_by_name[dead_wirevector.name]
block.wirevector_set.remove(dead_wirevector)
block.sanity_check() | python | def _remove_wire_nets(block):
""" Remove all wire nodes from the block. """
wire_src_dict = _ProducerList()
wire_removal_set = set() # set of all wirevectors to be removed
# one pass to build the map of value producers and
# all of the nets and wires to be removed
for net in block.logic:
if net.op == 'w':
wire_src_dict[net.dests[0]] = net.args[0]
if not isinstance(net.dests[0], Output):
wire_removal_set.add(net.dests[0])
# second full pass to create the new logic without the wire nets
new_logic = set()
for net in block.logic:
if net.op != 'w' or isinstance(net.dests[0], Output):
new_args = tuple(wire_src_dict.find_producer(x) for x in net.args)
new_net = LogicNet(net.op, net.op_param, new_args, net.dests)
new_logic.add(new_net)
# now update the block with the new logic and remove wirevectors
block.logic = new_logic
for dead_wirevector in wire_removal_set:
del block.wirevector_by_name[dead_wirevector.name]
block.wirevector_set.remove(dead_wirevector)
block.sanity_check() | [
"def",
"_remove_wire_nets",
"(",
"block",
")",
":",
"wire_src_dict",
"=",
"_ProducerList",
"(",
")",
"wire_removal_set",
"=",
"set",
"(",
")",
"# set of all wirevectors to be removed",
"# one pass to build the map of value producers and",
"# all of the nets and wires to be removed",
"for",
"net",
"in",
"block",
".",
"logic",
":",
"if",
"net",
".",
"op",
"==",
"'w'",
":",
"wire_src_dict",
"[",
"net",
".",
"dests",
"[",
"0",
"]",
"]",
"=",
"net",
".",
"args",
"[",
"0",
"]",
"if",
"not",
"isinstance",
"(",
"net",
".",
"dests",
"[",
"0",
"]",
",",
"Output",
")",
":",
"wire_removal_set",
".",
"add",
"(",
"net",
".",
"dests",
"[",
"0",
"]",
")",
"# second full pass to create the new logic without the wire nets",
"new_logic",
"=",
"set",
"(",
")",
"for",
"net",
"in",
"block",
".",
"logic",
":",
"if",
"net",
".",
"op",
"!=",
"'w'",
"or",
"isinstance",
"(",
"net",
".",
"dests",
"[",
"0",
"]",
",",
"Output",
")",
":",
"new_args",
"=",
"tuple",
"(",
"wire_src_dict",
".",
"find_producer",
"(",
"x",
")",
"for",
"x",
"in",
"net",
".",
"args",
")",
"new_net",
"=",
"LogicNet",
"(",
"net",
".",
"op",
",",
"net",
".",
"op_param",
",",
"new_args",
",",
"net",
".",
"dests",
")",
"new_logic",
".",
"add",
"(",
"new_net",
")",
"# now update the block with the new logic and remove wirevectors",
"block",
".",
"logic",
"=",
"new_logic",
"for",
"dead_wirevector",
"in",
"wire_removal_set",
":",
"del",
"block",
".",
"wirevector_by_name",
"[",
"dead_wirevector",
".",
"name",
"]",
"block",
".",
"wirevector_set",
".",
"remove",
"(",
"dead_wirevector",
")",
"block",
".",
"sanity_check",
"(",
")"
] | Remove all wire nodes from the block. | [
"Remove",
"all",
"wire",
"nodes",
"from",
"the",
"block",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/passes.py#L74-L102 |
UCSBarchlab/PyRTL | pyrtl/passes.py | constant_propagation | def constant_propagation(block, silence_unexpected_net_warnings=False):
""" Removes excess constants in the block.
Note on resulting block:
The output of the block can have wirevectors that are driven but not
listened to. This is to be expected. These are to be removed by the
_remove_unlistened_nets function
"""
net_count = _NetCount(block)
while net_count.shrinking():
_constant_prop_pass(block, silence_unexpected_net_warnings) | python | def constant_propagation(block, silence_unexpected_net_warnings=False):
""" Removes excess constants in the block.
Note on resulting block:
The output of the block can have wirevectors that are driven but not
listened to. This is to be expected. These are to be removed by the
_remove_unlistened_nets function
"""
net_count = _NetCount(block)
while net_count.shrinking():
_constant_prop_pass(block, silence_unexpected_net_warnings) | [
"def",
"constant_propagation",
"(",
"block",
",",
"silence_unexpected_net_warnings",
"=",
"False",
")",
":",
"net_count",
"=",
"_NetCount",
"(",
"block",
")",
"while",
"net_count",
".",
"shrinking",
"(",
")",
":",
"_constant_prop_pass",
"(",
"block",
",",
"silence_unexpected_net_warnings",
")"
] | Removes excess constants in the block.
Note on resulting block:
The output of the block can have wirevectors that are driven but not
listened to. This is to be expected. These are to be removed by the
_remove_unlistened_nets function | [
"Removes",
"excess",
"constants",
"in",
"the",
"block",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/passes.py#L105-L115 |
UCSBarchlab/PyRTL | pyrtl/passes.py | _constant_prop_pass | def _constant_prop_pass(block, silence_unexpected_net_warnings=False):
""" Does one constant propagation pass """
valid_net_ops = '~&|^nrwcsm@'
no_optimization_ops = 'wcsm@'
one_var_ops = {
'~': lambda x: 1-x,
'r': lambda x: x # This is only valid for constant folding purposes
}
two_var_ops = {
'&': lambda l, r: l & r,
'|': lambda l, r: l | r,
'^': lambda l, r: l ^ r,
'n': lambda l, r: 1-(l & r),
}
def _constant_prop_error(net, error_str):
if not silence_unexpected_net_warnings:
raise PyrtlError("Unexpected net, {}, has {}".format(net, error_str))
def constant_prop_check(net_checking):
def replace_net(new_net):
nets_to_remove.add(net_checking)
nets_to_add.add(new_net)
def replace_net_with_const(const_val):
new_const_wire = Const(bitwidth=1, val=const_val, block=block)
wire_add_set.add(new_const_wire)
replace_net_with_wire(new_const_wire)
def replace_net_with_wire(new_wire):
if isinstance(net_checking.dests[0], Output):
replace_net(LogicNet('w', None, args=(new_wire,),
dests=net_checking.dests))
else:
nets_to_remove.add(net_checking)
new_wire_src[net_checking.dests[0]] = new_wire
if net_checking.op not in valid_net_ops:
_constant_prop_error(net_checking, "has a net not handled by constant_propagation")
return # skip if we are ignoring unoptimizable ops
num_constants = sum((isinstance(arg, Const) for arg in net_checking.args))
if num_constants is 0 or net_checking.op in no_optimization_ops:
return # assuming wire nets are already optimized
if (net_checking.op in two_var_ops) and num_constants == 1:
long_wires = [w for w in net_checking.args + net_checking.dests if len(w) != 1]
if len(long_wires):
_constant_prop_error(net_checking, "has wire(s) {} with bitwidths that are not 1"
.format(long_wires))
return # skip if we are ignoring unoptimizable ops
# special case
const_wire, other_wire = net_checking.args
if isinstance(other_wire, Const):
const_wire, other_wire = other_wire, const_wire
outputs = [two_var_ops[net_checking.op](const_wire.val, other_val)
for other_val in (0, 1)]
if outputs[0] == outputs[1]:
replace_net_with_const(outputs[0])
elif outputs[0] == 0:
replace_net_with_wire(other_wire)
else:
replace_net(LogicNet('~', None, args=(other_wire,),
dests=net_checking.dests))
else:
# this optimization is actually compatible with long wires
if net_checking.op in two_var_ops:
output = two_var_ops[net_checking.op](net_checking.args[0].val,
net_checking.args[1].val)
else:
output = one_var_ops[net_checking.op](net_checking.args[0].val)
replace_net_with_const(output)
new_wire_src = _ProducerList()
wire_add_set = set()
nets_to_add = set()
nets_to_remove = set()
for a_net in block.logic:
constant_prop_check(a_net)
# second full pass to cleanup
new_logic = set()
for net in block.logic.union(nets_to_add) - nets_to_remove:
new_args = tuple(new_wire_src.find_producer(x) for x in net.args)
new_net = LogicNet(net.op, net.op_param, new_args, net.dests)
new_logic.add(new_net)
block.logic = new_logic
for new_wirevector in wire_add_set:
block.add_wirevector(new_wirevector)
_remove_unused_wires(block) | python | def _constant_prop_pass(block, silence_unexpected_net_warnings=False):
""" Does one constant propagation pass """
valid_net_ops = '~&|^nrwcsm@'
no_optimization_ops = 'wcsm@'
one_var_ops = {
'~': lambda x: 1-x,
'r': lambda x: x # This is only valid for constant folding purposes
}
two_var_ops = {
'&': lambda l, r: l & r,
'|': lambda l, r: l | r,
'^': lambda l, r: l ^ r,
'n': lambda l, r: 1-(l & r),
}
def _constant_prop_error(net, error_str):
if not silence_unexpected_net_warnings:
raise PyrtlError("Unexpected net, {}, has {}".format(net, error_str))
def constant_prop_check(net_checking):
def replace_net(new_net):
nets_to_remove.add(net_checking)
nets_to_add.add(new_net)
def replace_net_with_const(const_val):
new_const_wire = Const(bitwidth=1, val=const_val, block=block)
wire_add_set.add(new_const_wire)
replace_net_with_wire(new_const_wire)
def replace_net_with_wire(new_wire):
if isinstance(net_checking.dests[0], Output):
replace_net(LogicNet('w', None, args=(new_wire,),
dests=net_checking.dests))
else:
nets_to_remove.add(net_checking)
new_wire_src[net_checking.dests[0]] = new_wire
if net_checking.op not in valid_net_ops:
_constant_prop_error(net_checking, "has a net not handled by constant_propagation")
return # skip if we are ignoring unoptimizable ops
num_constants = sum((isinstance(arg, Const) for arg in net_checking.args))
if num_constants is 0 or net_checking.op in no_optimization_ops:
return # assuming wire nets are already optimized
if (net_checking.op in two_var_ops) and num_constants == 1:
long_wires = [w for w in net_checking.args + net_checking.dests if len(w) != 1]
if len(long_wires):
_constant_prop_error(net_checking, "has wire(s) {} with bitwidths that are not 1"
.format(long_wires))
return # skip if we are ignoring unoptimizable ops
# special case
const_wire, other_wire = net_checking.args
if isinstance(other_wire, Const):
const_wire, other_wire = other_wire, const_wire
outputs = [two_var_ops[net_checking.op](const_wire.val, other_val)
for other_val in (0, 1)]
if outputs[0] == outputs[1]:
replace_net_with_const(outputs[0])
elif outputs[0] == 0:
replace_net_with_wire(other_wire)
else:
replace_net(LogicNet('~', None, args=(other_wire,),
dests=net_checking.dests))
else:
# this optimization is actually compatible with long wires
if net_checking.op in two_var_ops:
output = two_var_ops[net_checking.op](net_checking.args[0].val,
net_checking.args[1].val)
else:
output = one_var_ops[net_checking.op](net_checking.args[0].val)
replace_net_with_const(output)
new_wire_src = _ProducerList()
wire_add_set = set()
nets_to_add = set()
nets_to_remove = set()
for a_net in block.logic:
constant_prop_check(a_net)
# second full pass to cleanup
new_logic = set()
for net in block.logic.union(nets_to_add) - nets_to_remove:
new_args = tuple(new_wire_src.find_producer(x) for x in net.args)
new_net = LogicNet(net.op, net.op_param, new_args, net.dests)
new_logic.add(new_net)
block.logic = new_logic
for new_wirevector in wire_add_set:
block.add_wirevector(new_wirevector)
_remove_unused_wires(block) | [
"def",
"_constant_prop_pass",
"(",
"block",
",",
"silence_unexpected_net_warnings",
"=",
"False",
")",
":",
"valid_net_ops",
"=",
"'~&|^nrwcsm@'",
"no_optimization_ops",
"=",
"'wcsm@'",
"one_var_ops",
"=",
"{",
"'~'",
":",
"lambda",
"x",
":",
"1",
"-",
"x",
",",
"'r'",
":",
"lambda",
"x",
":",
"x",
"# This is only valid for constant folding purposes",
"}",
"two_var_ops",
"=",
"{",
"'&'",
":",
"lambda",
"l",
",",
"r",
":",
"l",
"&",
"r",
",",
"'|'",
":",
"lambda",
"l",
",",
"r",
":",
"l",
"|",
"r",
",",
"'^'",
":",
"lambda",
"l",
",",
"r",
":",
"l",
"^",
"r",
",",
"'n'",
":",
"lambda",
"l",
",",
"r",
":",
"1",
"-",
"(",
"l",
"&",
"r",
")",
",",
"}",
"def",
"_constant_prop_error",
"(",
"net",
",",
"error_str",
")",
":",
"if",
"not",
"silence_unexpected_net_warnings",
":",
"raise",
"PyrtlError",
"(",
"\"Unexpected net, {}, has {}\"",
".",
"format",
"(",
"net",
",",
"error_str",
")",
")",
"def",
"constant_prop_check",
"(",
"net_checking",
")",
":",
"def",
"replace_net",
"(",
"new_net",
")",
":",
"nets_to_remove",
".",
"add",
"(",
"net_checking",
")",
"nets_to_add",
".",
"add",
"(",
"new_net",
")",
"def",
"replace_net_with_const",
"(",
"const_val",
")",
":",
"new_const_wire",
"=",
"Const",
"(",
"bitwidth",
"=",
"1",
",",
"val",
"=",
"const_val",
",",
"block",
"=",
"block",
")",
"wire_add_set",
".",
"add",
"(",
"new_const_wire",
")",
"replace_net_with_wire",
"(",
"new_const_wire",
")",
"def",
"replace_net_with_wire",
"(",
"new_wire",
")",
":",
"if",
"isinstance",
"(",
"net_checking",
".",
"dests",
"[",
"0",
"]",
",",
"Output",
")",
":",
"replace_net",
"(",
"LogicNet",
"(",
"'w'",
",",
"None",
",",
"args",
"=",
"(",
"new_wire",
",",
")",
",",
"dests",
"=",
"net_checking",
".",
"dests",
")",
")",
"else",
":",
"nets_to_remove",
".",
"add",
"(",
"net_checking",
")",
"new_wire_src",
"[",
"net_checking",
".",
"dests",
"[",
"0",
"]",
"]",
"=",
"new_wire",
"if",
"net_checking",
".",
"op",
"not",
"in",
"valid_net_ops",
":",
"_constant_prop_error",
"(",
"net_checking",
",",
"\"has a net not handled by constant_propagation\"",
")",
"return",
"# skip if we are ignoring unoptimizable ops",
"num_constants",
"=",
"sum",
"(",
"(",
"isinstance",
"(",
"arg",
",",
"Const",
")",
"for",
"arg",
"in",
"net_checking",
".",
"args",
")",
")",
"if",
"num_constants",
"is",
"0",
"or",
"net_checking",
".",
"op",
"in",
"no_optimization_ops",
":",
"return",
"# assuming wire nets are already optimized",
"if",
"(",
"net_checking",
".",
"op",
"in",
"two_var_ops",
")",
"and",
"num_constants",
"==",
"1",
":",
"long_wires",
"=",
"[",
"w",
"for",
"w",
"in",
"net_checking",
".",
"args",
"+",
"net_checking",
".",
"dests",
"if",
"len",
"(",
"w",
")",
"!=",
"1",
"]",
"if",
"len",
"(",
"long_wires",
")",
":",
"_constant_prop_error",
"(",
"net_checking",
",",
"\"has wire(s) {} with bitwidths that are not 1\"",
".",
"format",
"(",
"long_wires",
")",
")",
"return",
"# skip if we are ignoring unoptimizable ops",
"# special case",
"const_wire",
",",
"other_wire",
"=",
"net_checking",
".",
"args",
"if",
"isinstance",
"(",
"other_wire",
",",
"Const",
")",
":",
"const_wire",
",",
"other_wire",
"=",
"other_wire",
",",
"const_wire",
"outputs",
"=",
"[",
"two_var_ops",
"[",
"net_checking",
".",
"op",
"]",
"(",
"const_wire",
".",
"val",
",",
"other_val",
")",
"for",
"other_val",
"in",
"(",
"0",
",",
"1",
")",
"]",
"if",
"outputs",
"[",
"0",
"]",
"==",
"outputs",
"[",
"1",
"]",
":",
"replace_net_with_const",
"(",
"outputs",
"[",
"0",
"]",
")",
"elif",
"outputs",
"[",
"0",
"]",
"==",
"0",
":",
"replace_net_with_wire",
"(",
"other_wire",
")",
"else",
":",
"replace_net",
"(",
"LogicNet",
"(",
"'~'",
",",
"None",
",",
"args",
"=",
"(",
"other_wire",
",",
")",
",",
"dests",
"=",
"net_checking",
".",
"dests",
")",
")",
"else",
":",
"# this optimization is actually compatible with long wires",
"if",
"net_checking",
".",
"op",
"in",
"two_var_ops",
":",
"output",
"=",
"two_var_ops",
"[",
"net_checking",
".",
"op",
"]",
"(",
"net_checking",
".",
"args",
"[",
"0",
"]",
".",
"val",
",",
"net_checking",
".",
"args",
"[",
"1",
"]",
".",
"val",
")",
"else",
":",
"output",
"=",
"one_var_ops",
"[",
"net_checking",
".",
"op",
"]",
"(",
"net_checking",
".",
"args",
"[",
"0",
"]",
".",
"val",
")",
"replace_net_with_const",
"(",
"output",
")",
"new_wire_src",
"=",
"_ProducerList",
"(",
")",
"wire_add_set",
"=",
"set",
"(",
")",
"nets_to_add",
"=",
"set",
"(",
")",
"nets_to_remove",
"=",
"set",
"(",
")",
"for",
"a_net",
"in",
"block",
".",
"logic",
":",
"constant_prop_check",
"(",
"a_net",
")",
"# second full pass to cleanup",
"new_logic",
"=",
"set",
"(",
")",
"for",
"net",
"in",
"block",
".",
"logic",
".",
"union",
"(",
"nets_to_add",
")",
"-",
"nets_to_remove",
":",
"new_args",
"=",
"tuple",
"(",
"new_wire_src",
".",
"find_producer",
"(",
"x",
")",
"for",
"x",
"in",
"net",
".",
"args",
")",
"new_net",
"=",
"LogicNet",
"(",
"net",
".",
"op",
",",
"net",
".",
"op_param",
",",
"new_args",
",",
"net",
".",
"dests",
")",
"new_logic",
".",
"add",
"(",
"new_net",
")",
"block",
".",
"logic",
"=",
"new_logic",
"for",
"new_wirevector",
"in",
"wire_add_set",
":",
"block",
".",
"add_wirevector",
"(",
"new_wirevector",
")",
"_remove_unused_wires",
"(",
"block",
")"
] | Does one constant propagation pass | [
"Does",
"one",
"constant",
"propagation",
"pass"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/passes.py#L118-L215 |
UCSBarchlab/PyRTL | pyrtl/passes.py | common_subexp_elimination | def common_subexp_elimination(block=None, abs_thresh=1, percent_thresh=0):
"""
Common Subexpression Elimination for PyRTL blocks
:param block: the block to run the subexpression elimination on
:param abs_thresh: absolute threshold for stopping optimization
:param percent_thresh: percent threshold for stopping optimization
"""
block = working_block(block)
net_count = _NetCount(block)
while net_count.shrinking(block, percent_thresh, abs_thresh):
net_table = _find_common_subexps(block)
_replace_subexps(block, net_table) | python | def common_subexp_elimination(block=None, abs_thresh=1, percent_thresh=0):
"""
Common Subexpression Elimination for PyRTL blocks
:param block: the block to run the subexpression elimination on
:param abs_thresh: absolute threshold for stopping optimization
:param percent_thresh: percent threshold for stopping optimization
"""
block = working_block(block)
net_count = _NetCount(block)
while net_count.shrinking(block, percent_thresh, abs_thresh):
net_table = _find_common_subexps(block)
_replace_subexps(block, net_table) | [
"def",
"common_subexp_elimination",
"(",
"block",
"=",
"None",
",",
"abs_thresh",
"=",
"1",
",",
"percent_thresh",
"=",
"0",
")",
":",
"block",
"=",
"working_block",
"(",
"block",
")",
"net_count",
"=",
"_NetCount",
"(",
"block",
")",
"while",
"net_count",
".",
"shrinking",
"(",
"block",
",",
"percent_thresh",
",",
"abs_thresh",
")",
":",
"net_table",
"=",
"_find_common_subexps",
"(",
"block",
")",
"_replace_subexps",
"(",
"block",
",",
"net_table",
")"
] | Common Subexpression Elimination for PyRTL blocks
:param block: the block to run the subexpression elimination on
:param abs_thresh: absolute threshold for stopping optimization
:param percent_thresh: percent threshold for stopping optimization | [
"Common",
"Subexpression",
"Elimination",
"for",
"PyRTL",
"blocks"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/passes.py#L218-L231 |
UCSBarchlab/PyRTL | pyrtl/passes.py | _remove_unlistened_nets | def _remove_unlistened_nets(block):
""" Removes all nets that are not connected to an output wirevector
"""
listened_nets = set()
listened_wires = set()
prev_listened_net_count = 0
def add_to_listened(net):
listened_nets.add(net)
listened_wires.update(net.args)
for a_net in block.logic:
if a_net.op == '@':
add_to_listened(a_net)
elif any(isinstance(destW, Output) for destW in a_net.dests):
add_to_listened(a_net)
while len(listened_nets) > prev_listened_net_count:
prev_listened_net_count = len(listened_nets)
for net in block.logic - listened_nets:
if any((destWire in listened_wires) for destWire in net.dests):
add_to_listened(net)
block.logic = listened_nets
_remove_unused_wires(block) | python | def _remove_unlistened_nets(block):
""" Removes all nets that are not connected to an output wirevector
"""
listened_nets = set()
listened_wires = set()
prev_listened_net_count = 0
def add_to_listened(net):
listened_nets.add(net)
listened_wires.update(net.args)
for a_net in block.logic:
if a_net.op == '@':
add_to_listened(a_net)
elif any(isinstance(destW, Output) for destW in a_net.dests):
add_to_listened(a_net)
while len(listened_nets) > prev_listened_net_count:
prev_listened_net_count = len(listened_nets)
for net in block.logic - listened_nets:
if any((destWire in listened_wires) for destWire in net.dests):
add_to_listened(net)
block.logic = listened_nets
_remove_unused_wires(block) | [
"def",
"_remove_unlistened_nets",
"(",
"block",
")",
":",
"listened_nets",
"=",
"set",
"(",
")",
"listened_wires",
"=",
"set",
"(",
")",
"prev_listened_net_count",
"=",
"0",
"def",
"add_to_listened",
"(",
"net",
")",
":",
"listened_nets",
".",
"add",
"(",
"net",
")",
"listened_wires",
".",
"update",
"(",
"net",
".",
"args",
")",
"for",
"a_net",
"in",
"block",
".",
"logic",
":",
"if",
"a_net",
".",
"op",
"==",
"'@'",
":",
"add_to_listened",
"(",
"a_net",
")",
"elif",
"any",
"(",
"isinstance",
"(",
"destW",
",",
"Output",
")",
"for",
"destW",
"in",
"a_net",
".",
"dests",
")",
":",
"add_to_listened",
"(",
"a_net",
")",
"while",
"len",
"(",
"listened_nets",
")",
">",
"prev_listened_net_count",
":",
"prev_listened_net_count",
"=",
"len",
"(",
"listened_nets",
")",
"for",
"net",
"in",
"block",
".",
"logic",
"-",
"listened_nets",
":",
"if",
"any",
"(",
"(",
"destWire",
"in",
"listened_wires",
")",
"for",
"destWire",
"in",
"net",
".",
"dests",
")",
":",
"add_to_listened",
"(",
"net",
")",
"block",
".",
"logic",
"=",
"listened_nets",
"_remove_unused_wires",
"(",
"block",
")"
] | Removes all nets that are not connected to an output wirevector | [
"Removes",
"all",
"nets",
"that",
"are",
"not",
"connected",
"to",
"an",
"output",
"wirevector"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/passes.py#L299-L325 |
UCSBarchlab/PyRTL | pyrtl/passes.py | _remove_unused_wires | def _remove_unused_wires(block, keep_inputs=True):
""" Removes all unconnected wires from a block"""
valid_wires = set()
for logic_net in block.logic:
valid_wires.update(logic_net.args, logic_net.dests)
wire_removal_set = block.wirevector_set.difference(valid_wires)
for removed_wire in wire_removal_set:
if isinstance(removed_wire, Input):
term = " optimized away"
if keep_inputs:
valid_wires.add(removed_wire)
term = " deemed useless by optimization"
print("Input Wire, " + removed_wire.name + " has been" + term)
if isinstance(removed_wire, Output):
PyrtlInternalError("Output wire, " + removed_wire.name + " not driven")
block.wirevector_set = valid_wires | python | def _remove_unused_wires(block, keep_inputs=True):
""" Removes all unconnected wires from a block"""
valid_wires = set()
for logic_net in block.logic:
valid_wires.update(logic_net.args, logic_net.dests)
wire_removal_set = block.wirevector_set.difference(valid_wires)
for removed_wire in wire_removal_set:
if isinstance(removed_wire, Input):
term = " optimized away"
if keep_inputs:
valid_wires.add(removed_wire)
term = " deemed useless by optimization"
print("Input Wire, " + removed_wire.name + " has been" + term)
if isinstance(removed_wire, Output):
PyrtlInternalError("Output wire, " + removed_wire.name + " not driven")
block.wirevector_set = valid_wires | [
"def",
"_remove_unused_wires",
"(",
"block",
",",
"keep_inputs",
"=",
"True",
")",
":",
"valid_wires",
"=",
"set",
"(",
")",
"for",
"logic_net",
"in",
"block",
".",
"logic",
":",
"valid_wires",
".",
"update",
"(",
"logic_net",
".",
"args",
",",
"logic_net",
".",
"dests",
")",
"wire_removal_set",
"=",
"block",
".",
"wirevector_set",
".",
"difference",
"(",
"valid_wires",
")",
"for",
"removed_wire",
"in",
"wire_removal_set",
":",
"if",
"isinstance",
"(",
"removed_wire",
",",
"Input",
")",
":",
"term",
"=",
"\" optimized away\"",
"if",
"keep_inputs",
":",
"valid_wires",
".",
"add",
"(",
"removed_wire",
")",
"term",
"=",
"\" deemed useless by optimization\"",
"print",
"(",
"\"Input Wire, \"",
"+",
"removed_wire",
".",
"name",
"+",
"\" has been\"",
"+",
"term",
")",
"if",
"isinstance",
"(",
"removed_wire",
",",
"Output",
")",
":",
"PyrtlInternalError",
"(",
"\"Output wire, \"",
"+",
"removed_wire",
".",
"name",
"+",
"\" not driven\"",
")",
"block",
".",
"wirevector_set",
"=",
"valid_wires"
] | Removes all unconnected wires from a block | [
"Removes",
"all",
"unconnected",
"wires",
"from",
"a",
"block"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/passes.py#L328-L346 |
UCSBarchlab/PyRTL | pyrtl/passes.py | synthesize | def synthesize(update_working_block=True, block=None):
""" Lower the design to just single-bit "and", "or", and "not" gates.
:param update_working_block: Boolean specifying if working block update
:param block: The block you want to synthesize
:return: The newly synthesized block (of type PostSynthesisBlock).
Takes as input a block (default to working block) and creates a new
block which is identical in function but uses only single bit gates
and excludes many of the more complicated primitives. The new block
should consist *almost* exclusively of the combination elements
of w, &, |, ^, and ~ and sequential elements of registers (which are
one bit as well). The two exceptions are for inputs/outputs (so that
we can keep the same interface) which are immediately broken down into
the individual bits and memories. Memories (read and write ports) which
require the reassembly and disassembly of the wirevectors immediately
before and after. There arethe only two places where 'c' and 's' ops
should exist.
The block that results from synthesis is actually of type
"PostSynthesisBlock" which contains a mapping from the original inputs
and outputs to the inputs and outputs of this block. This is used during
simulation to map the input/outputs so that the same testbench can be
used both pre and post synthesis (see documentation for Simulation for
more details).
"""
block_pre = working_block(block)
block_pre.sanity_check() # before going further, make sure that pressynth is valid
block_in = copy_block(block_pre, update_working_block=False)
block_out = PostSynthBlock()
# resulting block should only have one of a restricted set of net ops
block_out.legal_ops = set('~&|^nrwcsm@')
wirevector_map = {} # map from (vector,index) -> new_wire
with set_working_block(block_out, no_sanity_check=True):
# First, replace advanced operators with simpler ones
for op, fun in [
('*', _basic_mult),
('+', _basic_add),
('-', _basic_sub),
('x', _basic_select),
('=', _basic_eq),
('<', _basic_lt),
('>', _basic_gt)]:
net_transform(_replace_op(op, fun), block_in)
# Next, create all of the new wires for the new block
# from the original wires and store them in the wirevector_map
# for reference.
for wirevector in block_in.wirevector_subset():
for i in range(len(wirevector)):
new_name = '_'.join((wirevector.name, 'synth', str(i)))
if isinstance(wirevector, Const):
new_val = (wirevector.val >> i) & 0x1
new_wirevector = Const(bitwidth=1, val=new_val)
elif isinstance(wirevector, (Input, Output)):
new_wirevector = WireVector(name="tmp_" + new_name, bitwidth=1)
else:
new_wirevector = wirevector.__class__(name=new_name, bitwidth=1)
wirevector_map[(wirevector, i)] = new_wirevector
# Now connect up the inputs and outputs to maintain the interface
for wirevector in block_in.wirevector_subset(Input):
input_vector = Input(name=wirevector.name, bitwidth=len(wirevector))
for i in range(len(wirevector)):
wirevector_map[(wirevector, i)] <<= input_vector[i]
for wirevector in block_in.wirevector_subset(Output):
output_vector = Output(name=wirevector.name, bitwidth=len(wirevector))
# the "reversed" is needed because most significant bit comes first in concat
output_bits = [wirevector_map[(wirevector, i)]
for i in range(len(output_vector))]
output_vector <<= concat_list(output_bits)
# Now that we have all the wires built and mapped, walk all the blocks
# and map the logic to the equivalent set of primitives in the system
out_mems = block_out.mem_map # dictionary: PreSynth Map -> PostSynth Map
for net in block_in.logic:
_decompose(net, wirevector_map, out_mems, block_out)
if update_working_block:
set_working_block(block_out, no_sanity_check=True)
return block_out | python | def synthesize(update_working_block=True, block=None):
""" Lower the design to just single-bit "and", "or", and "not" gates.
:param update_working_block: Boolean specifying if working block update
:param block: The block you want to synthesize
:return: The newly synthesized block (of type PostSynthesisBlock).
Takes as input a block (default to working block) and creates a new
block which is identical in function but uses only single bit gates
and excludes many of the more complicated primitives. The new block
should consist *almost* exclusively of the combination elements
of w, &, |, ^, and ~ and sequential elements of registers (which are
one bit as well). The two exceptions are for inputs/outputs (so that
we can keep the same interface) which are immediately broken down into
the individual bits and memories. Memories (read and write ports) which
require the reassembly and disassembly of the wirevectors immediately
before and after. There arethe only two places where 'c' and 's' ops
should exist.
The block that results from synthesis is actually of type
"PostSynthesisBlock" which contains a mapping from the original inputs
and outputs to the inputs and outputs of this block. This is used during
simulation to map the input/outputs so that the same testbench can be
used both pre and post synthesis (see documentation for Simulation for
more details).
"""
block_pre = working_block(block)
block_pre.sanity_check() # before going further, make sure that pressynth is valid
block_in = copy_block(block_pre, update_working_block=False)
block_out = PostSynthBlock()
# resulting block should only have one of a restricted set of net ops
block_out.legal_ops = set('~&|^nrwcsm@')
wirevector_map = {} # map from (vector,index) -> new_wire
with set_working_block(block_out, no_sanity_check=True):
# First, replace advanced operators with simpler ones
for op, fun in [
('*', _basic_mult),
('+', _basic_add),
('-', _basic_sub),
('x', _basic_select),
('=', _basic_eq),
('<', _basic_lt),
('>', _basic_gt)]:
net_transform(_replace_op(op, fun), block_in)
# Next, create all of the new wires for the new block
# from the original wires and store them in the wirevector_map
# for reference.
for wirevector in block_in.wirevector_subset():
for i in range(len(wirevector)):
new_name = '_'.join((wirevector.name, 'synth', str(i)))
if isinstance(wirevector, Const):
new_val = (wirevector.val >> i) & 0x1
new_wirevector = Const(bitwidth=1, val=new_val)
elif isinstance(wirevector, (Input, Output)):
new_wirevector = WireVector(name="tmp_" + new_name, bitwidth=1)
else:
new_wirevector = wirevector.__class__(name=new_name, bitwidth=1)
wirevector_map[(wirevector, i)] = new_wirevector
# Now connect up the inputs and outputs to maintain the interface
for wirevector in block_in.wirevector_subset(Input):
input_vector = Input(name=wirevector.name, bitwidth=len(wirevector))
for i in range(len(wirevector)):
wirevector_map[(wirevector, i)] <<= input_vector[i]
for wirevector in block_in.wirevector_subset(Output):
output_vector = Output(name=wirevector.name, bitwidth=len(wirevector))
# the "reversed" is needed because most significant bit comes first in concat
output_bits = [wirevector_map[(wirevector, i)]
for i in range(len(output_vector))]
output_vector <<= concat_list(output_bits)
# Now that we have all the wires built and mapped, walk all the blocks
# and map the logic to the equivalent set of primitives in the system
out_mems = block_out.mem_map # dictionary: PreSynth Map -> PostSynth Map
for net in block_in.logic:
_decompose(net, wirevector_map, out_mems, block_out)
if update_working_block:
set_working_block(block_out, no_sanity_check=True)
return block_out | [
"def",
"synthesize",
"(",
"update_working_block",
"=",
"True",
",",
"block",
"=",
"None",
")",
":",
"block_pre",
"=",
"working_block",
"(",
"block",
")",
"block_pre",
".",
"sanity_check",
"(",
")",
"# before going further, make sure that pressynth is valid",
"block_in",
"=",
"copy_block",
"(",
"block_pre",
",",
"update_working_block",
"=",
"False",
")",
"block_out",
"=",
"PostSynthBlock",
"(",
")",
"# resulting block should only have one of a restricted set of net ops",
"block_out",
".",
"legal_ops",
"=",
"set",
"(",
"'~&|^nrwcsm@'",
")",
"wirevector_map",
"=",
"{",
"}",
"# map from (vector,index) -> new_wire",
"with",
"set_working_block",
"(",
"block_out",
",",
"no_sanity_check",
"=",
"True",
")",
":",
"# First, replace advanced operators with simpler ones",
"for",
"op",
",",
"fun",
"in",
"[",
"(",
"'*'",
",",
"_basic_mult",
")",
",",
"(",
"'+'",
",",
"_basic_add",
")",
",",
"(",
"'-'",
",",
"_basic_sub",
")",
",",
"(",
"'x'",
",",
"_basic_select",
")",
",",
"(",
"'='",
",",
"_basic_eq",
")",
",",
"(",
"'<'",
",",
"_basic_lt",
")",
",",
"(",
"'>'",
",",
"_basic_gt",
")",
"]",
":",
"net_transform",
"(",
"_replace_op",
"(",
"op",
",",
"fun",
")",
",",
"block_in",
")",
"# Next, create all of the new wires for the new block",
"# from the original wires and store them in the wirevector_map",
"# for reference.",
"for",
"wirevector",
"in",
"block_in",
".",
"wirevector_subset",
"(",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"wirevector",
")",
")",
":",
"new_name",
"=",
"'_'",
".",
"join",
"(",
"(",
"wirevector",
".",
"name",
",",
"'synth'",
",",
"str",
"(",
"i",
")",
")",
")",
"if",
"isinstance",
"(",
"wirevector",
",",
"Const",
")",
":",
"new_val",
"=",
"(",
"wirevector",
".",
"val",
">>",
"i",
")",
"&",
"0x1",
"new_wirevector",
"=",
"Const",
"(",
"bitwidth",
"=",
"1",
",",
"val",
"=",
"new_val",
")",
"elif",
"isinstance",
"(",
"wirevector",
",",
"(",
"Input",
",",
"Output",
")",
")",
":",
"new_wirevector",
"=",
"WireVector",
"(",
"name",
"=",
"\"tmp_\"",
"+",
"new_name",
",",
"bitwidth",
"=",
"1",
")",
"else",
":",
"new_wirevector",
"=",
"wirevector",
".",
"__class__",
"(",
"name",
"=",
"new_name",
",",
"bitwidth",
"=",
"1",
")",
"wirevector_map",
"[",
"(",
"wirevector",
",",
"i",
")",
"]",
"=",
"new_wirevector",
"# Now connect up the inputs and outputs to maintain the interface",
"for",
"wirevector",
"in",
"block_in",
".",
"wirevector_subset",
"(",
"Input",
")",
":",
"input_vector",
"=",
"Input",
"(",
"name",
"=",
"wirevector",
".",
"name",
",",
"bitwidth",
"=",
"len",
"(",
"wirevector",
")",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"wirevector",
")",
")",
":",
"wirevector_map",
"[",
"(",
"wirevector",
",",
"i",
")",
"]",
"<<=",
"input_vector",
"[",
"i",
"]",
"for",
"wirevector",
"in",
"block_in",
".",
"wirevector_subset",
"(",
"Output",
")",
":",
"output_vector",
"=",
"Output",
"(",
"name",
"=",
"wirevector",
".",
"name",
",",
"bitwidth",
"=",
"len",
"(",
"wirevector",
")",
")",
"# the \"reversed\" is needed because most significant bit comes first in concat",
"output_bits",
"=",
"[",
"wirevector_map",
"[",
"(",
"wirevector",
",",
"i",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"output_vector",
")",
")",
"]",
"output_vector",
"<<=",
"concat_list",
"(",
"output_bits",
")",
"# Now that we have all the wires built and mapped, walk all the blocks",
"# and map the logic to the equivalent set of primitives in the system",
"out_mems",
"=",
"block_out",
".",
"mem_map",
"# dictionary: PreSynth Map -> PostSynth Map",
"for",
"net",
"in",
"block_in",
".",
"logic",
":",
"_decompose",
"(",
"net",
",",
"wirevector_map",
",",
"out_mems",
",",
"block_out",
")",
"if",
"update_working_block",
":",
"set_working_block",
"(",
"block_out",
",",
"no_sanity_check",
"=",
"True",
")",
"return",
"block_out"
] | Lower the design to just single-bit "and", "or", and "not" gates.
:param update_working_block: Boolean specifying if working block update
:param block: The block you want to synthesize
:return: The newly synthesized block (of type PostSynthesisBlock).
Takes as input a block (default to working block) and creates a new
block which is identical in function but uses only single bit gates
and excludes many of the more complicated primitives. The new block
should consist *almost* exclusively of the combination elements
of w, &, |, ^, and ~ and sequential elements of registers (which are
one bit as well). The two exceptions are for inputs/outputs (so that
we can keep the same interface) which are immediately broken down into
the individual bits and memories. Memories (read and write ports) which
require the reassembly and disassembly of the wirevectors immediately
before and after. There arethe only two places where 'c' and 's' ops
should exist.
The block that results from synthesis is actually of type
"PostSynthesisBlock" which contains a mapping from the original inputs
and outputs to the inputs and outputs of this block. This is used during
simulation to map the input/outputs so that the same testbench can be
used both pre and post synthesis (see documentation for Simulation for
more details). | [
"Lower",
"the",
"design",
"to",
"just",
"single",
"-",
"bit",
"and",
"or",
"and",
"not",
"gates",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/passes.py#L355-L438 |
UCSBarchlab/PyRTL | pyrtl/passes.py | _decompose | def _decompose(net, wv_map, mems, block_out):
""" Add the wires and logicnets to block_out and wv_map to decompose net """
def arg(x, i):
# return the mapped wire vector for argument x, wire number i
return wv_map[(net.args[x], i)]
def destlen():
# return iterator over length of the destination in bits
return range(len(net.dests[0]))
def assign_dest(i, v):
# assign v to the wiremap for dest[0], wire i
wv_map[(net.dests[0], i)] <<= v
one_var_ops = {
'w': lambda w: w,
'~': lambda w: ~w,
}
c_two_var_ops = {
'&': lambda l, r: l & r,
'|': lambda l, r: l | r,
'^': lambda l, r: l ^ r,
'n': lambda l, r: l.nand(r),
}
if net.op in one_var_ops:
for i in destlen():
assign_dest(i, one_var_ops[net.op](arg(0, i)))
elif net.op in c_two_var_ops:
for i in destlen():
assign_dest(i, c_two_var_ops[net.op](arg(0, i), arg(1, i)))
elif net.op == 's':
for i in destlen():
selected_bit = arg(0, net.op_param[i])
assign_dest(i, selected_bit)
elif net.op == 'c':
arg_wirelist = []
# generate list of wires for vectors being concatenated
for arg_vector in net.args:
arg_vector_as_list = [wv_map[(arg_vector, i)] for i in range(len(arg_vector))]
arg_wirelist = arg_vector_as_list + arg_wirelist
for i in destlen():
assign_dest(i, arg_wirelist[i])
elif net.op == 'r':
for i in destlen():
args = (arg(0, i),)
dests = (wv_map[(net.dests[0], i)],)
new_net = LogicNet('r', None, args=args, dests=dests)
block_out.add_net(new_net)
elif net.op == 'm':
arg0list = [arg(0, i) for i in range(len(net.args[0]))]
addr = concat_list(arg0list)
new_mem = _get_new_block_mem_instance(net.op_param, mems, block_out)[1]
data = as_wires(new_mem[addr])
for i in destlen():
assign_dest(i, data[i])
elif net.op == '@':
addrlist = [arg(0, i) for i in range(len(net.args[0]))]
addr = concat_list(addrlist)
datalist = [arg(1, i) for i in range(len(net.args[1]))]
data = concat_list(datalist)
enable = arg(2, 0)
new_mem = _get_new_block_mem_instance(net.op_param, mems, block_out)[1]
new_mem[addr] <<= MemBlock.EnabledWrite(data=data, enable=enable)
else:
raise PyrtlInternalError('Unable to synthesize the following net '
'due to unimplemented op :\n%s' % str(net))
return | python | def _decompose(net, wv_map, mems, block_out):
""" Add the wires and logicnets to block_out and wv_map to decompose net """
def arg(x, i):
# return the mapped wire vector for argument x, wire number i
return wv_map[(net.args[x], i)]
def destlen():
# return iterator over length of the destination in bits
return range(len(net.dests[0]))
def assign_dest(i, v):
# assign v to the wiremap for dest[0], wire i
wv_map[(net.dests[0], i)] <<= v
one_var_ops = {
'w': lambda w: w,
'~': lambda w: ~w,
}
c_two_var_ops = {
'&': lambda l, r: l & r,
'|': lambda l, r: l | r,
'^': lambda l, r: l ^ r,
'n': lambda l, r: l.nand(r),
}
if net.op in one_var_ops:
for i in destlen():
assign_dest(i, one_var_ops[net.op](arg(0, i)))
elif net.op in c_two_var_ops:
for i in destlen():
assign_dest(i, c_two_var_ops[net.op](arg(0, i), arg(1, i)))
elif net.op == 's':
for i in destlen():
selected_bit = arg(0, net.op_param[i])
assign_dest(i, selected_bit)
elif net.op == 'c':
arg_wirelist = []
# generate list of wires for vectors being concatenated
for arg_vector in net.args:
arg_vector_as_list = [wv_map[(arg_vector, i)] for i in range(len(arg_vector))]
arg_wirelist = arg_vector_as_list + arg_wirelist
for i in destlen():
assign_dest(i, arg_wirelist[i])
elif net.op == 'r':
for i in destlen():
args = (arg(0, i),)
dests = (wv_map[(net.dests[0], i)],)
new_net = LogicNet('r', None, args=args, dests=dests)
block_out.add_net(new_net)
elif net.op == 'm':
arg0list = [arg(0, i) for i in range(len(net.args[0]))]
addr = concat_list(arg0list)
new_mem = _get_new_block_mem_instance(net.op_param, mems, block_out)[1]
data = as_wires(new_mem[addr])
for i in destlen():
assign_dest(i, data[i])
elif net.op == '@':
addrlist = [arg(0, i) for i in range(len(net.args[0]))]
addr = concat_list(addrlist)
datalist = [arg(1, i) for i in range(len(net.args[1]))]
data = concat_list(datalist)
enable = arg(2, 0)
new_mem = _get_new_block_mem_instance(net.op_param, mems, block_out)[1]
new_mem[addr] <<= MemBlock.EnabledWrite(data=data, enable=enable)
else:
raise PyrtlInternalError('Unable to synthesize the following net '
'due to unimplemented op :\n%s' % str(net))
return | [
"def",
"_decompose",
"(",
"net",
",",
"wv_map",
",",
"mems",
",",
"block_out",
")",
":",
"def",
"arg",
"(",
"x",
",",
"i",
")",
":",
"# return the mapped wire vector for argument x, wire number i",
"return",
"wv_map",
"[",
"(",
"net",
".",
"args",
"[",
"x",
"]",
",",
"i",
")",
"]",
"def",
"destlen",
"(",
")",
":",
"# return iterator over length of the destination in bits",
"return",
"range",
"(",
"len",
"(",
"net",
".",
"dests",
"[",
"0",
"]",
")",
")",
"def",
"assign_dest",
"(",
"i",
",",
"v",
")",
":",
"# assign v to the wiremap for dest[0], wire i",
"wv_map",
"[",
"(",
"net",
".",
"dests",
"[",
"0",
"]",
",",
"i",
")",
"]",
"<<=",
"v",
"one_var_ops",
"=",
"{",
"'w'",
":",
"lambda",
"w",
":",
"w",
",",
"'~'",
":",
"lambda",
"w",
":",
"~",
"w",
",",
"}",
"c_two_var_ops",
"=",
"{",
"'&'",
":",
"lambda",
"l",
",",
"r",
":",
"l",
"&",
"r",
",",
"'|'",
":",
"lambda",
"l",
",",
"r",
":",
"l",
"|",
"r",
",",
"'^'",
":",
"lambda",
"l",
",",
"r",
":",
"l",
"^",
"r",
",",
"'n'",
":",
"lambda",
"l",
",",
"r",
":",
"l",
".",
"nand",
"(",
"r",
")",
",",
"}",
"if",
"net",
".",
"op",
"in",
"one_var_ops",
":",
"for",
"i",
"in",
"destlen",
"(",
")",
":",
"assign_dest",
"(",
"i",
",",
"one_var_ops",
"[",
"net",
".",
"op",
"]",
"(",
"arg",
"(",
"0",
",",
"i",
")",
")",
")",
"elif",
"net",
".",
"op",
"in",
"c_two_var_ops",
":",
"for",
"i",
"in",
"destlen",
"(",
")",
":",
"assign_dest",
"(",
"i",
",",
"c_two_var_ops",
"[",
"net",
".",
"op",
"]",
"(",
"arg",
"(",
"0",
",",
"i",
")",
",",
"arg",
"(",
"1",
",",
"i",
")",
")",
")",
"elif",
"net",
".",
"op",
"==",
"'s'",
":",
"for",
"i",
"in",
"destlen",
"(",
")",
":",
"selected_bit",
"=",
"arg",
"(",
"0",
",",
"net",
".",
"op_param",
"[",
"i",
"]",
")",
"assign_dest",
"(",
"i",
",",
"selected_bit",
")",
"elif",
"net",
".",
"op",
"==",
"'c'",
":",
"arg_wirelist",
"=",
"[",
"]",
"# generate list of wires for vectors being concatenated",
"for",
"arg_vector",
"in",
"net",
".",
"args",
":",
"arg_vector_as_list",
"=",
"[",
"wv_map",
"[",
"(",
"arg_vector",
",",
"i",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"arg_vector",
")",
")",
"]",
"arg_wirelist",
"=",
"arg_vector_as_list",
"+",
"arg_wirelist",
"for",
"i",
"in",
"destlen",
"(",
")",
":",
"assign_dest",
"(",
"i",
",",
"arg_wirelist",
"[",
"i",
"]",
")",
"elif",
"net",
".",
"op",
"==",
"'r'",
":",
"for",
"i",
"in",
"destlen",
"(",
")",
":",
"args",
"=",
"(",
"arg",
"(",
"0",
",",
"i",
")",
",",
")",
"dests",
"=",
"(",
"wv_map",
"[",
"(",
"net",
".",
"dests",
"[",
"0",
"]",
",",
"i",
")",
"]",
",",
")",
"new_net",
"=",
"LogicNet",
"(",
"'r'",
",",
"None",
",",
"args",
"=",
"args",
",",
"dests",
"=",
"dests",
")",
"block_out",
".",
"add_net",
"(",
"new_net",
")",
"elif",
"net",
".",
"op",
"==",
"'m'",
":",
"arg0list",
"=",
"[",
"arg",
"(",
"0",
",",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"net",
".",
"args",
"[",
"0",
"]",
")",
")",
"]",
"addr",
"=",
"concat_list",
"(",
"arg0list",
")",
"new_mem",
"=",
"_get_new_block_mem_instance",
"(",
"net",
".",
"op_param",
",",
"mems",
",",
"block_out",
")",
"[",
"1",
"]",
"data",
"=",
"as_wires",
"(",
"new_mem",
"[",
"addr",
"]",
")",
"for",
"i",
"in",
"destlen",
"(",
")",
":",
"assign_dest",
"(",
"i",
",",
"data",
"[",
"i",
"]",
")",
"elif",
"net",
".",
"op",
"==",
"'@'",
":",
"addrlist",
"=",
"[",
"arg",
"(",
"0",
",",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"net",
".",
"args",
"[",
"0",
"]",
")",
")",
"]",
"addr",
"=",
"concat_list",
"(",
"addrlist",
")",
"datalist",
"=",
"[",
"arg",
"(",
"1",
",",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"net",
".",
"args",
"[",
"1",
"]",
")",
")",
"]",
"data",
"=",
"concat_list",
"(",
"datalist",
")",
"enable",
"=",
"arg",
"(",
"2",
",",
"0",
")",
"new_mem",
"=",
"_get_new_block_mem_instance",
"(",
"net",
".",
"op_param",
",",
"mems",
",",
"block_out",
")",
"[",
"1",
"]",
"new_mem",
"[",
"addr",
"]",
"<<=",
"MemBlock",
".",
"EnabledWrite",
"(",
"data",
"=",
"data",
",",
"enable",
"=",
"enable",
")",
"else",
":",
"raise",
"PyrtlInternalError",
"(",
"'Unable to synthesize the following net '",
"'due to unimplemented op :\\n%s'",
"%",
"str",
"(",
"net",
")",
")",
"return"
] | Add the wires and logicnets to block_out and wv_map to decompose net | [
"Add",
"the",
"wires",
"and",
"logicnets",
"to",
"block_out",
"and",
"wv_map",
"to",
"decompose",
"net"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/passes.py#L451-L519 |
UCSBarchlab/PyRTL | pyrtl/passes.py | nand_synth | def nand_synth(net):
"""
Synthesizes an Post-Synthesis block into one consisting of nands and inverters in place
:param block: The block to synthesize.
"""
if net.op in '~nrwcsm@':
return True
def arg(num):
return net.args[num]
dest = net.dests[0]
if net.op == '&':
dest <<= ~(arg(0).nand(arg(1)))
elif net.op == '|':
dest <<= (~arg(0)).nand(~arg(1))
elif net.op == '^':
temp_0 = arg(0).nand(arg(1))
dest <<= temp_0.nand(arg(0)).nand(temp_0.nand(arg(1)))
else:
raise PyrtlError("Op, '{}' is not supported in nand_synth".format(net.op)) | python | def nand_synth(net):
"""
Synthesizes an Post-Synthesis block into one consisting of nands and inverters in place
:param block: The block to synthesize.
"""
if net.op in '~nrwcsm@':
return True
def arg(num):
return net.args[num]
dest = net.dests[0]
if net.op == '&':
dest <<= ~(arg(0).nand(arg(1)))
elif net.op == '|':
dest <<= (~arg(0)).nand(~arg(1))
elif net.op == '^':
temp_0 = arg(0).nand(arg(1))
dest <<= temp_0.nand(arg(0)).nand(temp_0.nand(arg(1)))
else:
raise PyrtlError("Op, '{}' is not supported in nand_synth".format(net.op)) | [
"def",
"nand_synth",
"(",
"net",
")",
":",
"if",
"net",
".",
"op",
"in",
"'~nrwcsm@'",
":",
"return",
"True",
"def",
"arg",
"(",
"num",
")",
":",
"return",
"net",
".",
"args",
"[",
"num",
"]",
"dest",
"=",
"net",
".",
"dests",
"[",
"0",
"]",
"if",
"net",
".",
"op",
"==",
"'&'",
":",
"dest",
"<<=",
"~",
"(",
"arg",
"(",
"0",
")",
".",
"nand",
"(",
"arg",
"(",
"1",
")",
")",
")",
"elif",
"net",
".",
"op",
"==",
"'|'",
":",
"dest",
"<<=",
"(",
"~",
"arg",
"(",
"0",
")",
")",
".",
"nand",
"(",
"~",
"arg",
"(",
"1",
")",
")",
"elif",
"net",
".",
"op",
"==",
"'^'",
":",
"temp_0",
"=",
"arg",
"(",
"0",
")",
".",
"nand",
"(",
"arg",
"(",
"1",
")",
")",
"dest",
"<<=",
"temp_0",
".",
"nand",
"(",
"arg",
"(",
"0",
")",
")",
".",
"nand",
"(",
"temp_0",
".",
"nand",
"(",
"arg",
"(",
"1",
")",
")",
")",
"else",
":",
"raise",
"PyrtlError",
"(",
"\"Op, '{}' is not supported in nand_synth\"",
".",
"format",
"(",
"net",
".",
"op",
")",
")"
] | Synthesizes an Post-Synthesis block into one consisting of nands and inverters in place
:param block: The block to synthesize. | [
"Synthesizes",
"an",
"Post",
"-",
"Synthesis",
"block",
"into",
"one",
"consisting",
"of",
"nands",
"and",
"inverters",
"in",
"place",
":",
"param",
"block",
":",
"The",
"block",
"to",
"synthesize",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/passes.py#L523-L543 |
UCSBarchlab/PyRTL | pyrtl/passes.py | and_inverter_synth | def and_inverter_synth(net):
"""
Transforms a decomposed block into one consisting of ands and inverters in place
:param block: The block to synthesize
"""
if net.op in '~&rwcsm@':
return True
def arg(num):
return net.args[num]
dest = net.dests[0]
if net.op == '|':
dest <<= ~(~arg(0) & ~arg(1))
elif net.op == '^':
all_1 = arg(0) & arg(1)
all_0 = ~arg(0) & ~arg(1)
dest <<= all_0 & ~all_1
elif net.op == 'n':
dest <<= ~(arg(0) & arg(1))
else:
raise PyrtlError("Op, '{}' is not supported in and_inv_synth".format(net.op)) | python | def and_inverter_synth(net):
"""
Transforms a decomposed block into one consisting of ands and inverters in place
:param block: The block to synthesize
"""
if net.op in '~&rwcsm@':
return True
def arg(num):
return net.args[num]
dest = net.dests[0]
if net.op == '|':
dest <<= ~(~arg(0) & ~arg(1))
elif net.op == '^':
all_1 = arg(0) & arg(1)
all_0 = ~arg(0) & ~arg(1)
dest <<= all_0 & ~all_1
elif net.op == 'n':
dest <<= ~(arg(0) & arg(1))
else:
raise PyrtlError("Op, '{}' is not supported in and_inv_synth".format(net.op)) | [
"def",
"and_inverter_synth",
"(",
"net",
")",
":",
"if",
"net",
".",
"op",
"in",
"'~&rwcsm@'",
":",
"return",
"True",
"def",
"arg",
"(",
"num",
")",
":",
"return",
"net",
".",
"args",
"[",
"num",
"]",
"dest",
"=",
"net",
".",
"dests",
"[",
"0",
"]",
"if",
"net",
".",
"op",
"==",
"'|'",
":",
"dest",
"<<=",
"~",
"(",
"~",
"arg",
"(",
"0",
")",
"&",
"~",
"arg",
"(",
"1",
")",
")",
"elif",
"net",
".",
"op",
"==",
"'^'",
":",
"all_1",
"=",
"arg",
"(",
"0",
")",
"&",
"arg",
"(",
"1",
")",
"all_0",
"=",
"~",
"arg",
"(",
"0",
")",
"&",
"~",
"arg",
"(",
"1",
")",
"dest",
"<<=",
"all_0",
"&",
"~",
"all_1",
"elif",
"net",
".",
"op",
"==",
"'n'",
":",
"dest",
"<<=",
"~",
"(",
"arg",
"(",
"0",
")",
"&",
"arg",
"(",
"1",
")",
")",
"else",
":",
"raise",
"PyrtlError",
"(",
"\"Op, '{}' is not supported in and_inv_synth\"",
".",
"format",
"(",
"net",
".",
"op",
")",
")"
] | Transforms a decomposed block into one consisting of ands and inverters in place
:param block: The block to synthesize | [
"Transforms",
"a",
"decomposed",
"block",
"into",
"one",
"consisting",
"of",
"ands",
"and",
"inverters",
"in",
"place",
":",
"param",
"block",
":",
"The",
"block",
"to",
"synthesize"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/passes.py#L547-L568 |
UCSBarchlab/PyRTL | pyrtl/rtllib/barrel.py | barrel_shifter | def barrel_shifter(bits_to_shift, bit_in, direction, shift_dist, wrap_around=0):
""" Create a barrel shifter that operates on data based on the wire width.
:param bits_to_shift: the input wire
:param bit_in: the 1-bit wire giving the value to shift in
:param direction: a one bit WireVector representing shift direction
(0 = shift down, 1 = shift up)
:param shift_dist: WireVector representing offset to shift
:param wrap_around: ****currently not implemented****
:return: shifted WireVector
"""
from pyrtl import concat, select # just for readability
if wrap_around != 0:
raise NotImplementedError
# Implement with logN stages pyrtl.muxing between shifted and un-shifted values
final_width = len(bits_to_shift)
val = bits_to_shift
append_val = bit_in
for i in range(len(shift_dist)):
shift_amt = pow(2, i) # stages shift 1,2,4,8,...
if shift_amt < final_width:
newval = select(direction,
concat(val[:-shift_amt], append_val), # shift up
concat(append_val, val[shift_amt:])) # shift down
val = select(shift_dist[i],
truecase=newval, # if bit of shift is 1, do the shift
falsecase=val) # otherwise, don't
# the value to append grows exponentially, but is capped at full width
append_val = concat(append_val, append_val)[:final_width]
else:
# if we are shifting this much, all the data is gone
val = select(shift_dist[i],
truecase=append_val, # if bit of shift is 1, do the shift
falsecase=val) # otherwise, don't
return val | python | def barrel_shifter(bits_to_shift, bit_in, direction, shift_dist, wrap_around=0):
""" Create a barrel shifter that operates on data based on the wire width.
:param bits_to_shift: the input wire
:param bit_in: the 1-bit wire giving the value to shift in
:param direction: a one bit WireVector representing shift direction
(0 = shift down, 1 = shift up)
:param shift_dist: WireVector representing offset to shift
:param wrap_around: ****currently not implemented****
:return: shifted WireVector
"""
from pyrtl import concat, select # just for readability
if wrap_around != 0:
raise NotImplementedError
# Implement with logN stages pyrtl.muxing between shifted and un-shifted values
final_width = len(bits_to_shift)
val = bits_to_shift
append_val = bit_in
for i in range(len(shift_dist)):
shift_amt = pow(2, i) # stages shift 1,2,4,8,...
if shift_amt < final_width:
newval = select(direction,
concat(val[:-shift_amt], append_val), # shift up
concat(append_val, val[shift_amt:])) # shift down
val = select(shift_dist[i],
truecase=newval, # if bit of shift is 1, do the shift
falsecase=val) # otherwise, don't
# the value to append grows exponentially, but is capped at full width
append_val = concat(append_val, append_val)[:final_width]
else:
# if we are shifting this much, all the data is gone
val = select(shift_dist[i],
truecase=append_val, # if bit of shift is 1, do the shift
falsecase=val) # otherwise, don't
return val | [
"def",
"barrel_shifter",
"(",
"bits_to_shift",
",",
"bit_in",
",",
"direction",
",",
"shift_dist",
",",
"wrap_around",
"=",
"0",
")",
":",
"from",
"pyrtl",
"import",
"concat",
",",
"select",
"# just for readability",
"if",
"wrap_around",
"!=",
"0",
":",
"raise",
"NotImplementedError",
"# Implement with logN stages pyrtl.muxing between shifted and un-shifted values",
"final_width",
"=",
"len",
"(",
"bits_to_shift",
")",
"val",
"=",
"bits_to_shift",
"append_val",
"=",
"bit_in",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"shift_dist",
")",
")",
":",
"shift_amt",
"=",
"pow",
"(",
"2",
",",
"i",
")",
"# stages shift 1,2,4,8,...",
"if",
"shift_amt",
"<",
"final_width",
":",
"newval",
"=",
"select",
"(",
"direction",
",",
"concat",
"(",
"val",
"[",
":",
"-",
"shift_amt",
"]",
",",
"append_val",
")",
",",
"# shift up",
"concat",
"(",
"append_val",
",",
"val",
"[",
"shift_amt",
":",
"]",
")",
")",
"# shift down",
"val",
"=",
"select",
"(",
"shift_dist",
"[",
"i",
"]",
",",
"truecase",
"=",
"newval",
",",
"# if bit of shift is 1, do the shift",
"falsecase",
"=",
"val",
")",
"# otherwise, don't",
"# the value to append grows exponentially, but is capped at full width",
"append_val",
"=",
"concat",
"(",
"append_val",
",",
"append_val",
")",
"[",
":",
"final_width",
"]",
"else",
":",
"# if we are shifting this much, all the data is gone",
"val",
"=",
"select",
"(",
"shift_dist",
"[",
"i",
"]",
",",
"truecase",
"=",
"append_val",
",",
"# if bit of shift is 1, do the shift",
"falsecase",
"=",
"val",
")",
"# otherwise, don't",
"return",
"val"
] | Create a barrel shifter that operates on data based on the wire width.
:param bits_to_shift: the input wire
:param bit_in: the 1-bit wire giving the value to shift in
:param direction: a one bit WireVector representing shift direction
(0 = shift down, 1 = shift up)
:param shift_dist: WireVector representing offset to shift
:param wrap_around: ****currently not implemented****
:return: shifted WireVector | [
"Create",
"a",
"barrel",
"shifter",
"that",
"operates",
"on",
"data",
"based",
"on",
"the",
"wire",
"width",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/barrel.py#L6-L44 |
usrlocalben/pydux | pydux/compose.py | compose | def compose(*funcs):
"""
chained function composition wrapper
creates function f, where f(x) = arg0(arg1(arg2(...argN(x))))
if *funcs is empty, an identity function is returned.
Args:
*funcs: list of functions to chain
Returns:
a new function composed of chained calls to *args
"""
if not funcs:
return lambda *args: args[0] if args else None
if len(funcs) == 1:
return funcs[0]
last = funcs[-1]
rest = funcs[0:-1]
return lambda *args: reduce(lambda ax, func: func(ax),
reversed(rest), last(*args)) | python | def compose(*funcs):
"""
chained function composition wrapper
creates function f, where f(x) = arg0(arg1(arg2(...argN(x))))
if *funcs is empty, an identity function is returned.
Args:
*funcs: list of functions to chain
Returns:
a new function composed of chained calls to *args
"""
if not funcs:
return lambda *args: args[0] if args else None
if len(funcs) == 1:
return funcs[0]
last = funcs[-1]
rest = funcs[0:-1]
return lambda *args: reduce(lambda ax, func: func(ax),
reversed(rest), last(*args)) | [
"def",
"compose",
"(",
"*",
"funcs",
")",
":",
"if",
"not",
"funcs",
":",
"return",
"lambda",
"*",
"args",
":",
"args",
"[",
"0",
"]",
"if",
"args",
"else",
"None",
"if",
"len",
"(",
"funcs",
")",
"==",
"1",
":",
"return",
"funcs",
"[",
"0",
"]",
"last",
"=",
"funcs",
"[",
"-",
"1",
"]",
"rest",
"=",
"funcs",
"[",
"0",
":",
"-",
"1",
"]",
"return",
"lambda",
"*",
"args",
":",
"reduce",
"(",
"lambda",
"ax",
",",
"func",
":",
"func",
"(",
"ax",
")",
",",
"reversed",
"(",
"rest",
")",
",",
"last",
"(",
"*",
"args",
")",
")"
] | chained function composition wrapper
creates function f, where f(x) = arg0(arg1(arg2(...argN(x))))
if *funcs is empty, an identity function is returned.
Args:
*funcs: list of functions to chain
Returns:
a new function composed of chained calls to *args | [
"chained",
"function",
"composition",
"wrapper"
] | train | https://github.com/usrlocalben/pydux/blob/943ca1c75357b9289f55f17ff2d997a66a3313a4/pydux/compose.py#L3-L26 |
usrlocalben/pydux | pydux/combine_reducers.py | combine_reducers | def combine_reducers(reducers):
"""
composition tool for creating reducer trees.
Args:
reducers: dict with state keys and reducer functions
that are responsible for each key
Returns:
a new, combined reducer function
"""
final_reducers = {key: reducer
for key, reducer in reducers.items()
if hasattr(reducer, '__call__')}
sanity_error = None
try:
assert_reducer_sanity(final_reducers)
except Exception as e:
sanity_error = e
def combination(state=None, action=None):
if state is None:
state = {}
if sanity_error:
raise sanity_error
has_changed = False
next_state = {}
for key, reducer in final_reducers.items():
previous_state_for_key = state.get(key)
next_state_for_key = reducer(previous_state_for_key, action)
if next_state_for_key is None:
msg = get_undefined_state_error_message(key, action)
raise Exception(msg)
next_state[key] = next_state_for_key
has_changed = (has_changed or
next_state_for_key != previous_state_for_key)
return next_state if has_changed else state
return combination | python | def combine_reducers(reducers):
"""
composition tool for creating reducer trees.
Args:
reducers: dict with state keys and reducer functions
that are responsible for each key
Returns:
a new, combined reducer function
"""
final_reducers = {key: reducer
for key, reducer in reducers.items()
if hasattr(reducer, '__call__')}
sanity_error = None
try:
assert_reducer_sanity(final_reducers)
except Exception as e:
sanity_error = e
def combination(state=None, action=None):
if state is None:
state = {}
if sanity_error:
raise sanity_error
has_changed = False
next_state = {}
for key, reducer in final_reducers.items():
previous_state_for_key = state.get(key)
next_state_for_key = reducer(previous_state_for_key, action)
if next_state_for_key is None:
msg = get_undefined_state_error_message(key, action)
raise Exception(msg)
next_state[key] = next_state_for_key
has_changed = (has_changed or
next_state_for_key != previous_state_for_key)
return next_state if has_changed else state
return combination | [
"def",
"combine_reducers",
"(",
"reducers",
")",
":",
"final_reducers",
"=",
"{",
"key",
":",
"reducer",
"for",
"key",
",",
"reducer",
"in",
"reducers",
".",
"items",
"(",
")",
"if",
"hasattr",
"(",
"reducer",
",",
"'__call__'",
")",
"}",
"sanity_error",
"=",
"None",
"try",
":",
"assert_reducer_sanity",
"(",
"final_reducers",
")",
"except",
"Exception",
"as",
"e",
":",
"sanity_error",
"=",
"e",
"def",
"combination",
"(",
"state",
"=",
"None",
",",
"action",
"=",
"None",
")",
":",
"if",
"state",
"is",
"None",
":",
"state",
"=",
"{",
"}",
"if",
"sanity_error",
":",
"raise",
"sanity_error",
"has_changed",
"=",
"False",
"next_state",
"=",
"{",
"}",
"for",
"key",
",",
"reducer",
"in",
"final_reducers",
".",
"items",
"(",
")",
":",
"previous_state_for_key",
"=",
"state",
".",
"get",
"(",
"key",
")",
"next_state_for_key",
"=",
"reducer",
"(",
"previous_state_for_key",
",",
"action",
")",
"if",
"next_state_for_key",
"is",
"None",
":",
"msg",
"=",
"get_undefined_state_error_message",
"(",
"key",
",",
"action",
")",
"raise",
"Exception",
"(",
"msg",
")",
"next_state",
"[",
"key",
"]",
"=",
"next_state_for_key",
"has_changed",
"=",
"(",
"has_changed",
"or",
"next_state_for_key",
"!=",
"previous_state_for_key",
")",
"return",
"next_state",
"if",
"has_changed",
"else",
"state",
"return",
"combination"
] | composition tool for creating reducer trees.
Args:
reducers: dict with state keys and reducer functions
that are responsible for each key
Returns:
a new, combined reducer function | [
"composition",
"tool",
"for",
"creating",
"reducer",
"trees",
".",
"Args",
":",
"reducers",
":",
"dict",
"with",
"state",
"keys",
"and",
"reducer",
"functions",
"that",
"are",
"responsible",
"for",
"each",
"key"
] | train | https://github.com/usrlocalben/pydux/blob/943ca1c75357b9289f55f17ff2d997a66a3313a4/pydux/combine_reducers.py#L41-L81 |
UCSBarchlab/PyRTL | examples/introduction-to-hardware.py | software_fibonacci | def software_fibonacci(n):
""" a normal old python function to return the Nth fibonacci number. """
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a | python | def software_fibonacci(n):
""" a normal old python function to return the Nth fibonacci number. """
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a | [
"def",
"software_fibonacci",
"(",
"n",
")",
":",
"a",
",",
"b",
"=",
"0",
",",
"1",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"a",
",",
"b",
"=",
"b",
",",
"a",
"+",
"b",
"return",
"a"
] | a normal old python function to return the Nth fibonacci number. | [
"a",
"normal",
"old",
"python",
"function",
"to",
"return",
"the",
"Nth",
"fibonacci",
"number",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/examples/introduction-to-hardware.py#L12-L17 |
usrlocalben/pydux | pydux/apply_middleware.py | apply_middleware | def apply_middleware(*middlewares):
"""
creates an enhancer function composed of middleware
Args:
*middlewares: list of middleware functions to apply
Returns:
an enhancer for subsequent calls to create_store()
"""
def inner(create_store_):
def create_wrapper(reducer, enhancer=None):
store = create_store_(reducer, enhancer)
dispatch = store['dispatch']
middleware_api = {
'get_state': store['get_state'],
'dispatch': lambda action: dispatch(action),
}
chain = [mw(middleware_api) for mw in middlewares]
dispatch = compose(*chain)(store['dispatch'])
return extend(store, {'dispatch': dispatch})
return create_wrapper
return inner | python | def apply_middleware(*middlewares):
"""
creates an enhancer function composed of middleware
Args:
*middlewares: list of middleware functions to apply
Returns:
an enhancer for subsequent calls to create_store()
"""
def inner(create_store_):
def create_wrapper(reducer, enhancer=None):
store = create_store_(reducer, enhancer)
dispatch = store['dispatch']
middleware_api = {
'get_state': store['get_state'],
'dispatch': lambda action: dispatch(action),
}
chain = [mw(middleware_api) for mw in middlewares]
dispatch = compose(*chain)(store['dispatch'])
return extend(store, {'dispatch': dispatch})
return create_wrapper
return inner | [
"def",
"apply_middleware",
"(",
"*",
"middlewares",
")",
":",
"def",
"inner",
"(",
"create_store_",
")",
":",
"def",
"create_wrapper",
"(",
"reducer",
",",
"enhancer",
"=",
"None",
")",
":",
"store",
"=",
"create_store_",
"(",
"reducer",
",",
"enhancer",
")",
"dispatch",
"=",
"store",
"[",
"'dispatch'",
"]",
"middleware_api",
"=",
"{",
"'get_state'",
":",
"store",
"[",
"'get_state'",
"]",
",",
"'dispatch'",
":",
"lambda",
"action",
":",
"dispatch",
"(",
"action",
")",
",",
"}",
"chain",
"=",
"[",
"mw",
"(",
"middleware_api",
")",
"for",
"mw",
"in",
"middlewares",
"]",
"dispatch",
"=",
"compose",
"(",
"*",
"chain",
")",
"(",
"store",
"[",
"'dispatch'",
"]",
")",
"return",
"extend",
"(",
"store",
",",
"{",
"'dispatch'",
":",
"dispatch",
"}",
")",
"return",
"create_wrapper",
"return",
"inner"
] | creates an enhancer function composed of middleware
Args:
*middlewares: list of middleware functions to apply
Returns:
an enhancer for subsequent calls to create_store() | [
"creates",
"an",
"enhancer",
"function",
"composed",
"of",
"middleware"
] | train | https://github.com/usrlocalben/pydux/blob/943ca1c75357b9289f55f17ff2d997a66a3313a4/pydux/apply_middleware.py#L5-L28 |
UCSBarchlab/PyRTL | pyrtl/corecircuits.py | mux | def mux(index, *mux_ins, **kwargs):
""" Multiplexer returning the value of the wire in .
:param WireVector index: used as the select input to the multiplexer
:param WireVector mux_ins: additional WireVector arguments selected when select>1
:param WireVector kwargs: additional WireVectors, keyword arg "default"
If you are selecting between less items than your index can address, you can
use the "default" keyword argument to auto-expand those terms. For example,
if you have a 3-bit index but are selecting between 6 options, you need to specify
a value for those other 2 possible values of index (0b110 and 0b111).
:return: WireVector of length of the longest input (not including select)
To avoid confusion, if you are using the mux where the select is a "predicate"
(meaning something that you are checking the truth value of rather than using it
as a number) it is recommended that you use the select function instead
as named arguments because the ordering is different from the classic ternary
operator of some languages.
Example of mux as "selector" to pick between a0 and a1: ::
index = WireVector(1)
mux( index, a0, a1 )
Example of mux as "selector" to pick between a0 ... a3: ::
index = WireVector(2)
mux( index, a0, a1, a2, a3 )
Example of "default" to specify additional arguments: ::
index = WireVector(3)
mux( index, a0, a1, a2, a3, a4, a5, default=0 )
"""
if kwargs: # only "default" is allowed as kwarg.
if len(kwargs) != 1 or 'default' not in kwargs:
try:
result = select(index, **kwargs)
import warnings
warnings.warn("Predicates are being deprecated in Mux. "
"Use the select operator instead.", stacklevel=2)
return result
except Exception:
bad_args = [k for k in kwargs.keys() if k != 'default']
raise PyrtlError('unknown keywords %s applied to mux' % str(bad_args))
default = kwargs['default']
else:
default = None
# find the diff between the addressable range and number of inputs given
short_by = 2**len(index) - len(mux_ins)
if short_by > 0:
if default is not None: # extend the list to appropriate size
mux_ins = list(mux_ins)
extention = [default] * short_by
mux_ins.extend(extention)
if 2 ** len(index) != len(mux_ins):
raise PyrtlError(
'Mux select line is %d bits, but selecting from %d inputs. '
% (len(index), len(mux_ins)))
if len(index) == 1:
return select(index, falsecase=mux_ins[0], truecase=mux_ins[1])
half = len(mux_ins) // 2
return select(index[-1],
falsecase=mux(index[0:-1], *mux_ins[:half]),
truecase=mux(index[0:-1], *mux_ins[half:])) | python | def mux(index, *mux_ins, **kwargs):
""" Multiplexer returning the value of the wire in .
:param WireVector index: used as the select input to the multiplexer
:param WireVector mux_ins: additional WireVector arguments selected when select>1
:param WireVector kwargs: additional WireVectors, keyword arg "default"
If you are selecting between less items than your index can address, you can
use the "default" keyword argument to auto-expand those terms. For example,
if you have a 3-bit index but are selecting between 6 options, you need to specify
a value for those other 2 possible values of index (0b110 and 0b111).
:return: WireVector of length of the longest input (not including select)
To avoid confusion, if you are using the mux where the select is a "predicate"
(meaning something that you are checking the truth value of rather than using it
as a number) it is recommended that you use the select function instead
as named arguments because the ordering is different from the classic ternary
operator of some languages.
Example of mux as "selector" to pick between a0 and a1: ::
index = WireVector(1)
mux( index, a0, a1 )
Example of mux as "selector" to pick between a0 ... a3: ::
index = WireVector(2)
mux( index, a0, a1, a2, a3 )
Example of "default" to specify additional arguments: ::
index = WireVector(3)
mux( index, a0, a1, a2, a3, a4, a5, default=0 )
"""
if kwargs: # only "default" is allowed as kwarg.
if len(kwargs) != 1 or 'default' not in kwargs:
try:
result = select(index, **kwargs)
import warnings
warnings.warn("Predicates are being deprecated in Mux. "
"Use the select operator instead.", stacklevel=2)
return result
except Exception:
bad_args = [k for k in kwargs.keys() if k != 'default']
raise PyrtlError('unknown keywords %s applied to mux' % str(bad_args))
default = kwargs['default']
else:
default = None
# find the diff between the addressable range and number of inputs given
short_by = 2**len(index) - len(mux_ins)
if short_by > 0:
if default is not None: # extend the list to appropriate size
mux_ins = list(mux_ins)
extention = [default] * short_by
mux_ins.extend(extention)
if 2 ** len(index) != len(mux_ins):
raise PyrtlError(
'Mux select line is %d bits, but selecting from %d inputs. '
% (len(index), len(mux_ins)))
if len(index) == 1:
return select(index, falsecase=mux_ins[0], truecase=mux_ins[1])
half = len(mux_ins) // 2
return select(index[-1],
falsecase=mux(index[0:-1], *mux_ins[:half]),
truecase=mux(index[0:-1], *mux_ins[half:])) | [
"def",
"mux",
"(",
"index",
",",
"*",
"mux_ins",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
":",
"# only \"default\" is allowed as kwarg.",
"if",
"len",
"(",
"kwargs",
")",
"!=",
"1",
"or",
"'default'",
"not",
"in",
"kwargs",
":",
"try",
":",
"result",
"=",
"select",
"(",
"index",
",",
"*",
"*",
"kwargs",
")",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"\"Predicates are being deprecated in Mux. \"",
"\"Use the select operator instead.\"",
",",
"stacklevel",
"=",
"2",
")",
"return",
"result",
"except",
"Exception",
":",
"bad_args",
"=",
"[",
"k",
"for",
"k",
"in",
"kwargs",
".",
"keys",
"(",
")",
"if",
"k",
"!=",
"'default'",
"]",
"raise",
"PyrtlError",
"(",
"'unknown keywords %s applied to mux'",
"%",
"str",
"(",
"bad_args",
")",
")",
"default",
"=",
"kwargs",
"[",
"'default'",
"]",
"else",
":",
"default",
"=",
"None",
"# find the diff between the addressable range and number of inputs given",
"short_by",
"=",
"2",
"**",
"len",
"(",
"index",
")",
"-",
"len",
"(",
"mux_ins",
")",
"if",
"short_by",
">",
"0",
":",
"if",
"default",
"is",
"not",
"None",
":",
"# extend the list to appropriate size",
"mux_ins",
"=",
"list",
"(",
"mux_ins",
")",
"extention",
"=",
"[",
"default",
"]",
"*",
"short_by",
"mux_ins",
".",
"extend",
"(",
"extention",
")",
"if",
"2",
"**",
"len",
"(",
"index",
")",
"!=",
"len",
"(",
"mux_ins",
")",
":",
"raise",
"PyrtlError",
"(",
"'Mux select line is %d bits, but selecting from %d inputs. '",
"%",
"(",
"len",
"(",
"index",
")",
",",
"len",
"(",
"mux_ins",
")",
")",
")",
"if",
"len",
"(",
"index",
")",
"==",
"1",
":",
"return",
"select",
"(",
"index",
",",
"falsecase",
"=",
"mux_ins",
"[",
"0",
"]",
",",
"truecase",
"=",
"mux_ins",
"[",
"1",
"]",
")",
"half",
"=",
"len",
"(",
"mux_ins",
")",
"//",
"2",
"return",
"select",
"(",
"index",
"[",
"-",
"1",
"]",
",",
"falsecase",
"=",
"mux",
"(",
"index",
"[",
"0",
":",
"-",
"1",
"]",
",",
"*",
"mux_ins",
"[",
":",
"half",
"]",
")",
",",
"truecase",
"=",
"mux",
"(",
"index",
"[",
"0",
":",
"-",
"1",
"]",
",",
"*",
"mux_ins",
"[",
"half",
":",
"]",
")",
")"
] | Multiplexer returning the value of the wire in .
:param WireVector index: used as the select input to the multiplexer
:param WireVector mux_ins: additional WireVector arguments selected when select>1
:param WireVector kwargs: additional WireVectors, keyword arg "default"
If you are selecting between less items than your index can address, you can
use the "default" keyword argument to auto-expand those terms. For example,
if you have a 3-bit index but are selecting between 6 options, you need to specify
a value for those other 2 possible values of index (0b110 and 0b111).
:return: WireVector of length of the longest input (not including select)
To avoid confusion, if you are using the mux where the select is a "predicate"
(meaning something that you are checking the truth value of rather than using it
as a number) it is recommended that you use the select function instead
as named arguments because the ordering is different from the classic ternary
operator of some languages.
Example of mux as "selector" to pick between a0 and a1: ::
index = WireVector(1)
mux( index, a0, a1 )
Example of mux as "selector" to pick between a0 ... a3: ::
index = WireVector(2)
mux( index, a0, a1, a2, a3 )
Example of "default" to specify additional arguments: ::
index = WireVector(3)
mux( index, a0, a1, a2, a3, a4, a5, default=0 ) | [
"Multiplexer",
"returning",
"the",
"value",
"of",
"the",
"wire",
"in",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/corecircuits.py#L16-L82 |
UCSBarchlab/PyRTL | pyrtl/corecircuits.py | select | def select(sel, truecase, falsecase):
""" Multiplexer returning falsecase for select==0, otherwise truecase.
:param WireVector sel: used as the select input to the multiplexer
:param WireVector falsecase: the WireVector selected if select==0
:param WireVector truecase: the WireVector selected if select==1
The hardware this generates is exactly the same as "mux" but by putting the
true case as the first argument it matches more of the C-style ternary operator
semantics which can be helpful for readablity.
Example of mux as "ternary operator" to take the max of 'a' and 5: ::
select( a<5, truecase=a, falsecase=5 )
"""
sel, f, t = (as_wires(w) for w in (sel, falsecase, truecase))
f, t = match_bitwidth(f, t)
outwire = WireVector(bitwidth=len(f))
net = LogicNet(op='x', op_param=None, args=(sel, f, t), dests=(outwire,))
working_block().add_net(net) # this includes sanity check on the mux
return outwire | python | def select(sel, truecase, falsecase):
""" Multiplexer returning falsecase for select==0, otherwise truecase.
:param WireVector sel: used as the select input to the multiplexer
:param WireVector falsecase: the WireVector selected if select==0
:param WireVector truecase: the WireVector selected if select==1
The hardware this generates is exactly the same as "mux" but by putting the
true case as the first argument it matches more of the C-style ternary operator
semantics which can be helpful for readablity.
Example of mux as "ternary operator" to take the max of 'a' and 5: ::
select( a<5, truecase=a, falsecase=5 )
"""
sel, f, t = (as_wires(w) for w in (sel, falsecase, truecase))
f, t = match_bitwidth(f, t)
outwire = WireVector(bitwidth=len(f))
net = LogicNet(op='x', op_param=None, args=(sel, f, t), dests=(outwire,))
working_block().add_net(net) # this includes sanity check on the mux
return outwire | [
"def",
"select",
"(",
"sel",
",",
"truecase",
",",
"falsecase",
")",
":",
"sel",
",",
"f",
",",
"t",
"=",
"(",
"as_wires",
"(",
"w",
")",
"for",
"w",
"in",
"(",
"sel",
",",
"falsecase",
",",
"truecase",
")",
")",
"f",
",",
"t",
"=",
"match_bitwidth",
"(",
"f",
",",
"t",
")",
"outwire",
"=",
"WireVector",
"(",
"bitwidth",
"=",
"len",
"(",
"f",
")",
")",
"net",
"=",
"LogicNet",
"(",
"op",
"=",
"'x'",
",",
"op_param",
"=",
"None",
",",
"args",
"=",
"(",
"sel",
",",
"f",
",",
"t",
")",
",",
"dests",
"=",
"(",
"outwire",
",",
")",
")",
"working_block",
"(",
")",
".",
"add_net",
"(",
"net",
")",
"# this includes sanity check on the mux",
"return",
"outwire"
] | Multiplexer returning falsecase for select==0, otherwise truecase.
:param WireVector sel: used as the select input to the multiplexer
:param WireVector falsecase: the WireVector selected if select==0
:param WireVector truecase: the WireVector selected if select==1
The hardware this generates is exactly the same as "mux" but by putting the
true case as the first argument it matches more of the C-style ternary operator
semantics which can be helpful for readablity.
Example of mux as "ternary operator" to take the max of 'a' and 5: ::
select( a<5, truecase=a, falsecase=5 ) | [
"Multiplexer",
"returning",
"falsecase",
"for",
"select",
"==",
"0",
"otherwise",
"truecase",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/corecircuits.py#L85-L106 |
UCSBarchlab/PyRTL | pyrtl/corecircuits.py | concat | def concat(*args):
""" Concatenates multiple WireVectors into a single WireVector
:param WireVector args: inputs to be concatenated
:return: WireVector with length equal to the sum of the args' lengths
You can provide multiple arguments and they will be combined with the right-most
argument being the least significant bits of the result. Note that if you have
a list of arguments to concat together you will likely want index 0 to be the least
significant bit and so if you unpack the list into the arguements here it will be
backwards. The function concat_list is provided for that case specifically.
Example using concat to combine two bytes into a 16-bit quantity: ::
concat( msb, lsb )
"""
if len(args) <= 0:
raise PyrtlError('error, concat requires at least 1 argument')
if len(args) == 1:
return as_wires(args[0])
arg_wirevectors = tuple(as_wires(arg) for arg in args)
final_width = sum(len(arg) for arg in arg_wirevectors)
outwire = WireVector(bitwidth=final_width)
net = LogicNet(
op='c',
op_param=None,
args=arg_wirevectors,
dests=(outwire,))
working_block().add_net(net)
return outwire | python | def concat(*args):
""" Concatenates multiple WireVectors into a single WireVector
:param WireVector args: inputs to be concatenated
:return: WireVector with length equal to the sum of the args' lengths
You can provide multiple arguments and they will be combined with the right-most
argument being the least significant bits of the result. Note that if you have
a list of arguments to concat together you will likely want index 0 to be the least
significant bit and so if you unpack the list into the arguements here it will be
backwards. The function concat_list is provided for that case specifically.
Example using concat to combine two bytes into a 16-bit quantity: ::
concat( msb, lsb )
"""
if len(args) <= 0:
raise PyrtlError('error, concat requires at least 1 argument')
if len(args) == 1:
return as_wires(args[0])
arg_wirevectors = tuple(as_wires(arg) for arg in args)
final_width = sum(len(arg) for arg in arg_wirevectors)
outwire = WireVector(bitwidth=final_width)
net = LogicNet(
op='c',
op_param=None,
args=arg_wirevectors,
dests=(outwire,))
working_block().add_net(net)
return outwire | [
"def",
"concat",
"(",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<=",
"0",
":",
"raise",
"PyrtlError",
"(",
"'error, concat requires at least 1 argument'",
")",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"return",
"as_wires",
"(",
"args",
"[",
"0",
"]",
")",
"arg_wirevectors",
"=",
"tuple",
"(",
"as_wires",
"(",
"arg",
")",
"for",
"arg",
"in",
"args",
")",
"final_width",
"=",
"sum",
"(",
"len",
"(",
"arg",
")",
"for",
"arg",
"in",
"arg_wirevectors",
")",
"outwire",
"=",
"WireVector",
"(",
"bitwidth",
"=",
"final_width",
")",
"net",
"=",
"LogicNet",
"(",
"op",
"=",
"'c'",
",",
"op_param",
"=",
"None",
",",
"args",
"=",
"arg_wirevectors",
",",
"dests",
"=",
"(",
"outwire",
",",
")",
")",
"working_block",
"(",
")",
".",
"add_net",
"(",
"net",
")",
"return",
"outwire"
] | Concatenates multiple WireVectors into a single WireVector
:param WireVector args: inputs to be concatenated
:return: WireVector with length equal to the sum of the args' lengths
You can provide multiple arguments and they will be combined with the right-most
argument being the least significant bits of the result. Note that if you have
a list of arguments to concat together you will likely want index 0 to be the least
significant bit and so if you unpack the list into the arguements here it will be
backwards. The function concat_list is provided for that case specifically.
Example using concat to combine two bytes into a 16-bit quantity: ::
concat( msb, lsb ) | [
"Concatenates",
"multiple",
"WireVectors",
"into",
"a",
"single",
"WireVector"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/corecircuits.py#L109-L139 |
UCSBarchlab/PyRTL | pyrtl/corecircuits.py | signed_add | def signed_add(a, b):
""" Return wirevector for result of signed addition.
:param a: a wirevector to serve as first input to addition
:param b: a wirevector to serve as second input to addition
Given a length n and length m wirevector the result of the
signed addition is length max(n,m)+1. The inputs are twos
complement sign extended to the same length before adding."""
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True)
result_len = len(a) + 1
ext_a = a.sign_extended(result_len)
ext_b = b.sign_extended(result_len)
# add and truncate to the correct length
return (ext_a + ext_b)[0:result_len] | python | def signed_add(a, b):
""" Return wirevector for result of signed addition.
:param a: a wirevector to serve as first input to addition
:param b: a wirevector to serve as second input to addition
Given a length n and length m wirevector the result of the
signed addition is length max(n,m)+1. The inputs are twos
complement sign extended to the same length before adding."""
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True)
result_len = len(a) + 1
ext_a = a.sign_extended(result_len)
ext_b = b.sign_extended(result_len)
# add and truncate to the correct length
return (ext_a + ext_b)[0:result_len] | [
"def",
"signed_add",
"(",
"a",
",",
"b",
")",
":",
"a",
",",
"b",
"=",
"match_bitwidth",
"(",
"as_wires",
"(",
"a",
")",
",",
"as_wires",
"(",
"b",
")",
",",
"signed",
"=",
"True",
")",
"result_len",
"=",
"len",
"(",
"a",
")",
"+",
"1",
"ext_a",
"=",
"a",
".",
"sign_extended",
"(",
"result_len",
")",
"ext_b",
"=",
"b",
".",
"sign_extended",
"(",
"result_len",
")",
"# add and truncate to the correct length",
"return",
"(",
"ext_a",
"+",
"ext_b",
")",
"[",
"0",
":",
"result_len",
"]"
] | Return wirevector for result of signed addition.
:param a: a wirevector to serve as first input to addition
:param b: a wirevector to serve as second input to addition
Given a length n and length m wirevector the result of the
signed addition is length max(n,m)+1. The inputs are twos
complement sign extended to the same length before adding. | [
"Return",
"wirevector",
"for",
"result",
"of",
"signed",
"addition",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/corecircuits.py#L162-L176 |
UCSBarchlab/PyRTL | pyrtl/corecircuits.py | signed_mult | def signed_mult(a, b):
""" Return a*b where a and b are treated as signed values. """
a, b = as_wires(a), as_wires(b)
final_len = len(a) + len(b)
# sign extend both inputs to the final target length
a, b = a.sign_extended(final_len), b.sign_extended(final_len)
# the result is the multiplication of both, but truncated
# TODO: this may make estimates based on the multiplication overly
# pessimistic as half of the multiply result is thrown right away!
return (a * b)[0:final_len] | python | def signed_mult(a, b):
""" Return a*b where a and b are treated as signed values. """
a, b = as_wires(a), as_wires(b)
final_len = len(a) + len(b)
# sign extend both inputs to the final target length
a, b = a.sign_extended(final_len), b.sign_extended(final_len)
# the result is the multiplication of both, but truncated
# TODO: this may make estimates based on the multiplication overly
# pessimistic as half of the multiply result is thrown right away!
return (a * b)[0:final_len] | [
"def",
"signed_mult",
"(",
"a",
",",
"b",
")",
":",
"a",
",",
"b",
"=",
"as_wires",
"(",
"a",
")",
",",
"as_wires",
"(",
"b",
")",
"final_len",
"=",
"len",
"(",
"a",
")",
"+",
"len",
"(",
"b",
")",
"# sign extend both inputs to the final target length",
"a",
",",
"b",
"=",
"a",
".",
"sign_extended",
"(",
"final_len",
")",
",",
"b",
".",
"sign_extended",
"(",
"final_len",
")",
"# the result is the multiplication of both, but truncated",
"# TODO: this may make estimates based on the multiplication overly",
"# pessimistic as half of the multiply result is thrown right away!",
"return",
"(",
"a",
"*",
"b",
")",
"[",
"0",
":",
"final_len",
"]"
] | Return a*b where a and b are treated as signed values. | [
"Return",
"a",
"*",
"b",
"where",
"a",
"and",
"b",
"are",
"treated",
"as",
"signed",
"values",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/corecircuits.py#L184-L193 |
UCSBarchlab/PyRTL | pyrtl/corecircuits.py | signed_lt | def signed_lt(a, b):
""" Return a single bit result of signed less than comparison. """
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True)
r = a - b
return r[-1] ^ (~a[-1]) ^ (~b[-1]) | python | def signed_lt(a, b):
""" Return a single bit result of signed less than comparison. """
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True)
r = a - b
return r[-1] ^ (~a[-1]) ^ (~b[-1]) | [
"def",
"signed_lt",
"(",
"a",
",",
"b",
")",
":",
"a",
",",
"b",
"=",
"match_bitwidth",
"(",
"as_wires",
"(",
"a",
")",
",",
"as_wires",
"(",
"b",
")",
",",
"signed",
"=",
"True",
")",
"r",
"=",
"a",
"-",
"b",
"return",
"r",
"[",
"-",
"1",
"]",
"^",
"(",
"~",
"a",
"[",
"-",
"1",
"]",
")",
"^",
"(",
"~",
"b",
"[",
"-",
"1",
"]",
")"
] | Return a single bit result of signed less than comparison. | [
"Return",
"a",
"single",
"bit",
"result",
"of",
"signed",
"less",
"than",
"comparison",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/corecircuits.py#L196-L200 |
UCSBarchlab/PyRTL | pyrtl/corecircuits.py | signed_le | def signed_le(a, b):
""" Return a single bit result of signed less than or equal comparison. """
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True)
r = a - b
return (r[-1] ^ (~a[-1]) ^ (~b[-1])) | (a == b) | python | def signed_le(a, b):
""" Return a single bit result of signed less than or equal comparison. """
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True)
r = a - b
return (r[-1] ^ (~a[-1]) ^ (~b[-1])) | (a == b) | [
"def",
"signed_le",
"(",
"a",
",",
"b",
")",
":",
"a",
",",
"b",
"=",
"match_bitwidth",
"(",
"as_wires",
"(",
"a",
")",
",",
"as_wires",
"(",
"b",
")",
",",
"signed",
"=",
"True",
")",
"r",
"=",
"a",
"-",
"b",
"return",
"(",
"r",
"[",
"-",
"1",
"]",
"^",
"(",
"~",
"a",
"[",
"-",
"1",
"]",
")",
"^",
"(",
"~",
"b",
"[",
"-",
"1",
"]",
")",
")",
"|",
"(",
"a",
"==",
"b",
")"
] | Return a single bit result of signed less than or equal comparison. | [
"Return",
"a",
"single",
"bit",
"result",
"of",
"signed",
"less",
"than",
"or",
"equal",
"comparison",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/corecircuits.py#L203-L207 |
UCSBarchlab/PyRTL | pyrtl/corecircuits.py | signed_gt | def signed_gt(a, b):
""" Return a single bit result of signed greater than comparison. """
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True)
r = b - a
return r[-1] ^ (~a[-1]) ^ (~b[-1]) | python | def signed_gt(a, b):
""" Return a single bit result of signed greater than comparison. """
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True)
r = b - a
return r[-1] ^ (~a[-1]) ^ (~b[-1]) | [
"def",
"signed_gt",
"(",
"a",
",",
"b",
")",
":",
"a",
",",
"b",
"=",
"match_bitwidth",
"(",
"as_wires",
"(",
"a",
")",
",",
"as_wires",
"(",
"b",
")",
",",
"signed",
"=",
"True",
")",
"r",
"=",
"b",
"-",
"a",
"return",
"r",
"[",
"-",
"1",
"]",
"^",
"(",
"~",
"a",
"[",
"-",
"1",
"]",
")",
"^",
"(",
"~",
"b",
"[",
"-",
"1",
"]",
")"
] | Return a single bit result of signed greater than comparison. | [
"Return",
"a",
"single",
"bit",
"result",
"of",
"signed",
"greater",
"than",
"comparison",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/corecircuits.py#L210-L214 |
UCSBarchlab/PyRTL | pyrtl/corecircuits.py | signed_ge | def signed_ge(a, b):
""" Return a single bit result of signed greater than or equal comparison. """
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True)
r = b - a
return (r[-1] ^ (~a[-1]) ^ (~b[-1])) | (a == b) | python | def signed_ge(a, b):
""" Return a single bit result of signed greater than or equal comparison. """
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True)
r = b - a
return (r[-1] ^ (~a[-1]) ^ (~b[-1])) | (a == b) | [
"def",
"signed_ge",
"(",
"a",
",",
"b",
")",
":",
"a",
",",
"b",
"=",
"match_bitwidth",
"(",
"as_wires",
"(",
"a",
")",
",",
"as_wires",
"(",
"b",
")",
",",
"signed",
"=",
"True",
")",
"r",
"=",
"b",
"-",
"a",
"return",
"(",
"r",
"[",
"-",
"1",
"]",
"^",
"(",
"~",
"a",
"[",
"-",
"1",
"]",
")",
"^",
"(",
"~",
"b",
"[",
"-",
"1",
"]",
")",
")",
"|",
"(",
"a",
"==",
"b",
")"
] | Return a single bit result of signed greater than or equal comparison. | [
"Return",
"a",
"single",
"bit",
"result",
"of",
"signed",
"greater",
"than",
"or",
"equal",
"comparison",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/corecircuits.py#L217-L221 |
UCSBarchlab/PyRTL | pyrtl/corecircuits.py | shift_right_arithmetic | def shift_right_arithmetic(bits_to_shift, shift_amount):
""" Shift right arithmetic operation.
:param bits_to_shift: WireVector to shift right
:param shift_amount: WireVector specifying amount to shift
:return: WireVector of same length as bits_to_shift
This function returns a new WireVector of length equal to the length
of the input `bits_to_shift` but where the bits have been shifted
to the right. An arithemetic shift is one that treats the value as
as signed number, meaning the sign bit (the most significant bit of
`bits_to_shift`) is shifted in. Note that `shift_amount` is treated as
unsigned.
"""
a, shamt = _check_shift_inputs(bits_to_shift, shift_amount)
bit_in = bits_to_shift[-1] # shift in sign_bit
dir = Const(0) # shift right
return barrel.barrel_shifter(bits_to_shift, bit_in, dir, shift_amount) | python | def shift_right_arithmetic(bits_to_shift, shift_amount):
""" Shift right arithmetic operation.
:param bits_to_shift: WireVector to shift right
:param shift_amount: WireVector specifying amount to shift
:return: WireVector of same length as bits_to_shift
This function returns a new WireVector of length equal to the length
of the input `bits_to_shift` but where the bits have been shifted
to the right. An arithemetic shift is one that treats the value as
as signed number, meaning the sign bit (the most significant bit of
`bits_to_shift`) is shifted in. Note that `shift_amount` is treated as
unsigned.
"""
a, shamt = _check_shift_inputs(bits_to_shift, shift_amount)
bit_in = bits_to_shift[-1] # shift in sign_bit
dir = Const(0) # shift right
return barrel.barrel_shifter(bits_to_shift, bit_in, dir, shift_amount) | [
"def",
"shift_right_arithmetic",
"(",
"bits_to_shift",
",",
"shift_amount",
")",
":",
"a",
",",
"shamt",
"=",
"_check_shift_inputs",
"(",
"bits_to_shift",
",",
"shift_amount",
")",
"bit_in",
"=",
"bits_to_shift",
"[",
"-",
"1",
"]",
"# shift in sign_bit",
"dir",
"=",
"Const",
"(",
"0",
")",
"# shift right",
"return",
"barrel",
".",
"barrel_shifter",
"(",
"bits_to_shift",
",",
"bit_in",
",",
"dir",
",",
"shift_amount",
")"
] | Shift right arithmetic operation.
:param bits_to_shift: WireVector to shift right
:param shift_amount: WireVector specifying amount to shift
:return: WireVector of same length as bits_to_shift
This function returns a new WireVector of length equal to the length
of the input `bits_to_shift` but where the bits have been shifted
to the right. An arithemetic shift is one that treats the value as
as signed number, meaning the sign bit (the most significant bit of
`bits_to_shift`) is shifted in. Note that `shift_amount` is treated as
unsigned. | [
"Shift",
"right",
"arithmetic",
"operation",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/corecircuits.py#L250-L267 |
UCSBarchlab/PyRTL | pyrtl/corecircuits.py | match_bitwidth | def match_bitwidth(*args, **opt):
""" Matches the bitwidth of all of the input arguments with zero or sign extend
:param args: WireVectors of which to match bitwidths
:param opt: Optional keyword argument 'signed=True' (defaults to False)
:return: tuple of args in order with extended bits
Example of matching the bitwidths of two WireVectors `a` and `b` with
with zero extention: ::
a,b = match_bitwidth(a, b)
Example of matching the bitwidths of three WireVectors `a`,`b`, and `c` with
with sign extention: ::
a,b = match_bitwidth(a, b, c, signed=True)
"""
# TODO: when we drop 2.7 support, this code should be cleaned up with explicit
# kwarg support for "signed" rather than the less than helpful "**opt"
if len(opt) == 0:
signed = False
else:
if len(opt) > 1 or 'signed' not in opt:
raise PyrtlError('error, only supported kwarg to match_bitwidth is "signed"')
signed = bool(opt['signed'])
max_len = max(len(wv) for wv in args)
if signed:
return (wv.sign_extended(max_len) for wv in args)
else:
return (wv.zero_extended(max_len) for wv in args) | python | def match_bitwidth(*args, **opt):
""" Matches the bitwidth of all of the input arguments with zero or sign extend
:param args: WireVectors of which to match bitwidths
:param opt: Optional keyword argument 'signed=True' (defaults to False)
:return: tuple of args in order with extended bits
Example of matching the bitwidths of two WireVectors `a` and `b` with
with zero extention: ::
a,b = match_bitwidth(a, b)
Example of matching the bitwidths of three WireVectors `a`,`b`, and `c` with
with sign extention: ::
a,b = match_bitwidth(a, b, c, signed=True)
"""
# TODO: when we drop 2.7 support, this code should be cleaned up with explicit
# kwarg support for "signed" rather than the less than helpful "**opt"
if len(opt) == 0:
signed = False
else:
if len(opt) > 1 or 'signed' not in opt:
raise PyrtlError('error, only supported kwarg to match_bitwidth is "signed"')
signed = bool(opt['signed'])
max_len = max(len(wv) for wv in args)
if signed:
return (wv.sign_extended(max_len) for wv in args)
else:
return (wv.zero_extended(max_len) for wv in args) | [
"def",
"match_bitwidth",
"(",
"*",
"args",
",",
"*",
"*",
"opt",
")",
":",
"# TODO: when we drop 2.7 support, this code should be cleaned up with explicit",
"# kwarg support for \"signed\" rather than the less than helpful \"**opt\"",
"if",
"len",
"(",
"opt",
")",
"==",
"0",
":",
"signed",
"=",
"False",
"else",
":",
"if",
"len",
"(",
"opt",
")",
">",
"1",
"or",
"'signed'",
"not",
"in",
"opt",
":",
"raise",
"PyrtlError",
"(",
"'error, only supported kwarg to match_bitwidth is \"signed\"'",
")",
"signed",
"=",
"bool",
"(",
"opt",
"[",
"'signed'",
"]",
")",
"max_len",
"=",
"max",
"(",
"len",
"(",
"wv",
")",
"for",
"wv",
"in",
"args",
")",
"if",
"signed",
":",
"return",
"(",
"wv",
".",
"sign_extended",
"(",
"max_len",
")",
"for",
"wv",
"in",
"args",
")",
"else",
":",
"return",
"(",
"wv",
".",
"zero_extended",
"(",
"max_len",
")",
"for",
"wv",
"in",
"args",
")"
] | Matches the bitwidth of all of the input arguments with zero or sign extend
:param args: WireVectors of which to match bitwidths
:param opt: Optional keyword argument 'signed=True' (defaults to False)
:return: tuple of args in order with extended bits
Example of matching the bitwidths of two WireVectors `a` and `b` with
with zero extention: ::
a,b = match_bitwidth(a, b)
Example of matching the bitwidths of three WireVectors `a`,`b`, and `c` with
with sign extention: ::
a,b = match_bitwidth(a, b, c, signed=True) | [
"Matches",
"the",
"bitwidth",
"of",
"all",
"of",
"the",
"input",
"arguments",
"with",
"zero",
"or",
"sign",
"extend"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/corecircuits.py#L308-L338 |
UCSBarchlab/PyRTL | pyrtl/corecircuits.py | as_wires | def as_wires(val, bitwidth=None, truncating=True, block=None):
""" Return wires from val which may be wires, integers, strings, or bools.
:param val: a wirevector-like object or something that can be converted into
a Const
:param bitwidth: The bitwidth the resulting wire should be
:param bool truncating: determines whether bits will be dropped to achieve
the desired bitwidth if it is too long (if true, the most-significant bits
will be dropped)
:param Block block: block to use for wire
This function is mainly used to coerce values into WireVectors (for
example, operations such as "x+1" where "1" needs to be converted to
a Const WireVector). An example: ::
def myhardware(input_a, input_b):
a = as_wires(input_a)
b = as_wires(input_b)
myhardware(3, x)
The function as_wires will covert the 3 to Const but keep `x` unchanged
assuming it is a WireVector.
"""
from .memory import _MemIndexed
block = working_block(block)
if isinstance(val, (int, six.string_types)):
# note that this case captures bool as well (as bools are instances of ints)
return Const(val, bitwidth=bitwidth, block=block)
elif isinstance(val, _MemIndexed):
# convert to a memory read when the value is actually used
if val.wire is None:
val.wire = as_wires(val.mem._readaccess(val.index), bitwidth, truncating, block)
return val.wire
elif not isinstance(val, WireVector):
raise PyrtlError('error, expecting a wirevector, int, or verilog-style '
'const string got %s instead' % repr(val))
elif bitwidth == '0':
raise PyrtlError('error, bitwidth must be >= 1')
elif val.bitwidth is None:
raise PyrtlError('error, attempting to use wirevector with no defined bitwidth')
elif bitwidth and bitwidth > val.bitwidth:
return val.zero_extended(bitwidth)
elif bitwidth and truncating and bitwidth < val.bitwidth:
return val[:bitwidth] # truncate the upper bits
else:
return val | python | def as_wires(val, bitwidth=None, truncating=True, block=None):
""" Return wires from val which may be wires, integers, strings, or bools.
:param val: a wirevector-like object or something that can be converted into
a Const
:param bitwidth: The bitwidth the resulting wire should be
:param bool truncating: determines whether bits will be dropped to achieve
the desired bitwidth if it is too long (if true, the most-significant bits
will be dropped)
:param Block block: block to use for wire
This function is mainly used to coerce values into WireVectors (for
example, operations such as "x+1" where "1" needs to be converted to
a Const WireVector). An example: ::
def myhardware(input_a, input_b):
a = as_wires(input_a)
b = as_wires(input_b)
myhardware(3, x)
The function as_wires will covert the 3 to Const but keep `x` unchanged
assuming it is a WireVector.
"""
from .memory import _MemIndexed
block = working_block(block)
if isinstance(val, (int, six.string_types)):
# note that this case captures bool as well (as bools are instances of ints)
return Const(val, bitwidth=bitwidth, block=block)
elif isinstance(val, _MemIndexed):
# convert to a memory read when the value is actually used
if val.wire is None:
val.wire = as_wires(val.mem._readaccess(val.index), bitwidth, truncating, block)
return val.wire
elif not isinstance(val, WireVector):
raise PyrtlError('error, expecting a wirevector, int, or verilog-style '
'const string got %s instead' % repr(val))
elif bitwidth == '0':
raise PyrtlError('error, bitwidth must be >= 1')
elif val.bitwidth is None:
raise PyrtlError('error, attempting to use wirevector with no defined bitwidth')
elif bitwidth and bitwidth > val.bitwidth:
return val.zero_extended(bitwidth)
elif bitwidth and truncating and bitwidth < val.bitwidth:
return val[:bitwidth] # truncate the upper bits
else:
return val | [
"def",
"as_wires",
"(",
"val",
",",
"bitwidth",
"=",
"None",
",",
"truncating",
"=",
"True",
",",
"block",
"=",
"None",
")",
":",
"from",
".",
"memory",
"import",
"_MemIndexed",
"block",
"=",
"working_block",
"(",
"block",
")",
"if",
"isinstance",
"(",
"val",
",",
"(",
"int",
",",
"six",
".",
"string_types",
")",
")",
":",
"# note that this case captures bool as well (as bools are instances of ints)",
"return",
"Const",
"(",
"val",
",",
"bitwidth",
"=",
"bitwidth",
",",
"block",
"=",
"block",
")",
"elif",
"isinstance",
"(",
"val",
",",
"_MemIndexed",
")",
":",
"# convert to a memory read when the value is actually used",
"if",
"val",
".",
"wire",
"is",
"None",
":",
"val",
".",
"wire",
"=",
"as_wires",
"(",
"val",
".",
"mem",
".",
"_readaccess",
"(",
"val",
".",
"index",
")",
",",
"bitwidth",
",",
"truncating",
",",
"block",
")",
"return",
"val",
".",
"wire",
"elif",
"not",
"isinstance",
"(",
"val",
",",
"WireVector",
")",
":",
"raise",
"PyrtlError",
"(",
"'error, expecting a wirevector, int, or verilog-style '",
"'const string got %s instead'",
"%",
"repr",
"(",
"val",
")",
")",
"elif",
"bitwidth",
"==",
"'0'",
":",
"raise",
"PyrtlError",
"(",
"'error, bitwidth must be >= 1'",
")",
"elif",
"val",
".",
"bitwidth",
"is",
"None",
":",
"raise",
"PyrtlError",
"(",
"'error, attempting to use wirevector with no defined bitwidth'",
")",
"elif",
"bitwidth",
"and",
"bitwidth",
">",
"val",
".",
"bitwidth",
":",
"return",
"val",
".",
"zero_extended",
"(",
"bitwidth",
")",
"elif",
"bitwidth",
"and",
"truncating",
"and",
"bitwidth",
"<",
"val",
".",
"bitwidth",
":",
"return",
"val",
"[",
":",
"bitwidth",
"]",
"# truncate the upper bits",
"else",
":",
"return",
"val"
] | Return wires from val which may be wires, integers, strings, or bools.
:param val: a wirevector-like object or something that can be converted into
a Const
:param bitwidth: The bitwidth the resulting wire should be
:param bool truncating: determines whether bits will be dropped to achieve
the desired bitwidth if it is too long (if true, the most-significant bits
will be dropped)
:param Block block: block to use for wire
This function is mainly used to coerce values into WireVectors (for
example, operations such as "x+1" where "1" needs to be converted to
a Const WireVector). An example: ::
def myhardware(input_a, input_b):
a = as_wires(input_a)
b = as_wires(input_b)
myhardware(3, x)
The function as_wires will covert the 3 to Const but keep `x` unchanged
assuming it is a WireVector. | [
"Return",
"wires",
"from",
"val",
"which",
"may",
"be",
"wires",
"integers",
"strings",
"or",
"bools",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/corecircuits.py#L341-L388 |
UCSBarchlab/PyRTL | pyrtl/corecircuits.py | bitfield_update | def bitfield_update(w, range_start, range_end, newvalue, truncating=False):
""" Return wirevector w but with some of the bits overwritten by newvalue.
:param w: a wirevector to use as the starting point for the update
:param range_start: the start of the range of bits to be updated
:param range_end: the end of the range of bits to be updated
:param newvalue: the value to be written in to the start:end range
:param truncating: if true, clip the newvalue to be the proper number of bits
Given a wirevector w, this function returns a new wirevector that
is identical to w except in the range of bits specified. In that
specified range, the value newvalue is swapped in. For example:
`bitfield_update(w, 20, 23, 0x7)` will return return a wirevector
of the same length as w, and with the same values as w, but with
bits 20, 21, and 22 all set to 1.
Note that range_start and range_end will be inputs to a slice and
so standar Python slicing rules apply (e.g. negative values for
end-relative indexing and support for None). ::
w = bitfield_update(w, 20, 23, 0x7) # sets bits 20, 21, 22 to 1
w = bitfield_update(w, 20, 23, 0x6) # sets bit 20 to 0, bits 21 and 22 to 1
w = bitfield_update(w, 20, None, 0x7) # assuming w is 32 bits, sets bits 31..20 = 0x7
w = bitfield_update(w, -1, None, 0x1) # set the LSB (bit) to 1
"""
from .corecircuits import concat_list
w = as_wires(w)
idxs = list(range(len(w))) # we make a list of integers and slice those up to use as indexes
idxs_lower = idxs[0:range_start]
idxs_middle = idxs[range_start:range_end]
idxs_upper = idxs[range_end:]
if len(idxs_middle) == 0:
raise PyrtlError('Cannot update bitfield of size 0 (i.e. there are no bits to update)')
newvalue = as_wires(newvalue, bitwidth=len(idxs_middle), truncating=truncating)
if len(idxs_middle) != len(newvalue):
raise PyrtlError('Cannot update bitfield of length %d with value of length %d '
'unless truncating=True is specified' % (len(idxs_middle), len(newvalue)))
result_list = []
if idxs_lower:
result_list.append(w[idxs_lower[0]:idxs_lower[-1]+1])
result_list.append(newvalue)
if idxs_upper:
result_list.append(w[idxs_upper[0]:idxs_upper[-1]+1])
result = concat_list(result_list)
if len(result) != len(w):
raise PyrtlInternalError('len(result)=%d, len(original)=%d' % (len(result), len(w)))
return result | python | def bitfield_update(w, range_start, range_end, newvalue, truncating=False):
""" Return wirevector w but with some of the bits overwritten by newvalue.
:param w: a wirevector to use as the starting point for the update
:param range_start: the start of the range of bits to be updated
:param range_end: the end of the range of bits to be updated
:param newvalue: the value to be written in to the start:end range
:param truncating: if true, clip the newvalue to be the proper number of bits
Given a wirevector w, this function returns a new wirevector that
is identical to w except in the range of bits specified. In that
specified range, the value newvalue is swapped in. For example:
`bitfield_update(w, 20, 23, 0x7)` will return return a wirevector
of the same length as w, and with the same values as w, but with
bits 20, 21, and 22 all set to 1.
Note that range_start and range_end will be inputs to a slice and
so standar Python slicing rules apply (e.g. negative values for
end-relative indexing and support for None). ::
w = bitfield_update(w, 20, 23, 0x7) # sets bits 20, 21, 22 to 1
w = bitfield_update(w, 20, 23, 0x6) # sets bit 20 to 0, bits 21 and 22 to 1
w = bitfield_update(w, 20, None, 0x7) # assuming w is 32 bits, sets bits 31..20 = 0x7
w = bitfield_update(w, -1, None, 0x1) # set the LSB (bit) to 1
"""
from .corecircuits import concat_list
w = as_wires(w)
idxs = list(range(len(w))) # we make a list of integers and slice those up to use as indexes
idxs_lower = idxs[0:range_start]
idxs_middle = idxs[range_start:range_end]
idxs_upper = idxs[range_end:]
if len(idxs_middle) == 0:
raise PyrtlError('Cannot update bitfield of size 0 (i.e. there are no bits to update)')
newvalue = as_wires(newvalue, bitwidth=len(idxs_middle), truncating=truncating)
if len(idxs_middle) != len(newvalue):
raise PyrtlError('Cannot update bitfield of length %d with value of length %d '
'unless truncating=True is specified' % (len(idxs_middle), len(newvalue)))
result_list = []
if idxs_lower:
result_list.append(w[idxs_lower[0]:idxs_lower[-1]+1])
result_list.append(newvalue)
if idxs_upper:
result_list.append(w[idxs_upper[0]:idxs_upper[-1]+1])
result = concat_list(result_list)
if len(result) != len(w):
raise PyrtlInternalError('len(result)=%d, len(original)=%d' % (len(result), len(w)))
return result | [
"def",
"bitfield_update",
"(",
"w",
",",
"range_start",
",",
"range_end",
",",
"newvalue",
",",
"truncating",
"=",
"False",
")",
":",
"from",
".",
"corecircuits",
"import",
"concat_list",
"w",
"=",
"as_wires",
"(",
"w",
")",
"idxs",
"=",
"list",
"(",
"range",
"(",
"len",
"(",
"w",
")",
")",
")",
"# we make a list of integers and slice those up to use as indexes",
"idxs_lower",
"=",
"idxs",
"[",
"0",
":",
"range_start",
"]",
"idxs_middle",
"=",
"idxs",
"[",
"range_start",
":",
"range_end",
"]",
"idxs_upper",
"=",
"idxs",
"[",
"range_end",
":",
"]",
"if",
"len",
"(",
"idxs_middle",
")",
"==",
"0",
":",
"raise",
"PyrtlError",
"(",
"'Cannot update bitfield of size 0 (i.e. there are no bits to update)'",
")",
"newvalue",
"=",
"as_wires",
"(",
"newvalue",
",",
"bitwidth",
"=",
"len",
"(",
"idxs_middle",
")",
",",
"truncating",
"=",
"truncating",
")",
"if",
"len",
"(",
"idxs_middle",
")",
"!=",
"len",
"(",
"newvalue",
")",
":",
"raise",
"PyrtlError",
"(",
"'Cannot update bitfield of length %d with value of length %d '",
"'unless truncating=True is specified'",
"%",
"(",
"len",
"(",
"idxs_middle",
")",
",",
"len",
"(",
"newvalue",
")",
")",
")",
"result_list",
"=",
"[",
"]",
"if",
"idxs_lower",
":",
"result_list",
".",
"append",
"(",
"w",
"[",
"idxs_lower",
"[",
"0",
"]",
":",
"idxs_lower",
"[",
"-",
"1",
"]",
"+",
"1",
"]",
")",
"result_list",
".",
"append",
"(",
"newvalue",
")",
"if",
"idxs_upper",
":",
"result_list",
".",
"append",
"(",
"w",
"[",
"idxs_upper",
"[",
"0",
"]",
":",
"idxs_upper",
"[",
"-",
"1",
"]",
"+",
"1",
"]",
")",
"result",
"=",
"concat_list",
"(",
"result_list",
")",
"if",
"len",
"(",
"result",
")",
"!=",
"len",
"(",
"w",
")",
":",
"raise",
"PyrtlInternalError",
"(",
"'len(result)=%d, len(original)=%d'",
"%",
"(",
"len",
"(",
"result",
")",
",",
"len",
"(",
"w",
")",
")",
")",
"return",
"result"
] | Return wirevector w but with some of the bits overwritten by newvalue.
:param w: a wirevector to use as the starting point for the update
:param range_start: the start of the range of bits to be updated
:param range_end: the end of the range of bits to be updated
:param newvalue: the value to be written in to the start:end range
:param truncating: if true, clip the newvalue to be the proper number of bits
Given a wirevector w, this function returns a new wirevector that
is identical to w except in the range of bits specified. In that
specified range, the value newvalue is swapped in. For example:
`bitfield_update(w, 20, 23, 0x7)` will return return a wirevector
of the same length as w, and with the same values as w, but with
bits 20, 21, and 22 all set to 1.
Note that range_start and range_end will be inputs to a slice and
so standar Python slicing rules apply (e.g. negative values for
end-relative indexing and support for None). ::
w = bitfield_update(w, 20, 23, 0x7) # sets bits 20, 21, 22 to 1
w = bitfield_update(w, 20, 23, 0x6) # sets bit 20 to 0, bits 21 and 22 to 1
w = bitfield_update(w, 20, None, 0x7) # assuming w is 32 bits, sets bits 31..20 = 0x7
w = bitfield_update(w, -1, None, 0x1) # set the LSB (bit) to 1 | [
"Return",
"wirevector",
"w",
"but",
"with",
"some",
"of",
"the",
"bits",
"overwritten",
"by",
"newvalue",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/corecircuits.py#L391-L441 |
UCSBarchlab/PyRTL | pyrtl/corecircuits.py | enum_mux | def enum_mux(cntrl, table, default=None, strict=True):
""" Build a mux for the control signals specified by an enum.
:param cntrl: is a wirevector and control for the mux.
:param table: is a dictionary of the form mapping enum->wirevector.
:param default: is a wirevector to use when the key is not present. In addtion
it is possible to use the key 'otherwise' to specify a default value, but
it is an error if both are supplied.
:param strict: is flag, that when set, will cause enum_mux to check
that the dictionary has an entry for every possible value in the enum.
Note that if a default is set, then this check is not performed as
the default will provide valid values for any underspecified keys.
:return: a wirevector which is the result of the mux.
::
class Command(Enum):
ADD = 1
SUB = 2
enum_mux(cntrl, {ADD: a+b, SUB: a-b})
enum_mux(cntrl, {ADD: a+b}, strict=False) # SUB case undefined
enum_mux(cntrl, {ADD: a+b, otherwise: a-b})
enum_mux(cntrl, {ADD: a+b}, default=a-b)
"""
# check dictionary keys are of the right type
keytypeset = set(type(x) for x in table.keys() if x is not otherwise)
if len(keytypeset) != 1:
raise PyrtlError('table mixes multiple types {} as keys'.format(keytypeset))
keytype = list(keytypeset)[0]
# check that dictionary is complete for the enum
try:
enumkeys = list(keytype.__members__.values())
except AttributeError:
raise PyrtlError('type {} not an Enum and does not support the same interface'
.format(keytype))
missingkeys = [e for e in enumkeys if e not in table]
# check for "otherwise" in table and move it to a default
if otherwise in table:
if default is not None:
raise PyrtlError('both "otherwise" and default provided to enum_mux')
else:
default = table[otherwise]
if strict and default is None and missingkeys:
raise PyrtlError('table provided is incomplete, missing: {}'.format(missingkeys))
# generate the actual mux
vals = {k.value: d for k, d in table.items() if k is not otherwise}
if default is not None:
vals['default'] = default
return muxes.sparse_mux(cntrl, vals) | python | def enum_mux(cntrl, table, default=None, strict=True):
""" Build a mux for the control signals specified by an enum.
:param cntrl: is a wirevector and control for the mux.
:param table: is a dictionary of the form mapping enum->wirevector.
:param default: is a wirevector to use when the key is not present. In addtion
it is possible to use the key 'otherwise' to specify a default value, but
it is an error if both are supplied.
:param strict: is flag, that when set, will cause enum_mux to check
that the dictionary has an entry for every possible value in the enum.
Note that if a default is set, then this check is not performed as
the default will provide valid values for any underspecified keys.
:return: a wirevector which is the result of the mux.
::
class Command(Enum):
ADD = 1
SUB = 2
enum_mux(cntrl, {ADD: a+b, SUB: a-b})
enum_mux(cntrl, {ADD: a+b}, strict=False) # SUB case undefined
enum_mux(cntrl, {ADD: a+b, otherwise: a-b})
enum_mux(cntrl, {ADD: a+b}, default=a-b)
"""
# check dictionary keys are of the right type
keytypeset = set(type(x) for x in table.keys() if x is not otherwise)
if len(keytypeset) != 1:
raise PyrtlError('table mixes multiple types {} as keys'.format(keytypeset))
keytype = list(keytypeset)[0]
# check that dictionary is complete for the enum
try:
enumkeys = list(keytype.__members__.values())
except AttributeError:
raise PyrtlError('type {} not an Enum and does not support the same interface'
.format(keytype))
missingkeys = [e for e in enumkeys if e not in table]
# check for "otherwise" in table and move it to a default
if otherwise in table:
if default is not None:
raise PyrtlError('both "otherwise" and default provided to enum_mux')
else:
default = table[otherwise]
if strict and default is None and missingkeys:
raise PyrtlError('table provided is incomplete, missing: {}'.format(missingkeys))
# generate the actual mux
vals = {k.value: d for k, d in table.items() if k is not otherwise}
if default is not None:
vals['default'] = default
return muxes.sparse_mux(cntrl, vals) | [
"def",
"enum_mux",
"(",
"cntrl",
",",
"table",
",",
"default",
"=",
"None",
",",
"strict",
"=",
"True",
")",
":",
"# check dictionary keys are of the right type",
"keytypeset",
"=",
"set",
"(",
"type",
"(",
"x",
")",
"for",
"x",
"in",
"table",
".",
"keys",
"(",
")",
"if",
"x",
"is",
"not",
"otherwise",
")",
"if",
"len",
"(",
"keytypeset",
")",
"!=",
"1",
":",
"raise",
"PyrtlError",
"(",
"'table mixes multiple types {} as keys'",
".",
"format",
"(",
"keytypeset",
")",
")",
"keytype",
"=",
"list",
"(",
"keytypeset",
")",
"[",
"0",
"]",
"# check that dictionary is complete for the enum",
"try",
":",
"enumkeys",
"=",
"list",
"(",
"keytype",
".",
"__members__",
".",
"values",
"(",
")",
")",
"except",
"AttributeError",
":",
"raise",
"PyrtlError",
"(",
"'type {} not an Enum and does not support the same interface'",
".",
"format",
"(",
"keytype",
")",
")",
"missingkeys",
"=",
"[",
"e",
"for",
"e",
"in",
"enumkeys",
"if",
"e",
"not",
"in",
"table",
"]",
"# check for \"otherwise\" in table and move it to a default",
"if",
"otherwise",
"in",
"table",
":",
"if",
"default",
"is",
"not",
"None",
":",
"raise",
"PyrtlError",
"(",
"'both \"otherwise\" and default provided to enum_mux'",
")",
"else",
":",
"default",
"=",
"table",
"[",
"otherwise",
"]",
"if",
"strict",
"and",
"default",
"is",
"None",
"and",
"missingkeys",
":",
"raise",
"PyrtlError",
"(",
"'table provided is incomplete, missing: {}'",
".",
"format",
"(",
"missingkeys",
")",
")",
"# generate the actual mux",
"vals",
"=",
"{",
"k",
".",
"value",
":",
"d",
"for",
"k",
",",
"d",
"in",
"table",
".",
"items",
"(",
")",
"if",
"k",
"is",
"not",
"otherwise",
"}",
"if",
"default",
"is",
"not",
"None",
":",
"vals",
"[",
"'default'",
"]",
"=",
"default",
"return",
"muxes",
".",
"sparse_mux",
"(",
"cntrl",
",",
"vals",
")"
] | Build a mux for the control signals specified by an enum.
:param cntrl: is a wirevector and control for the mux.
:param table: is a dictionary of the form mapping enum->wirevector.
:param default: is a wirevector to use when the key is not present. In addtion
it is possible to use the key 'otherwise' to specify a default value, but
it is an error if both are supplied.
:param strict: is flag, that when set, will cause enum_mux to check
that the dictionary has an entry for every possible value in the enum.
Note that if a default is set, then this check is not performed as
the default will provide valid values for any underspecified keys.
:return: a wirevector which is the result of the mux.
::
class Command(Enum):
ADD = 1
SUB = 2
enum_mux(cntrl, {ADD: a+b, SUB: a-b})
enum_mux(cntrl, {ADD: a+b}, strict=False) # SUB case undefined
enum_mux(cntrl, {ADD: a+b, otherwise: a-b})
enum_mux(cntrl, {ADD: a+b}, default=a-b) | [
"Build",
"a",
"mux",
"for",
"the",
"control",
"signals",
"specified",
"by",
"an",
"enum",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/corecircuits.py#L444-L495 |
UCSBarchlab/PyRTL | pyrtl/corecircuits.py | rtl_any | def rtl_any(*vectorlist):
""" Hardware equivalent of python native "any".
:param WireVector vectorlist: all arguments are WireVectors of length 1
:return: WireVector of length 1
Returns a 1-bit WireVector which will hold a '1' if any of the inputs
are '1' (i.e. it is a big ol' OR gate)
"""
if len(vectorlist) <= 0:
raise PyrtlError('rtl_any requires at least 1 argument')
converted_vectorlist = [as_wires(v) for v in vectorlist]
if any(len(v) != 1 for v in converted_vectorlist):
raise PyrtlError('only length 1 WireVectors can be inputs to rtl_any')
return or_all_bits(concat_list(converted_vectorlist)) | python | def rtl_any(*vectorlist):
""" Hardware equivalent of python native "any".
:param WireVector vectorlist: all arguments are WireVectors of length 1
:return: WireVector of length 1
Returns a 1-bit WireVector which will hold a '1' if any of the inputs
are '1' (i.e. it is a big ol' OR gate)
"""
if len(vectorlist) <= 0:
raise PyrtlError('rtl_any requires at least 1 argument')
converted_vectorlist = [as_wires(v) for v in vectorlist]
if any(len(v) != 1 for v in converted_vectorlist):
raise PyrtlError('only length 1 WireVectors can be inputs to rtl_any')
return or_all_bits(concat_list(converted_vectorlist)) | [
"def",
"rtl_any",
"(",
"*",
"vectorlist",
")",
":",
"if",
"len",
"(",
"vectorlist",
")",
"<=",
"0",
":",
"raise",
"PyrtlError",
"(",
"'rtl_any requires at least 1 argument'",
")",
"converted_vectorlist",
"=",
"[",
"as_wires",
"(",
"v",
")",
"for",
"v",
"in",
"vectorlist",
"]",
"if",
"any",
"(",
"len",
"(",
"v",
")",
"!=",
"1",
"for",
"v",
"in",
"converted_vectorlist",
")",
":",
"raise",
"PyrtlError",
"(",
"'only length 1 WireVectors can be inputs to rtl_any'",
")",
"return",
"or_all_bits",
"(",
"concat_list",
"(",
"converted_vectorlist",
")",
")"
] | Hardware equivalent of python native "any".
:param WireVector vectorlist: all arguments are WireVectors of length 1
:return: WireVector of length 1
Returns a 1-bit WireVector which will hold a '1' if any of the inputs
are '1' (i.e. it is a big ol' OR gate) | [
"Hardware",
"equivalent",
"of",
"python",
"native",
"any",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/corecircuits.py#L548-L562 |
UCSBarchlab/PyRTL | pyrtl/corecircuits.py | rtl_all | def rtl_all(*vectorlist):
""" Hardware equivalent of python native "all".
:param WireVector vectorlist: all arguments are WireVectors of length 1
:return: WireVector of length 1
Returns a 1-bit WireVector which will hold a '1' only if all of the
inputs are '1' (i.e. it is a big ol' AND gate)
"""
if len(vectorlist) <= 0:
raise PyrtlError('rtl_all requires at least 1 argument')
converted_vectorlist = [as_wires(v) for v in vectorlist]
if any(len(v) != 1 for v in converted_vectorlist):
raise PyrtlError('only length 1 WireVectors can be inputs to rtl_all')
return and_all_bits(concat_list(converted_vectorlist)) | python | def rtl_all(*vectorlist):
""" Hardware equivalent of python native "all".
:param WireVector vectorlist: all arguments are WireVectors of length 1
:return: WireVector of length 1
Returns a 1-bit WireVector which will hold a '1' only if all of the
inputs are '1' (i.e. it is a big ol' AND gate)
"""
if len(vectorlist) <= 0:
raise PyrtlError('rtl_all requires at least 1 argument')
converted_vectorlist = [as_wires(v) for v in vectorlist]
if any(len(v) != 1 for v in converted_vectorlist):
raise PyrtlError('only length 1 WireVectors can be inputs to rtl_all')
return and_all_bits(concat_list(converted_vectorlist)) | [
"def",
"rtl_all",
"(",
"*",
"vectorlist",
")",
":",
"if",
"len",
"(",
"vectorlist",
")",
"<=",
"0",
":",
"raise",
"PyrtlError",
"(",
"'rtl_all requires at least 1 argument'",
")",
"converted_vectorlist",
"=",
"[",
"as_wires",
"(",
"v",
")",
"for",
"v",
"in",
"vectorlist",
"]",
"if",
"any",
"(",
"len",
"(",
"v",
")",
"!=",
"1",
"for",
"v",
"in",
"converted_vectorlist",
")",
":",
"raise",
"PyrtlError",
"(",
"'only length 1 WireVectors can be inputs to rtl_all'",
")",
"return",
"and_all_bits",
"(",
"concat_list",
"(",
"converted_vectorlist",
")",
")"
] | Hardware equivalent of python native "all".
:param WireVector vectorlist: all arguments are WireVectors of length 1
:return: WireVector of length 1
Returns a 1-bit WireVector which will hold a '1' only if all of the
inputs are '1' (i.e. it is a big ol' AND gate) | [
"Hardware",
"equivalent",
"of",
"python",
"native",
"all",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/corecircuits.py#L565-L579 |
UCSBarchlab/PyRTL | pyrtl/corecircuits.py | _basic_mult | def _basic_mult(A, B):
""" A stripped-down copy of the Wallace multiplier in rtllib """
if len(B) == 1:
A, B = B, A # so that we can reuse the code below :)
if len(A) == 1:
return concat_list(list(A & b for b in B) + [Const(0)]) # keep WireVector len consistent
result_bitwidth = len(A) + len(B)
bits = [[] for weight in range(result_bitwidth)]
for i, a in enumerate(A):
for j, b in enumerate(B):
bits[i + j].append(a & b)
while not all(len(i) <= 2 for i in bits):
deferred = [[] for weight in range(result_bitwidth + 1)]
for i, w_array in enumerate(bits): # Start with low weights and start reducing
while len(w_array) >= 3: # build a new full adder
a, b, cin = (w_array.pop(0) for j in range(3))
deferred[i].append(a ^ b ^ cin)
deferred[i + 1].append(a & b | a & cin | b & cin)
if len(w_array) == 2:
a, b = w_array
deferred[i].append(a ^ b)
deferred[i + 1].append(a & b)
else:
deferred[i].extend(w_array)
bits = deferred[:result_bitwidth]
import six
add_wires = tuple(six.moves.zip_longest(*bits, fillvalue=Const(0)))
adder_result = concat_list(add_wires[0]) + concat_list(add_wires[1])
return adder_result[:result_bitwidth] | python | def _basic_mult(A, B):
""" A stripped-down copy of the Wallace multiplier in rtllib """
if len(B) == 1:
A, B = B, A # so that we can reuse the code below :)
if len(A) == 1:
return concat_list(list(A & b for b in B) + [Const(0)]) # keep WireVector len consistent
result_bitwidth = len(A) + len(B)
bits = [[] for weight in range(result_bitwidth)]
for i, a in enumerate(A):
for j, b in enumerate(B):
bits[i + j].append(a & b)
while not all(len(i) <= 2 for i in bits):
deferred = [[] for weight in range(result_bitwidth + 1)]
for i, w_array in enumerate(bits): # Start with low weights and start reducing
while len(w_array) >= 3: # build a new full adder
a, b, cin = (w_array.pop(0) for j in range(3))
deferred[i].append(a ^ b ^ cin)
deferred[i + 1].append(a & b | a & cin | b & cin)
if len(w_array) == 2:
a, b = w_array
deferred[i].append(a ^ b)
deferred[i + 1].append(a & b)
else:
deferred[i].extend(w_array)
bits = deferred[:result_bitwidth]
import six
add_wires = tuple(six.moves.zip_longest(*bits, fillvalue=Const(0)))
adder_result = concat_list(add_wires[0]) + concat_list(add_wires[1])
return adder_result[:result_bitwidth] | [
"def",
"_basic_mult",
"(",
"A",
",",
"B",
")",
":",
"if",
"len",
"(",
"B",
")",
"==",
"1",
":",
"A",
",",
"B",
"=",
"B",
",",
"A",
"# so that we can reuse the code below :)",
"if",
"len",
"(",
"A",
")",
"==",
"1",
":",
"return",
"concat_list",
"(",
"list",
"(",
"A",
"&",
"b",
"for",
"b",
"in",
"B",
")",
"+",
"[",
"Const",
"(",
"0",
")",
"]",
")",
"# keep WireVector len consistent",
"result_bitwidth",
"=",
"len",
"(",
"A",
")",
"+",
"len",
"(",
"B",
")",
"bits",
"=",
"[",
"[",
"]",
"for",
"weight",
"in",
"range",
"(",
"result_bitwidth",
")",
"]",
"for",
"i",
",",
"a",
"in",
"enumerate",
"(",
"A",
")",
":",
"for",
"j",
",",
"b",
"in",
"enumerate",
"(",
"B",
")",
":",
"bits",
"[",
"i",
"+",
"j",
"]",
".",
"append",
"(",
"a",
"&",
"b",
")",
"while",
"not",
"all",
"(",
"len",
"(",
"i",
")",
"<=",
"2",
"for",
"i",
"in",
"bits",
")",
":",
"deferred",
"=",
"[",
"[",
"]",
"for",
"weight",
"in",
"range",
"(",
"result_bitwidth",
"+",
"1",
")",
"]",
"for",
"i",
",",
"w_array",
"in",
"enumerate",
"(",
"bits",
")",
":",
"# Start with low weights and start reducing",
"while",
"len",
"(",
"w_array",
")",
">=",
"3",
":",
"# build a new full adder",
"a",
",",
"b",
",",
"cin",
"=",
"(",
"w_array",
".",
"pop",
"(",
"0",
")",
"for",
"j",
"in",
"range",
"(",
"3",
")",
")",
"deferred",
"[",
"i",
"]",
".",
"append",
"(",
"a",
"^",
"b",
"^",
"cin",
")",
"deferred",
"[",
"i",
"+",
"1",
"]",
".",
"append",
"(",
"a",
"&",
"b",
"|",
"a",
"&",
"cin",
"|",
"b",
"&",
"cin",
")",
"if",
"len",
"(",
"w_array",
")",
"==",
"2",
":",
"a",
",",
"b",
"=",
"w_array",
"deferred",
"[",
"i",
"]",
".",
"append",
"(",
"a",
"^",
"b",
")",
"deferred",
"[",
"i",
"+",
"1",
"]",
".",
"append",
"(",
"a",
"&",
"b",
")",
"else",
":",
"deferred",
"[",
"i",
"]",
".",
"extend",
"(",
"w_array",
")",
"bits",
"=",
"deferred",
"[",
":",
"result_bitwidth",
"]",
"import",
"six",
"add_wires",
"=",
"tuple",
"(",
"six",
".",
"moves",
".",
"zip_longest",
"(",
"*",
"bits",
",",
"fillvalue",
"=",
"Const",
"(",
"0",
")",
")",
")",
"adder_result",
"=",
"concat_list",
"(",
"add_wires",
"[",
"0",
"]",
")",
"+",
"concat_list",
"(",
"add_wires",
"[",
"1",
"]",
")",
"return",
"adder_result",
"[",
":",
"result_bitwidth",
"]"
] | A stripped-down copy of the Wallace multiplier in rtllib | [
"A",
"stripped",
"-",
"down",
"copy",
"of",
"the",
"Wallace",
"multiplier",
"in",
"rtllib"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/corecircuits.py#L582-L613 |
UCSBarchlab/PyRTL | pyrtl/conditional.py | _push_condition | def _push_condition(predicate):
"""As we enter new conditions, this pushes them on the predicate stack."""
global _depth
_check_under_condition()
_depth += 1
if predicate is not otherwise and len(predicate) > 1:
raise PyrtlError('all predicates for conditional assignments must wirevectors of len 1')
_conditions_list_stack[-1].append(predicate)
_conditions_list_stack.append([]) | python | def _push_condition(predicate):
"""As we enter new conditions, this pushes them on the predicate stack."""
global _depth
_check_under_condition()
_depth += 1
if predicate is not otherwise and len(predicate) > 1:
raise PyrtlError('all predicates for conditional assignments must wirevectors of len 1')
_conditions_list_stack[-1].append(predicate)
_conditions_list_stack.append([]) | [
"def",
"_push_condition",
"(",
"predicate",
")",
":",
"global",
"_depth",
"_check_under_condition",
"(",
")",
"_depth",
"+=",
"1",
"if",
"predicate",
"is",
"not",
"otherwise",
"and",
"len",
"(",
"predicate",
")",
">",
"1",
":",
"raise",
"PyrtlError",
"(",
"'all predicates for conditional assignments must wirevectors of len 1'",
")",
"_conditions_list_stack",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"predicate",
")",
"_conditions_list_stack",
".",
"append",
"(",
"[",
"]",
")"
] | As we enter new conditions, this pushes them on the predicate stack. | [
"As",
"we",
"enter",
"new",
"conditions",
"this",
"pushes",
"them",
"on",
"the",
"predicate",
"stack",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/conditional.py#L119-L127 |
UCSBarchlab/PyRTL | pyrtl/conditional.py | _build | def _build(lhs, rhs):
"""Stores the wire assignment details until finalize is called."""
_check_under_condition()
final_predicate, pred_set = _current_select()
_check_and_add_pred_set(lhs, pred_set)
_predicate_map.setdefault(lhs, []).append((final_predicate, rhs)) | python | def _build(lhs, rhs):
"""Stores the wire assignment details until finalize is called."""
_check_under_condition()
final_predicate, pred_set = _current_select()
_check_and_add_pred_set(lhs, pred_set)
_predicate_map.setdefault(lhs, []).append((final_predicate, rhs)) | [
"def",
"_build",
"(",
"lhs",
",",
"rhs",
")",
":",
"_check_under_condition",
"(",
")",
"final_predicate",
",",
"pred_set",
"=",
"_current_select",
"(",
")",
"_check_and_add_pred_set",
"(",
"lhs",
",",
"pred_set",
")",
"_predicate_map",
".",
"setdefault",
"(",
"lhs",
",",
"[",
"]",
")",
".",
"append",
"(",
"(",
"final_predicate",
",",
"rhs",
")",
")"
] | Stores the wire assignment details until finalize is called. | [
"Stores",
"the",
"wire",
"assignment",
"details",
"until",
"finalize",
"is",
"called",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/conditional.py#L138-L143 |
UCSBarchlab/PyRTL | pyrtl/conditional.py | _pred_sets_are_in_conflict | def _pred_sets_are_in_conflict(pred_set_a, pred_set_b):
""" Find conflict in sets, return conflict if found, else None. """
# pred_sets conflict if we cannot find one shared predicate that is "negated" in one
# and "non-negated" in the other
for pred_a, bool_a in pred_set_a:
for pred_b, bool_b in pred_set_b:
if pred_a is pred_b and bool_a != bool_b:
return False
return True | python | def _pred_sets_are_in_conflict(pred_set_a, pred_set_b):
""" Find conflict in sets, return conflict if found, else None. """
# pred_sets conflict if we cannot find one shared predicate that is "negated" in one
# and "non-negated" in the other
for pred_a, bool_a in pred_set_a:
for pred_b, bool_b in pred_set_b:
if pred_a is pred_b and bool_a != bool_b:
return False
return True | [
"def",
"_pred_sets_are_in_conflict",
"(",
"pred_set_a",
",",
"pred_set_b",
")",
":",
"# pred_sets conflict if we cannot find one shared predicate that is \"negated\" in one",
"# and \"non-negated\" in the other",
"for",
"pred_a",
",",
"bool_a",
"in",
"pred_set_a",
":",
"for",
"pred_b",
",",
"bool_b",
"in",
"pred_set_b",
":",
"if",
"pred_a",
"is",
"pred_b",
"and",
"bool_a",
"!=",
"bool_b",
":",
"return",
"False",
"return",
"True"
] | Find conflict in sets, return conflict if found, else None. | [
"Find",
"conflict",
"in",
"sets",
"return",
"conflict",
"if",
"found",
"else",
"None",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/conditional.py#L171-L179 |
UCSBarchlab/PyRTL | pyrtl/conditional.py | _finalize | def _finalize():
"""Build the required muxes and call back to WireVector to finalize the wirevector build."""
from .memory import MemBlock
from pyrtl.corecircuits import select
for lhs in _predicate_map:
# handle memory write ports
if isinstance(lhs, MemBlock):
p, (addr, data, enable) = _predicate_map[lhs][0]
combined_enable = select(p, truecase=enable, falsecase=Const(0))
combined_addr = addr
combined_data = data
for p, (addr, data, enable) in _predicate_map[lhs][1:]:
combined_enable = select(p, truecase=enable, falsecase=combined_enable)
combined_addr = select(p, truecase=addr, falsecase=combined_addr)
combined_data = select(p, truecase=data, falsecase=combined_data)
lhs._build(combined_addr, combined_data, combined_enable)
# handle wirevector and register assignments
else:
if isinstance(lhs, Register):
result = lhs # default for registers is "self"
elif isinstance(lhs, WireVector):
result = 0 # default for wire is "0"
else:
raise PyrtlInternalError('unknown assignment in finalize')
predlist = _predicate_map[lhs]
for p, rhs in predlist:
result = select(p, truecase=rhs, falsecase=result)
lhs._build(result) | python | def _finalize():
"""Build the required muxes and call back to WireVector to finalize the wirevector build."""
from .memory import MemBlock
from pyrtl.corecircuits import select
for lhs in _predicate_map:
# handle memory write ports
if isinstance(lhs, MemBlock):
p, (addr, data, enable) = _predicate_map[lhs][0]
combined_enable = select(p, truecase=enable, falsecase=Const(0))
combined_addr = addr
combined_data = data
for p, (addr, data, enable) in _predicate_map[lhs][1:]:
combined_enable = select(p, truecase=enable, falsecase=combined_enable)
combined_addr = select(p, truecase=addr, falsecase=combined_addr)
combined_data = select(p, truecase=data, falsecase=combined_data)
lhs._build(combined_addr, combined_data, combined_enable)
# handle wirevector and register assignments
else:
if isinstance(lhs, Register):
result = lhs # default for registers is "self"
elif isinstance(lhs, WireVector):
result = 0 # default for wire is "0"
else:
raise PyrtlInternalError('unknown assignment in finalize')
predlist = _predicate_map[lhs]
for p, rhs in predlist:
result = select(p, truecase=rhs, falsecase=result)
lhs._build(result) | [
"def",
"_finalize",
"(",
")",
":",
"from",
".",
"memory",
"import",
"MemBlock",
"from",
"pyrtl",
".",
"corecircuits",
"import",
"select",
"for",
"lhs",
"in",
"_predicate_map",
":",
"# handle memory write ports",
"if",
"isinstance",
"(",
"lhs",
",",
"MemBlock",
")",
":",
"p",
",",
"(",
"addr",
",",
"data",
",",
"enable",
")",
"=",
"_predicate_map",
"[",
"lhs",
"]",
"[",
"0",
"]",
"combined_enable",
"=",
"select",
"(",
"p",
",",
"truecase",
"=",
"enable",
",",
"falsecase",
"=",
"Const",
"(",
"0",
")",
")",
"combined_addr",
"=",
"addr",
"combined_data",
"=",
"data",
"for",
"p",
",",
"(",
"addr",
",",
"data",
",",
"enable",
")",
"in",
"_predicate_map",
"[",
"lhs",
"]",
"[",
"1",
":",
"]",
":",
"combined_enable",
"=",
"select",
"(",
"p",
",",
"truecase",
"=",
"enable",
",",
"falsecase",
"=",
"combined_enable",
")",
"combined_addr",
"=",
"select",
"(",
"p",
",",
"truecase",
"=",
"addr",
",",
"falsecase",
"=",
"combined_addr",
")",
"combined_data",
"=",
"select",
"(",
"p",
",",
"truecase",
"=",
"data",
",",
"falsecase",
"=",
"combined_data",
")",
"lhs",
".",
"_build",
"(",
"combined_addr",
",",
"combined_data",
",",
"combined_enable",
")",
"# handle wirevector and register assignments",
"else",
":",
"if",
"isinstance",
"(",
"lhs",
",",
"Register",
")",
":",
"result",
"=",
"lhs",
"# default for registers is \"self\"",
"elif",
"isinstance",
"(",
"lhs",
",",
"WireVector",
")",
":",
"result",
"=",
"0",
"# default for wire is \"0\"",
"else",
":",
"raise",
"PyrtlInternalError",
"(",
"'unknown assignment in finalize'",
")",
"predlist",
"=",
"_predicate_map",
"[",
"lhs",
"]",
"for",
"p",
",",
"rhs",
"in",
"predlist",
":",
"result",
"=",
"select",
"(",
"p",
",",
"truecase",
"=",
"rhs",
",",
"falsecase",
"=",
"result",
")",
"lhs",
".",
"_build",
"(",
"result",
")"
] | Build the required muxes and call back to WireVector to finalize the wirevector build. | [
"Build",
"the",
"required",
"muxes",
"and",
"call",
"back",
"to",
"WireVector",
"to",
"finalize",
"the",
"wirevector",
"build",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/conditional.py#L182-L212 |
UCSBarchlab/PyRTL | pyrtl/conditional.py | _current_select | def _current_select():
""" Function to calculate the current "predicate" in the current context.
Returns a tuple of information: (predicate, pred_set).
The value pred_set is a set([ (predicate, bool), ... ]) as described in
the _reset_conditional_state
"""
# helper to create the conjuction of predicates
def and_with_possible_none(a, b):
assert(a is not None or b is not None)
if a is None:
return b
if b is None:
return a
return a & b
def between_otherwise_and_current(predlist):
lastother = None
for i, p in enumerate(predlist[:-1]):
if p is otherwise:
lastother = i
if lastother is None:
return predlist[:-1]
else:
return predlist[lastother+1:-1]
select = None
pred_set = set()
# for all conditions except the current children (which should be [])
for predlist in _conditions_list_stack[:-1]:
# negate all of the predicates between "otherwise" and the current one
for predicate in between_otherwise_and_current(predlist):
select = and_with_possible_none(select, ~predicate)
pred_set.add((predicate, True))
# include the predicate for the current one (not negated)
if predlist[-1] is not otherwise:
predicate = predlist[-1]
select = and_with_possible_none(select, predicate)
pred_set.add((predicate, False))
if select is None:
raise PyrtlError('problem with conditional assignment')
if len(select) != 1:
raise PyrtlInternalError('conditional predicate with length greater than 1')
return select, pred_set | python | def _current_select():
""" Function to calculate the current "predicate" in the current context.
Returns a tuple of information: (predicate, pred_set).
The value pred_set is a set([ (predicate, bool), ... ]) as described in
the _reset_conditional_state
"""
# helper to create the conjuction of predicates
def and_with_possible_none(a, b):
assert(a is not None or b is not None)
if a is None:
return b
if b is None:
return a
return a & b
def between_otherwise_and_current(predlist):
lastother = None
for i, p in enumerate(predlist[:-1]):
if p is otherwise:
lastother = i
if lastother is None:
return predlist[:-1]
else:
return predlist[lastother+1:-1]
select = None
pred_set = set()
# for all conditions except the current children (which should be [])
for predlist in _conditions_list_stack[:-1]:
# negate all of the predicates between "otherwise" and the current one
for predicate in between_otherwise_and_current(predlist):
select = and_with_possible_none(select, ~predicate)
pred_set.add((predicate, True))
# include the predicate for the current one (not negated)
if predlist[-1] is not otherwise:
predicate = predlist[-1]
select = and_with_possible_none(select, predicate)
pred_set.add((predicate, False))
if select is None:
raise PyrtlError('problem with conditional assignment')
if len(select) != 1:
raise PyrtlInternalError('conditional predicate with length greater than 1')
return select, pred_set | [
"def",
"_current_select",
"(",
")",
":",
"# helper to create the conjuction of predicates",
"def",
"and_with_possible_none",
"(",
"a",
",",
"b",
")",
":",
"assert",
"(",
"a",
"is",
"not",
"None",
"or",
"b",
"is",
"not",
"None",
")",
"if",
"a",
"is",
"None",
":",
"return",
"b",
"if",
"b",
"is",
"None",
":",
"return",
"a",
"return",
"a",
"&",
"b",
"def",
"between_otherwise_and_current",
"(",
"predlist",
")",
":",
"lastother",
"=",
"None",
"for",
"i",
",",
"p",
"in",
"enumerate",
"(",
"predlist",
"[",
":",
"-",
"1",
"]",
")",
":",
"if",
"p",
"is",
"otherwise",
":",
"lastother",
"=",
"i",
"if",
"lastother",
"is",
"None",
":",
"return",
"predlist",
"[",
":",
"-",
"1",
"]",
"else",
":",
"return",
"predlist",
"[",
"lastother",
"+",
"1",
":",
"-",
"1",
"]",
"select",
"=",
"None",
"pred_set",
"=",
"set",
"(",
")",
"# for all conditions except the current children (which should be [])",
"for",
"predlist",
"in",
"_conditions_list_stack",
"[",
":",
"-",
"1",
"]",
":",
"# negate all of the predicates between \"otherwise\" and the current one",
"for",
"predicate",
"in",
"between_otherwise_and_current",
"(",
"predlist",
")",
":",
"select",
"=",
"and_with_possible_none",
"(",
"select",
",",
"~",
"predicate",
")",
"pred_set",
".",
"add",
"(",
"(",
"predicate",
",",
"True",
")",
")",
"# include the predicate for the current one (not negated)",
"if",
"predlist",
"[",
"-",
"1",
"]",
"is",
"not",
"otherwise",
":",
"predicate",
"=",
"predlist",
"[",
"-",
"1",
"]",
"select",
"=",
"and_with_possible_none",
"(",
"select",
",",
"predicate",
")",
"pred_set",
".",
"add",
"(",
"(",
"predicate",
",",
"False",
")",
")",
"if",
"select",
"is",
"None",
":",
"raise",
"PyrtlError",
"(",
"'problem with conditional assignment'",
")",
"if",
"len",
"(",
"select",
")",
"!=",
"1",
":",
"raise",
"PyrtlInternalError",
"(",
"'conditional predicate with length greater than 1'",
")",
"return",
"select",
",",
"pred_set"
] | Function to calculate the current "predicate" in the current context.
Returns a tuple of information: (predicate, pred_set).
The value pred_set is a set([ (predicate, bool), ... ]) as described in
the _reset_conditional_state | [
"Function",
"to",
"calculate",
"the",
"current",
"predicate",
"in",
"the",
"current",
"context",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/conditional.py#L215-L262 |
UCSBarchlab/PyRTL | pyrtl/analysis/estimate.py | area_estimation | def area_estimation(tech_in_nm=130, block=None):
""" Estimates the total area of the block.
:param tech_in_nm: the size of the circuit technology to be estimated
(for example, 65 is 65nm and 250 is 0.25um)
:return: tuple of estimated areas (logic, mem) in terms of mm^2
The estimations are based off of 130nm stdcell designs for the logic, and
custom memory blocks from the literature. The results are not fully validated
and we do not recommend that this function be used in carrying out science for
publication.
"""
def mem_area_estimate(tech_in_nm, bits, ports, is_rom):
# http://www.cs.ucsb.edu/~sherwood/pubs/ICCD-srammodel.pdf
# ROM is assumed to be 1/10th of area of SRAM
tech_in_um = tech_in_nm / 1000.0
area_estimate = 0.001 * tech_in_um**2.07 * bits**0.9 * ports**0.7 + 0.0048
return area_estimate if not is_rom else area_estimate / 10.0
# Subset of the raw data gathered from yosys, mapping to vsclib 130nm library
# Width Adder_Area Mult_Area (area in "tracks" as discussed below)
# 8 211 2684
# 16 495 12742
# 32 1110 49319
# 64 2397 199175
# 128 4966 749828
def adder_stdcell_estimate(width):
return width * 34.4 - 25.8
def multiplier_stdcell_estimate(width):
if width == 1:
return 5
elif width == 2:
return 39
elif width == 3:
return 219
else:
return -958 + (150 * width) + (45 * width**2)
def stdcell_estimate(net):
if net.op in 'w~sc':
return 0
elif net.op in '&|n':
return 40/8.0 * len(net.args[0]) # 40 lambda
elif net.op in '^=<>x':
return 80/8.0 * len(net.args[0]) # 80 lambda
elif net.op == 'r':
return 144/8.0 * len(net.args[0]) # 144 lambda
elif net.op in '+-':
return adder_stdcell_estimate(len(net.args[0]))
elif net.op == '*':
return multiplier_stdcell_estimate(len(net.args[0]))
elif net.op in 'm@':
return 0 # memories handled elsewhere
else:
raise PyrtlInternalError('Unable to estimate the following net '
'due to unimplemented op :\n%s' % str(net))
block = working_block(block)
# The functions above were gathered and calibrated by mapping
# reference designs to an openly available 130nm stdcell library.
# http://www.vlsitechnology.org/html/vsc_description.html
# http://www.vlsitechnology.org/html/cells/vsclib013/lib_gif_index.html
# In a standard cell design, each gate takes up a length of standard "track"
# in the chip. The functions above return that length for each of the different
# types of functions in the units of "tracks". In the 130nm process used,
# 1 lambda is 55nm, and 1 track is 8 lambda.
# first, sum up the area of all of the logic elements (including registers)
total_tracks = sum(stdcell_estimate(a_net) for a_net in block.logic)
total_length_in_nm = total_tracks * 8 * 55
# each track is then 72 lambda tall, and converted from nm2 to mm2
area_in_mm2_for_130nm = (total_length_in_nm * (72 * 55)) / 1e12
# scaling from 130nm to the target tech
logic_area = area_in_mm2_for_130nm / (130.0/tech_in_nm)**2
# now sum up the area of the memories
mem_area = 0
for mem in set(net.op_param[1] for net in block.logic_subset('@m')):
bits, ports, is_rom = _bits_ports_and_isrom_from_memory(mem)
mem_area += mem_area_estimate(tech_in_nm, bits, ports, is_rom)
return logic_area, mem_area | python | def area_estimation(tech_in_nm=130, block=None):
""" Estimates the total area of the block.
:param tech_in_nm: the size of the circuit technology to be estimated
(for example, 65 is 65nm and 250 is 0.25um)
:return: tuple of estimated areas (logic, mem) in terms of mm^2
The estimations are based off of 130nm stdcell designs for the logic, and
custom memory blocks from the literature. The results are not fully validated
and we do not recommend that this function be used in carrying out science for
publication.
"""
def mem_area_estimate(tech_in_nm, bits, ports, is_rom):
# http://www.cs.ucsb.edu/~sherwood/pubs/ICCD-srammodel.pdf
# ROM is assumed to be 1/10th of area of SRAM
tech_in_um = tech_in_nm / 1000.0
area_estimate = 0.001 * tech_in_um**2.07 * bits**0.9 * ports**0.7 + 0.0048
return area_estimate if not is_rom else area_estimate / 10.0
# Subset of the raw data gathered from yosys, mapping to vsclib 130nm library
# Width Adder_Area Mult_Area (area in "tracks" as discussed below)
# 8 211 2684
# 16 495 12742
# 32 1110 49319
# 64 2397 199175
# 128 4966 749828
def adder_stdcell_estimate(width):
return width * 34.4 - 25.8
def multiplier_stdcell_estimate(width):
if width == 1:
return 5
elif width == 2:
return 39
elif width == 3:
return 219
else:
return -958 + (150 * width) + (45 * width**2)
def stdcell_estimate(net):
if net.op in 'w~sc':
return 0
elif net.op in '&|n':
return 40/8.0 * len(net.args[0]) # 40 lambda
elif net.op in '^=<>x':
return 80/8.0 * len(net.args[0]) # 80 lambda
elif net.op == 'r':
return 144/8.0 * len(net.args[0]) # 144 lambda
elif net.op in '+-':
return adder_stdcell_estimate(len(net.args[0]))
elif net.op == '*':
return multiplier_stdcell_estimate(len(net.args[0]))
elif net.op in 'm@':
return 0 # memories handled elsewhere
else:
raise PyrtlInternalError('Unable to estimate the following net '
'due to unimplemented op :\n%s' % str(net))
block = working_block(block)
# The functions above were gathered and calibrated by mapping
# reference designs to an openly available 130nm stdcell library.
# http://www.vlsitechnology.org/html/vsc_description.html
# http://www.vlsitechnology.org/html/cells/vsclib013/lib_gif_index.html
# In a standard cell design, each gate takes up a length of standard "track"
# in the chip. The functions above return that length for each of the different
# types of functions in the units of "tracks". In the 130nm process used,
# 1 lambda is 55nm, and 1 track is 8 lambda.
# first, sum up the area of all of the logic elements (including registers)
total_tracks = sum(stdcell_estimate(a_net) for a_net in block.logic)
total_length_in_nm = total_tracks * 8 * 55
# each track is then 72 lambda tall, and converted from nm2 to mm2
area_in_mm2_for_130nm = (total_length_in_nm * (72 * 55)) / 1e12
# scaling from 130nm to the target tech
logic_area = area_in_mm2_for_130nm / (130.0/tech_in_nm)**2
# now sum up the area of the memories
mem_area = 0
for mem in set(net.op_param[1] for net in block.logic_subset('@m')):
bits, ports, is_rom = _bits_ports_and_isrom_from_memory(mem)
mem_area += mem_area_estimate(tech_in_nm, bits, ports, is_rom)
return logic_area, mem_area | [
"def",
"area_estimation",
"(",
"tech_in_nm",
"=",
"130",
",",
"block",
"=",
"None",
")",
":",
"def",
"mem_area_estimate",
"(",
"tech_in_nm",
",",
"bits",
",",
"ports",
",",
"is_rom",
")",
":",
"# http://www.cs.ucsb.edu/~sherwood/pubs/ICCD-srammodel.pdf",
"# ROM is assumed to be 1/10th of area of SRAM",
"tech_in_um",
"=",
"tech_in_nm",
"/",
"1000.0",
"area_estimate",
"=",
"0.001",
"*",
"tech_in_um",
"**",
"2.07",
"*",
"bits",
"**",
"0.9",
"*",
"ports",
"**",
"0.7",
"+",
"0.0048",
"return",
"area_estimate",
"if",
"not",
"is_rom",
"else",
"area_estimate",
"/",
"10.0",
"# Subset of the raw data gathered from yosys, mapping to vsclib 130nm library",
"# Width Adder_Area Mult_Area (area in \"tracks\" as discussed below)",
"# 8 211 2684",
"# 16 495 12742",
"# 32 1110 49319",
"# 64 2397 199175",
"# 128 4966 749828",
"def",
"adder_stdcell_estimate",
"(",
"width",
")",
":",
"return",
"width",
"*",
"34.4",
"-",
"25.8",
"def",
"multiplier_stdcell_estimate",
"(",
"width",
")",
":",
"if",
"width",
"==",
"1",
":",
"return",
"5",
"elif",
"width",
"==",
"2",
":",
"return",
"39",
"elif",
"width",
"==",
"3",
":",
"return",
"219",
"else",
":",
"return",
"-",
"958",
"+",
"(",
"150",
"*",
"width",
")",
"+",
"(",
"45",
"*",
"width",
"**",
"2",
")",
"def",
"stdcell_estimate",
"(",
"net",
")",
":",
"if",
"net",
".",
"op",
"in",
"'w~sc'",
":",
"return",
"0",
"elif",
"net",
".",
"op",
"in",
"'&|n'",
":",
"return",
"40",
"/",
"8.0",
"*",
"len",
"(",
"net",
".",
"args",
"[",
"0",
"]",
")",
"# 40 lambda",
"elif",
"net",
".",
"op",
"in",
"'^=<>x'",
":",
"return",
"80",
"/",
"8.0",
"*",
"len",
"(",
"net",
".",
"args",
"[",
"0",
"]",
")",
"# 80 lambda",
"elif",
"net",
".",
"op",
"==",
"'r'",
":",
"return",
"144",
"/",
"8.0",
"*",
"len",
"(",
"net",
".",
"args",
"[",
"0",
"]",
")",
"# 144 lambda",
"elif",
"net",
".",
"op",
"in",
"'+-'",
":",
"return",
"adder_stdcell_estimate",
"(",
"len",
"(",
"net",
".",
"args",
"[",
"0",
"]",
")",
")",
"elif",
"net",
".",
"op",
"==",
"'*'",
":",
"return",
"multiplier_stdcell_estimate",
"(",
"len",
"(",
"net",
".",
"args",
"[",
"0",
"]",
")",
")",
"elif",
"net",
".",
"op",
"in",
"'m@'",
":",
"return",
"0",
"# memories handled elsewhere",
"else",
":",
"raise",
"PyrtlInternalError",
"(",
"'Unable to estimate the following net '",
"'due to unimplemented op :\\n%s'",
"%",
"str",
"(",
"net",
")",
")",
"block",
"=",
"working_block",
"(",
"block",
")",
"# The functions above were gathered and calibrated by mapping",
"# reference designs to an openly available 130nm stdcell library.",
"# http://www.vlsitechnology.org/html/vsc_description.html",
"# http://www.vlsitechnology.org/html/cells/vsclib013/lib_gif_index.html",
"# In a standard cell design, each gate takes up a length of standard \"track\"",
"# in the chip. The functions above return that length for each of the different",
"# types of functions in the units of \"tracks\". In the 130nm process used,",
"# 1 lambda is 55nm, and 1 track is 8 lambda.",
"# first, sum up the area of all of the logic elements (including registers)",
"total_tracks",
"=",
"sum",
"(",
"stdcell_estimate",
"(",
"a_net",
")",
"for",
"a_net",
"in",
"block",
".",
"logic",
")",
"total_length_in_nm",
"=",
"total_tracks",
"*",
"8",
"*",
"55",
"# each track is then 72 lambda tall, and converted from nm2 to mm2",
"area_in_mm2_for_130nm",
"=",
"(",
"total_length_in_nm",
"*",
"(",
"72",
"*",
"55",
")",
")",
"/",
"1e12",
"# scaling from 130nm to the target tech",
"logic_area",
"=",
"area_in_mm2_for_130nm",
"/",
"(",
"130.0",
"/",
"tech_in_nm",
")",
"**",
"2",
"# now sum up the area of the memories",
"mem_area",
"=",
"0",
"for",
"mem",
"in",
"set",
"(",
"net",
".",
"op_param",
"[",
"1",
"]",
"for",
"net",
"in",
"block",
".",
"logic_subset",
"(",
"'@m'",
")",
")",
":",
"bits",
",",
"ports",
",",
"is_rom",
"=",
"_bits_ports_and_isrom_from_memory",
"(",
"mem",
")",
"mem_area",
"+=",
"mem_area_estimate",
"(",
"tech_in_nm",
",",
"bits",
",",
"ports",
",",
"is_rom",
")",
"return",
"logic_area",
",",
"mem_area"
] | Estimates the total area of the block.
:param tech_in_nm: the size of the circuit technology to be estimated
(for example, 65 is 65nm and 250 is 0.25um)
:return: tuple of estimated areas (logic, mem) in terms of mm^2
The estimations are based off of 130nm stdcell designs for the logic, and
custom memory blocks from the literature. The results are not fully validated
and we do not recommend that this function be used in carrying out science for
publication. | [
"Estimates",
"the",
"total",
"area",
"of",
"the",
"block",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/analysis/estimate.py#L29-L116 |
UCSBarchlab/PyRTL | pyrtl/analysis/estimate.py | _bits_ports_and_isrom_from_memory | def _bits_ports_and_isrom_from_memory(mem):
""" Helper to extract mem bits and ports for estimation. """
is_rom = False
bits = 2**mem.addrwidth * mem.bitwidth
read_ports = len(mem.readport_nets)
try:
write_ports = len(mem.writeport_nets)
except AttributeError: # dealing with ROMs
if not isinstance(mem, RomBlock):
raise PyrtlInternalError('Mem with no writeport_nets attribute'
' but not a ROM? Thats an error')
write_ports = 0
is_rom = True
ports = max(read_ports, write_ports)
return bits, ports, is_rom | python | def _bits_ports_and_isrom_from_memory(mem):
""" Helper to extract mem bits and ports for estimation. """
is_rom = False
bits = 2**mem.addrwidth * mem.bitwidth
read_ports = len(mem.readport_nets)
try:
write_ports = len(mem.writeport_nets)
except AttributeError: # dealing with ROMs
if not isinstance(mem, RomBlock):
raise PyrtlInternalError('Mem with no writeport_nets attribute'
' but not a ROM? Thats an error')
write_ports = 0
is_rom = True
ports = max(read_ports, write_ports)
return bits, ports, is_rom | [
"def",
"_bits_ports_and_isrom_from_memory",
"(",
"mem",
")",
":",
"is_rom",
"=",
"False",
"bits",
"=",
"2",
"**",
"mem",
".",
"addrwidth",
"*",
"mem",
".",
"bitwidth",
"read_ports",
"=",
"len",
"(",
"mem",
".",
"readport_nets",
")",
"try",
":",
"write_ports",
"=",
"len",
"(",
"mem",
".",
"writeport_nets",
")",
"except",
"AttributeError",
":",
"# dealing with ROMs",
"if",
"not",
"isinstance",
"(",
"mem",
",",
"RomBlock",
")",
":",
"raise",
"PyrtlInternalError",
"(",
"'Mem with no writeport_nets attribute'",
"' but not a ROM? Thats an error'",
")",
"write_ports",
"=",
"0",
"is_rom",
"=",
"True",
"ports",
"=",
"max",
"(",
"read_ports",
",",
"write_ports",
")",
"return",
"bits",
",",
"ports",
",",
"is_rom"
] | Helper to extract mem bits and ports for estimation. | [
"Helper",
"to",
"extract",
"mem",
"bits",
"and",
"ports",
"for",
"estimation",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/analysis/estimate.py#L119-L133 |
UCSBarchlab/PyRTL | pyrtl/analysis/estimate.py | yosys_area_delay | def yosys_area_delay(library, abc_cmd=None, block=None):
""" Synthesize with Yosys and return estimate of area and delay.
:param library: stdcell library file to target in liberty format
:param abc_cmd: string of commands for yosys to pass to abc for synthesis
:param block: pyrtl block to analyze
:return: a tuple of numbers: area, delay
The area and delay are returned in units as defined by the stdcell
library. In the standard vsc 130nm library, the area is in a number of
"tracks", each of which is about 1.74 square um (see area estimation
for more details) and the delay is in ps.
http://www.vlsitechnology.org/html/vsc_description.html
May raise `PyrtlError` if yosys is not configured correctly, and
`PyrtlInternalError` if the call to yosys was not able successfully
"""
if abc_cmd is None:
abc_cmd = 'strash;scorr;ifraig;retime;dch,-f;map;print_stats;'
else:
# first, replace whitespace with commas as per yosys requirements
re.sub(r"\s+", ',', abc_cmd)
# then append with "print_stats" to generate the area and delay info
abc_cmd = '%s;print_stats;' % abc_cmd
def extract_area_delay_from_yosys_output(yosys_output):
report_lines = [line for line in yosys_output.split('\n') if 'ABC: netlist' in line]
area = re.match('.*area\s*=\s*([0-9\.]*)', report_lines[0]).group(1)
delay = re.match('.*delay\s*=\s*([0-9\.]*)', report_lines[0]).group(1)
return float(area), float(delay)
yosys_arg_template = """-p
read_verilog %s;
synth -top toplevel;
dfflibmap -liberty %s;
abc -liberty %s -script +%s
"""
temp_d, temp_path = tempfile.mkstemp(suffix='.v')
try:
# write the verilog to a temp
with os.fdopen(temp_d, 'w') as f:
OutputToVerilog(f, block=block)
# call yosys on the temp, and grab the output
yosys_arg = yosys_arg_template % (temp_path, library, library, abc_cmd)
yosys_output = subprocess.check_output(['yosys', yosys_arg])
area, delay = extract_area_delay_from_yosys_output(yosys_output)
except (subprocess.CalledProcessError, ValueError) as e:
print('Error with call to yosys...', file=sys.stderr)
print('---------------------------------------------', file=sys.stderr)
print(e.output, file=sys.stderr)
print('---------------------------------------------', file=sys.stderr)
raise PyrtlError('Yosys callfailed')
except OSError as e:
print('Error with call to yosys...', file=sys.stderr)
raise PyrtlError('Call to yosys failed (not installed or on path?)')
finally:
os.remove(temp_path)
return area, delay | python | def yosys_area_delay(library, abc_cmd=None, block=None):
""" Synthesize with Yosys and return estimate of area and delay.
:param library: stdcell library file to target in liberty format
:param abc_cmd: string of commands for yosys to pass to abc for synthesis
:param block: pyrtl block to analyze
:return: a tuple of numbers: area, delay
The area and delay are returned in units as defined by the stdcell
library. In the standard vsc 130nm library, the area is in a number of
"tracks", each of which is about 1.74 square um (see area estimation
for more details) and the delay is in ps.
http://www.vlsitechnology.org/html/vsc_description.html
May raise `PyrtlError` if yosys is not configured correctly, and
`PyrtlInternalError` if the call to yosys was not able successfully
"""
if abc_cmd is None:
abc_cmd = 'strash;scorr;ifraig;retime;dch,-f;map;print_stats;'
else:
# first, replace whitespace with commas as per yosys requirements
re.sub(r"\s+", ',', abc_cmd)
# then append with "print_stats" to generate the area and delay info
abc_cmd = '%s;print_stats;' % abc_cmd
def extract_area_delay_from_yosys_output(yosys_output):
report_lines = [line for line in yosys_output.split('\n') if 'ABC: netlist' in line]
area = re.match('.*area\s*=\s*([0-9\.]*)', report_lines[0]).group(1)
delay = re.match('.*delay\s*=\s*([0-9\.]*)', report_lines[0]).group(1)
return float(area), float(delay)
yosys_arg_template = """-p
read_verilog %s;
synth -top toplevel;
dfflibmap -liberty %s;
abc -liberty %s -script +%s
"""
temp_d, temp_path = tempfile.mkstemp(suffix='.v')
try:
# write the verilog to a temp
with os.fdopen(temp_d, 'w') as f:
OutputToVerilog(f, block=block)
# call yosys on the temp, and grab the output
yosys_arg = yosys_arg_template % (temp_path, library, library, abc_cmd)
yosys_output = subprocess.check_output(['yosys', yosys_arg])
area, delay = extract_area_delay_from_yosys_output(yosys_output)
except (subprocess.CalledProcessError, ValueError) as e:
print('Error with call to yosys...', file=sys.stderr)
print('---------------------------------------------', file=sys.stderr)
print(e.output, file=sys.stderr)
print('---------------------------------------------', file=sys.stderr)
raise PyrtlError('Yosys callfailed')
except OSError as e:
print('Error with call to yosys...', file=sys.stderr)
raise PyrtlError('Call to yosys failed (not installed or on path?)')
finally:
os.remove(temp_path)
return area, delay | [
"def",
"yosys_area_delay",
"(",
"library",
",",
"abc_cmd",
"=",
"None",
",",
"block",
"=",
"None",
")",
":",
"if",
"abc_cmd",
"is",
"None",
":",
"abc_cmd",
"=",
"'strash;scorr;ifraig;retime;dch,-f;map;print_stats;'",
"else",
":",
"# first, replace whitespace with commas as per yosys requirements",
"re",
".",
"sub",
"(",
"r\"\\s+\"",
",",
"','",
",",
"abc_cmd",
")",
"# then append with \"print_stats\" to generate the area and delay info",
"abc_cmd",
"=",
"'%s;print_stats;'",
"%",
"abc_cmd",
"def",
"extract_area_delay_from_yosys_output",
"(",
"yosys_output",
")",
":",
"report_lines",
"=",
"[",
"line",
"for",
"line",
"in",
"yosys_output",
".",
"split",
"(",
"'\\n'",
")",
"if",
"'ABC: netlist'",
"in",
"line",
"]",
"area",
"=",
"re",
".",
"match",
"(",
"'.*area\\s*=\\s*([0-9\\.]*)'",
",",
"report_lines",
"[",
"0",
"]",
")",
".",
"group",
"(",
"1",
")",
"delay",
"=",
"re",
".",
"match",
"(",
"'.*delay\\s*=\\s*([0-9\\.]*)'",
",",
"report_lines",
"[",
"0",
"]",
")",
".",
"group",
"(",
"1",
")",
"return",
"float",
"(",
"area",
")",
",",
"float",
"(",
"delay",
")",
"yosys_arg_template",
"=",
"\"\"\"-p\n read_verilog %s;\n synth -top toplevel;\n dfflibmap -liberty %s;\n abc -liberty %s -script +%s\n \"\"\"",
"temp_d",
",",
"temp_path",
"=",
"tempfile",
".",
"mkstemp",
"(",
"suffix",
"=",
"'.v'",
")",
"try",
":",
"# write the verilog to a temp",
"with",
"os",
".",
"fdopen",
"(",
"temp_d",
",",
"'w'",
")",
"as",
"f",
":",
"OutputToVerilog",
"(",
"f",
",",
"block",
"=",
"block",
")",
"# call yosys on the temp, and grab the output",
"yosys_arg",
"=",
"yosys_arg_template",
"%",
"(",
"temp_path",
",",
"library",
",",
"library",
",",
"abc_cmd",
")",
"yosys_output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'yosys'",
",",
"yosys_arg",
"]",
")",
"area",
",",
"delay",
"=",
"extract_area_delay_from_yosys_output",
"(",
"yosys_output",
")",
"except",
"(",
"subprocess",
".",
"CalledProcessError",
",",
"ValueError",
")",
"as",
"e",
":",
"print",
"(",
"'Error with call to yosys...'",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"print",
"(",
"'---------------------------------------------'",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"print",
"(",
"e",
".",
"output",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"print",
"(",
"'---------------------------------------------'",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"raise",
"PyrtlError",
"(",
"'Yosys callfailed'",
")",
"except",
"OSError",
"as",
"e",
":",
"print",
"(",
"'Error with call to yosys...'",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"raise",
"PyrtlError",
"(",
"'Call to yosys failed (not installed or on path?)'",
")",
"finally",
":",
"os",
".",
"remove",
"(",
"temp_path",
")",
"return",
"area",
",",
"delay"
] | Synthesize with Yosys and return estimate of area and delay.
:param library: stdcell library file to target in liberty format
:param abc_cmd: string of commands for yosys to pass to abc for synthesis
:param block: pyrtl block to analyze
:return: a tuple of numbers: area, delay
The area and delay are returned in units as defined by the stdcell
library. In the standard vsc 130nm library, the area is in a number of
"tracks", each of which is about 1.74 square um (see area estimation
for more details) and the delay is in ps.
http://www.vlsitechnology.org/html/vsc_description.html
May raise `PyrtlError` if yosys is not configured correctly, and
`PyrtlInternalError` if the call to yosys was not able successfully | [
"Synthesize",
"with",
"Yosys",
"and",
"return",
"estimate",
"of",
"area",
"and",
"delay",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/analysis/estimate.py#L329-L389 |
UCSBarchlab/PyRTL | pyrtl/analysis/estimate.py | TimingAnalysis.max_freq | def max_freq(self, tech_in_nm=130, ffoverhead=None):
""" Estimates the max frequency of a block in MHz.
:param tech_in_nm: the size of the circuit technology to be estimated
(for example, 65 is 65nm and 250 is 0.25um)
:param ffoverhead: setup and ff propagation delay in picoseconds
:return: a number representing an estimate of the max frequency in Mhz
If a timing_map has already been generated by timing_analysis, it will be used
to generate the estimate (and `gate_delay_funcs` will be ignored). Regardless,
all params are optional and have reasonable default values. Estimation is based
on Dennard Scaling assumption and does not include wiring effect -- as a result
the estimates may be optimistic (especially below 65nm).
"""
cp_length = self.max_length()
scale_factor = 130.0 / tech_in_nm
if ffoverhead is None:
clock_period_in_ps = scale_factor * (cp_length + 189 + 194)
else:
clock_period_in_ps = (scale_factor * cp_length) + ffoverhead
return 1e6 * 1.0/clock_period_in_ps | python | def max_freq(self, tech_in_nm=130, ffoverhead=None):
""" Estimates the max frequency of a block in MHz.
:param tech_in_nm: the size of the circuit technology to be estimated
(for example, 65 is 65nm and 250 is 0.25um)
:param ffoverhead: setup and ff propagation delay in picoseconds
:return: a number representing an estimate of the max frequency in Mhz
If a timing_map has already been generated by timing_analysis, it will be used
to generate the estimate (and `gate_delay_funcs` will be ignored). Regardless,
all params are optional and have reasonable default values. Estimation is based
on Dennard Scaling assumption and does not include wiring effect -- as a result
the estimates may be optimistic (especially below 65nm).
"""
cp_length = self.max_length()
scale_factor = 130.0 / tech_in_nm
if ffoverhead is None:
clock_period_in_ps = scale_factor * (cp_length + 189 + 194)
else:
clock_period_in_ps = (scale_factor * cp_length) + ffoverhead
return 1e6 * 1.0/clock_period_in_ps | [
"def",
"max_freq",
"(",
"self",
",",
"tech_in_nm",
"=",
"130",
",",
"ffoverhead",
"=",
"None",
")",
":",
"cp_length",
"=",
"self",
".",
"max_length",
"(",
")",
"scale_factor",
"=",
"130.0",
"/",
"tech_in_nm",
"if",
"ffoverhead",
"is",
"None",
":",
"clock_period_in_ps",
"=",
"scale_factor",
"*",
"(",
"cp_length",
"+",
"189",
"+",
"194",
")",
"else",
":",
"clock_period_in_ps",
"=",
"(",
"scale_factor",
"*",
"cp_length",
")",
"+",
"ffoverhead",
"return",
"1e6",
"*",
"1.0",
"/",
"clock_period_in_ps"
] | Estimates the max frequency of a block in MHz.
:param tech_in_nm: the size of the circuit technology to be estimated
(for example, 65 is 65nm and 250 is 0.25um)
:param ffoverhead: setup and ff propagation delay in picoseconds
:return: a number representing an estimate of the max frequency in Mhz
If a timing_map has already been generated by timing_analysis, it will be used
to generate the estimate (and `gate_delay_funcs` will be ignored). Regardless,
all params are optional and have reasonable default values. Estimation is based
on Dennard Scaling assumption and does not include wiring effect -- as a result
the estimates may be optimistic (especially below 65nm). | [
"Estimates",
"the",
"max",
"frequency",
"of",
"a",
"block",
"in",
"MHz",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/analysis/estimate.py#L234-L254 |
UCSBarchlab/PyRTL | pyrtl/analysis/estimate.py | TimingAnalysis.critical_path | def critical_path(self, print_cp=True, cp_limit=100):
""" Takes a timing map and returns the critical paths of the system.
:param print_cp: Whether to print the critical path to the terminal
after calculation
:return: a list containing tuples with the 'first' wire as the
first value and the critical paths (which themselves are lists
of nets) as the second
"""
critical_paths = [] # storage of all completed critical paths
wire_src_map, dst_map = self.block.net_connections()
def critical_path_pass(old_critical_path, first_wire):
if isinstance(first_wire, (Input, Const, Register)):
critical_paths.append((first_wire, old_critical_path))
return
if len(critical_paths) >= cp_limit:
raise self._TooManyCPsError()
source = wire_src_map[first_wire]
critical_path = [source]
critical_path.extend(old_critical_path)
arg_max_time = max(self.timing_map[arg_wire] for arg_wire in source.args)
for arg_wire in source.args:
# if the time for both items are the max, both will be on a critical path
if self.timing_map[arg_wire] == arg_max_time:
critical_path_pass(critical_path, arg_wire)
max_time = self.max_length()
try:
for wire_pair in self.timing_map.items():
if wire_pair[1] == max_time:
critical_path_pass([], wire_pair[0])
except self._TooManyCPsError:
print("Critical path count limit reached")
if print_cp:
self.print_critical_paths(critical_paths)
return critical_paths | python | def critical_path(self, print_cp=True, cp_limit=100):
""" Takes a timing map and returns the critical paths of the system.
:param print_cp: Whether to print the critical path to the terminal
after calculation
:return: a list containing tuples with the 'first' wire as the
first value and the critical paths (which themselves are lists
of nets) as the second
"""
critical_paths = [] # storage of all completed critical paths
wire_src_map, dst_map = self.block.net_connections()
def critical_path_pass(old_critical_path, first_wire):
if isinstance(first_wire, (Input, Const, Register)):
critical_paths.append((first_wire, old_critical_path))
return
if len(critical_paths) >= cp_limit:
raise self._TooManyCPsError()
source = wire_src_map[first_wire]
critical_path = [source]
critical_path.extend(old_critical_path)
arg_max_time = max(self.timing_map[arg_wire] for arg_wire in source.args)
for arg_wire in source.args:
# if the time for both items are the max, both will be on a critical path
if self.timing_map[arg_wire] == arg_max_time:
critical_path_pass(critical_path, arg_wire)
max_time = self.max_length()
try:
for wire_pair in self.timing_map.items():
if wire_pair[1] == max_time:
critical_path_pass([], wire_pair[0])
except self._TooManyCPsError:
print("Critical path count limit reached")
if print_cp:
self.print_critical_paths(critical_paths)
return critical_paths | [
"def",
"critical_path",
"(",
"self",
",",
"print_cp",
"=",
"True",
",",
"cp_limit",
"=",
"100",
")",
":",
"critical_paths",
"=",
"[",
"]",
"# storage of all completed critical paths",
"wire_src_map",
",",
"dst_map",
"=",
"self",
".",
"block",
".",
"net_connections",
"(",
")",
"def",
"critical_path_pass",
"(",
"old_critical_path",
",",
"first_wire",
")",
":",
"if",
"isinstance",
"(",
"first_wire",
",",
"(",
"Input",
",",
"Const",
",",
"Register",
")",
")",
":",
"critical_paths",
".",
"append",
"(",
"(",
"first_wire",
",",
"old_critical_path",
")",
")",
"return",
"if",
"len",
"(",
"critical_paths",
")",
">=",
"cp_limit",
":",
"raise",
"self",
".",
"_TooManyCPsError",
"(",
")",
"source",
"=",
"wire_src_map",
"[",
"first_wire",
"]",
"critical_path",
"=",
"[",
"source",
"]",
"critical_path",
".",
"extend",
"(",
"old_critical_path",
")",
"arg_max_time",
"=",
"max",
"(",
"self",
".",
"timing_map",
"[",
"arg_wire",
"]",
"for",
"arg_wire",
"in",
"source",
".",
"args",
")",
"for",
"arg_wire",
"in",
"source",
".",
"args",
":",
"# if the time for both items are the max, both will be on a critical path",
"if",
"self",
".",
"timing_map",
"[",
"arg_wire",
"]",
"==",
"arg_max_time",
":",
"critical_path_pass",
"(",
"critical_path",
",",
"arg_wire",
")",
"max_time",
"=",
"self",
".",
"max_length",
"(",
")",
"try",
":",
"for",
"wire_pair",
"in",
"self",
".",
"timing_map",
".",
"items",
"(",
")",
":",
"if",
"wire_pair",
"[",
"1",
"]",
"==",
"max_time",
":",
"critical_path_pass",
"(",
"[",
"]",
",",
"wire_pair",
"[",
"0",
"]",
")",
"except",
"self",
".",
"_TooManyCPsError",
":",
"print",
"(",
"\"Critical path count limit reached\"",
")",
"if",
"print_cp",
":",
"self",
".",
"print_critical_paths",
"(",
"critical_paths",
")",
"return",
"critical_paths"
] | Takes a timing map and returns the critical paths of the system.
:param print_cp: Whether to print the critical path to the terminal
after calculation
:return: a list containing tuples with the 'first' wire as the
first value and the critical paths (which themselves are lists
of nets) as the second | [
"Takes",
"a",
"timing",
"map",
"and",
"returns",
"the",
"critical",
"paths",
"of",
"the",
"system",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/analysis/estimate.py#L267-L306 |
UCSBarchlab/PyRTL | pyrtl/analysis/estimate.py | TimingAnalysis.print_critical_paths | def print_critical_paths(critical_paths):
""" Prints the results of the critical path length analysis.
Done by default by the `timing_critical_path()` function.
"""
line_indent = " " * 2
# print the critical path
for cp_with_num in enumerate(critical_paths):
print("Critical path", cp_with_num[0], ":")
print(line_indent, "The first wire is:", cp_with_num[1][0])
for net in cp_with_num[1][1]:
print(line_indent, (net))
print() | python | def print_critical_paths(critical_paths):
""" Prints the results of the critical path length analysis.
Done by default by the `timing_critical_path()` function.
"""
line_indent = " " * 2
# print the critical path
for cp_with_num in enumerate(critical_paths):
print("Critical path", cp_with_num[0], ":")
print(line_indent, "The first wire is:", cp_with_num[1][0])
for net in cp_with_num[1][1]:
print(line_indent, (net))
print() | [
"def",
"print_critical_paths",
"(",
"critical_paths",
")",
":",
"line_indent",
"=",
"\" \"",
"*",
"2",
"# print the critical path",
"for",
"cp_with_num",
"in",
"enumerate",
"(",
"critical_paths",
")",
":",
"print",
"(",
"\"Critical path\"",
",",
"cp_with_num",
"[",
"0",
"]",
",",
"\":\"",
")",
"print",
"(",
"line_indent",
",",
"\"The first wire is:\"",
",",
"cp_with_num",
"[",
"1",
"]",
"[",
"0",
"]",
")",
"for",
"net",
"in",
"cp_with_num",
"[",
"1",
"]",
"[",
"1",
"]",
":",
"print",
"(",
"line_indent",
",",
"(",
"net",
")",
")",
"print",
"(",
")"
] | Prints the results of the critical path length analysis.
Done by default by the `timing_critical_path()` function. | [
"Prints",
"the",
"results",
"of",
"the",
"critical",
"path",
"length",
"analysis",
".",
"Done",
"by",
"default",
"by",
"the",
"timing_critical_path",
"()",
"function",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/analysis/estimate.py#L309-L320 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client._post | def _post(self, endpoint, data, **kwargs):
"""
Method to perform POST request on the API.
:param endpoint: Endpoint of the API.
:param data: POST DATA for the request.
:param kwargs: Other keyword arguments for requests.
:return: Response of the POST request.
"""
return self._request(endpoint, 'post', data, **kwargs) | python | def _post(self, endpoint, data, **kwargs):
"""
Method to perform POST request on the API.
:param endpoint: Endpoint of the API.
:param data: POST DATA for the request.
:param kwargs: Other keyword arguments for requests.
:return: Response of the POST request.
"""
return self._request(endpoint, 'post', data, **kwargs) | [
"def",
"_post",
"(",
"self",
",",
"endpoint",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_request",
"(",
"endpoint",
",",
"'post'",
",",
"data",
",",
"*",
"*",
"kwargs",
")"
] | Method to perform POST request on the API.
:param endpoint: Endpoint of the API.
:param data: POST DATA for the request.
:param kwargs: Other keyword arguments for requests.
:return: Response of the POST request. | [
"Method",
"to",
"perform",
"POST",
"request",
"on",
"the",
"API",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L46-L56 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client._request | def _request(self, endpoint, method, data=None, **kwargs):
"""
Method to hanle both GET and POST requests.
:param endpoint: Endpoint of the API.
:param method: Method of HTTP request.
:param data: POST DATA for the request.
:param kwargs: Other keyword arguments.
:return: Response for the request.
"""
final_url = self.url + endpoint
if not self._is_authenticated:
raise LoginRequired
rq = self.session
if method == 'get':
request = rq.get(final_url, **kwargs)
else:
request = rq.post(final_url, data, **kwargs)
request.raise_for_status()
request.encoding = 'utf_8'
if len(request.text) == 0:
data = json.loads('{}')
else:
try:
data = json.loads(request.text)
except ValueError:
data = request.text
return data | python | def _request(self, endpoint, method, data=None, **kwargs):
"""
Method to hanle both GET and POST requests.
:param endpoint: Endpoint of the API.
:param method: Method of HTTP request.
:param data: POST DATA for the request.
:param kwargs: Other keyword arguments.
:return: Response for the request.
"""
final_url = self.url + endpoint
if not self._is_authenticated:
raise LoginRequired
rq = self.session
if method == 'get':
request = rq.get(final_url, **kwargs)
else:
request = rq.post(final_url, data, **kwargs)
request.raise_for_status()
request.encoding = 'utf_8'
if len(request.text) == 0:
data = json.loads('{}')
else:
try:
data = json.loads(request.text)
except ValueError:
data = request.text
return data | [
"def",
"_request",
"(",
"self",
",",
"endpoint",
",",
"method",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"final_url",
"=",
"self",
".",
"url",
"+",
"endpoint",
"if",
"not",
"self",
".",
"_is_authenticated",
":",
"raise",
"LoginRequired",
"rq",
"=",
"self",
".",
"session",
"if",
"method",
"==",
"'get'",
":",
"request",
"=",
"rq",
".",
"get",
"(",
"final_url",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"request",
"=",
"rq",
".",
"post",
"(",
"final_url",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
"request",
".",
"raise_for_status",
"(",
")",
"request",
".",
"encoding",
"=",
"'utf_8'",
"if",
"len",
"(",
"request",
".",
"text",
")",
"==",
"0",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"'{}'",
")",
"else",
":",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"request",
".",
"text",
")",
"except",
"ValueError",
":",
"data",
"=",
"request",
".",
"text",
"return",
"data"
] | Method to hanle both GET and POST requests.
:param endpoint: Endpoint of the API.
:param method: Method of HTTP request.
:param data: POST DATA for the request.
:param kwargs: Other keyword arguments.
:return: Response for the request. | [
"Method",
"to",
"hanle",
"both",
"GET",
"and",
"POST",
"requests",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L58-L91 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.login | def login(self, username='admin', password='admin'):
"""
Method to authenticate the qBittorrent Client.
Declares a class attribute named ``session`` which
stores the authenticated session if the login is correct.
Else, shows the login error.
:param username: Username.
:param password: Password.
:return: Response to login request to the API.
"""
self.session = requests.Session()
login = self.session.post(self.url+'login',
data={'username': username,
'password': password})
if login.text == 'Ok.':
self._is_authenticated = True
else:
return login.text | python | def login(self, username='admin', password='admin'):
"""
Method to authenticate the qBittorrent Client.
Declares a class attribute named ``session`` which
stores the authenticated session if the login is correct.
Else, shows the login error.
:param username: Username.
:param password: Password.
:return: Response to login request to the API.
"""
self.session = requests.Session()
login = self.session.post(self.url+'login',
data={'username': username,
'password': password})
if login.text == 'Ok.':
self._is_authenticated = True
else:
return login.text | [
"def",
"login",
"(",
"self",
",",
"username",
"=",
"'admin'",
",",
"password",
"=",
"'admin'",
")",
":",
"self",
".",
"session",
"=",
"requests",
".",
"Session",
"(",
")",
"login",
"=",
"self",
".",
"session",
".",
"post",
"(",
"self",
".",
"url",
"+",
"'login'",
",",
"data",
"=",
"{",
"'username'",
":",
"username",
",",
"'password'",
":",
"password",
"}",
")",
"if",
"login",
".",
"text",
"==",
"'Ok.'",
":",
"self",
".",
"_is_authenticated",
"=",
"True",
"else",
":",
"return",
"login",
".",
"text"
] | Method to authenticate the qBittorrent Client.
Declares a class attribute named ``session`` which
stores the authenticated session if the login is correct.
Else, shows the login error.
:param username: Username.
:param password: Password.
:return: Response to login request to the API. | [
"Method",
"to",
"authenticate",
"the",
"qBittorrent",
"Client",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L93-L113 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.torrents | def torrents(self, **filters):
"""
Returns a list of torrents matching the supplied filters.
:param filter: Current status of the torrents.
:param category: Fetch all torrents with the supplied label.
:param sort: Sort torrents by.
:param reverse: Enable reverse sorting.
:param limit: Limit the number of torrents returned.
:param offset: Set offset (if less than 0, offset from end).
:return: list() of torrent with matching filter.
"""
params = {}
for name, value in filters.items():
# make sure that old 'status' argument still works
name = 'filter' if name == 'status' else name
params[name] = value
return self._get('query/torrents', params=params) | python | def torrents(self, **filters):
"""
Returns a list of torrents matching the supplied filters.
:param filter: Current status of the torrents.
:param category: Fetch all torrents with the supplied label.
:param sort: Sort torrents by.
:param reverse: Enable reverse sorting.
:param limit: Limit the number of torrents returned.
:param offset: Set offset (if less than 0, offset from end).
:return: list() of torrent with matching filter.
"""
params = {}
for name, value in filters.items():
# make sure that old 'status' argument still works
name = 'filter' if name == 'status' else name
params[name] = value
return self._get('query/torrents', params=params) | [
"def",
"torrents",
"(",
"self",
",",
"*",
"*",
"filters",
")",
":",
"params",
"=",
"{",
"}",
"for",
"name",
",",
"value",
"in",
"filters",
".",
"items",
"(",
")",
":",
"# make sure that old 'status' argument still works",
"name",
"=",
"'filter'",
"if",
"name",
"==",
"'status'",
"else",
"name",
"params",
"[",
"name",
"]",
"=",
"value",
"return",
"self",
".",
"_get",
"(",
"'query/torrents'",
",",
"params",
"=",
"params",
")"
] | Returns a list of torrents matching the supplied filters.
:param filter: Current status of the torrents.
:param category: Fetch all torrents with the supplied label.
:param sort: Sort torrents by.
:param reverse: Enable reverse sorting.
:param limit: Limit the number of torrents returned.
:param offset: Set offset (if less than 0, offset from end).
:return: list() of torrent with matching filter. | [
"Returns",
"a",
"list",
"of",
"torrents",
"matching",
"the",
"supplied",
"filters",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L150-L169 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.preferences | def preferences(self):
"""
Get the current qBittorrent preferences.
Can also be used to assign individual preferences.
For setting multiple preferences at once,
see ``set_preferences`` method.
Note: Even if this is a ``property``,
to fetch the current preferences dict, you are required
to call it like a bound method.
Wrong::
qb.preferences
Right::
qb.preferences()
"""
prefs = self._get('query/preferences')
class Proxy(Client):
"""
Proxy class to to allow assignment of individual preferences.
this class overrides some methods to ease things.
Because of this, settings can be assigned like::
In [5]: prefs = qb.preferences()
In [6]: prefs['autorun_enabled']
Out[6]: True
In [7]: prefs['autorun_enabled'] = False
In [8]: prefs['autorun_enabled']
Out[8]: False
"""
def __init__(self, url, prefs, auth, session):
super(Proxy, self).__init__(url)
self.prefs = prefs
self._is_authenticated = auth
self.session = session
def __getitem__(self, key):
return self.prefs[key]
def __setitem__(self, key, value):
kwargs = {key: value}
return self.set_preferences(**kwargs)
def __call__(self):
return self.prefs
return Proxy(self.url, prefs, self._is_authenticated, self.session) | python | def preferences(self):
"""
Get the current qBittorrent preferences.
Can also be used to assign individual preferences.
For setting multiple preferences at once,
see ``set_preferences`` method.
Note: Even if this is a ``property``,
to fetch the current preferences dict, you are required
to call it like a bound method.
Wrong::
qb.preferences
Right::
qb.preferences()
"""
prefs = self._get('query/preferences')
class Proxy(Client):
"""
Proxy class to to allow assignment of individual preferences.
this class overrides some methods to ease things.
Because of this, settings can be assigned like::
In [5]: prefs = qb.preferences()
In [6]: prefs['autorun_enabled']
Out[6]: True
In [7]: prefs['autorun_enabled'] = False
In [8]: prefs['autorun_enabled']
Out[8]: False
"""
def __init__(self, url, prefs, auth, session):
super(Proxy, self).__init__(url)
self.prefs = prefs
self._is_authenticated = auth
self.session = session
def __getitem__(self, key):
return self.prefs[key]
def __setitem__(self, key, value):
kwargs = {key: value}
return self.set_preferences(**kwargs)
def __call__(self):
return self.prefs
return Proxy(self.url, prefs, self._is_authenticated, self.session) | [
"def",
"preferences",
"(",
"self",
")",
":",
"prefs",
"=",
"self",
".",
"_get",
"(",
"'query/preferences'",
")",
"class",
"Proxy",
"(",
"Client",
")",
":",
"\"\"\"\n Proxy class to to allow assignment of individual preferences.\n this class overrides some methods to ease things.\n\n Because of this, settings can be assigned like::\n\n In [5]: prefs = qb.preferences()\n\n In [6]: prefs['autorun_enabled']\n Out[6]: True\n\n In [7]: prefs['autorun_enabled'] = False\n\n In [8]: prefs['autorun_enabled']\n Out[8]: False\n\n \"\"\"",
"def",
"__init__",
"(",
"self",
",",
"url",
",",
"prefs",
",",
"auth",
",",
"session",
")",
":",
"super",
"(",
"Proxy",
",",
"self",
")",
".",
"__init__",
"(",
"url",
")",
"self",
".",
"prefs",
"=",
"prefs",
"self",
".",
"_is_authenticated",
"=",
"auth",
"self",
".",
"session",
"=",
"session",
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"return",
"self",
".",
"prefs",
"[",
"key",
"]",
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"kwargs",
"=",
"{",
"key",
":",
"value",
"}",
"return",
"self",
".",
"set_preferences",
"(",
"*",
"*",
"kwargs",
")",
"def",
"__call__",
"(",
"self",
")",
":",
"return",
"self",
".",
"prefs",
"return",
"Proxy",
"(",
"self",
".",
"url",
",",
"prefs",
",",
"self",
".",
"_is_authenticated",
",",
"self",
".",
"session",
")"
] | Get the current qBittorrent preferences.
Can also be used to assign individual preferences.
For setting multiple preferences at once,
see ``set_preferences`` method.
Note: Even if this is a ``property``,
to fetch the current preferences dict, you are required
to call it like a bound method.
Wrong::
qb.preferences
Right::
qb.preferences() | [
"Get",
"the",
"current",
"qBittorrent",
"preferences",
".",
"Can",
"also",
"be",
"used",
"to",
"assign",
"individual",
"preferences",
".",
"For",
"setting",
"multiple",
"preferences",
"at",
"once",
"see",
"set_preferences",
"method",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L211-L268 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.download_from_link | def download_from_link(self, link, **kwargs):
"""
Download torrent using a link.
:param link: URL Link or list of.
:param savepath: Path to download the torrent.
:param category: Label or Category of the torrent(s).
:return: Empty JSON data.
"""
# old:new format
old_arg_map = {'save_path': 'savepath'} # , 'label': 'category'}
# convert old option names to new option names
options = kwargs.copy()
for old_arg, new_arg in old_arg_map.items():
if options.get(old_arg) and not options.get(new_arg):
options[new_arg] = options[old_arg]
if type(link) is list:
options['urls'] = "\n".join(link)
else:
options['urls'] = link
# workaround to send multipart/formdata request
# http://stackoverflow.com/a/23131823/4726598
dummy_file = {'_dummy': (None, '_dummy')}
return self._post('command/download', data=options, files=dummy_file) | python | def download_from_link(self, link, **kwargs):
"""
Download torrent using a link.
:param link: URL Link or list of.
:param savepath: Path to download the torrent.
:param category: Label or Category of the torrent(s).
:return: Empty JSON data.
"""
# old:new format
old_arg_map = {'save_path': 'savepath'} # , 'label': 'category'}
# convert old option names to new option names
options = kwargs.copy()
for old_arg, new_arg in old_arg_map.items():
if options.get(old_arg) and not options.get(new_arg):
options[new_arg] = options[old_arg]
if type(link) is list:
options['urls'] = "\n".join(link)
else:
options['urls'] = link
# workaround to send multipart/formdata request
# http://stackoverflow.com/a/23131823/4726598
dummy_file = {'_dummy': (None, '_dummy')}
return self._post('command/download', data=options, files=dummy_file) | [
"def",
"download_from_link",
"(",
"self",
",",
"link",
",",
"*",
"*",
"kwargs",
")",
":",
"# old:new format",
"old_arg_map",
"=",
"{",
"'save_path'",
":",
"'savepath'",
"}",
"# , 'label': 'category'}",
"# convert old option names to new option names",
"options",
"=",
"kwargs",
".",
"copy",
"(",
")",
"for",
"old_arg",
",",
"new_arg",
"in",
"old_arg_map",
".",
"items",
"(",
")",
":",
"if",
"options",
".",
"get",
"(",
"old_arg",
")",
"and",
"not",
"options",
".",
"get",
"(",
"new_arg",
")",
":",
"options",
"[",
"new_arg",
"]",
"=",
"options",
"[",
"old_arg",
"]",
"if",
"type",
"(",
"link",
")",
"is",
"list",
":",
"options",
"[",
"'urls'",
"]",
"=",
"\"\\n\"",
".",
"join",
"(",
"link",
")",
"else",
":",
"options",
"[",
"'urls'",
"]",
"=",
"link",
"# workaround to send multipart/formdata request",
"# http://stackoverflow.com/a/23131823/4726598",
"dummy_file",
"=",
"{",
"'_dummy'",
":",
"(",
"None",
",",
"'_dummy'",
")",
"}",
"return",
"self",
".",
"_post",
"(",
"'command/download'",
",",
"data",
"=",
"options",
",",
"files",
"=",
"dummy_file",
")"
] | Download torrent using a link.
:param link: URL Link or list of.
:param savepath: Path to download the torrent.
:param category: Label or Category of the torrent(s).
:return: Empty JSON data. | [
"Download",
"torrent",
"using",
"a",
"link",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L279-L307 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.download_from_file | def download_from_file(self, file_buffer, **kwargs):
"""
Download torrent using a file.
:param file_buffer: Single file() buffer or list of.
:param save_path: Path to download the torrent.
:param label: Label of the torrent(s).
:return: Empty JSON data.
"""
if isinstance(file_buffer, list):
torrent_files = {}
for i, f in enumerate(file_buffer):
torrent_files.update({'torrents%s' % i: f})
else:
torrent_files = {'torrents': file_buffer}
data = kwargs.copy()
if data.get('save_path'):
data.update({'savepath': data['save_path']})
return self._post('command/upload', data=data, files=torrent_files) | python | def download_from_file(self, file_buffer, **kwargs):
"""
Download torrent using a file.
:param file_buffer: Single file() buffer or list of.
:param save_path: Path to download the torrent.
:param label: Label of the torrent(s).
:return: Empty JSON data.
"""
if isinstance(file_buffer, list):
torrent_files = {}
for i, f in enumerate(file_buffer):
torrent_files.update({'torrents%s' % i: f})
else:
torrent_files = {'torrents': file_buffer}
data = kwargs.copy()
if data.get('save_path'):
data.update({'savepath': data['save_path']})
return self._post('command/upload', data=data, files=torrent_files) | [
"def",
"download_from_file",
"(",
"self",
",",
"file_buffer",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"file_buffer",
",",
"list",
")",
":",
"torrent_files",
"=",
"{",
"}",
"for",
"i",
",",
"f",
"in",
"enumerate",
"(",
"file_buffer",
")",
":",
"torrent_files",
".",
"update",
"(",
"{",
"'torrents%s'",
"%",
"i",
":",
"f",
"}",
")",
"else",
":",
"torrent_files",
"=",
"{",
"'torrents'",
":",
"file_buffer",
"}",
"data",
"=",
"kwargs",
".",
"copy",
"(",
")",
"if",
"data",
".",
"get",
"(",
"'save_path'",
")",
":",
"data",
".",
"update",
"(",
"{",
"'savepath'",
":",
"data",
"[",
"'save_path'",
"]",
"}",
")",
"return",
"self",
".",
"_post",
"(",
"'command/upload'",
",",
"data",
"=",
"data",
",",
"files",
"=",
"torrent_files",
")"
] | Download torrent using a file.
:param file_buffer: Single file() buffer or list of.
:param save_path: Path to download the torrent.
:param label: Label of the torrent(s).
:return: Empty JSON data. | [
"Download",
"torrent",
"using",
"a",
"file",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L309-L330 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.add_trackers | def add_trackers(self, infohash, trackers):
"""
Add trackers to a torrent.
:param infohash: INFO HASH of torrent.
:param trackers: Trackers.
"""
data = {'hash': infohash.lower(),
'urls': trackers}
return self._post('command/addTrackers', data=data) | python | def add_trackers(self, infohash, trackers):
"""
Add trackers to a torrent.
:param infohash: INFO HASH of torrent.
:param trackers: Trackers.
"""
data = {'hash': infohash.lower(),
'urls': trackers}
return self._post('command/addTrackers', data=data) | [
"def",
"add_trackers",
"(",
"self",
",",
"infohash",
",",
"trackers",
")",
":",
"data",
"=",
"{",
"'hash'",
":",
"infohash",
".",
"lower",
"(",
")",
",",
"'urls'",
":",
"trackers",
"}",
"return",
"self",
".",
"_post",
"(",
"'command/addTrackers'",
",",
"data",
"=",
"data",
")"
] | Add trackers to a torrent.
:param infohash: INFO HASH of torrent.
:param trackers: Trackers. | [
"Add",
"trackers",
"to",
"a",
"torrent",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L332-L341 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client._process_infohash_list | def _process_infohash_list(infohash_list):
"""
Method to convert the infohash_list to qBittorrent API friendly values.
:param infohash_list: List of infohash.
"""
if isinstance(infohash_list, list):
data = {'hashes': '|'.join([h.lower() for h in infohash_list])}
else:
data = {'hashes': infohash_list.lower()}
return data | python | def _process_infohash_list(infohash_list):
"""
Method to convert the infohash_list to qBittorrent API friendly values.
:param infohash_list: List of infohash.
"""
if isinstance(infohash_list, list):
data = {'hashes': '|'.join([h.lower() for h in infohash_list])}
else:
data = {'hashes': infohash_list.lower()}
return data | [
"def",
"_process_infohash_list",
"(",
"infohash_list",
")",
":",
"if",
"isinstance",
"(",
"infohash_list",
",",
"list",
")",
":",
"data",
"=",
"{",
"'hashes'",
":",
"'|'",
".",
"join",
"(",
"[",
"h",
".",
"lower",
"(",
")",
"for",
"h",
"in",
"infohash_list",
"]",
")",
"}",
"else",
":",
"data",
"=",
"{",
"'hashes'",
":",
"infohash_list",
".",
"lower",
"(",
")",
"}",
"return",
"data"
] | Method to convert the infohash_list to qBittorrent API friendly values.
:param infohash_list: List of infohash. | [
"Method",
"to",
"convert",
"the",
"infohash_list",
"to",
"qBittorrent",
"API",
"friendly",
"values",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L344-L354 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.pause_multiple | def pause_multiple(self, infohash_list):
"""
Pause multiple torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/pauseAll', data=data) | python | def pause_multiple(self, infohash_list):
"""
Pause multiple torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/pauseAll', data=data) | [
"def",
"pause_multiple",
"(",
"self",
",",
"infohash_list",
")",
":",
"data",
"=",
"self",
".",
"_process_infohash_list",
"(",
"infohash_list",
")",
"return",
"self",
".",
"_post",
"(",
"'command/pauseAll'",
",",
"data",
"=",
"data",
")"
] | Pause multiple torrents.
:param infohash_list: Single or list() of infohashes. | [
"Pause",
"multiple",
"torrents",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L370-L377 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.set_label | def set_label(self, infohash_list, label):
"""
Set the label on multiple torrents.
IMPORTANT: OLD API method, kept as it is to avoid breaking stuffs.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
data['label'] = label
return self._post('command/setLabel', data=data) | python | def set_label(self, infohash_list, label):
"""
Set the label on multiple torrents.
IMPORTANT: OLD API method, kept as it is to avoid breaking stuffs.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
data['label'] = label
return self._post('command/setLabel', data=data) | [
"def",
"set_label",
"(",
"self",
",",
"infohash_list",
",",
"label",
")",
":",
"data",
"=",
"self",
".",
"_process_infohash_list",
"(",
"infohash_list",
")",
"data",
"[",
"'label'",
"]",
"=",
"label",
"return",
"self",
".",
"_post",
"(",
"'command/setLabel'",
",",
"data",
"=",
"data",
")"
] | Set the label on multiple torrents.
IMPORTANT: OLD API method, kept as it is to avoid breaking stuffs.
:param infohash_list: Single or list() of infohashes. | [
"Set",
"the",
"label",
"on",
"multiple",
"torrents",
".",
"IMPORTANT",
":",
"OLD",
"API",
"method",
"kept",
"as",
"it",
"is",
"to",
"avoid",
"breaking",
"stuffs",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L379-L388 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.set_category | def set_category(self, infohash_list, category):
"""
Set the category on multiple torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
data['category'] = category
return self._post('command/setCategory', data=data) | python | def set_category(self, infohash_list, category):
"""
Set the category on multiple torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
data['category'] = category
return self._post('command/setCategory', data=data) | [
"def",
"set_category",
"(",
"self",
",",
"infohash_list",
",",
"category",
")",
":",
"data",
"=",
"self",
".",
"_process_infohash_list",
"(",
"infohash_list",
")",
"data",
"[",
"'category'",
"]",
"=",
"category",
"return",
"self",
".",
"_post",
"(",
"'command/setCategory'",
",",
"data",
"=",
"data",
")"
] | Set the category on multiple torrents.
:param infohash_list: Single or list() of infohashes. | [
"Set",
"the",
"category",
"on",
"multiple",
"torrents",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L390-L398 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.resume_multiple | def resume_multiple(self, infohash_list):
"""
Resume multiple paused torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/resumeAll', data=data) | python | def resume_multiple(self, infohash_list):
"""
Resume multiple paused torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/resumeAll', data=data) | [
"def",
"resume_multiple",
"(",
"self",
",",
"infohash_list",
")",
":",
"data",
"=",
"self",
".",
"_process_infohash_list",
"(",
"infohash_list",
")",
"return",
"self",
".",
"_post",
"(",
"'command/resumeAll'",
",",
"data",
"=",
"data",
")"
] | Resume multiple paused torrents.
:param infohash_list: Single or list() of infohashes. | [
"Resume",
"multiple",
"paused",
"torrents",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L414-L421 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.delete | def delete(self, infohash_list):
"""
Delete torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/delete', data=data) | python | def delete(self, infohash_list):
"""
Delete torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/delete', data=data) | [
"def",
"delete",
"(",
"self",
",",
"infohash_list",
")",
":",
"data",
"=",
"self",
".",
"_process_infohash_list",
"(",
"infohash_list",
")",
"return",
"self",
".",
"_post",
"(",
"'command/delete'",
",",
"data",
"=",
"data",
")"
] | Delete torrents.
:param infohash_list: Single or list() of infohashes. | [
"Delete",
"torrents",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L423-L430 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.delete_permanently | def delete_permanently(self, infohash_list):
"""
Permanently delete torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/deletePerm', data=data) | python | def delete_permanently(self, infohash_list):
"""
Permanently delete torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/deletePerm', data=data) | [
"def",
"delete_permanently",
"(",
"self",
",",
"infohash_list",
")",
":",
"data",
"=",
"self",
".",
"_process_infohash_list",
"(",
"infohash_list",
")",
"return",
"self",
".",
"_post",
"(",
"'command/deletePerm'",
",",
"data",
"=",
"data",
")"
] | Permanently delete torrents.
:param infohash_list: Single or list() of infohashes. | [
"Permanently",
"delete",
"torrents",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L432-L439 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.recheck | def recheck(self, infohash_list):
"""
Recheck torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/recheck', data=data) | python | def recheck(self, infohash_list):
"""
Recheck torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/recheck', data=data) | [
"def",
"recheck",
"(",
"self",
",",
"infohash_list",
")",
":",
"data",
"=",
"self",
".",
"_process_infohash_list",
"(",
"infohash_list",
")",
"return",
"self",
".",
"_post",
"(",
"'command/recheck'",
",",
"data",
"=",
"data",
")"
] | Recheck torrents.
:param infohash_list: Single or list() of infohashes. | [
"Recheck",
"torrents",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L441-L448 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.increase_priority | def increase_priority(self, infohash_list):
"""
Increase priority of torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/increasePrio', data=data) | python | def increase_priority(self, infohash_list):
"""
Increase priority of torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/increasePrio', data=data) | [
"def",
"increase_priority",
"(",
"self",
",",
"infohash_list",
")",
":",
"data",
"=",
"self",
".",
"_process_infohash_list",
"(",
"infohash_list",
")",
"return",
"self",
".",
"_post",
"(",
"'command/increasePrio'",
",",
"data",
"=",
"data",
")"
] | Increase priority of torrents.
:param infohash_list: Single or list() of infohashes. | [
"Increase",
"priority",
"of",
"torrents",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L450-L457 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.decrease_priority | def decrease_priority(self, infohash_list):
"""
Decrease priority of torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/decreasePrio', data=data) | python | def decrease_priority(self, infohash_list):
"""
Decrease priority of torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/decreasePrio', data=data) | [
"def",
"decrease_priority",
"(",
"self",
",",
"infohash_list",
")",
":",
"data",
"=",
"self",
".",
"_process_infohash_list",
"(",
"infohash_list",
")",
"return",
"self",
".",
"_post",
"(",
"'command/decreasePrio'",
",",
"data",
"=",
"data",
")"
] | Decrease priority of torrents.
:param infohash_list: Single or list() of infohashes. | [
"Decrease",
"priority",
"of",
"torrents",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L459-L466 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.set_max_priority | def set_max_priority(self, infohash_list):
"""
Set torrents to maximum priority level.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/topPrio', data=data) | python | def set_max_priority(self, infohash_list):
"""
Set torrents to maximum priority level.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/topPrio', data=data) | [
"def",
"set_max_priority",
"(",
"self",
",",
"infohash_list",
")",
":",
"data",
"=",
"self",
".",
"_process_infohash_list",
"(",
"infohash_list",
")",
"return",
"self",
".",
"_post",
"(",
"'command/topPrio'",
",",
"data",
"=",
"data",
")"
] | Set torrents to maximum priority level.
:param infohash_list: Single or list() of infohashes. | [
"Set",
"torrents",
"to",
"maximum",
"priority",
"level",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L468-L475 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.set_min_priority | def set_min_priority(self, infohash_list):
"""
Set torrents to minimum priority level.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/bottomPrio', data=data) | python | def set_min_priority(self, infohash_list):
"""
Set torrents to minimum priority level.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/bottomPrio', data=data) | [
"def",
"set_min_priority",
"(",
"self",
",",
"infohash_list",
")",
":",
"data",
"=",
"self",
".",
"_process_infohash_list",
"(",
"infohash_list",
")",
"return",
"self",
".",
"_post",
"(",
"'command/bottomPrio'",
",",
"data",
"=",
"data",
")"
] | Set torrents to minimum priority level.
:param infohash_list: Single or list() of infohashes. | [
"Set",
"torrents",
"to",
"minimum",
"priority",
"level",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L477-L484 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.set_file_priority | def set_file_priority(self, infohash, file_id, priority):
"""
Set file of a torrent to a supplied priority level.
:param infohash: INFO HASH of torrent.
:param file_id: ID of the file to set priority.
:param priority: Priority level of the file.
"""
if priority not in [0, 1, 2, 7]:
raise ValueError("Invalid priority, refer WEB-UI docs for info.")
elif not isinstance(file_id, int):
raise TypeError("File ID must be an int")
data = {'hash': infohash.lower(),
'id': file_id,
'priority': priority}
return self._post('command/setFilePrio', data=data) | python | def set_file_priority(self, infohash, file_id, priority):
"""
Set file of a torrent to a supplied priority level.
:param infohash: INFO HASH of torrent.
:param file_id: ID of the file to set priority.
:param priority: Priority level of the file.
"""
if priority not in [0, 1, 2, 7]:
raise ValueError("Invalid priority, refer WEB-UI docs for info.")
elif not isinstance(file_id, int):
raise TypeError("File ID must be an int")
data = {'hash': infohash.lower(),
'id': file_id,
'priority': priority}
return self._post('command/setFilePrio', data=data) | [
"def",
"set_file_priority",
"(",
"self",
",",
"infohash",
",",
"file_id",
",",
"priority",
")",
":",
"if",
"priority",
"not",
"in",
"[",
"0",
",",
"1",
",",
"2",
",",
"7",
"]",
":",
"raise",
"ValueError",
"(",
"\"Invalid priority, refer WEB-UI docs for info.\"",
")",
"elif",
"not",
"isinstance",
"(",
"file_id",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"File ID must be an int\"",
")",
"data",
"=",
"{",
"'hash'",
":",
"infohash",
".",
"lower",
"(",
")",
",",
"'id'",
":",
"file_id",
",",
"'priority'",
":",
"priority",
"}",
"return",
"self",
".",
"_post",
"(",
"'command/setFilePrio'",
",",
"data",
"=",
"data",
")"
] | Set file of a torrent to a supplied priority level.
:param infohash: INFO HASH of torrent.
:param file_id: ID of the file to set priority.
:param priority: Priority level of the file. | [
"Set",
"file",
"of",
"a",
"torrent",
"to",
"a",
"supplied",
"priority",
"level",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L486-L503 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.get_torrent_download_limit | def get_torrent_download_limit(self, infohash_list):
"""
Get download speed limit of the supplied torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/getTorrentsDlLimit', data=data) | python | def get_torrent_download_limit(self, infohash_list):
"""
Get download speed limit of the supplied torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/getTorrentsDlLimit', data=data) | [
"def",
"get_torrent_download_limit",
"(",
"self",
",",
"infohash_list",
")",
":",
"data",
"=",
"self",
".",
"_process_infohash_list",
"(",
"infohash_list",
")",
"return",
"self",
".",
"_post",
"(",
"'command/getTorrentsDlLimit'",
",",
"data",
"=",
"data",
")"
] | Get download speed limit of the supplied torrents.
:param infohash_list: Single or list() of infohashes. | [
"Get",
"download",
"speed",
"limit",
"of",
"the",
"supplied",
"torrents",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L542-L549 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.set_torrent_download_limit | def set_torrent_download_limit(self, infohash_list, limit):
"""
Set download speed limit of the supplied torrents.
:param infohash_list: Single or list() of infohashes.
:param limit: Speed limit in bytes.
"""
data = self._process_infohash_list(infohash_list)
data.update({'limit': limit})
return self._post('command/setTorrentsDlLimit', data=data) | python | def set_torrent_download_limit(self, infohash_list, limit):
"""
Set download speed limit of the supplied torrents.
:param infohash_list: Single or list() of infohashes.
:param limit: Speed limit in bytes.
"""
data = self._process_infohash_list(infohash_list)
data.update({'limit': limit})
return self._post('command/setTorrentsDlLimit', data=data) | [
"def",
"set_torrent_download_limit",
"(",
"self",
",",
"infohash_list",
",",
"limit",
")",
":",
"data",
"=",
"self",
".",
"_process_infohash_list",
"(",
"infohash_list",
")",
"data",
".",
"update",
"(",
"{",
"'limit'",
":",
"limit",
"}",
")",
"return",
"self",
".",
"_post",
"(",
"'command/setTorrentsDlLimit'",
",",
"data",
"=",
"data",
")"
] | Set download speed limit of the supplied torrents.
:param infohash_list: Single or list() of infohashes.
:param limit: Speed limit in bytes. | [
"Set",
"download",
"speed",
"limit",
"of",
"the",
"supplied",
"torrents",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L551-L560 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.get_torrent_upload_limit | def get_torrent_upload_limit(self, infohash_list):
"""
Get upoload speed limit of the supplied torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/getTorrentsUpLimit', data=data) | python | def get_torrent_upload_limit(self, infohash_list):
"""
Get upoload speed limit of the supplied torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/getTorrentsUpLimit', data=data) | [
"def",
"get_torrent_upload_limit",
"(",
"self",
",",
"infohash_list",
")",
":",
"data",
"=",
"self",
".",
"_process_infohash_list",
"(",
"infohash_list",
")",
"return",
"self",
".",
"_post",
"(",
"'command/getTorrentsUpLimit'",
",",
"data",
"=",
"data",
")"
] | Get upoload speed limit of the supplied torrents.
:param infohash_list: Single or list() of infohashes. | [
"Get",
"upoload",
"speed",
"limit",
"of",
"the",
"supplied",
"torrents",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L562-L569 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.set_torrent_upload_limit | def set_torrent_upload_limit(self, infohash_list, limit):
"""
Set upload speed limit of the supplied torrents.
:param infohash_list: Single or list() of infohashes.
:param limit: Speed limit in bytes.
"""
data = self._process_infohash_list(infohash_list)
data.update({'limit': limit})
return self._post('command/setTorrentsUpLimit', data=data) | python | def set_torrent_upload_limit(self, infohash_list, limit):
"""
Set upload speed limit of the supplied torrents.
:param infohash_list: Single or list() of infohashes.
:param limit: Speed limit in bytes.
"""
data = self._process_infohash_list(infohash_list)
data.update({'limit': limit})
return self._post('command/setTorrentsUpLimit', data=data) | [
"def",
"set_torrent_upload_limit",
"(",
"self",
",",
"infohash_list",
",",
"limit",
")",
":",
"data",
"=",
"self",
".",
"_process_infohash_list",
"(",
"infohash_list",
")",
"data",
".",
"update",
"(",
"{",
"'limit'",
":",
"limit",
"}",
")",
"return",
"self",
".",
"_post",
"(",
"'command/setTorrentsUpLimit'",
",",
"data",
"=",
"data",
")"
] | Set upload speed limit of the supplied torrents.
:param infohash_list: Single or list() of infohashes.
:param limit: Speed limit in bytes. | [
"Set",
"upload",
"speed",
"limit",
"of",
"the",
"supplied",
"torrents",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L571-L580 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.set_preferences | def set_preferences(self, **kwargs):
"""
Set preferences of qBittorrent.
Read all possible preferences @ http://git.io/vEgDQ
:param kwargs: set preferences in kwargs form.
"""
json_data = "json={}".format(json.dumps(kwargs))
headers = {'content-type': 'application/x-www-form-urlencoded'}
return self._post('command/setPreferences', data=json_data,
headers=headers) | python | def set_preferences(self, **kwargs):
"""
Set preferences of qBittorrent.
Read all possible preferences @ http://git.io/vEgDQ
:param kwargs: set preferences in kwargs form.
"""
json_data = "json={}".format(json.dumps(kwargs))
headers = {'content-type': 'application/x-www-form-urlencoded'}
return self._post('command/setPreferences', data=json_data,
headers=headers) | [
"def",
"set_preferences",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"json_data",
"=",
"\"json={}\"",
".",
"format",
"(",
"json",
".",
"dumps",
"(",
"kwargs",
")",
")",
"headers",
"=",
"{",
"'content-type'",
":",
"'application/x-www-form-urlencoded'",
"}",
"return",
"self",
".",
"_post",
"(",
"'command/setPreferences'",
",",
"data",
"=",
"json_data",
",",
"headers",
"=",
"headers",
")"
] | Set preferences of qBittorrent.
Read all possible preferences @ http://git.io/vEgDQ
:param kwargs: set preferences in kwargs form. | [
"Set",
"preferences",
"of",
"qBittorrent",
".",
"Read",
"all",
"possible",
"preferences",
"@",
"http",
":",
"//",
"git",
".",
"io",
"/",
"vEgDQ"
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L583-L593 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.toggle_sequential_download | def toggle_sequential_download(self, infohash_list):
"""
Toggle sequential download in supplied torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/toggleSequentialDownload', data=data) | python | def toggle_sequential_download(self, infohash_list):
"""
Toggle sequential download in supplied torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/toggleSequentialDownload', data=data) | [
"def",
"toggle_sequential_download",
"(",
"self",
",",
"infohash_list",
")",
":",
"data",
"=",
"self",
".",
"_process_infohash_list",
"(",
"infohash_list",
")",
"return",
"self",
".",
"_post",
"(",
"'command/toggleSequentialDownload'",
",",
"data",
"=",
"data",
")"
] | Toggle sequential download in supplied torrents.
:param infohash_list: Single or list() of infohashes. | [
"Toggle",
"sequential",
"download",
"in",
"supplied",
"torrents",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L609-L616 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.toggle_first_last_piece_priority | def toggle_first_last_piece_priority(self, infohash_list):
"""
Toggle first/last piece priority of supplied torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/toggleFirstLastPiecePrio', data=data) | python | def toggle_first_last_piece_priority(self, infohash_list):
"""
Toggle first/last piece priority of supplied torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/toggleFirstLastPiecePrio', data=data) | [
"def",
"toggle_first_last_piece_priority",
"(",
"self",
",",
"infohash_list",
")",
":",
"data",
"=",
"self",
".",
"_process_infohash_list",
"(",
"infohash_list",
")",
"return",
"self",
".",
"_post",
"(",
"'command/toggleFirstLastPiecePrio'",
",",
"data",
"=",
"data",
")"
] | Toggle first/last piece priority of supplied torrents.
:param infohash_list: Single or list() of infohashes. | [
"Toggle",
"first",
"/",
"last",
"piece",
"priority",
"of",
"supplied",
"torrents",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L618-L625 |
v1k45/python-qBittorrent | qbittorrent/client.py | Client.force_start | def force_start(self, infohash_list, value=True):
"""
Force start selected torrents.
:param infohash_list: Single or list() of infohashes.
:param value: Force start value (bool)
"""
data = self._process_infohash_list(infohash_list)
data.update({'value': json.dumps(value)})
return self._post('command/setForceStart', data=data) | python | def force_start(self, infohash_list, value=True):
"""
Force start selected torrents.
:param infohash_list: Single or list() of infohashes.
:param value: Force start value (bool)
"""
data = self._process_infohash_list(infohash_list)
data.update({'value': json.dumps(value)})
return self._post('command/setForceStart', data=data) | [
"def",
"force_start",
"(",
"self",
",",
"infohash_list",
",",
"value",
"=",
"True",
")",
":",
"data",
"=",
"self",
".",
"_process_infohash_list",
"(",
"infohash_list",
")",
"data",
".",
"update",
"(",
"{",
"'value'",
":",
"json",
".",
"dumps",
"(",
"value",
")",
"}",
")",
"return",
"self",
".",
"_post",
"(",
"'command/setForceStart'",
",",
"data",
"=",
"data",
")"
] | Force start selected torrents.
:param infohash_list: Single or list() of infohashes.
:param value: Force start value (bool) | [
"Force",
"start",
"selected",
"torrents",
"."
] | train | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L627-L636 |
taogeT/flask-vue | flask_vue/__init__.py | vue_find_resource | def vue_find_resource(name, use_minified=None):
"""Resource finding function, also available in templates.
:param name: Script to find a URL for.
:param use_minified': If set to True/False, use/don't use minified.
If None, honors VUE_USE_MINIFIED.
:return: A URL.
"""
target = list(filter(lambda x: x['name'] == name, current_app.config['VUE_CONFIGURATION']))
if not target:
raise ValueError('Can not find resource from configuration.')
target = target[0]
use_minified = (isinstance(use_minified, bool) and use_minified) or current_app.config['VUE_USE_MINIFIED']
CdnClass = LocalCDN if target['use_local'] else getattr(cdn, target['cdn'], CDN)
resource_url = CdnClass(name=name, version=target.get('version', ''),
use_minified=use_minified).get_resource_url()
if resource_url.startswith('//') and current_app.config['VUE_CDN_FORCE_SSL']:
resource_url = 'https:%s' % resource_url
return resource_url | python | def vue_find_resource(name, use_minified=None):
"""Resource finding function, also available in templates.
:param name: Script to find a URL for.
:param use_minified': If set to True/False, use/don't use minified.
If None, honors VUE_USE_MINIFIED.
:return: A URL.
"""
target = list(filter(lambda x: x['name'] == name, current_app.config['VUE_CONFIGURATION']))
if not target:
raise ValueError('Can not find resource from configuration.')
target = target[0]
use_minified = (isinstance(use_minified, bool) and use_minified) or current_app.config['VUE_USE_MINIFIED']
CdnClass = LocalCDN if target['use_local'] else getattr(cdn, target['cdn'], CDN)
resource_url = CdnClass(name=name, version=target.get('version', ''),
use_minified=use_minified).get_resource_url()
if resource_url.startswith('//') and current_app.config['VUE_CDN_FORCE_SSL']:
resource_url = 'https:%s' % resource_url
return resource_url | [
"def",
"vue_find_resource",
"(",
"name",
",",
"use_minified",
"=",
"None",
")",
":",
"target",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
"[",
"'name'",
"]",
"==",
"name",
",",
"current_app",
".",
"config",
"[",
"'VUE_CONFIGURATION'",
"]",
")",
")",
"if",
"not",
"target",
":",
"raise",
"ValueError",
"(",
"'Can not find resource from configuration.'",
")",
"target",
"=",
"target",
"[",
"0",
"]",
"use_minified",
"=",
"(",
"isinstance",
"(",
"use_minified",
",",
"bool",
")",
"and",
"use_minified",
")",
"or",
"current_app",
".",
"config",
"[",
"'VUE_USE_MINIFIED'",
"]",
"CdnClass",
"=",
"LocalCDN",
"if",
"target",
"[",
"'use_local'",
"]",
"else",
"getattr",
"(",
"cdn",
",",
"target",
"[",
"'cdn'",
"]",
",",
"CDN",
")",
"resource_url",
"=",
"CdnClass",
"(",
"name",
"=",
"name",
",",
"version",
"=",
"target",
".",
"get",
"(",
"'version'",
",",
"''",
")",
",",
"use_minified",
"=",
"use_minified",
")",
".",
"get_resource_url",
"(",
")",
"if",
"resource_url",
".",
"startswith",
"(",
"'//'",
")",
"and",
"current_app",
".",
"config",
"[",
"'VUE_CDN_FORCE_SSL'",
"]",
":",
"resource_url",
"=",
"'https:%s'",
"%",
"resource_url",
"return",
"resource_url"
] | Resource finding function, also available in templates.
:param name: Script to find a URL for.
:param use_minified': If set to True/False, use/don't use minified.
If None, honors VUE_USE_MINIFIED.
:return: A URL. | [
"Resource",
"finding",
"function",
"also",
"available",
"in",
"templates",
"."
] | train | https://github.com/taogeT/flask-vue/blob/7a742f1de60ce8e0ca5eb7a22f03d826f242b86b/flask_vue/__init__.py#L9-L27 |
nirum/tableprint | tableprint/utils.py | humantime | def humantime(time):
"""Converts a time in seconds to a reasonable human readable time
Parameters
----------
t : float
The number of seconds
Returns
-------
time : string
The human readable formatted value of the given time
"""
try:
time = float(time)
except (ValueError, TypeError):
raise ValueError("Input must be numeric")
# weeks
if time >= 7 * 60 * 60 * 24:
weeks = math.floor(time / (7 * 60 * 60 * 24))
timestr = "{:g} weeks, ".format(weeks) + humantime(time % (7 * 60 * 60 * 24))
# days
elif time >= 60 * 60 * 24:
days = math.floor(time / (60 * 60 * 24))
timestr = "{:g} days, ".format(days) + humantime(time % (60 * 60 * 24))
# hours
elif time >= 60 * 60:
hours = math.floor(time / (60 * 60))
timestr = "{:g} hours, ".format(hours) + humantime(time % (60 * 60))
# minutes
elif time >= 60:
minutes = math.floor(time / 60.)
timestr = "{:g} min., ".format(minutes) + humantime(time % 60)
# seconds
elif (time >= 1) | (time == 0):
timestr = "{:g} s".format(time)
# milliseconds
elif time >= 1e-3:
timestr = "{:g} ms".format(time * 1e3)
# microseconds
elif time >= 1e-6:
timestr = "{:g} \u03BCs".format(time * 1e6)
# nanoseconds or smaller
else:
timestr = "{:g} ns".format(time * 1e9)
return timestr | python | def humantime(time):
"""Converts a time in seconds to a reasonable human readable time
Parameters
----------
t : float
The number of seconds
Returns
-------
time : string
The human readable formatted value of the given time
"""
try:
time = float(time)
except (ValueError, TypeError):
raise ValueError("Input must be numeric")
# weeks
if time >= 7 * 60 * 60 * 24:
weeks = math.floor(time / (7 * 60 * 60 * 24))
timestr = "{:g} weeks, ".format(weeks) + humantime(time % (7 * 60 * 60 * 24))
# days
elif time >= 60 * 60 * 24:
days = math.floor(time / (60 * 60 * 24))
timestr = "{:g} days, ".format(days) + humantime(time % (60 * 60 * 24))
# hours
elif time >= 60 * 60:
hours = math.floor(time / (60 * 60))
timestr = "{:g} hours, ".format(hours) + humantime(time % (60 * 60))
# minutes
elif time >= 60:
minutes = math.floor(time / 60.)
timestr = "{:g} min., ".format(minutes) + humantime(time % 60)
# seconds
elif (time >= 1) | (time == 0):
timestr = "{:g} s".format(time)
# milliseconds
elif time >= 1e-3:
timestr = "{:g} ms".format(time * 1e3)
# microseconds
elif time >= 1e-6:
timestr = "{:g} \u03BCs".format(time * 1e6)
# nanoseconds or smaller
else:
timestr = "{:g} ns".format(time * 1e9)
return timestr | [
"def",
"humantime",
"(",
"time",
")",
":",
"try",
":",
"time",
"=",
"float",
"(",
"time",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"raise",
"ValueError",
"(",
"\"Input must be numeric\"",
")",
"# weeks",
"if",
"time",
">=",
"7",
"*",
"60",
"*",
"60",
"*",
"24",
":",
"weeks",
"=",
"math",
".",
"floor",
"(",
"time",
"/",
"(",
"7",
"*",
"60",
"*",
"60",
"*",
"24",
")",
")",
"timestr",
"=",
"\"{:g} weeks, \"",
".",
"format",
"(",
"weeks",
")",
"+",
"humantime",
"(",
"time",
"%",
"(",
"7",
"*",
"60",
"*",
"60",
"*",
"24",
")",
")",
"# days",
"elif",
"time",
">=",
"60",
"*",
"60",
"*",
"24",
":",
"days",
"=",
"math",
".",
"floor",
"(",
"time",
"/",
"(",
"60",
"*",
"60",
"*",
"24",
")",
")",
"timestr",
"=",
"\"{:g} days, \"",
".",
"format",
"(",
"days",
")",
"+",
"humantime",
"(",
"time",
"%",
"(",
"60",
"*",
"60",
"*",
"24",
")",
")",
"# hours",
"elif",
"time",
">=",
"60",
"*",
"60",
":",
"hours",
"=",
"math",
".",
"floor",
"(",
"time",
"/",
"(",
"60",
"*",
"60",
")",
")",
"timestr",
"=",
"\"{:g} hours, \"",
".",
"format",
"(",
"hours",
")",
"+",
"humantime",
"(",
"time",
"%",
"(",
"60",
"*",
"60",
")",
")",
"# minutes",
"elif",
"time",
">=",
"60",
":",
"minutes",
"=",
"math",
".",
"floor",
"(",
"time",
"/",
"60.",
")",
"timestr",
"=",
"\"{:g} min., \"",
".",
"format",
"(",
"minutes",
")",
"+",
"humantime",
"(",
"time",
"%",
"60",
")",
"# seconds",
"elif",
"(",
"time",
">=",
"1",
")",
"|",
"(",
"time",
"==",
"0",
")",
":",
"timestr",
"=",
"\"{:g} s\"",
".",
"format",
"(",
"time",
")",
"# milliseconds",
"elif",
"time",
">=",
"1e-3",
":",
"timestr",
"=",
"\"{:g} ms\"",
".",
"format",
"(",
"time",
"*",
"1e3",
")",
"# microseconds",
"elif",
"time",
">=",
"1e-6",
":",
"timestr",
"=",
"\"{:g} \\u03BCs\"",
".",
"format",
"(",
"time",
"*",
"1e6",
")",
"# nanoseconds or smaller",
"else",
":",
"timestr",
"=",
"\"{:g} ns\"",
".",
"format",
"(",
"time",
"*",
"1e9",
")",
"return",
"timestr"
] | Converts a time in seconds to a reasonable human readable time
Parameters
----------
t : float
The number of seconds
Returns
-------
time : string
The human readable formatted value of the given time | [
"Converts",
"a",
"time",
"in",
"seconds",
"to",
"a",
"reasonable",
"human",
"readable",
"time"
] | train | https://github.com/nirum/tableprint/blob/50ab4b96706fce8ee035a4d48cb456e3271eab3d/tableprint/utils.py#L13-L67 |
nirum/tableprint | tableprint/utils.py | ansi_len | def ansi_len(string):
"""Extra length due to any ANSI sequences in the string."""
return len(string) - wcswidth(re.compile(r'\x1b[^m]*m').sub('', string)) | python | def ansi_len(string):
"""Extra length due to any ANSI sequences in the string."""
return len(string) - wcswidth(re.compile(r'\x1b[^m]*m').sub('', string)) | [
"def",
"ansi_len",
"(",
"string",
")",
":",
"return",
"len",
"(",
"string",
")",
"-",
"wcswidth",
"(",
"re",
".",
"compile",
"(",
"r'\\x1b[^m]*m'",
")",
".",
"sub",
"(",
"''",
",",
"string",
")",
")"
] | Extra length due to any ANSI sequences in the string. | [
"Extra",
"length",
"due",
"to",
"any",
"ANSI",
"sequences",
"in",
"the",
"string",
"."
] | train | https://github.com/nirum/tableprint/blob/50ab4b96706fce8ee035a4d48cb456e3271eab3d/tableprint/utils.py#L70-L72 |
nirum/tableprint | tableprint/utils.py | format_line | def format_line(data, linestyle):
"""Formats a list of elements using the given line style"""
return linestyle.begin + linestyle.sep.join(data) + linestyle.end | python | def format_line(data, linestyle):
"""Formats a list of elements using the given line style"""
return linestyle.begin + linestyle.sep.join(data) + linestyle.end | [
"def",
"format_line",
"(",
"data",
",",
"linestyle",
")",
":",
"return",
"linestyle",
".",
"begin",
"+",
"linestyle",
".",
"sep",
".",
"join",
"(",
"data",
")",
"+",
"linestyle",
".",
"end"
] | Formats a list of elements using the given line style | [
"Formats",
"a",
"list",
"of",
"elements",
"using",
"the",
"given",
"line",
"style"
] | train | https://github.com/nirum/tableprint/blob/50ab4b96706fce8ee035a4d48cb456e3271eab3d/tableprint/utils.py#L75-L77 |
nirum/tableprint | tableprint/utils.py | parse_width | def parse_width(width, n):
"""Parses an int or array of widths
Parameters
----------
width : int or array_like
n : int
"""
if isinstance(width, int):
widths = [width] * n
else:
assert len(width) == n, "Widths and data do not match"
widths = width
return widths | python | def parse_width(width, n):
"""Parses an int or array of widths
Parameters
----------
width : int or array_like
n : int
"""
if isinstance(width, int):
widths = [width] * n
else:
assert len(width) == n, "Widths and data do not match"
widths = width
return widths | [
"def",
"parse_width",
"(",
"width",
",",
"n",
")",
":",
"if",
"isinstance",
"(",
"width",
",",
"int",
")",
":",
"widths",
"=",
"[",
"width",
"]",
"*",
"n",
"else",
":",
"assert",
"len",
"(",
"width",
")",
"==",
"n",
",",
"\"Widths and data do not match\"",
"widths",
"=",
"width",
"return",
"widths"
] | Parses an int or array of widths
Parameters
----------
width : int or array_like
n : int | [
"Parses",
"an",
"int",
"or",
"array",
"of",
"widths"
] | train | https://github.com/nirum/tableprint/blob/50ab4b96706fce8ee035a4d48cb456e3271eab3d/tableprint/utils.py#L80-L95 |
nirum/tableprint | tableprint/printer.py | table | def table(data, headers=None, format_spec=FMT, width=WIDTH, align=ALIGN, style=STYLE, out=sys.stdout):
"""Print a table with the given data
Parameters
----------
data : array_like
An (m x n) array containing the data to print (m rows of n columns)
headers : list, optional
A list of n strings consisting of the header of each of the n columns (Default: None)
format_spec : string, optional
Format specification for formatting numbers (Default: '5g')
width : int or array_like, optional
The width of each column in the table (Default: 11)
align : string
The alignment to use ('left', 'center', or 'right'). (Default: 'right')
style : string or tuple, optional
A formatting style. (Default: 'fancy_grid')
out : writer, optional
A file handle or object that has write() and flush() methods (Default: sys.stdout)
"""
# Number of columns in the table.
ncols = len(data[0]) if headers is None else len(headers)
tablestyle = STYLES[style]
widths = parse_width(width, ncols)
# Initialize with a hr or the header
tablestr = [hrule(ncols, widths, tablestyle.top)] \
if headers is None else [header(headers, width=widths, align=align, style=style)]
# parse each row
tablestr += [row(d, widths, format_spec, align, style) for d in data]
# only add the final border if there was data in the table
if len(data) > 0:
tablestr += [hrule(ncols, widths, tablestyle.bottom)]
# print the table
out.write('\n'.join(tablestr) + '\n')
out.flush() | python | def table(data, headers=None, format_spec=FMT, width=WIDTH, align=ALIGN, style=STYLE, out=sys.stdout):
"""Print a table with the given data
Parameters
----------
data : array_like
An (m x n) array containing the data to print (m rows of n columns)
headers : list, optional
A list of n strings consisting of the header of each of the n columns (Default: None)
format_spec : string, optional
Format specification for formatting numbers (Default: '5g')
width : int or array_like, optional
The width of each column in the table (Default: 11)
align : string
The alignment to use ('left', 'center', or 'right'). (Default: 'right')
style : string or tuple, optional
A formatting style. (Default: 'fancy_grid')
out : writer, optional
A file handle or object that has write() and flush() methods (Default: sys.stdout)
"""
# Number of columns in the table.
ncols = len(data[0]) if headers is None else len(headers)
tablestyle = STYLES[style]
widths = parse_width(width, ncols)
# Initialize with a hr or the header
tablestr = [hrule(ncols, widths, tablestyle.top)] \
if headers is None else [header(headers, width=widths, align=align, style=style)]
# parse each row
tablestr += [row(d, widths, format_spec, align, style) for d in data]
# only add the final border if there was data in the table
if len(data) > 0:
tablestr += [hrule(ncols, widths, tablestyle.bottom)]
# print the table
out.write('\n'.join(tablestr) + '\n')
out.flush() | [
"def",
"table",
"(",
"data",
",",
"headers",
"=",
"None",
",",
"format_spec",
"=",
"FMT",
",",
"width",
"=",
"WIDTH",
",",
"align",
"=",
"ALIGN",
",",
"style",
"=",
"STYLE",
",",
"out",
"=",
"sys",
".",
"stdout",
")",
":",
"# Number of columns in the table.",
"ncols",
"=",
"len",
"(",
"data",
"[",
"0",
"]",
")",
"if",
"headers",
"is",
"None",
"else",
"len",
"(",
"headers",
")",
"tablestyle",
"=",
"STYLES",
"[",
"style",
"]",
"widths",
"=",
"parse_width",
"(",
"width",
",",
"ncols",
")",
"# Initialize with a hr or the header",
"tablestr",
"=",
"[",
"hrule",
"(",
"ncols",
",",
"widths",
",",
"tablestyle",
".",
"top",
")",
"]",
"if",
"headers",
"is",
"None",
"else",
"[",
"header",
"(",
"headers",
",",
"width",
"=",
"widths",
",",
"align",
"=",
"align",
",",
"style",
"=",
"style",
")",
"]",
"# parse each row",
"tablestr",
"+=",
"[",
"row",
"(",
"d",
",",
"widths",
",",
"format_spec",
",",
"align",
",",
"style",
")",
"for",
"d",
"in",
"data",
"]",
"# only add the final border if there was data in the table",
"if",
"len",
"(",
"data",
")",
">",
"0",
":",
"tablestr",
"+=",
"[",
"hrule",
"(",
"ncols",
",",
"widths",
",",
"tablestyle",
".",
"bottom",
")",
"]",
"# print the table",
"out",
".",
"write",
"(",
"'\\n'",
".",
"join",
"(",
"tablestr",
")",
"+",
"'\\n'",
")",
"out",
".",
"flush",
"(",
")"
] | Print a table with the given data
Parameters
----------
data : array_like
An (m x n) array containing the data to print (m rows of n columns)
headers : list, optional
A list of n strings consisting of the header of each of the n columns (Default: None)
format_spec : string, optional
Format specification for formatting numbers (Default: '5g')
width : int or array_like, optional
The width of each column in the table (Default: 11)
align : string
The alignment to use ('left', 'center', or 'right'). (Default: 'right')
style : string or tuple, optional
A formatting style. (Default: 'fancy_grid')
out : writer, optional
A file handle or object that has write() and flush() methods (Default: sys.stdout) | [
"Print",
"a",
"table",
"with",
"the",
"given",
"data"
] | train | https://github.com/nirum/tableprint/blob/50ab4b96706fce8ee035a4d48cb456e3271eab3d/tableprint/printer.py#L79-L123 |
nirum/tableprint | tableprint/printer.py | header | def header(headers, width=WIDTH, align=ALIGN, style=STYLE, add_hr=True):
"""Returns a formatted row of column header strings
Parameters
----------
headers : list of strings
A list of n strings, the column headers
width : int
The width of each column (Default: 11)
style : string or tuple, optional
A formatting style (see STYLES)
Returns
-------
headerstr : string
A string consisting of the full header row to print
"""
tablestyle = STYLES[style]
widths = parse_width(width, len(headers))
alignment = ALIGNMENTS[align]
# string formatter
data = map(lambda x: ('{:%s%d}' % (alignment, x[0] + ansi_len(x[1]))).format(x[1]), zip(widths, headers))
# build the formatted str
headerstr = format_line(data, tablestyle.row)
if add_hr:
upper = hrule(len(headers), widths, tablestyle.top)
lower = hrule(len(headers), widths, tablestyle.below_header)
headerstr = '\n'.join([upper, headerstr, lower])
return headerstr | python | def header(headers, width=WIDTH, align=ALIGN, style=STYLE, add_hr=True):
"""Returns a formatted row of column header strings
Parameters
----------
headers : list of strings
A list of n strings, the column headers
width : int
The width of each column (Default: 11)
style : string or tuple, optional
A formatting style (see STYLES)
Returns
-------
headerstr : string
A string consisting of the full header row to print
"""
tablestyle = STYLES[style]
widths = parse_width(width, len(headers))
alignment = ALIGNMENTS[align]
# string formatter
data = map(lambda x: ('{:%s%d}' % (alignment, x[0] + ansi_len(x[1]))).format(x[1]), zip(widths, headers))
# build the formatted str
headerstr = format_line(data, tablestyle.row)
if add_hr:
upper = hrule(len(headers), widths, tablestyle.top)
lower = hrule(len(headers), widths, tablestyle.below_header)
headerstr = '\n'.join([upper, headerstr, lower])
return headerstr | [
"def",
"header",
"(",
"headers",
",",
"width",
"=",
"WIDTH",
",",
"align",
"=",
"ALIGN",
",",
"style",
"=",
"STYLE",
",",
"add_hr",
"=",
"True",
")",
":",
"tablestyle",
"=",
"STYLES",
"[",
"style",
"]",
"widths",
"=",
"parse_width",
"(",
"width",
",",
"len",
"(",
"headers",
")",
")",
"alignment",
"=",
"ALIGNMENTS",
"[",
"align",
"]",
"# string formatter",
"data",
"=",
"map",
"(",
"lambda",
"x",
":",
"(",
"'{:%s%d}'",
"%",
"(",
"alignment",
",",
"x",
"[",
"0",
"]",
"+",
"ansi_len",
"(",
"x",
"[",
"1",
"]",
")",
")",
")",
".",
"format",
"(",
"x",
"[",
"1",
"]",
")",
",",
"zip",
"(",
"widths",
",",
"headers",
")",
")",
"# build the formatted str",
"headerstr",
"=",
"format_line",
"(",
"data",
",",
"tablestyle",
".",
"row",
")",
"if",
"add_hr",
":",
"upper",
"=",
"hrule",
"(",
"len",
"(",
"headers",
")",
",",
"widths",
",",
"tablestyle",
".",
"top",
")",
"lower",
"=",
"hrule",
"(",
"len",
"(",
"headers",
")",
",",
"widths",
",",
"tablestyle",
".",
"below_header",
")",
"headerstr",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"upper",
",",
"headerstr",
",",
"lower",
"]",
")",
"return",
"headerstr"
] | Returns a formatted row of column header strings
Parameters
----------
headers : list of strings
A list of n strings, the column headers
width : int
The width of each column (Default: 11)
style : string or tuple, optional
A formatting style (see STYLES)
Returns
-------
headerstr : string
A string consisting of the full header row to print | [
"Returns",
"a",
"formatted",
"row",
"of",
"column",
"header",
"strings"
] | train | https://github.com/nirum/tableprint/blob/50ab4b96706fce8ee035a4d48cb456e3271eab3d/tableprint/printer.py#L126-L160 |
nirum/tableprint | tableprint/printer.py | row | def row(values, width=WIDTH, format_spec=FMT, align=ALIGN, style=STYLE):
"""Returns a formatted row of data
Parameters
----------
values : array_like
An iterable array of data (numbers or strings), each value is printed in a separate column
width : int
The width of each column (Default: 11)
format_spec : string
The precision format string used to format numbers in the values array (Default: '5g')
align : string
The alignment to use ('left', 'center', or 'right'). (Default: 'right')
style : namedtuple, optional
A line formatting style
Returns
-------
rowstr : string
A string consisting of the full row of data to print
"""
tablestyle = STYLES[style]
widths = parse_width(width, len(values))
assert isinstance(format_spec, string_types) | isinstance(format_spec, list), \
"format_spec must be a string or list of strings"
if isinstance(format_spec, string_types):
format_spec = [format_spec] * len(list(values))
# mapping function for string formatting
def mapdata(val):
# unpack
width, datum, prec = val
if isinstance(datum, string_types):
return ('{:%s%i}' % (ALIGNMENTS[align], width + ansi_len(datum))).format(datum)
elif isinstance(datum, Number):
return ('{:%s%i.%s}' % (ALIGNMENTS[align], width, prec)).format(datum)
else:
raise ValueError('Elements in the values array must be strings, ints, or floats')
# string formatter
data = map(mapdata, zip(widths, values, format_spec))
# build the row string
return format_line(data, tablestyle.row) | python | def row(values, width=WIDTH, format_spec=FMT, align=ALIGN, style=STYLE):
"""Returns a formatted row of data
Parameters
----------
values : array_like
An iterable array of data (numbers or strings), each value is printed in a separate column
width : int
The width of each column (Default: 11)
format_spec : string
The precision format string used to format numbers in the values array (Default: '5g')
align : string
The alignment to use ('left', 'center', or 'right'). (Default: 'right')
style : namedtuple, optional
A line formatting style
Returns
-------
rowstr : string
A string consisting of the full row of data to print
"""
tablestyle = STYLES[style]
widths = parse_width(width, len(values))
assert isinstance(format_spec, string_types) | isinstance(format_spec, list), \
"format_spec must be a string or list of strings"
if isinstance(format_spec, string_types):
format_spec = [format_spec] * len(list(values))
# mapping function for string formatting
def mapdata(val):
# unpack
width, datum, prec = val
if isinstance(datum, string_types):
return ('{:%s%i}' % (ALIGNMENTS[align], width + ansi_len(datum))).format(datum)
elif isinstance(datum, Number):
return ('{:%s%i.%s}' % (ALIGNMENTS[align], width, prec)).format(datum)
else:
raise ValueError('Elements in the values array must be strings, ints, or floats')
# string formatter
data = map(mapdata, zip(widths, values, format_spec))
# build the row string
return format_line(data, tablestyle.row) | [
"def",
"row",
"(",
"values",
",",
"width",
"=",
"WIDTH",
",",
"format_spec",
"=",
"FMT",
",",
"align",
"=",
"ALIGN",
",",
"style",
"=",
"STYLE",
")",
":",
"tablestyle",
"=",
"STYLES",
"[",
"style",
"]",
"widths",
"=",
"parse_width",
"(",
"width",
",",
"len",
"(",
"values",
")",
")",
"assert",
"isinstance",
"(",
"format_spec",
",",
"string_types",
")",
"|",
"isinstance",
"(",
"format_spec",
",",
"list",
")",
",",
"\"format_spec must be a string or list of strings\"",
"if",
"isinstance",
"(",
"format_spec",
",",
"string_types",
")",
":",
"format_spec",
"=",
"[",
"format_spec",
"]",
"*",
"len",
"(",
"list",
"(",
"values",
")",
")",
"# mapping function for string formatting",
"def",
"mapdata",
"(",
"val",
")",
":",
"# unpack",
"width",
",",
"datum",
",",
"prec",
"=",
"val",
"if",
"isinstance",
"(",
"datum",
",",
"string_types",
")",
":",
"return",
"(",
"'{:%s%i}'",
"%",
"(",
"ALIGNMENTS",
"[",
"align",
"]",
",",
"width",
"+",
"ansi_len",
"(",
"datum",
")",
")",
")",
".",
"format",
"(",
"datum",
")",
"elif",
"isinstance",
"(",
"datum",
",",
"Number",
")",
":",
"return",
"(",
"'{:%s%i.%s}'",
"%",
"(",
"ALIGNMENTS",
"[",
"align",
"]",
",",
"width",
",",
"prec",
")",
")",
".",
"format",
"(",
"datum",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Elements in the values array must be strings, ints, or floats'",
")",
"# string formatter",
"data",
"=",
"map",
"(",
"mapdata",
",",
"zip",
"(",
"widths",
",",
"values",
",",
"format_spec",
")",
")",
"# build the row string",
"return",
"format_line",
"(",
"data",
",",
"tablestyle",
".",
"row",
")"
] | Returns a formatted row of data
Parameters
----------
values : array_like
An iterable array of data (numbers or strings), each value is printed in a separate column
width : int
The width of each column (Default: 11)
format_spec : string
The precision format string used to format numbers in the values array (Default: '5g')
align : string
The alignment to use ('left', 'center', or 'right'). (Default: 'right')
style : namedtuple, optional
A line formatting style
Returns
-------
rowstr : string
A string consisting of the full row of data to print | [
"Returns",
"a",
"formatted",
"row",
"of",
"data"
] | train | https://github.com/nirum/tableprint/blob/50ab4b96706fce8ee035a4d48cb456e3271eab3d/tableprint/printer.py#L163-L216 |
nirum/tableprint | tableprint/printer.py | hrule | def hrule(n=1, width=WIDTH, linestyle=LineStyle('', 'β', 'β', '')):
"""Returns a formatted string used as a border between table rows
Parameters
----------
n : int
The number of columns in the table
width : int
The width of each column (Default: 11)
linestyle : tuple
A LineStyle namedtuple containing the characters for (begin, hr, sep, end).
(Default: ('', 'β', 'β', ''))
Returns
-------
rowstr : string
A string consisting of the row border to print
"""
widths = parse_width(width, n)
hrstr = linestyle.sep.join([('{:%s^%i}' % (linestyle.hline, width)).format('')
for width in widths])
return linestyle.begin + hrstr + linestyle.end | python | def hrule(n=1, width=WIDTH, linestyle=LineStyle('', 'β', 'β', '')):
"""Returns a formatted string used as a border between table rows
Parameters
----------
n : int
The number of columns in the table
width : int
The width of each column (Default: 11)
linestyle : tuple
A LineStyle namedtuple containing the characters for (begin, hr, sep, end).
(Default: ('', 'β', 'β', ''))
Returns
-------
rowstr : string
A string consisting of the row border to print
"""
widths = parse_width(width, n)
hrstr = linestyle.sep.join([('{:%s^%i}' % (linestyle.hline, width)).format('')
for width in widths])
return linestyle.begin + hrstr + linestyle.end | [
"def",
"hrule",
"(",
"n",
"=",
"1",
",",
"width",
"=",
"WIDTH",
",",
"linestyle",
"=",
"LineStyle",
"(",
"''",
",",
"'β', ",
"'",
"', ''",
")",
":",
"",
"",
"",
"widths",
"=",
"parse_width",
"(",
"width",
",",
"n",
")",
"hrstr",
"=",
"linestyle",
".",
"sep",
".",
"join",
"(",
"[",
"(",
"'{:%s^%i}'",
"%",
"(",
"linestyle",
".",
"hline",
",",
"width",
")",
")",
".",
"format",
"(",
"''",
")",
"for",
"width",
"in",
"widths",
"]",
")",
"return",
"linestyle",
".",
"begin",
"+",
"hrstr",
"+",
"linestyle",
".",
"end"
] | Returns a formatted string used as a border between table rows
Parameters
----------
n : int
The number of columns in the table
width : int
The width of each column (Default: 11)
linestyle : tuple
A LineStyle namedtuple containing the characters for (begin, hr, sep, end).
(Default: ('', 'β', 'β', ''))
Returns
-------
rowstr : string
A string consisting of the row border to print | [
"Returns",
"a",
"formatted",
"string",
"used",
"as",
"a",
"border",
"between",
"table",
"rows"
] | train | https://github.com/nirum/tableprint/blob/50ab4b96706fce8ee035a4d48cb456e3271eab3d/tableprint/printer.py#L219-L242 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.