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
|
---|---|---|---|---|---|---|---|---|---|---|
kvesteri/postgresql-audit | postgresql_audit/migrations.py | remove_column | def remove_column(conn, table, column_name, schema=None):
"""
Removes given `activity` jsonb data column key. This function is useful
when you are doing schema changes that require removing a column.
Let's say you've been using PostgreSQL-Audit for a while for a table called
article. Now you want to remove one audited column called 'created_at' from
this table.
::
from alembic import op
from postgresql_audit import remove_column
def upgrade():
op.remove_column('article', 'created_at')
remove_column(op, 'article', 'created_at')
:param conn:
An object that is able to execute SQL (either SQLAlchemy Connection,
Engine or Alembic Operations object)
:param table:
The table to remove the column from
:param column_name:
Name of the column to remove
:param schema:
Optional name of schema to use.
"""
activity_table = get_activity_table(schema=schema)
remove = sa.cast(column_name, sa.Text)
query = (
activity_table
.update()
.values(
old_data=activity_table.c.old_data - remove,
changed_data=activity_table.c.changed_data - remove,
)
.where(activity_table.c.table_name == table)
)
return conn.execute(query) | python | def remove_column(conn, table, column_name, schema=None):
"""
Removes given `activity` jsonb data column key. This function is useful
when you are doing schema changes that require removing a column.
Let's say you've been using PostgreSQL-Audit for a while for a table called
article. Now you want to remove one audited column called 'created_at' from
this table.
::
from alembic import op
from postgresql_audit import remove_column
def upgrade():
op.remove_column('article', 'created_at')
remove_column(op, 'article', 'created_at')
:param conn:
An object that is able to execute SQL (either SQLAlchemy Connection,
Engine or Alembic Operations object)
:param table:
The table to remove the column from
:param column_name:
Name of the column to remove
:param schema:
Optional name of schema to use.
"""
activity_table = get_activity_table(schema=schema)
remove = sa.cast(column_name, sa.Text)
query = (
activity_table
.update()
.values(
old_data=activity_table.c.old_data - remove,
changed_data=activity_table.c.changed_data - remove,
)
.where(activity_table.c.table_name == table)
)
return conn.execute(query) | [
"def",
"remove_column",
"(",
"conn",
",",
"table",
",",
"column_name",
",",
"schema",
"=",
"None",
")",
":",
"activity_table",
"=",
"get_activity_table",
"(",
"schema",
"=",
"schema",
")",
"remove",
"=",
"sa",
".",
"cast",
"(",
"column_name",
",",
"sa",
".",
"Text",
")",
"query",
"=",
"(",
"activity_table",
".",
"update",
"(",
")",
".",
"values",
"(",
"old_data",
"=",
"activity_table",
".",
"c",
".",
"old_data",
"-",
"remove",
",",
"changed_data",
"=",
"activity_table",
".",
"c",
".",
"changed_data",
"-",
"remove",
",",
")",
".",
"where",
"(",
"activity_table",
".",
"c",
".",
"table_name",
"==",
"table",
")",
")",
"return",
"conn",
".",
"execute",
"(",
"query",
")"
] | Removes given `activity` jsonb data column key. This function is useful
when you are doing schema changes that require removing a column.
Let's say you've been using PostgreSQL-Audit for a while for a table called
article. Now you want to remove one audited column called 'created_at' from
this table.
::
from alembic import op
from postgresql_audit import remove_column
def upgrade():
op.remove_column('article', 'created_at')
remove_column(op, 'article', 'created_at')
:param conn:
An object that is able to execute SQL (either SQLAlchemy Connection,
Engine or Alembic Operations object)
:param table:
The table to remove the column from
:param column_name:
Name of the column to remove
:param schema:
Optional name of schema to use. | [
"Removes",
"given",
"activity",
"jsonb",
"data",
"column",
"key",
".",
"This",
"function",
"is",
"useful",
"when",
"you",
"are",
"doing",
"schema",
"changes",
"that",
"require",
"removing",
"a",
"column",
"."
] | train | https://github.com/kvesteri/postgresql-audit/blob/91b497ced2e04dd44bb757b02983d2a64a2b1514/postgresql_audit/migrations.py#L223-L264 |
kvesteri/postgresql-audit | postgresql_audit/migrations.py | rename_table | def rename_table(conn, old_table_name, new_table_name, schema=None):
"""
Renames given table in activity table. You should remember to call this
function whenever you rename a versioned table.
::
from alembic import op
from postgresql_audit import rename_table
def upgrade():
op.rename_table('article', 'article_v2')
rename_table(op, 'article', 'article_v2')
:param conn:
An object that is able to execute SQL (either SQLAlchemy Connection,
Engine or Alembic Operations object)
:param old_table_name:
The name of table to rename
:param new_table_name:
New name of the renamed table
:param schema:
Optional name of schema to use.
"""
activity_table = get_activity_table(schema=schema)
query = (
activity_table
.update()
.values(table_name=new_table_name)
.where(activity_table.c.table_name == old_table_name)
)
return conn.execute(query) | python | def rename_table(conn, old_table_name, new_table_name, schema=None):
"""
Renames given table in activity table. You should remember to call this
function whenever you rename a versioned table.
::
from alembic import op
from postgresql_audit import rename_table
def upgrade():
op.rename_table('article', 'article_v2')
rename_table(op, 'article', 'article_v2')
:param conn:
An object that is able to execute SQL (either SQLAlchemy Connection,
Engine or Alembic Operations object)
:param old_table_name:
The name of table to rename
:param new_table_name:
New name of the renamed table
:param schema:
Optional name of schema to use.
"""
activity_table = get_activity_table(schema=schema)
query = (
activity_table
.update()
.values(table_name=new_table_name)
.where(activity_table.c.table_name == old_table_name)
)
return conn.execute(query) | [
"def",
"rename_table",
"(",
"conn",
",",
"old_table_name",
",",
"new_table_name",
",",
"schema",
"=",
"None",
")",
":",
"activity_table",
"=",
"get_activity_table",
"(",
"schema",
"=",
"schema",
")",
"query",
"=",
"(",
"activity_table",
".",
"update",
"(",
")",
".",
"values",
"(",
"table_name",
"=",
"new_table_name",
")",
".",
"where",
"(",
"activity_table",
".",
"c",
".",
"table_name",
"==",
"old_table_name",
")",
")",
"return",
"conn",
".",
"execute",
"(",
"query",
")"
] | Renames given table in activity table. You should remember to call this
function whenever you rename a versioned table.
::
from alembic import op
from postgresql_audit import rename_table
def upgrade():
op.rename_table('article', 'article_v2')
rename_table(op, 'article', 'article_v2')
:param conn:
An object that is able to execute SQL (either SQLAlchemy Connection,
Engine or Alembic Operations object)
:param old_table_name:
The name of table to rename
:param new_table_name:
New name of the renamed table
:param schema:
Optional name of schema to use. | [
"Renames",
"given",
"table",
"in",
"activity",
"table",
".",
"You",
"should",
"remember",
"to",
"call",
"this",
"function",
"whenever",
"you",
"rename",
"a",
"versioned",
"table",
"."
] | train | https://github.com/kvesteri/postgresql-audit/blob/91b497ced2e04dd44bb757b02983d2a64a2b1514/postgresql_audit/migrations.py#L267-L300 |
kvesteri/postgresql-audit | postgresql_audit/base.py | VersioningManager.instrument_versioned_classes | def instrument_versioned_classes(self, mapper, cls):
"""
Collect versioned class and add it to pending_classes list.
:mapper mapper: SQLAlchemy mapper object
:cls cls: SQLAlchemy declarative class
"""
if hasattr(cls, '__versioned__') and cls not in self.pending_classes:
self.pending_classes.add(cls) | python | def instrument_versioned_classes(self, mapper, cls):
"""
Collect versioned class and add it to pending_classes list.
:mapper mapper: SQLAlchemy mapper object
:cls cls: SQLAlchemy declarative class
"""
if hasattr(cls, '__versioned__') and cls not in self.pending_classes:
self.pending_classes.add(cls) | [
"def",
"instrument_versioned_classes",
"(",
"self",
",",
"mapper",
",",
"cls",
")",
":",
"if",
"hasattr",
"(",
"cls",
",",
"'__versioned__'",
")",
"and",
"cls",
"not",
"in",
"self",
".",
"pending_classes",
":",
"self",
".",
"pending_classes",
".",
"add",
"(",
"cls",
")"
] | Collect versioned class and add it to pending_classes list.
:mapper mapper: SQLAlchemy mapper object
:cls cls: SQLAlchemy declarative class | [
"Collect",
"versioned",
"class",
"and",
"add",
"it",
"to",
"pending_classes",
"list",
"."
] | train | https://github.com/kvesteri/postgresql-audit/blob/91b497ced2e04dd44bb757b02983d2a64a2b1514/postgresql_audit/base.py#L346-L354 |
kvesteri/postgresql-audit | postgresql_audit/base.py | VersioningManager.configure_versioned_classes | def configure_versioned_classes(self):
"""
Configures all versioned classes that were collected during
instrumentation process.
"""
for cls in self.pending_classes:
self.audit_table(cls.__table__, cls.__versioned__.get('exclude'))
assign_actor(self.base, self.transaction_cls, self.actor_cls) | python | def configure_versioned_classes(self):
"""
Configures all versioned classes that were collected during
instrumentation process.
"""
for cls in self.pending_classes:
self.audit_table(cls.__table__, cls.__versioned__.get('exclude'))
assign_actor(self.base, self.transaction_cls, self.actor_cls) | [
"def",
"configure_versioned_classes",
"(",
"self",
")",
":",
"for",
"cls",
"in",
"self",
".",
"pending_classes",
":",
"self",
".",
"audit_table",
"(",
"cls",
".",
"__table__",
",",
"cls",
".",
"__versioned__",
".",
"get",
"(",
"'exclude'",
")",
")",
"assign_actor",
"(",
"self",
".",
"base",
",",
"self",
".",
"transaction_cls",
",",
"self",
".",
"actor_cls",
")"
] | Configures all versioned classes that were collected during
instrumentation process. | [
"Configures",
"all",
"versioned",
"classes",
"that",
"were",
"collected",
"during",
"instrumentation",
"process",
"."
] | train | https://github.com/kvesteri/postgresql-audit/blob/91b497ced2e04dd44bb757b02983d2a64a2b1514/postgresql_audit/base.py#L356-L363 |
mfcovington/pubmed-lookup | pubmed_lookup/command_line.py | pubmed_citation | def pubmed_citation(args=sys.argv[1:], out=sys.stdout):
"""Get a citation via the command line using a PubMed ID or PubMed URL"""
parser = argparse.ArgumentParser(
description='Get a citation using a PubMed ID or PubMed URL')
parser.add_argument('query', help='PubMed ID or PubMed URL')
parser.add_argument(
'-m', '--mini', action='store_true', help='get mini citation')
parser.add_argument(
'-e', '--email', action='store', help='set user email', default='')
args = parser.parse_args(args=args)
lookup = PubMedLookup(args.query, args.email)
publication = Publication(lookup, resolve_doi=False)
if args.mini:
out.write(publication.cite_mini() + '\n')
else:
out.write(publication.cite() + '\n') | python | def pubmed_citation(args=sys.argv[1:], out=sys.stdout):
"""Get a citation via the command line using a PubMed ID or PubMed URL"""
parser = argparse.ArgumentParser(
description='Get a citation using a PubMed ID or PubMed URL')
parser.add_argument('query', help='PubMed ID or PubMed URL')
parser.add_argument(
'-m', '--mini', action='store_true', help='get mini citation')
parser.add_argument(
'-e', '--email', action='store', help='set user email', default='')
args = parser.parse_args(args=args)
lookup = PubMedLookup(args.query, args.email)
publication = Publication(lookup, resolve_doi=False)
if args.mini:
out.write(publication.cite_mini() + '\n')
else:
out.write(publication.cite() + '\n') | [
"def",
"pubmed_citation",
"(",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
",",
"out",
"=",
"sys",
".",
"stdout",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Get a citation using a PubMed ID or PubMed URL'",
")",
"parser",
".",
"add_argument",
"(",
"'query'",
",",
"help",
"=",
"'PubMed ID or PubMed URL'",
")",
"parser",
".",
"add_argument",
"(",
"'-m'",
",",
"'--mini'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'get mini citation'",
")",
"parser",
".",
"add_argument",
"(",
"'-e'",
",",
"'--email'",
",",
"action",
"=",
"'store'",
",",
"help",
"=",
"'set user email'",
",",
"default",
"=",
"''",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"args",
"=",
"args",
")",
"lookup",
"=",
"PubMedLookup",
"(",
"args",
".",
"query",
",",
"args",
".",
"email",
")",
"publication",
"=",
"Publication",
"(",
"lookup",
",",
"resolve_doi",
"=",
"False",
")",
"if",
"args",
".",
"mini",
":",
"out",
".",
"write",
"(",
"publication",
".",
"cite_mini",
"(",
")",
"+",
"'\\n'",
")",
"else",
":",
"out",
".",
"write",
"(",
"publication",
".",
"cite",
"(",
")",
"+",
"'\\n'",
")"
] | Get a citation via the command line using a PubMed ID or PubMed URL | [
"Get",
"a",
"citation",
"via",
"the",
"command",
"line",
"using",
"a",
"PubMed",
"ID",
"or",
"PubMed",
"URL"
] | train | https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/command_line.py#L7-L26 |
mfcovington/pubmed-lookup | pubmed_lookup/command_line.py | pubmed_url | def pubmed_url(args=sys.argv[1:], resolve_doi=True, out=sys.stdout):
"""
Get a publication URL via the command line using a PubMed ID or PubMed URL
"""
parser = argparse.ArgumentParser(
description='Get a publication URL using a PubMed ID or PubMed URL')
parser.add_argument('query', help='PubMed ID or PubMed URL')
parser.add_argument(
'-d', '--doi', action='store_false', help='get DOI URL')
parser.add_argument(
'-e', '--email', action='store', help='set user email', default='')
args = parser.parse_args(args=args)
lookup = PubMedLookup(args.query, args.email)
publication = Publication(lookup, resolve_doi=args.doi)
out.write(publication.url + '\n') | python | def pubmed_url(args=sys.argv[1:], resolve_doi=True, out=sys.stdout):
"""
Get a publication URL via the command line using a PubMed ID or PubMed URL
"""
parser = argparse.ArgumentParser(
description='Get a publication URL using a PubMed ID or PubMed URL')
parser.add_argument('query', help='PubMed ID or PubMed URL')
parser.add_argument(
'-d', '--doi', action='store_false', help='get DOI URL')
parser.add_argument(
'-e', '--email', action='store', help='set user email', default='')
args = parser.parse_args(args=args)
lookup = PubMedLookup(args.query, args.email)
publication = Publication(lookup, resolve_doi=args.doi)
out.write(publication.url + '\n') | [
"def",
"pubmed_url",
"(",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
",",
"resolve_doi",
"=",
"True",
",",
"out",
"=",
"sys",
".",
"stdout",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Get a publication URL using a PubMed ID or PubMed URL'",
")",
"parser",
".",
"add_argument",
"(",
"'query'",
",",
"help",
"=",
"'PubMed ID or PubMed URL'",
")",
"parser",
".",
"add_argument",
"(",
"'-d'",
",",
"'--doi'",
",",
"action",
"=",
"'store_false'",
",",
"help",
"=",
"'get DOI URL'",
")",
"parser",
".",
"add_argument",
"(",
"'-e'",
",",
"'--email'",
",",
"action",
"=",
"'store'",
",",
"help",
"=",
"'set user email'",
",",
"default",
"=",
"''",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"args",
"=",
"args",
")",
"lookup",
"=",
"PubMedLookup",
"(",
"args",
".",
"query",
",",
"args",
".",
"email",
")",
"publication",
"=",
"Publication",
"(",
"lookup",
",",
"resolve_doi",
"=",
"args",
".",
"doi",
")",
"out",
".",
"write",
"(",
"publication",
".",
"url",
"+",
"'\\n'",
")"
] | Get a publication URL via the command line using a PubMed ID or PubMed URL | [
"Get",
"a",
"publication",
"URL",
"via",
"the",
"command",
"line",
"using",
"a",
"PubMed",
"ID",
"or",
"PubMed",
"URL"
] | train | https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/command_line.py#L29-L47 |
mfcovington/pubmed-lookup | pubmed_lookup/pubmed_lookup.py | Publication.authors_et_al | def authors_et_al(self, max_authors=5):
"""
Return string with a truncated author list followed by 'et al.'
"""
author_list = self._author_list
if len(author_list) <= max_authors:
authors_et_al = self.authors
else:
authors_et_al = ", ".join(
self._author_list[:max_authors]) + ", et al."
return authors_et_al | python | def authors_et_al(self, max_authors=5):
"""
Return string with a truncated author list followed by 'et al.'
"""
author_list = self._author_list
if len(author_list) <= max_authors:
authors_et_al = self.authors
else:
authors_et_al = ", ".join(
self._author_list[:max_authors]) + ", et al."
return authors_et_al | [
"def",
"authors_et_al",
"(",
"self",
",",
"max_authors",
"=",
"5",
")",
":",
"author_list",
"=",
"self",
".",
"_author_list",
"if",
"len",
"(",
"author_list",
")",
"<=",
"max_authors",
":",
"authors_et_al",
"=",
"self",
".",
"authors",
"else",
":",
"authors_et_al",
"=",
"\", \"",
".",
"join",
"(",
"self",
".",
"_author_list",
"[",
":",
"max_authors",
"]",
")",
"+",
"\", et al.\"",
"return",
"authors_et_al"
] | Return string with a truncated author list followed by 'et al.' | [
"Return",
"string",
"with",
"a",
"truncated",
"author",
"list",
"followed",
"by",
"et",
"al",
"."
] | train | https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/pubmed_lookup.py#L48-L58 |
mfcovington/pubmed-lookup | pubmed_lookup/pubmed_lookup.py | Publication.cite | def cite(self, max_authors=5):
"""
Return string with a citation for the record, formatted as:
'{authors} ({year}). {title} {journal} {volume}({issue}): {pages}.'
"""
citation_data = {
'title': self.title,
'authors': self.authors_et_al(max_authors),
'year': self.year,
'journal': self.journal,
'volume': self.volume,
'issue': self.issue,
'pages': self.pages,
}
citation = "{authors} ({year}). {title} {journal}".format(
**citation_data)
if self.volume and self.issue and self.pages:
citation += " {volume}({issue}): {pages}.".format(**citation_data)
elif self.volume and self.issue:
citation += " {volume}({issue}).".format(**citation_data)
elif self.volume and self.pages:
citation += " {volume}: {pages}.".format(**citation_data)
elif self.volume:
citation += " {volume}.".format(**citation_data)
elif self.pages:
citation += " {pages}.".format(**citation_data)
else:
citation += "."
return citation | python | def cite(self, max_authors=5):
"""
Return string with a citation for the record, formatted as:
'{authors} ({year}). {title} {journal} {volume}({issue}): {pages}.'
"""
citation_data = {
'title': self.title,
'authors': self.authors_et_al(max_authors),
'year': self.year,
'journal': self.journal,
'volume': self.volume,
'issue': self.issue,
'pages': self.pages,
}
citation = "{authors} ({year}). {title} {journal}".format(
**citation_data)
if self.volume and self.issue and self.pages:
citation += " {volume}({issue}): {pages}.".format(**citation_data)
elif self.volume and self.issue:
citation += " {volume}({issue}).".format(**citation_data)
elif self.volume and self.pages:
citation += " {volume}: {pages}.".format(**citation_data)
elif self.volume:
citation += " {volume}.".format(**citation_data)
elif self.pages:
citation += " {pages}.".format(**citation_data)
else:
citation += "."
return citation | [
"def",
"cite",
"(",
"self",
",",
"max_authors",
"=",
"5",
")",
":",
"citation_data",
"=",
"{",
"'title'",
":",
"self",
".",
"title",
",",
"'authors'",
":",
"self",
".",
"authors_et_al",
"(",
"max_authors",
")",
",",
"'year'",
":",
"self",
".",
"year",
",",
"'journal'",
":",
"self",
".",
"journal",
",",
"'volume'",
":",
"self",
".",
"volume",
",",
"'issue'",
":",
"self",
".",
"issue",
",",
"'pages'",
":",
"self",
".",
"pages",
",",
"}",
"citation",
"=",
"\"{authors} ({year}). {title} {journal}\"",
".",
"format",
"(",
"*",
"*",
"citation_data",
")",
"if",
"self",
".",
"volume",
"and",
"self",
".",
"issue",
"and",
"self",
".",
"pages",
":",
"citation",
"+=",
"\" {volume}({issue}): {pages}.\"",
".",
"format",
"(",
"*",
"*",
"citation_data",
")",
"elif",
"self",
".",
"volume",
"and",
"self",
".",
"issue",
":",
"citation",
"+=",
"\" {volume}({issue}).\"",
".",
"format",
"(",
"*",
"*",
"citation_data",
")",
"elif",
"self",
".",
"volume",
"and",
"self",
".",
"pages",
":",
"citation",
"+=",
"\" {volume}: {pages}.\"",
".",
"format",
"(",
"*",
"*",
"citation_data",
")",
"elif",
"self",
".",
"volume",
":",
"citation",
"+=",
"\" {volume}.\"",
".",
"format",
"(",
"*",
"*",
"citation_data",
")",
"elif",
"self",
".",
"pages",
":",
"citation",
"+=",
"\" {pages}.\"",
".",
"format",
"(",
"*",
"*",
"citation_data",
")",
"else",
":",
"citation",
"+=",
"\".\"",
"return",
"citation"
] | Return string with a citation for the record, formatted as:
'{authors} ({year}). {title} {journal} {volume}({issue}): {pages}.' | [
"Return",
"string",
"with",
"a",
"citation",
"for",
"the",
"record",
"formatted",
"as",
":",
"{",
"authors",
"}",
"(",
"{",
"year",
"}",
")",
".",
"{",
"title",
"}",
"{",
"journal",
"}",
"{",
"volume",
"}",
"(",
"{",
"issue",
"}",
")",
":",
"{",
"pages",
"}",
"."
] | train | https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/pubmed_lookup.py#L60-L90 |
mfcovington/pubmed-lookup | pubmed_lookup/pubmed_lookup.py | Publication.cite_mini | def cite_mini(self):
"""
Return string with a citation for the record, formatted as:
'{first_author} - {year} - {journal}'
"""
citation_data = [self.first_author]
if len(self._author_list) > 1:
citation_data.append(self.last_author)
citation_data.extend([self.year, self.journal])
return " - ".join(citation_data) | python | def cite_mini(self):
"""
Return string with a citation for the record, formatted as:
'{first_author} - {year} - {journal}'
"""
citation_data = [self.first_author]
if len(self._author_list) > 1:
citation_data.append(self.last_author)
citation_data.extend([self.year, self.journal])
return " - ".join(citation_data) | [
"def",
"cite_mini",
"(",
"self",
")",
":",
"citation_data",
"=",
"[",
"self",
".",
"first_author",
"]",
"if",
"len",
"(",
"self",
".",
"_author_list",
")",
">",
"1",
":",
"citation_data",
".",
"append",
"(",
"self",
".",
"last_author",
")",
"citation_data",
".",
"extend",
"(",
"[",
"self",
".",
"year",
",",
"self",
".",
"journal",
"]",
")",
"return",
"\" - \"",
".",
"join",
"(",
"citation_data",
")"
] | Return string with a citation for the record, formatted as:
'{first_author} - {year} - {journal}' | [
"Return",
"string",
"with",
"a",
"citation",
"for",
"the",
"record",
"formatted",
"as",
":",
"{",
"first_author",
"}",
"-",
"{",
"year",
"}",
"-",
"{",
"journal",
"}"
] | train | https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/pubmed_lookup.py#L92-L104 |
mfcovington/pubmed-lookup | pubmed_lookup/pubmed_lookup.py | Publication.parse_abstract | def parse_abstract(xml_dict):
"""
Parse PubMed XML dictionary to retrieve abstract.
"""
key_path = ['PubmedArticleSet', 'PubmedArticle', 'MedlineCitation',
'Article', 'Abstract', 'AbstractText']
abstract_xml = reduce(dict.get, key_path, xml_dict)
abstract_paragraphs = []
if isinstance(abstract_xml, str):
abstract_paragraphs.append(abstract_xml)
elif isinstance(abstract_xml, dict):
abstract_text = abstract_xml.get('#text')
try:
abstract_label = abstract_xml['@Label']
except KeyError:
abstract_paragraphs.append(abstract_text)
else:
abstract_paragraphs.append(
"{}: {}".format(abstract_label, abstract_text))
elif isinstance(abstract_xml, list):
for abstract_section in abstract_xml:
try:
abstract_text = abstract_section['#text']
except KeyError:
abstract_text = abstract_section
try:
abstract_label = abstract_section['@Label']
except KeyError:
abstract_paragraphs.append(abstract_text)
else:
abstract_paragraphs.append(
"{}: {}".format(abstract_label, abstract_text))
else:
raise RuntimeError("Error parsing abstract.")
return "\n\n".join(abstract_paragraphs) | python | def parse_abstract(xml_dict):
"""
Parse PubMed XML dictionary to retrieve abstract.
"""
key_path = ['PubmedArticleSet', 'PubmedArticle', 'MedlineCitation',
'Article', 'Abstract', 'AbstractText']
abstract_xml = reduce(dict.get, key_path, xml_dict)
abstract_paragraphs = []
if isinstance(abstract_xml, str):
abstract_paragraphs.append(abstract_xml)
elif isinstance(abstract_xml, dict):
abstract_text = abstract_xml.get('#text')
try:
abstract_label = abstract_xml['@Label']
except KeyError:
abstract_paragraphs.append(abstract_text)
else:
abstract_paragraphs.append(
"{}: {}".format(abstract_label, abstract_text))
elif isinstance(abstract_xml, list):
for abstract_section in abstract_xml:
try:
abstract_text = abstract_section['#text']
except KeyError:
abstract_text = abstract_section
try:
abstract_label = abstract_section['@Label']
except KeyError:
abstract_paragraphs.append(abstract_text)
else:
abstract_paragraphs.append(
"{}: {}".format(abstract_label, abstract_text))
else:
raise RuntimeError("Error parsing abstract.")
return "\n\n".join(abstract_paragraphs) | [
"def",
"parse_abstract",
"(",
"xml_dict",
")",
":",
"key_path",
"=",
"[",
"'PubmedArticleSet'",
",",
"'PubmedArticle'",
",",
"'MedlineCitation'",
",",
"'Article'",
",",
"'Abstract'",
",",
"'AbstractText'",
"]",
"abstract_xml",
"=",
"reduce",
"(",
"dict",
".",
"get",
",",
"key_path",
",",
"xml_dict",
")",
"abstract_paragraphs",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"abstract_xml",
",",
"str",
")",
":",
"abstract_paragraphs",
".",
"append",
"(",
"abstract_xml",
")",
"elif",
"isinstance",
"(",
"abstract_xml",
",",
"dict",
")",
":",
"abstract_text",
"=",
"abstract_xml",
".",
"get",
"(",
"'#text'",
")",
"try",
":",
"abstract_label",
"=",
"abstract_xml",
"[",
"'@Label'",
"]",
"except",
"KeyError",
":",
"abstract_paragraphs",
".",
"append",
"(",
"abstract_text",
")",
"else",
":",
"abstract_paragraphs",
".",
"append",
"(",
"\"{}: {}\"",
".",
"format",
"(",
"abstract_label",
",",
"abstract_text",
")",
")",
"elif",
"isinstance",
"(",
"abstract_xml",
",",
"list",
")",
":",
"for",
"abstract_section",
"in",
"abstract_xml",
":",
"try",
":",
"abstract_text",
"=",
"abstract_section",
"[",
"'#text'",
"]",
"except",
"KeyError",
":",
"abstract_text",
"=",
"abstract_section",
"try",
":",
"abstract_label",
"=",
"abstract_section",
"[",
"'@Label'",
"]",
"except",
"KeyError",
":",
"abstract_paragraphs",
".",
"append",
"(",
"abstract_text",
")",
"else",
":",
"abstract_paragraphs",
".",
"append",
"(",
"\"{}: {}\"",
".",
"format",
"(",
"abstract_label",
",",
"abstract_text",
")",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Error parsing abstract.\"",
")",
"return",
"\"\\n\\n\"",
".",
"join",
"(",
"abstract_paragraphs",
")"
] | Parse PubMed XML dictionary to retrieve abstract. | [
"Parse",
"PubMed",
"XML",
"dictionary",
"to",
"retrieve",
"abstract",
"."
] | train | https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/pubmed_lookup.py#L107-L148 |
mfcovington/pubmed-lookup | pubmed_lookup/pubmed_lookup.py | Publication.get_pubmed_xml | def get_pubmed_xml(self):
"""
Use a PubMed ID to retrieve PubMed metadata in XML form.
"""
url = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/' \
'efetch.fcgi?db=pubmed&rettype=abstract&id={}' \
.format(self.pmid)
try:
response = urlopen(url)
except URLError:
xml_dict = ''
else:
xml = response.read().decode()
xml_dict = xmltodict.parse(xml)
return xml_dict | python | def get_pubmed_xml(self):
"""
Use a PubMed ID to retrieve PubMed metadata in XML form.
"""
url = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/' \
'efetch.fcgi?db=pubmed&rettype=abstract&id={}' \
.format(self.pmid)
try:
response = urlopen(url)
except URLError:
xml_dict = ''
else:
xml = response.read().decode()
xml_dict = xmltodict.parse(xml)
return xml_dict | [
"def",
"get_pubmed_xml",
"(",
"self",
")",
":",
"url",
"=",
"'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/'",
"'efetch.fcgi?db=pubmed&rettype=abstract&id={}'",
".",
"format",
"(",
"self",
".",
"pmid",
")",
"try",
":",
"response",
"=",
"urlopen",
"(",
"url",
")",
"except",
"URLError",
":",
"xml_dict",
"=",
"''",
"else",
":",
"xml",
"=",
"response",
".",
"read",
"(",
")",
".",
"decode",
"(",
")",
"xml_dict",
"=",
"xmltodict",
".",
"parse",
"(",
"xml",
")",
"return",
"xml_dict"
] | Use a PubMed ID to retrieve PubMed metadata in XML form. | [
"Use",
"a",
"PubMed",
"ID",
"to",
"retrieve",
"PubMed",
"metadata",
"in",
"XML",
"form",
"."
] | train | https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/pubmed_lookup.py#L150-L166 |
mfcovington/pubmed-lookup | pubmed_lookup/pubmed_lookup.py | Publication.set_abstract | def set_abstract(self, xml_dict):
"""
If record has an abstract, extract it from PubMed's XML data
"""
if self.record.get('HasAbstract') == 1 and xml_dict:
self.abstract = self.parse_abstract(xml_dict)
else:
self.abstract = '' | python | def set_abstract(self, xml_dict):
"""
If record has an abstract, extract it from PubMed's XML data
"""
if self.record.get('HasAbstract') == 1 and xml_dict:
self.abstract = self.parse_abstract(xml_dict)
else:
self.abstract = '' | [
"def",
"set_abstract",
"(",
"self",
",",
"xml_dict",
")",
":",
"if",
"self",
".",
"record",
".",
"get",
"(",
"'HasAbstract'",
")",
"==",
"1",
"and",
"xml_dict",
":",
"self",
".",
"abstract",
"=",
"self",
".",
"parse_abstract",
"(",
"xml_dict",
")",
"else",
":",
"self",
".",
"abstract",
"=",
"''"
] | If record has an abstract, extract it from PubMed's XML data | [
"If",
"record",
"has",
"an",
"abstract",
"extract",
"it",
"from",
"PubMed",
"s",
"XML",
"data"
] | train | https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/pubmed_lookup.py#L168-L175 |
mfcovington/pubmed-lookup | pubmed_lookup/pubmed_lookup.py | Publication.set_article_url | def set_article_url(self, resolve_doi=True):
"""
If record has a DOI, set article URL based on where the DOI points.
"""
if 'DOI' in self.record:
doi_url = "/".join(['http://dx.doi.org', self.record['DOI']])
if resolve_doi:
try:
response = urlopen(doi_url)
except URLError:
self.url = ''
else:
self.url = response.geturl()
else:
self.url = doi_url
else:
self.url = '' | python | def set_article_url(self, resolve_doi=True):
"""
If record has a DOI, set article URL based on where the DOI points.
"""
if 'DOI' in self.record:
doi_url = "/".join(['http://dx.doi.org', self.record['DOI']])
if resolve_doi:
try:
response = urlopen(doi_url)
except URLError:
self.url = ''
else:
self.url = response.geturl()
else:
self.url = doi_url
else:
self.url = '' | [
"def",
"set_article_url",
"(",
"self",
",",
"resolve_doi",
"=",
"True",
")",
":",
"if",
"'DOI'",
"in",
"self",
".",
"record",
":",
"doi_url",
"=",
"\"/\"",
".",
"join",
"(",
"[",
"'http://dx.doi.org'",
",",
"self",
".",
"record",
"[",
"'DOI'",
"]",
"]",
")",
"if",
"resolve_doi",
":",
"try",
":",
"response",
"=",
"urlopen",
"(",
"doi_url",
")",
"except",
"URLError",
":",
"self",
".",
"url",
"=",
"''",
"else",
":",
"self",
".",
"url",
"=",
"response",
".",
"geturl",
"(",
")",
"else",
":",
"self",
".",
"url",
"=",
"doi_url",
"else",
":",
"self",
".",
"url",
"=",
"''"
] | If record has a DOI, set article URL based on where the DOI points. | [
"If",
"record",
"has",
"a",
"DOI",
"set",
"article",
"URL",
"based",
"on",
"where",
"the",
"DOI",
"points",
"."
] | train | https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/pubmed_lookup.py#L177-L195 |
mfcovington/pubmed-lookup | pubmed_lookup/pubmed_lookup.py | Publication.set_pub_year_month_day | def set_pub_year_month_day(self, xml_dict):
"""
Set publication year, month, day from PubMed's XML data
"""
key_path = ['PubmedArticleSet', 'PubmedArticle', 'MedlineCitation',
'Article', 'Journal', 'JournalIssue', 'PubDate']
pubdate_xml = reduce(dict.get, key_path, xml_dict)
if isinstance(pubdate_xml, dict):
self.year = pubdate_xml.get('Year')
month_short = pubdate_xml.get('Month')
self.day = pubdate_xml.get('Day')
try:
self.month = datetime.datetime.strptime(
month_short, "%b").month
except (ValueError, TypeError):
self.month = ''
else:
self.year = ''
self.month = ''
self.day = '' | python | def set_pub_year_month_day(self, xml_dict):
"""
Set publication year, month, day from PubMed's XML data
"""
key_path = ['PubmedArticleSet', 'PubmedArticle', 'MedlineCitation',
'Article', 'Journal', 'JournalIssue', 'PubDate']
pubdate_xml = reduce(dict.get, key_path, xml_dict)
if isinstance(pubdate_xml, dict):
self.year = pubdate_xml.get('Year')
month_short = pubdate_xml.get('Month')
self.day = pubdate_xml.get('Day')
try:
self.month = datetime.datetime.strptime(
month_short, "%b").month
except (ValueError, TypeError):
self.month = ''
else:
self.year = ''
self.month = ''
self.day = '' | [
"def",
"set_pub_year_month_day",
"(",
"self",
",",
"xml_dict",
")",
":",
"key_path",
"=",
"[",
"'PubmedArticleSet'",
",",
"'PubmedArticle'",
",",
"'MedlineCitation'",
",",
"'Article'",
",",
"'Journal'",
",",
"'JournalIssue'",
",",
"'PubDate'",
"]",
"pubdate_xml",
"=",
"reduce",
"(",
"dict",
".",
"get",
",",
"key_path",
",",
"xml_dict",
")",
"if",
"isinstance",
"(",
"pubdate_xml",
",",
"dict",
")",
":",
"self",
".",
"year",
"=",
"pubdate_xml",
".",
"get",
"(",
"'Year'",
")",
"month_short",
"=",
"pubdate_xml",
".",
"get",
"(",
"'Month'",
")",
"self",
".",
"day",
"=",
"pubdate_xml",
".",
"get",
"(",
"'Day'",
")",
"try",
":",
"self",
".",
"month",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"month_short",
",",
"\"%b\"",
")",
".",
"month",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"self",
".",
"month",
"=",
"''",
"else",
":",
"self",
".",
"year",
"=",
"''",
"self",
".",
"month",
"=",
"''",
"self",
".",
"day",
"=",
"''"
] | Set publication year, month, day from PubMed's XML data | [
"Set",
"publication",
"year",
"month",
"day",
"from",
"PubMed",
"s",
"XML",
"data"
] | train | https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/pubmed_lookup.py#L197-L219 |
mfcovington/pubmed-lookup | pubmed_lookup/pubmed_lookup.py | PubMedLookup.parse_pubmed_url | def parse_pubmed_url(pubmed_url):
"""Get PubMed ID (pmid) from PubMed URL."""
parse_result = urlparse(pubmed_url)
pattern = re.compile(r'^/pubmed/(\d+)$')
pmid = pattern.match(parse_result.path).group(1)
return pmid | python | def parse_pubmed_url(pubmed_url):
"""Get PubMed ID (pmid) from PubMed URL."""
parse_result = urlparse(pubmed_url)
pattern = re.compile(r'^/pubmed/(\d+)$')
pmid = pattern.match(parse_result.path).group(1)
return pmid | [
"def",
"parse_pubmed_url",
"(",
"pubmed_url",
")",
":",
"parse_result",
"=",
"urlparse",
"(",
"pubmed_url",
")",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'^/pubmed/(\\d+)$'",
")",
"pmid",
"=",
"pattern",
".",
"match",
"(",
"parse_result",
".",
"path",
")",
".",
"group",
"(",
"1",
")",
"return",
"pmid"
] | Get PubMed ID (pmid) from PubMed URL. | [
"Get",
"PubMed",
"ID",
"(",
"pmid",
")",
"from",
"PubMed",
"URL",
"."
] | train | https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/pubmed_lookup.py#L249-L254 |
mfcovington/pubmed-lookup | pubmed_lookup/pubmed_lookup.py | PubMedLookup.get_pubmed_record | def get_pubmed_record(pmid):
"""Get PubMed record from PubMed ID."""
handle = Entrez.esummary(db="pubmed", id=pmid)
record = Entrez.read(handle)
return record | python | def get_pubmed_record(pmid):
"""Get PubMed record from PubMed ID."""
handle = Entrez.esummary(db="pubmed", id=pmid)
record = Entrez.read(handle)
return record | [
"def",
"get_pubmed_record",
"(",
"pmid",
")",
":",
"handle",
"=",
"Entrez",
".",
"esummary",
"(",
"db",
"=",
"\"pubmed\"",
",",
"id",
"=",
"pmid",
")",
"record",
"=",
"Entrez",
".",
"read",
"(",
"handle",
")",
"return",
"record"
] | Get PubMed record from PubMed ID. | [
"Get",
"PubMed",
"record",
"from",
"PubMed",
"ID",
"."
] | train | https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/pubmed_lookup.py#L257-L261 |
UCSBarchlab/PyRTL | pyrtl/simulation.py | Simulation._initialize | def _initialize(self, register_value_map=None, memory_value_map=None, default_value=None):
""" Sets the wire, register, and memory values to default or as specified.
:param register_value_map: is a map of {Register: value}.
:param memory_value_map: is a map of maps {Memory: {address: Value}}.
:param default_value: is the value that all unspecified registers and memories will
default to. If no default_value is specified, it will use the value stored in the
object (default to 0)
"""
if default_value is None:
default_value = self.default_value
# set registers to their values
reg_set = self.block.wirevector_subset(Register)
if register_value_map is not None:
for r in reg_set:
self.value[r] = self.regvalue[r] = register_value_map.get(r, default_value)
# set constants to their set values
for w in self.block.wirevector_subset(Const):
self.value[w] = w.val
assert isinstance(w.val, numbers.Integral) # for now
# set memories to their passed values
for mem_net in self.block.logic_subset('m@'):
memid = mem_net.op_param[1].id
if memid not in self.memvalue:
self.memvalue[memid] = {}
if memory_value_map is not None:
for (mem, mem_map) in memory_value_map.items():
if isinstance(mem, RomBlock):
raise PyrtlError('error, one or more of the memories in the map is a RomBlock')
if isinstance(self.block, PostSynthBlock):
mem = self.block.mem_map[mem] # pylint: disable=maybe-no-member
self.memvalue[mem.id] = mem_map
max_addr_val, max_bit_val = 2**mem.addrwidth, 2**mem.bitwidth
for (addr, val) in mem_map.items():
if addr < 0 or addr >= max_addr_val:
raise PyrtlError('error, address %s in %s outside of bounds' %
(str(addr), mem.name))
if val < 0 or val >= max_bit_val:
raise PyrtlError('error, %s at %s in %s outside of bounds' %
(str(val), str(addr), mem.name))
# set all other variables to default value
for w in self.block.wirevector_set:
if w not in self.value:
self.value[w] = default_value
self.ordered_nets = tuple((i for i in self.block))
self.reg_update_nets = tuple((self.block.logic_subset('r')))
self.mem_update_nets = tuple((self.block.logic_subset('@'))) | python | def _initialize(self, register_value_map=None, memory_value_map=None, default_value=None):
""" Sets the wire, register, and memory values to default or as specified.
:param register_value_map: is a map of {Register: value}.
:param memory_value_map: is a map of maps {Memory: {address: Value}}.
:param default_value: is the value that all unspecified registers and memories will
default to. If no default_value is specified, it will use the value stored in the
object (default to 0)
"""
if default_value is None:
default_value = self.default_value
# set registers to their values
reg_set = self.block.wirevector_subset(Register)
if register_value_map is not None:
for r in reg_set:
self.value[r] = self.regvalue[r] = register_value_map.get(r, default_value)
# set constants to their set values
for w in self.block.wirevector_subset(Const):
self.value[w] = w.val
assert isinstance(w.val, numbers.Integral) # for now
# set memories to their passed values
for mem_net in self.block.logic_subset('m@'):
memid = mem_net.op_param[1].id
if memid not in self.memvalue:
self.memvalue[memid] = {}
if memory_value_map is not None:
for (mem, mem_map) in memory_value_map.items():
if isinstance(mem, RomBlock):
raise PyrtlError('error, one or more of the memories in the map is a RomBlock')
if isinstance(self.block, PostSynthBlock):
mem = self.block.mem_map[mem] # pylint: disable=maybe-no-member
self.memvalue[mem.id] = mem_map
max_addr_val, max_bit_val = 2**mem.addrwidth, 2**mem.bitwidth
for (addr, val) in mem_map.items():
if addr < 0 or addr >= max_addr_val:
raise PyrtlError('error, address %s in %s outside of bounds' %
(str(addr), mem.name))
if val < 0 or val >= max_bit_val:
raise PyrtlError('error, %s at %s in %s outside of bounds' %
(str(val), str(addr), mem.name))
# set all other variables to default value
for w in self.block.wirevector_set:
if w not in self.value:
self.value[w] = default_value
self.ordered_nets = tuple((i for i in self.block))
self.reg_update_nets = tuple((self.block.logic_subset('r')))
self.mem_update_nets = tuple((self.block.logic_subset('@'))) | [
"def",
"_initialize",
"(",
"self",
",",
"register_value_map",
"=",
"None",
",",
"memory_value_map",
"=",
"None",
",",
"default_value",
"=",
"None",
")",
":",
"if",
"default_value",
"is",
"None",
":",
"default_value",
"=",
"self",
".",
"default_value",
"# set registers to their values",
"reg_set",
"=",
"self",
".",
"block",
".",
"wirevector_subset",
"(",
"Register",
")",
"if",
"register_value_map",
"is",
"not",
"None",
":",
"for",
"r",
"in",
"reg_set",
":",
"self",
".",
"value",
"[",
"r",
"]",
"=",
"self",
".",
"regvalue",
"[",
"r",
"]",
"=",
"register_value_map",
".",
"get",
"(",
"r",
",",
"default_value",
")",
"# set constants to their set values",
"for",
"w",
"in",
"self",
".",
"block",
".",
"wirevector_subset",
"(",
"Const",
")",
":",
"self",
".",
"value",
"[",
"w",
"]",
"=",
"w",
".",
"val",
"assert",
"isinstance",
"(",
"w",
".",
"val",
",",
"numbers",
".",
"Integral",
")",
"# for now",
"# set memories to their passed values",
"for",
"mem_net",
"in",
"self",
".",
"block",
".",
"logic_subset",
"(",
"'m@'",
")",
":",
"memid",
"=",
"mem_net",
".",
"op_param",
"[",
"1",
"]",
".",
"id",
"if",
"memid",
"not",
"in",
"self",
".",
"memvalue",
":",
"self",
".",
"memvalue",
"[",
"memid",
"]",
"=",
"{",
"}",
"if",
"memory_value_map",
"is",
"not",
"None",
":",
"for",
"(",
"mem",
",",
"mem_map",
")",
"in",
"memory_value_map",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"mem",
",",
"RomBlock",
")",
":",
"raise",
"PyrtlError",
"(",
"'error, one or more of the memories in the map is a RomBlock'",
")",
"if",
"isinstance",
"(",
"self",
".",
"block",
",",
"PostSynthBlock",
")",
":",
"mem",
"=",
"self",
".",
"block",
".",
"mem_map",
"[",
"mem",
"]",
"# pylint: disable=maybe-no-member",
"self",
".",
"memvalue",
"[",
"mem",
".",
"id",
"]",
"=",
"mem_map",
"max_addr_val",
",",
"max_bit_val",
"=",
"2",
"**",
"mem",
".",
"addrwidth",
",",
"2",
"**",
"mem",
".",
"bitwidth",
"for",
"(",
"addr",
",",
"val",
")",
"in",
"mem_map",
".",
"items",
"(",
")",
":",
"if",
"addr",
"<",
"0",
"or",
"addr",
">=",
"max_addr_val",
":",
"raise",
"PyrtlError",
"(",
"'error, address %s in %s outside of bounds'",
"%",
"(",
"str",
"(",
"addr",
")",
",",
"mem",
".",
"name",
")",
")",
"if",
"val",
"<",
"0",
"or",
"val",
">=",
"max_bit_val",
":",
"raise",
"PyrtlError",
"(",
"'error, %s at %s in %s outside of bounds'",
"%",
"(",
"str",
"(",
"val",
")",
",",
"str",
"(",
"addr",
")",
",",
"mem",
".",
"name",
")",
")",
"# set all other variables to default value",
"for",
"w",
"in",
"self",
".",
"block",
".",
"wirevector_set",
":",
"if",
"w",
"not",
"in",
"self",
".",
"value",
":",
"self",
".",
"value",
"[",
"w",
"]",
"=",
"default_value",
"self",
".",
"ordered_nets",
"=",
"tuple",
"(",
"(",
"i",
"for",
"i",
"in",
"self",
".",
"block",
")",
")",
"self",
".",
"reg_update_nets",
"=",
"tuple",
"(",
"(",
"self",
".",
"block",
".",
"logic_subset",
"(",
"'r'",
")",
")",
")",
"self",
".",
"mem_update_nets",
"=",
"tuple",
"(",
"(",
"self",
".",
"block",
".",
"logic_subset",
"(",
"'@'",
")",
")",
")"
] | Sets the wire, register, and memory values to default or as specified.
:param register_value_map: is a map of {Register: value}.
:param memory_value_map: is a map of maps {Memory: {address: Value}}.
:param default_value: is the value that all unspecified registers and memories will
default to. If no default_value is specified, it will use the value stored in the
object (default to 0) | [
"Sets",
"the",
"wire",
"register",
"and",
"memory",
"values",
"to",
"default",
"or",
"as",
"specified",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L96-L150 |
UCSBarchlab/PyRTL | pyrtl/simulation.py | Simulation.step | def step(self, provided_inputs):
""" Take the simulation forward one cycle
:param provided_inputs: a dictionary mapping wirevectors to their values for this step
All input wires must be in the provided_inputs in order for the simulation
to accept these values
Example: if we have inputs named 'a' and 'x', we can call:
sim.step({'a': 1, 'x': 23}) to simulate a cycle with values 1 and 23
respectively
"""
# Check that all Input have a corresponding provided_input
input_set = self.block.wirevector_subset(Input)
supplied_inputs = set()
for i in provided_inputs:
if isinstance(i, WireVector):
name = i.name
else:
name = i
sim_wire = self.block.wirevector_by_name[name]
if sim_wire not in input_set:
raise PyrtlError(
'step provided a value for input for "%s" which is '
'not a known input ' % name)
if not isinstance(provided_inputs[i], numbers.Integral) or provided_inputs[i] < 0:
raise PyrtlError(
'step provided an input "%s" which is not a valid '
'positive integer' % provided_inputs[i])
if len(bin(provided_inputs[i]))-2 > sim_wire.bitwidth:
raise PyrtlError(
'the bitwidth for "%s" is %d, but the provided input '
'%d requires %d bits to represent'
% (name, sim_wire.bitwidth,
provided_inputs[i], len(bin(provided_inputs[i]))-2))
self.value[sim_wire] = provided_inputs[i]
supplied_inputs.add(sim_wire)
# Check that only inputs are specified, and set the values
if input_set != supplied_inputs:
for i in input_set.difference(supplied_inputs):
raise PyrtlError('Input "%s" has no input value specified' % i.name)
self.value.update(self.regvalue) # apply register updates from previous step
for net in self.ordered_nets:
self._execute(net)
# Do all of the mem operations based off the new values changed in _execute()
for net in self.mem_update_nets:
self._mem_update(net)
# at the end of the step, record the values to the trace
# print self.value # Helpful Debug Print
if self.tracer is not None:
self.tracer.add_step(self.value)
# Do all of the reg updates based off of the new values
for net in self.reg_update_nets:
argval = self.value[net.args[0]]
self.regvalue[net.dests[0]] = self._sanitize(argval, net.dests[0])
# finally, if any of the rtl_assert assertions are failing then we should
# raise the appropriate exceptions
check_rtl_assertions(self) | python | def step(self, provided_inputs):
""" Take the simulation forward one cycle
:param provided_inputs: a dictionary mapping wirevectors to their values for this step
All input wires must be in the provided_inputs in order for the simulation
to accept these values
Example: if we have inputs named 'a' and 'x', we can call:
sim.step({'a': 1, 'x': 23}) to simulate a cycle with values 1 and 23
respectively
"""
# Check that all Input have a corresponding provided_input
input_set = self.block.wirevector_subset(Input)
supplied_inputs = set()
for i in provided_inputs:
if isinstance(i, WireVector):
name = i.name
else:
name = i
sim_wire = self.block.wirevector_by_name[name]
if sim_wire not in input_set:
raise PyrtlError(
'step provided a value for input for "%s" which is '
'not a known input ' % name)
if not isinstance(provided_inputs[i], numbers.Integral) or provided_inputs[i] < 0:
raise PyrtlError(
'step provided an input "%s" which is not a valid '
'positive integer' % provided_inputs[i])
if len(bin(provided_inputs[i]))-2 > sim_wire.bitwidth:
raise PyrtlError(
'the bitwidth for "%s" is %d, but the provided input '
'%d requires %d bits to represent'
% (name, sim_wire.bitwidth,
provided_inputs[i], len(bin(provided_inputs[i]))-2))
self.value[sim_wire] = provided_inputs[i]
supplied_inputs.add(sim_wire)
# Check that only inputs are specified, and set the values
if input_set != supplied_inputs:
for i in input_set.difference(supplied_inputs):
raise PyrtlError('Input "%s" has no input value specified' % i.name)
self.value.update(self.regvalue) # apply register updates from previous step
for net in self.ordered_nets:
self._execute(net)
# Do all of the mem operations based off the new values changed in _execute()
for net in self.mem_update_nets:
self._mem_update(net)
# at the end of the step, record the values to the trace
# print self.value # Helpful Debug Print
if self.tracer is not None:
self.tracer.add_step(self.value)
# Do all of the reg updates based off of the new values
for net in self.reg_update_nets:
argval = self.value[net.args[0]]
self.regvalue[net.dests[0]] = self._sanitize(argval, net.dests[0])
# finally, if any of the rtl_assert assertions are failing then we should
# raise the appropriate exceptions
check_rtl_assertions(self) | [
"def",
"step",
"(",
"self",
",",
"provided_inputs",
")",
":",
"# Check that all Input have a corresponding provided_input",
"input_set",
"=",
"self",
".",
"block",
".",
"wirevector_subset",
"(",
"Input",
")",
"supplied_inputs",
"=",
"set",
"(",
")",
"for",
"i",
"in",
"provided_inputs",
":",
"if",
"isinstance",
"(",
"i",
",",
"WireVector",
")",
":",
"name",
"=",
"i",
".",
"name",
"else",
":",
"name",
"=",
"i",
"sim_wire",
"=",
"self",
".",
"block",
".",
"wirevector_by_name",
"[",
"name",
"]",
"if",
"sim_wire",
"not",
"in",
"input_set",
":",
"raise",
"PyrtlError",
"(",
"'step provided a value for input for \"%s\" which is '",
"'not a known input '",
"%",
"name",
")",
"if",
"not",
"isinstance",
"(",
"provided_inputs",
"[",
"i",
"]",
",",
"numbers",
".",
"Integral",
")",
"or",
"provided_inputs",
"[",
"i",
"]",
"<",
"0",
":",
"raise",
"PyrtlError",
"(",
"'step provided an input \"%s\" which is not a valid '",
"'positive integer'",
"%",
"provided_inputs",
"[",
"i",
"]",
")",
"if",
"len",
"(",
"bin",
"(",
"provided_inputs",
"[",
"i",
"]",
")",
")",
"-",
"2",
">",
"sim_wire",
".",
"bitwidth",
":",
"raise",
"PyrtlError",
"(",
"'the bitwidth for \"%s\" is %d, but the provided input '",
"'%d requires %d bits to represent'",
"%",
"(",
"name",
",",
"sim_wire",
".",
"bitwidth",
",",
"provided_inputs",
"[",
"i",
"]",
",",
"len",
"(",
"bin",
"(",
"provided_inputs",
"[",
"i",
"]",
")",
")",
"-",
"2",
")",
")",
"self",
".",
"value",
"[",
"sim_wire",
"]",
"=",
"provided_inputs",
"[",
"i",
"]",
"supplied_inputs",
".",
"add",
"(",
"sim_wire",
")",
"# Check that only inputs are specified, and set the values",
"if",
"input_set",
"!=",
"supplied_inputs",
":",
"for",
"i",
"in",
"input_set",
".",
"difference",
"(",
"supplied_inputs",
")",
":",
"raise",
"PyrtlError",
"(",
"'Input \"%s\" has no input value specified'",
"%",
"i",
".",
"name",
")",
"self",
".",
"value",
".",
"update",
"(",
"self",
".",
"regvalue",
")",
"# apply register updates from previous step",
"for",
"net",
"in",
"self",
".",
"ordered_nets",
":",
"self",
".",
"_execute",
"(",
"net",
")",
"# Do all of the mem operations based off the new values changed in _execute()",
"for",
"net",
"in",
"self",
".",
"mem_update_nets",
":",
"self",
".",
"_mem_update",
"(",
"net",
")",
"# at the end of the step, record the values to the trace",
"# print self.value # Helpful Debug Print",
"if",
"self",
".",
"tracer",
"is",
"not",
"None",
":",
"self",
".",
"tracer",
".",
"add_step",
"(",
"self",
".",
"value",
")",
"# Do all of the reg updates based off of the new values",
"for",
"net",
"in",
"self",
".",
"reg_update_nets",
":",
"argval",
"=",
"self",
".",
"value",
"[",
"net",
".",
"args",
"[",
"0",
"]",
"]",
"self",
".",
"regvalue",
"[",
"net",
".",
"dests",
"[",
"0",
"]",
"]",
"=",
"self",
".",
"_sanitize",
"(",
"argval",
",",
"net",
".",
"dests",
"[",
"0",
"]",
")",
"# finally, if any of the rtl_assert assertions are failing then we should",
"# raise the appropriate exceptions",
"check_rtl_assertions",
"(",
"self",
")"
] | Take the simulation forward one cycle
:param provided_inputs: a dictionary mapping wirevectors to their values for this step
All input wires must be in the provided_inputs in order for the simulation
to accept these values
Example: if we have inputs named 'a' and 'x', we can call:
sim.step({'a': 1, 'x': 23}) to simulate a cycle with values 1 and 23
respectively | [
"Take",
"the",
"simulation",
"forward",
"one",
"cycle"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L152-L218 |
UCSBarchlab/PyRTL | pyrtl/simulation.py | Simulation.inspect | def inspect(self, w):
""" Get the value of a wirevector in the last simulation cycle.
:param w: the name of the WireVector to inspect
(passing in a WireVector instead of a name is deprecated)
:return: value of w in the current step of simulation
Will throw KeyError if w does not exist in the simulation.
"""
wire = self.block.wirevector_by_name.get(w, w)
return self.value[wire] | python | def inspect(self, w):
""" Get the value of a wirevector in the last simulation cycle.
:param w: the name of the WireVector to inspect
(passing in a WireVector instead of a name is deprecated)
:return: value of w in the current step of simulation
Will throw KeyError if w does not exist in the simulation.
"""
wire = self.block.wirevector_by_name.get(w, w)
return self.value[wire] | [
"def",
"inspect",
"(",
"self",
",",
"w",
")",
":",
"wire",
"=",
"self",
".",
"block",
".",
"wirevector_by_name",
".",
"get",
"(",
"w",
",",
"w",
")",
"return",
"self",
".",
"value",
"[",
"wire",
"]"
] | Get the value of a wirevector in the last simulation cycle.
:param w: the name of the WireVector to inspect
(passing in a WireVector instead of a name is deprecated)
:return: value of w in the current step of simulation
Will throw KeyError if w does not exist in the simulation. | [
"Get",
"the",
"value",
"of",
"a",
"wirevector",
"in",
"the",
"last",
"simulation",
"cycle",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L220-L230 |
UCSBarchlab/PyRTL | pyrtl/simulation.py | Simulation._execute | def _execute(self, net):
"""Handle the combinational logic update rules for the given net.
This function, along with edge_update, defined the semantics
of the primitive ops. Function updates self.value accordingly.
"""
if net.op in 'r@':
return # registers and memory write ports have no logic function
elif net.op in self.simple_func:
argvals = (self.value[arg] for arg in net.args)
result = self.simple_func[net.op](*argvals)
elif net.op == 'c':
result = 0
for arg in net.args:
result = result << len(arg)
result = result | self.value[arg]
elif net.op == 's':
result = 0
source = self.value[net.args[0]]
for b in net.op_param[::-1]:
result = (result << 1) | (0x1 & (source >> b))
elif net.op == 'm':
# memories act async for reads
memid = net.op_param[0]
mem = net.op_param[1]
read_addr = self.value[net.args[0]]
if isinstance(mem, RomBlock):
result = mem._get_read_data(read_addr)
else:
result = self.memvalue[memid].get(read_addr, self.default_value)
else:
raise PyrtlInternalError('error, unknown op type')
self.value[net.dests[0]] = self._sanitize(result, net.dests[0]) | python | def _execute(self, net):
"""Handle the combinational logic update rules for the given net.
This function, along with edge_update, defined the semantics
of the primitive ops. Function updates self.value accordingly.
"""
if net.op in 'r@':
return # registers and memory write ports have no logic function
elif net.op in self.simple_func:
argvals = (self.value[arg] for arg in net.args)
result = self.simple_func[net.op](*argvals)
elif net.op == 'c':
result = 0
for arg in net.args:
result = result << len(arg)
result = result | self.value[arg]
elif net.op == 's':
result = 0
source = self.value[net.args[0]]
for b in net.op_param[::-1]:
result = (result << 1) | (0x1 & (source >> b))
elif net.op == 'm':
# memories act async for reads
memid = net.op_param[0]
mem = net.op_param[1]
read_addr = self.value[net.args[0]]
if isinstance(mem, RomBlock):
result = mem._get_read_data(read_addr)
else:
result = self.memvalue[memid].get(read_addr, self.default_value)
else:
raise PyrtlInternalError('error, unknown op type')
self.value[net.dests[0]] = self._sanitize(result, net.dests[0]) | [
"def",
"_execute",
"(",
"self",
",",
"net",
")",
":",
"if",
"net",
".",
"op",
"in",
"'r@'",
":",
"return",
"# registers and memory write ports have no logic function",
"elif",
"net",
".",
"op",
"in",
"self",
".",
"simple_func",
":",
"argvals",
"=",
"(",
"self",
".",
"value",
"[",
"arg",
"]",
"for",
"arg",
"in",
"net",
".",
"args",
")",
"result",
"=",
"self",
".",
"simple_func",
"[",
"net",
".",
"op",
"]",
"(",
"*",
"argvals",
")",
"elif",
"net",
".",
"op",
"==",
"'c'",
":",
"result",
"=",
"0",
"for",
"arg",
"in",
"net",
".",
"args",
":",
"result",
"=",
"result",
"<<",
"len",
"(",
"arg",
")",
"result",
"=",
"result",
"|",
"self",
".",
"value",
"[",
"arg",
"]",
"elif",
"net",
".",
"op",
"==",
"'s'",
":",
"result",
"=",
"0",
"source",
"=",
"self",
".",
"value",
"[",
"net",
".",
"args",
"[",
"0",
"]",
"]",
"for",
"b",
"in",
"net",
".",
"op_param",
"[",
":",
":",
"-",
"1",
"]",
":",
"result",
"=",
"(",
"result",
"<<",
"1",
")",
"|",
"(",
"0x1",
"&",
"(",
"source",
">>",
"b",
")",
")",
"elif",
"net",
".",
"op",
"==",
"'m'",
":",
"# memories act async for reads",
"memid",
"=",
"net",
".",
"op_param",
"[",
"0",
"]",
"mem",
"=",
"net",
".",
"op_param",
"[",
"1",
"]",
"read_addr",
"=",
"self",
".",
"value",
"[",
"net",
".",
"args",
"[",
"0",
"]",
"]",
"if",
"isinstance",
"(",
"mem",
",",
"RomBlock",
")",
":",
"result",
"=",
"mem",
".",
"_get_read_data",
"(",
"read_addr",
")",
"else",
":",
"result",
"=",
"self",
".",
"memvalue",
"[",
"memid",
"]",
".",
"get",
"(",
"read_addr",
",",
"self",
".",
"default_value",
")",
"else",
":",
"raise",
"PyrtlInternalError",
"(",
"'error, unknown op type'",
")",
"self",
".",
"value",
"[",
"net",
".",
"dests",
"[",
"0",
"]",
"]",
"=",
"self",
".",
"_sanitize",
"(",
"result",
",",
"net",
".",
"dests",
"[",
"0",
"]",
")"
] | Handle the combinational logic update rules for the given net.
This function, along with edge_update, defined the semantics
of the primitive ops. Function updates self.value accordingly. | [
"Handle",
"the",
"combinational",
"logic",
"update",
"rules",
"for",
"the",
"given",
"net",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L253-L286 |
UCSBarchlab/PyRTL | pyrtl/simulation.py | Simulation._mem_update | def _mem_update(self, net):
"""Handle the mem update for the simulation of the given net (which is a memory).
Combinational logic should have no posedge behavior, but registers and
memory should. This function, used after _execute, defines the
semantics of the primitive ops. Function updates self.memvalue accordingly
(using prior_value)
"""
if net.op != '@':
raise PyrtlInternalError
memid = net.op_param[0]
write_addr = self.value[net.args[0]]
write_val = self.value[net.args[1]]
write_enable = self.value[net.args[2]]
if write_enable:
self.memvalue[memid][write_addr] = write_val | python | def _mem_update(self, net):
"""Handle the mem update for the simulation of the given net (which is a memory).
Combinational logic should have no posedge behavior, but registers and
memory should. This function, used after _execute, defines the
semantics of the primitive ops. Function updates self.memvalue accordingly
(using prior_value)
"""
if net.op != '@':
raise PyrtlInternalError
memid = net.op_param[0]
write_addr = self.value[net.args[0]]
write_val = self.value[net.args[1]]
write_enable = self.value[net.args[2]]
if write_enable:
self.memvalue[memid][write_addr] = write_val | [
"def",
"_mem_update",
"(",
"self",
",",
"net",
")",
":",
"if",
"net",
".",
"op",
"!=",
"'@'",
":",
"raise",
"PyrtlInternalError",
"memid",
"=",
"net",
".",
"op_param",
"[",
"0",
"]",
"write_addr",
"=",
"self",
".",
"value",
"[",
"net",
".",
"args",
"[",
"0",
"]",
"]",
"write_val",
"=",
"self",
".",
"value",
"[",
"net",
".",
"args",
"[",
"1",
"]",
"]",
"write_enable",
"=",
"self",
".",
"value",
"[",
"net",
".",
"args",
"[",
"2",
"]",
"]",
"if",
"write_enable",
":",
"self",
".",
"memvalue",
"[",
"memid",
"]",
"[",
"write_addr",
"]",
"=",
"write_val"
] | Handle the mem update for the simulation of the given net (which is a memory).
Combinational logic should have no posedge behavior, but registers and
memory should. This function, used after _execute, defines the
semantics of the primitive ops. Function updates self.memvalue accordingly
(using prior_value) | [
"Handle",
"the",
"mem",
"update",
"for",
"the",
"simulation",
"of",
"the",
"given",
"net",
"(",
"which",
"is",
"a",
"memory",
")",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L288-L303 |
UCSBarchlab/PyRTL | pyrtl/simulation.py | FastSimulation.step | def step(self, provided_inputs):
""" Run the simulation for a cycle
:param provided_inputs: a dictionary mapping WireVectors (or their names)
to their values for this step
eg: {wire: 3, "wire_name": 17}
"""
# validate_inputs
for wire, value in provided_inputs.items():
wire = self.block.get_wirevector_by_name(wire) if isinstance(wire, str) else wire
if value > wire.bitmask or value < 0:
raise PyrtlError("Wire {} has value {} which cannot be represented"
" using its bitwidth".format(wire, value))
# building the simulation data
ins = {self._to_name(wire): value for wire, value in provided_inputs.items()}
ins.update(self.regs)
ins.update(self.mems)
# propagate through logic
self.regs, self.outs, mem_writes = self.sim_func(ins)
for mem, addr, value in mem_writes:
self.mems[mem][addr] = value
# for tracer compatibility
self.context = self.outs.copy()
self.context.update(ins) # also gets old register values
if self.tracer is not None:
self.tracer.add_fast_step(self)
# check the rtl assertions
check_rtl_assertions(self) | python | def step(self, provided_inputs):
""" Run the simulation for a cycle
:param provided_inputs: a dictionary mapping WireVectors (or their names)
to their values for this step
eg: {wire: 3, "wire_name": 17}
"""
# validate_inputs
for wire, value in provided_inputs.items():
wire = self.block.get_wirevector_by_name(wire) if isinstance(wire, str) else wire
if value > wire.bitmask or value < 0:
raise PyrtlError("Wire {} has value {} which cannot be represented"
" using its bitwidth".format(wire, value))
# building the simulation data
ins = {self._to_name(wire): value for wire, value in provided_inputs.items()}
ins.update(self.regs)
ins.update(self.mems)
# propagate through logic
self.regs, self.outs, mem_writes = self.sim_func(ins)
for mem, addr, value in mem_writes:
self.mems[mem][addr] = value
# for tracer compatibility
self.context = self.outs.copy()
self.context.update(ins) # also gets old register values
if self.tracer is not None:
self.tracer.add_fast_step(self)
# check the rtl assertions
check_rtl_assertions(self) | [
"def",
"step",
"(",
"self",
",",
"provided_inputs",
")",
":",
"# validate_inputs",
"for",
"wire",
",",
"value",
"in",
"provided_inputs",
".",
"items",
"(",
")",
":",
"wire",
"=",
"self",
".",
"block",
".",
"get_wirevector_by_name",
"(",
"wire",
")",
"if",
"isinstance",
"(",
"wire",
",",
"str",
")",
"else",
"wire",
"if",
"value",
">",
"wire",
".",
"bitmask",
"or",
"value",
"<",
"0",
":",
"raise",
"PyrtlError",
"(",
"\"Wire {} has value {} which cannot be represented\"",
"\" using its bitwidth\"",
".",
"format",
"(",
"wire",
",",
"value",
")",
")",
"# building the simulation data",
"ins",
"=",
"{",
"self",
".",
"_to_name",
"(",
"wire",
")",
":",
"value",
"for",
"wire",
",",
"value",
"in",
"provided_inputs",
".",
"items",
"(",
")",
"}",
"ins",
".",
"update",
"(",
"self",
".",
"regs",
")",
"ins",
".",
"update",
"(",
"self",
".",
"mems",
")",
"# propagate through logic",
"self",
".",
"regs",
",",
"self",
".",
"outs",
",",
"mem_writes",
"=",
"self",
".",
"sim_func",
"(",
"ins",
")",
"for",
"mem",
",",
"addr",
",",
"value",
"in",
"mem_writes",
":",
"self",
".",
"mems",
"[",
"mem",
"]",
"[",
"addr",
"]",
"=",
"value",
"# for tracer compatibility",
"self",
".",
"context",
"=",
"self",
".",
"outs",
".",
"copy",
"(",
")",
"self",
".",
"context",
".",
"update",
"(",
"ins",
")",
"# also gets old register values",
"if",
"self",
".",
"tracer",
"is",
"not",
"None",
":",
"self",
".",
"tracer",
".",
"add_fast_step",
"(",
"self",
")",
"# check the rtl assertions",
"check_rtl_assertions",
"(",
"self",
")"
] | Run the simulation for a cycle
:param provided_inputs: a dictionary mapping WireVectors (or their names)
to their values for this step
eg: {wire: 3, "wire_name": 17} | [
"Run",
"the",
"simulation",
"for",
"a",
"cycle"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L404-L436 |
UCSBarchlab/PyRTL | pyrtl/simulation.py | FastSimulation.inspect | def inspect(self, w):
""" Get the value of a wirevector in the last simulation cycle.
:param w: the name of the WireVector to inspect
(passing in a WireVector instead of a name is deprecated)
:return: value of w in the current step of simulation
Will throw KeyError if w is not being tracked in the simulation.
"""
try:
return self.context[self._to_name(w)]
except AttributeError:
raise PyrtlError("No context available. Please run a simulation step in "
"order to populate values for wires") | python | def inspect(self, w):
""" Get the value of a wirevector in the last simulation cycle.
:param w: the name of the WireVector to inspect
(passing in a WireVector instead of a name is deprecated)
:return: value of w in the current step of simulation
Will throw KeyError if w is not being tracked in the simulation.
"""
try:
return self.context[self._to_name(w)]
except AttributeError:
raise PyrtlError("No context available. Please run a simulation step in "
"order to populate values for wires") | [
"def",
"inspect",
"(",
"self",
",",
"w",
")",
":",
"try",
":",
"return",
"self",
".",
"context",
"[",
"self",
".",
"_to_name",
"(",
"w",
")",
"]",
"except",
"AttributeError",
":",
"raise",
"PyrtlError",
"(",
"\"No context available. Please run a simulation step in \"",
"\"order to populate values for wires\"",
")"
] | Get the value of a wirevector in the last simulation cycle.
:param w: the name of the WireVector to inspect
(passing in a WireVector instead of a name is deprecated)
:return: value of w in the current step of simulation
Will throw KeyError if w is not being tracked in the simulation. | [
"Get",
"the",
"value",
"of",
"a",
"wirevector",
"in",
"the",
"last",
"simulation",
"cycle",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L438-L451 |
UCSBarchlab/PyRTL | pyrtl/simulation.py | FastSimulation.inspect_mem | def inspect_mem(self, mem):
""" Get the values in a map during the current simulation cycle.
:param mem: the memory to inspect
:return: {address: value}
Note that this returns the current memory state. Modifying the dictonary
will also modify the state in the simulator
"""
if isinstance(mem, RomBlock):
raise PyrtlError("ROM blocks are not stored in the simulation object")
return self.mems[self._mem_varname(mem)] | python | def inspect_mem(self, mem):
""" Get the values in a map during the current simulation cycle.
:param mem: the memory to inspect
:return: {address: value}
Note that this returns the current memory state. Modifying the dictonary
will also modify the state in the simulator
"""
if isinstance(mem, RomBlock):
raise PyrtlError("ROM blocks are not stored in the simulation object")
return self.mems[self._mem_varname(mem)] | [
"def",
"inspect_mem",
"(",
"self",
",",
"mem",
")",
":",
"if",
"isinstance",
"(",
"mem",
",",
"RomBlock",
")",
":",
"raise",
"PyrtlError",
"(",
"\"ROM blocks are not stored in the simulation object\"",
")",
"return",
"self",
".",
"mems",
"[",
"self",
".",
"_mem_varname",
"(",
"mem",
")",
"]"
] | Get the values in a map during the current simulation cycle.
:param mem: the memory to inspect
:return: {address: value}
Note that this returns the current memory state. Modifying the dictonary
will also modify the state in the simulator | [
"Get",
"the",
"values",
"in",
"a",
"map",
"during",
"the",
"current",
"simulation",
"cycle",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L457-L468 |
UCSBarchlab/PyRTL | pyrtl/simulation.py | FastSimulation._arg_varname | def _arg_varname(self, wire):
"""
Input, Const, and Registers have special input values
"""
if isinstance(wire, (Input, Register)):
return 'd[' + repr(wire.name) + ']' # passed in
elif isinstance(wire, Const):
return str(wire.val) # hardcoded
else:
return self._varname(wire) | python | def _arg_varname(self, wire):
"""
Input, Const, and Registers have special input values
"""
if isinstance(wire, (Input, Register)):
return 'd[' + repr(wire.name) + ']' # passed in
elif isinstance(wire, Const):
return str(wire.val) # hardcoded
else:
return self._varname(wire) | [
"def",
"_arg_varname",
"(",
"self",
",",
"wire",
")",
":",
"if",
"isinstance",
"(",
"wire",
",",
"(",
"Input",
",",
"Register",
")",
")",
":",
"return",
"'d['",
"+",
"repr",
"(",
"wire",
".",
"name",
")",
"+",
"']'",
"# passed in",
"elif",
"isinstance",
"(",
"wire",
",",
"Const",
")",
":",
"return",
"str",
"(",
"wire",
".",
"val",
")",
"# hardcoded",
"else",
":",
"return",
"self",
".",
"_varname",
"(",
"wire",
")"
] | Input, Const, and Registers have special input values | [
"Input",
"Const",
"and",
"Registers",
"have",
"special",
"input",
"values"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L483-L492 |
UCSBarchlab/PyRTL | pyrtl/simulation.py | FastSimulation._compiled | def _compiled(self):
"""Return a string of the self.block compiled to a block of
code that can be execed to get a function to execute"""
# Dev Notes:
# Because of fast locals in functions in both CPython and PyPy, getting a
# function to execute makes the code a few times faster than
# just executing it in the global exec scope.
prog = [self._prog_start]
simple_func = { # OPS
'w': lambda x: x,
'r': lambda x: x,
'~': lambda x: '(~' + x + ')',
'&': lambda l, r: '(' + l + '&' + r + ')',
'|': lambda l, r: '(' + l + '|' + r + ')',
'^': lambda l, r: '(' + l + '^' + r + ')',
'n': lambda l, r: '(~(' + l + '&' + r + '))',
'+': lambda l, r: '(' + l + '+' + r + ')',
'-': lambda l, r: '(' + l + '-' + r + ')',
'*': lambda l, r: '(' + l + '*' + r + ')',
'<': lambda l, r: 'int(' + l + '<' + r + ')',
'>': lambda l, r: 'int(' + l + '>' + r + ')',
'=': lambda l, r: 'int(' + l + '==' + r + ')',
'x': lambda sel, f, t: '({}) if ({}==0) else ({})'.format(f, sel, t),
}
def shift(value, direction, shift_amt):
if shift_amt == 0:
return value
else:
return '(%s %s %d)' % (value, direction, shift_amt)
def make_split():
if split_start_bit == 0:
bit = '(%d & %s)' % ((1 << split_length) - 1, source)
elif len(net.args[0]) - split_start_bit == split_length:
bit = '(%s >> %d)' % (source, split_start_bit)
else:
bit = '(%d & (%s >> %d))' % ((1 << split_length) - 1, source, split_start_bit)
return shift(bit, '<<', split_res_start_bit)
for net in self.block:
if net.op in simple_func:
argvals = (self._arg_varname(arg) for arg in net.args)
expr = simple_func[net.op](*argvals)
elif net.op == 'c':
expr = ''
for i in range(len(net.args)):
if expr is not '':
expr += ' | '
shiftby = sum(len(j) for j in net.args[i+1:])
expr += shift(self._arg_varname(net.args[i]), '<<', shiftby)
elif net.op == 's':
source = self._arg_varname(net.args[0])
expr = ''
split_length = 0
split_start_bit = -2
split_res_start_bit = -1
for i, b in enumerate(net.op_param):
if b != split_start_bit + split_length:
if split_start_bit >= 0:
# create a wire
expr += make_split() + '|'
split_length = 1
split_start_bit = b
split_res_start_bit = i
else:
split_length += 1
expr += make_split()
elif net.op == 'm':
read_addr = self._arg_varname(net.args[0])
mem = net.op_param[1]
if isinstance(net.op_param[1], RomBlock):
expr = 'd["%s"]._get_read_data(%s)' % (self._mem_varname(mem), read_addr)
else: # memories act async for reads
expr = 'd["%s"].get(%s, %s)' % (self._mem_varname(mem),
read_addr, self.default_value)
elif net.op == '@':
mem = self._mem_varname(net.op_param[1])
write_addr, write_val, write_enable = (self._arg_varname(a) for a in net.args)
prog.append(' if {}:'.format(write_enable))
prog.append(' mem_ws.append(("{}", {}, {}))'
.format(mem, write_addr, write_val))
continue # memwrites are special
else:
raise PyrtlError('FastSimulation cannot handle primitive "%s"' % net.op)
# prog.append(' # ' + str(net))
result = self._dest_varname(net.dests[0])
if len(net.dests[0]) == self._no_mask_bitwidth[net.op](net):
prog.append(" %s = %s" % (result, expr))
else:
mask = str(net.dests[0].bitmask)
prog.append(' %s = %s & %s' % (result, mask, expr))
# add traced wires to dict
if self.tracer is not None:
for wire_name in self.tracer.trace:
wire = self.block.wirevector_by_name[wire_name]
if not isinstance(wire, (Input, Const, Register, Output)):
v_wire_name = self._varname(wire)
prog.append(' outs["%s"] = %s' % (wire_name, v_wire_name))
prog.append(" return regs, outs, mem_ws")
return '\n'.join(prog) | python | def _compiled(self):
"""Return a string of the self.block compiled to a block of
code that can be execed to get a function to execute"""
# Dev Notes:
# Because of fast locals in functions in both CPython and PyPy, getting a
# function to execute makes the code a few times faster than
# just executing it in the global exec scope.
prog = [self._prog_start]
simple_func = { # OPS
'w': lambda x: x,
'r': lambda x: x,
'~': lambda x: '(~' + x + ')',
'&': lambda l, r: '(' + l + '&' + r + ')',
'|': lambda l, r: '(' + l + '|' + r + ')',
'^': lambda l, r: '(' + l + '^' + r + ')',
'n': lambda l, r: '(~(' + l + '&' + r + '))',
'+': lambda l, r: '(' + l + '+' + r + ')',
'-': lambda l, r: '(' + l + '-' + r + ')',
'*': lambda l, r: '(' + l + '*' + r + ')',
'<': lambda l, r: 'int(' + l + '<' + r + ')',
'>': lambda l, r: 'int(' + l + '>' + r + ')',
'=': lambda l, r: 'int(' + l + '==' + r + ')',
'x': lambda sel, f, t: '({}) if ({}==0) else ({})'.format(f, sel, t),
}
def shift(value, direction, shift_amt):
if shift_amt == 0:
return value
else:
return '(%s %s %d)' % (value, direction, shift_amt)
def make_split():
if split_start_bit == 0:
bit = '(%d & %s)' % ((1 << split_length) - 1, source)
elif len(net.args[0]) - split_start_bit == split_length:
bit = '(%s >> %d)' % (source, split_start_bit)
else:
bit = '(%d & (%s >> %d))' % ((1 << split_length) - 1, source, split_start_bit)
return shift(bit, '<<', split_res_start_bit)
for net in self.block:
if net.op in simple_func:
argvals = (self._arg_varname(arg) for arg in net.args)
expr = simple_func[net.op](*argvals)
elif net.op == 'c':
expr = ''
for i in range(len(net.args)):
if expr is not '':
expr += ' | '
shiftby = sum(len(j) for j in net.args[i+1:])
expr += shift(self._arg_varname(net.args[i]), '<<', shiftby)
elif net.op == 's':
source = self._arg_varname(net.args[0])
expr = ''
split_length = 0
split_start_bit = -2
split_res_start_bit = -1
for i, b in enumerate(net.op_param):
if b != split_start_bit + split_length:
if split_start_bit >= 0:
# create a wire
expr += make_split() + '|'
split_length = 1
split_start_bit = b
split_res_start_bit = i
else:
split_length += 1
expr += make_split()
elif net.op == 'm':
read_addr = self._arg_varname(net.args[0])
mem = net.op_param[1]
if isinstance(net.op_param[1], RomBlock):
expr = 'd["%s"]._get_read_data(%s)' % (self._mem_varname(mem), read_addr)
else: # memories act async for reads
expr = 'd["%s"].get(%s, %s)' % (self._mem_varname(mem),
read_addr, self.default_value)
elif net.op == '@':
mem = self._mem_varname(net.op_param[1])
write_addr, write_val, write_enable = (self._arg_varname(a) for a in net.args)
prog.append(' if {}:'.format(write_enable))
prog.append(' mem_ws.append(("{}", {}, {}))'
.format(mem, write_addr, write_val))
continue # memwrites are special
else:
raise PyrtlError('FastSimulation cannot handle primitive "%s"' % net.op)
# prog.append(' # ' + str(net))
result = self._dest_varname(net.dests[0])
if len(net.dests[0]) == self._no_mask_bitwidth[net.op](net):
prog.append(" %s = %s" % (result, expr))
else:
mask = str(net.dests[0].bitmask)
prog.append(' %s = %s & %s' % (result, mask, expr))
# add traced wires to dict
if self.tracer is not None:
for wire_name in self.tracer.trace:
wire = self.block.wirevector_by_name[wire_name]
if not isinstance(wire, (Input, Const, Register, Output)):
v_wire_name = self._varname(wire)
prog.append(' outs["%s"] = %s' % (wire_name, v_wire_name))
prog.append(" return regs, outs, mem_ws")
return '\n'.join(prog) | [
"def",
"_compiled",
"(",
"self",
")",
":",
"# Dev Notes:",
"# Because of fast locals in functions in both CPython and PyPy, getting a",
"# function to execute makes the code a few times faster than",
"# just executing it in the global exec scope.",
"prog",
"=",
"[",
"self",
".",
"_prog_start",
"]",
"simple_func",
"=",
"{",
"# OPS",
"'w'",
":",
"lambda",
"x",
":",
"x",
",",
"'r'",
":",
"lambda",
"x",
":",
"x",
",",
"'~'",
":",
"lambda",
"x",
":",
"'(~'",
"+",
"x",
"+",
"')'",
",",
"'&'",
":",
"lambda",
"l",
",",
"r",
":",
"'('",
"+",
"l",
"+",
"'&'",
"+",
"r",
"+",
"')'",
",",
"'|'",
":",
"lambda",
"l",
",",
"r",
":",
"'('",
"+",
"l",
"+",
"'|'",
"+",
"r",
"+",
"')'",
",",
"'^'",
":",
"lambda",
"l",
",",
"r",
":",
"'('",
"+",
"l",
"+",
"'^'",
"+",
"r",
"+",
"')'",
",",
"'n'",
":",
"lambda",
"l",
",",
"r",
":",
"'(~('",
"+",
"l",
"+",
"'&'",
"+",
"r",
"+",
"'))'",
",",
"'+'",
":",
"lambda",
"l",
",",
"r",
":",
"'('",
"+",
"l",
"+",
"'+'",
"+",
"r",
"+",
"')'",
",",
"'-'",
":",
"lambda",
"l",
",",
"r",
":",
"'('",
"+",
"l",
"+",
"'-'",
"+",
"r",
"+",
"')'",
",",
"'*'",
":",
"lambda",
"l",
",",
"r",
":",
"'('",
"+",
"l",
"+",
"'*'",
"+",
"r",
"+",
"')'",
",",
"'<'",
":",
"lambda",
"l",
",",
"r",
":",
"'int('",
"+",
"l",
"+",
"'<'",
"+",
"r",
"+",
"')'",
",",
"'>'",
":",
"lambda",
"l",
",",
"r",
":",
"'int('",
"+",
"l",
"+",
"'>'",
"+",
"r",
"+",
"')'",
",",
"'='",
":",
"lambda",
"l",
",",
"r",
":",
"'int('",
"+",
"l",
"+",
"'=='",
"+",
"r",
"+",
"')'",
",",
"'x'",
":",
"lambda",
"sel",
",",
"f",
",",
"t",
":",
"'({}) if ({}==0) else ({})'",
".",
"format",
"(",
"f",
",",
"sel",
",",
"t",
")",
",",
"}",
"def",
"shift",
"(",
"value",
",",
"direction",
",",
"shift_amt",
")",
":",
"if",
"shift_amt",
"==",
"0",
":",
"return",
"value",
"else",
":",
"return",
"'(%s %s %d)'",
"%",
"(",
"value",
",",
"direction",
",",
"shift_amt",
")",
"def",
"make_split",
"(",
")",
":",
"if",
"split_start_bit",
"==",
"0",
":",
"bit",
"=",
"'(%d & %s)'",
"%",
"(",
"(",
"1",
"<<",
"split_length",
")",
"-",
"1",
",",
"source",
")",
"elif",
"len",
"(",
"net",
".",
"args",
"[",
"0",
"]",
")",
"-",
"split_start_bit",
"==",
"split_length",
":",
"bit",
"=",
"'(%s >> %d)'",
"%",
"(",
"source",
",",
"split_start_bit",
")",
"else",
":",
"bit",
"=",
"'(%d & (%s >> %d))'",
"%",
"(",
"(",
"1",
"<<",
"split_length",
")",
"-",
"1",
",",
"source",
",",
"split_start_bit",
")",
"return",
"shift",
"(",
"bit",
",",
"'<<'",
",",
"split_res_start_bit",
")",
"for",
"net",
"in",
"self",
".",
"block",
":",
"if",
"net",
".",
"op",
"in",
"simple_func",
":",
"argvals",
"=",
"(",
"self",
".",
"_arg_varname",
"(",
"arg",
")",
"for",
"arg",
"in",
"net",
".",
"args",
")",
"expr",
"=",
"simple_func",
"[",
"net",
".",
"op",
"]",
"(",
"*",
"argvals",
")",
"elif",
"net",
".",
"op",
"==",
"'c'",
":",
"expr",
"=",
"''",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"net",
".",
"args",
")",
")",
":",
"if",
"expr",
"is",
"not",
"''",
":",
"expr",
"+=",
"' | '",
"shiftby",
"=",
"sum",
"(",
"len",
"(",
"j",
")",
"for",
"j",
"in",
"net",
".",
"args",
"[",
"i",
"+",
"1",
":",
"]",
")",
"expr",
"+=",
"shift",
"(",
"self",
".",
"_arg_varname",
"(",
"net",
".",
"args",
"[",
"i",
"]",
")",
",",
"'<<'",
",",
"shiftby",
")",
"elif",
"net",
".",
"op",
"==",
"'s'",
":",
"source",
"=",
"self",
".",
"_arg_varname",
"(",
"net",
".",
"args",
"[",
"0",
"]",
")",
"expr",
"=",
"''",
"split_length",
"=",
"0",
"split_start_bit",
"=",
"-",
"2",
"split_res_start_bit",
"=",
"-",
"1",
"for",
"i",
",",
"b",
"in",
"enumerate",
"(",
"net",
".",
"op_param",
")",
":",
"if",
"b",
"!=",
"split_start_bit",
"+",
"split_length",
":",
"if",
"split_start_bit",
">=",
"0",
":",
"# create a wire",
"expr",
"+=",
"make_split",
"(",
")",
"+",
"'|'",
"split_length",
"=",
"1",
"split_start_bit",
"=",
"b",
"split_res_start_bit",
"=",
"i",
"else",
":",
"split_length",
"+=",
"1",
"expr",
"+=",
"make_split",
"(",
")",
"elif",
"net",
".",
"op",
"==",
"'m'",
":",
"read_addr",
"=",
"self",
".",
"_arg_varname",
"(",
"net",
".",
"args",
"[",
"0",
"]",
")",
"mem",
"=",
"net",
".",
"op_param",
"[",
"1",
"]",
"if",
"isinstance",
"(",
"net",
".",
"op_param",
"[",
"1",
"]",
",",
"RomBlock",
")",
":",
"expr",
"=",
"'d[\"%s\"]._get_read_data(%s)'",
"%",
"(",
"self",
".",
"_mem_varname",
"(",
"mem",
")",
",",
"read_addr",
")",
"else",
":",
"# memories act async for reads",
"expr",
"=",
"'d[\"%s\"].get(%s, %s)'",
"%",
"(",
"self",
".",
"_mem_varname",
"(",
"mem",
")",
",",
"read_addr",
",",
"self",
".",
"default_value",
")",
"elif",
"net",
".",
"op",
"==",
"'@'",
":",
"mem",
"=",
"self",
".",
"_mem_varname",
"(",
"net",
".",
"op_param",
"[",
"1",
"]",
")",
"write_addr",
",",
"write_val",
",",
"write_enable",
"=",
"(",
"self",
".",
"_arg_varname",
"(",
"a",
")",
"for",
"a",
"in",
"net",
".",
"args",
")",
"prog",
".",
"append",
"(",
"' if {}:'",
".",
"format",
"(",
"write_enable",
")",
")",
"prog",
".",
"append",
"(",
"' mem_ws.append((\"{}\", {}, {}))'",
".",
"format",
"(",
"mem",
",",
"write_addr",
",",
"write_val",
")",
")",
"continue",
"# memwrites are special",
"else",
":",
"raise",
"PyrtlError",
"(",
"'FastSimulation cannot handle primitive \"%s\"'",
"%",
"net",
".",
"op",
")",
"# prog.append(' # ' + str(net))",
"result",
"=",
"self",
".",
"_dest_varname",
"(",
"net",
".",
"dests",
"[",
"0",
"]",
")",
"if",
"len",
"(",
"net",
".",
"dests",
"[",
"0",
"]",
")",
"==",
"self",
".",
"_no_mask_bitwidth",
"[",
"net",
".",
"op",
"]",
"(",
"net",
")",
":",
"prog",
".",
"append",
"(",
"\" %s = %s\"",
"%",
"(",
"result",
",",
"expr",
")",
")",
"else",
":",
"mask",
"=",
"str",
"(",
"net",
".",
"dests",
"[",
"0",
"]",
".",
"bitmask",
")",
"prog",
".",
"append",
"(",
"' %s = %s & %s'",
"%",
"(",
"result",
",",
"mask",
",",
"expr",
")",
")",
"# add traced wires to dict",
"if",
"self",
".",
"tracer",
"is",
"not",
"None",
":",
"for",
"wire_name",
"in",
"self",
".",
"tracer",
".",
"trace",
":",
"wire",
"=",
"self",
".",
"block",
".",
"wirevector_by_name",
"[",
"wire_name",
"]",
"if",
"not",
"isinstance",
"(",
"wire",
",",
"(",
"Input",
",",
"Const",
",",
"Register",
",",
"Output",
")",
")",
":",
"v_wire_name",
"=",
"self",
".",
"_varname",
"(",
"wire",
")",
"prog",
".",
"append",
"(",
"' outs[\"%s\"] = %s'",
"%",
"(",
"wire_name",
",",
"v_wire_name",
")",
")",
"prog",
".",
"append",
"(",
"\" return regs, outs, mem_ws\"",
")",
"return",
"'\\n'",
".",
"join",
"(",
"prog",
")"
] | Return a string of the self.block compiled to a block of
code that can be execed to get a function to execute | [
"Return",
"a",
"string",
"of",
"the",
"self",
".",
"block",
"compiled",
"to",
"a",
"block",
"of",
"code",
"that",
"can",
"be",
"execed",
"to",
"get",
"a",
"function",
"to",
"execute"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L529-L634 |
UCSBarchlab/PyRTL | pyrtl/simulation.py | _WaveRendererBase._render_val_with_prev | def _render_val_with_prev(self, w, n, current_val, symbol_len):
"""Return a string encoding the given value in a waveform.
:param w: The WireVector we are rendering to a waveform
:param n: An integer from 0 to segment_len-1
:param current_val: the value to be rendered
:param symbol_len: and integer for how big to draw the current value
Returns a string of printed length symbol_len that will draw the
representation of current_val. The input prior_val is used to
render transitions.
"""
sl = symbol_len-1
if len(w) > 1:
out = self._revstart
if current_val != self.prior_val:
out += self._x + hex(current_val).rstrip('L').ljust(sl)[:sl]
elif n == 0:
out += hex(current_val).rstrip('L').ljust(symbol_len)[:symbol_len]
else:
out += ' '*symbol_len
out += self._revstop
else:
pretty_map = {
(0, 0): self._low + self._low * sl,
(0, 1): self._up + self._high * sl,
(1, 0): self._down + self._low * sl,
(1, 1): self._high + self._high * sl,
}
out = pretty_map[(self.prior_val, current_val)]
return out | python | def _render_val_with_prev(self, w, n, current_val, symbol_len):
"""Return a string encoding the given value in a waveform.
:param w: The WireVector we are rendering to a waveform
:param n: An integer from 0 to segment_len-1
:param current_val: the value to be rendered
:param symbol_len: and integer for how big to draw the current value
Returns a string of printed length symbol_len that will draw the
representation of current_val. The input prior_val is used to
render transitions.
"""
sl = symbol_len-1
if len(w) > 1:
out = self._revstart
if current_val != self.prior_val:
out += self._x + hex(current_val).rstrip('L').ljust(sl)[:sl]
elif n == 0:
out += hex(current_val).rstrip('L').ljust(symbol_len)[:symbol_len]
else:
out += ' '*symbol_len
out += self._revstop
else:
pretty_map = {
(0, 0): self._low + self._low * sl,
(0, 1): self._up + self._high * sl,
(1, 0): self._down + self._low * sl,
(1, 1): self._high + self._high * sl,
}
out = pretty_map[(self.prior_val, current_val)]
return out | [
"def",
"_render_val_with_prev",
"(",
"self",
",",
"w",
",",
"n",
",",
"current_val",
",",
"symbol_len",
")",
":",
"sl",
"=",
"symbol_len",
"-",
"1",
"if",
"len",
"(",
"w",
")",
">",
"1",
":",
"out",
"=",
"self",
".",
"_revstart",
"if",
"current_val",
"!=",
"self",
".",
"prior_val",
":",
"out",
"+=",
"self",
".",
"_x",
"+",
"hex",
"(",
"current_val",
")",
".",
"rstrip",
"(",
"'L'",
")",
".",
"ljust",
"(",
"sl",
")",
"[",
":",
"sl",
"]",
"elif",
"n",
"==",
"0",
":",
"out",
"+=",
"hex",
"(",
"current_val",
")",
".",
"rstrip",
"(",
"'L'",
")",
".",
"ljust",
"(",
"symbol_len",
")",
"[",
":",
"symbol_len",
"]",
"else",
":",
"out",
"+=",
"' '",
"*",
"symbol_len",
"out",
"+=",
"self",
".",
"_revstop",
"else",
":",
"pretty_map",
"=",
"{",
"(",
"0",
",",
"0",
")",
":",
"self",
".",
"_low",
"+",
"self",
".",
"_low",
"*",
"sl",
",",
"(",
"0",
",",
"1",
")",
":",
"self",
".",
"_up",
"+",
"self",
".",
"_high",
"*",
"sl",
",",
"(",
"1",
",",
"0",
")",
":",
"self",
".",
"_down",
"+",
"self",
".",
"_low",
"*",
"sl",
",",
"(",
"1",
",",
"1",
")",
":",
"self",
".",
"_high",
"+",
"self",
".",
"_high",
"*",
"sl",
",",
"}",
"out",
"=",
"pretty_map",
"[",
"(",
"self",
".",
"prior_val",
",",
"current_val",
")",
"]",
"return",
"out"
] | Return a string encoding the given value in a waveform.
:param w: The WireVector we are rendering to a waveform
:param n: An integer from 0 to segment_len-1
:param current_val: the value to be rendered
:param symbol_len: and integer for how big to draw the current value
Returns a string of printed length symbol_len that will draw the
representation of current_val. The input prior_val is used to
render transitions. | [
"Return",
"a",
"string",
"encoding",
"the",
"given",
"value",
"in",
"a",
"waveform",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L664-L694 |
UCSBarchlab/PyRTL | pyrtl/simulation.py | SimulationTrace.add_step | def add_step(self, value_map):
""" Add the values in value_map to the end of the trace. """
if len(self.trace) == 0:
raise PyrtlError('error, simulation trace needs at least 1 signal to track '
'(by default, unnamed signals are not traced -- try either passing '
'a name to a WireVector or setting a "wirevector_subset" option)')
for wire in self.trace:
tracelist = self.trace[wire]
wirevec = self._wires[wire]
tracelist.append(value_map[wirevec]) | python | def add_step(self, value_map):
""" Add the values in value_map to the end of the trace. """
if len(self.trace) == 0:
raise PyrtlError('error, simulation trace needs at least 1 signal to track '
'(by default, unnamed signals are not traced -- try either passing '
'a name to a WireVector or setting a "wirevector_subset" option)')
for wire in self.trace:
tracelist = self.trace[wire]
wirevec = self._wires[wire]
tracelist.append(value_map[wirevec]) | [
"def",
"add_step",
"(",
"self",
",",
"value_map",
")",
":",
"if",
"len",
"(",
"self",
".",
"trace",
")",
"==",
"0",
":",
"raise",
"PyrtlError",
"(",
"'error, simulation trace needs at least 1 signal to track '",
"'(by default, unnamed signals are not traced -- try either passing '",
"'a name to a WireVector or setting a \"wirevector_subset\" option)'",
")",
"for",
"wire",
"in",
"self",
".",
"trace",
":",
"tracelist",
"=",
"self",
".",
"trace",
"[",
"wire",
"]",
"wirevec",
"=",
"self",
".",
"_wires",
"[",
"wire",
"]",
"tracelist",
".",
"append",
"(",
"value_map",
"[",
"wirevec",
"]",
")"
] | Add the values in value_map to the end of the trace. | [
"Add",
"the",
"values",
"in",
"value_map",
"to",
"the",
"end",
"of",
"the",
"trace",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L794-L803 |
UCSBarchlab/PyRTL | pyrtl/simulation.py | SimulationTrace.add_fast_step | def add_fast_step(self, fastsim):
""" Add the fastsim context to the trace. """
for wire_name in self.trace:
self.trace[wire_name].append(fastsim.context[wire_name]) | python | def add_fast_step(self, fastsim):
""" Add the fastsim context to the trace. """
for wire_name in self.trace:
self.trace[wire_name].append(fastsim.context[wire_name]) | [
"def",
"add_fast_step",
"(",
"self",
",",
"fastsim",
")",
":",
"for",
"wire_name",
"in",
"self",
".",
"trace",
":",
"self",
".",
"trace",
"[",
"wire_name",
"]",
".",
"append",
"(",
"fastsim",
".",
"context",
"[",
"wire_name",
"]",
")"
] | Add the fastsim context to the trace. | [
"Add",
"the",
"fastsim",
"context",
"to",
"the",
"trace",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L810-L813 |
UCSBarchlab/PyRTL | pyrtl/simulation.py | SimulationTrace.print_trace | def print_trace(self, file=sys.stdout, base=10, compact=False):
"""
Prints a list of wires and their current values.
:param int base: the base the values are to be printed in
:param bool compact: whether to omit spaces in output lines
"""
if len(self.trace) == 0:
raise PyrtlError('error, cannot print an empty trace')
if base not in (2, 8, 10, 16):
raise PyrtlError('please choose a valid base (2,8,10,16)')
basekey = {2: 'b', 8: 'o', 10: 'd', 16: 'x'}[base]
ident_len = max(len(w) for w in self.trace)
if compact:
for w in sorted(self.trace, key=_trace_sort_key):
vals = ''.join('{0:{1}}'.format(x, basekey) for x in self.trace[w])
file.write(w.rjust(ident_len) + ' ' + vals + '\n')
else:
maxlenval = max(len('{0:{1}}'.format(x, basekey))
for w in self.trace for x in self.trace[w])
file.write(' ' * (ident_len - 3) + "--- Values in base %d ---\n" % base)
for w in sorted(self.trace, key=_trace_sort_key):
vals = ' '.join('{0:>{1}{2}}'.format(x, maxlenval, basekey) for x in self.trace[w])
file.write(w.ljust(ident_len + 1) + vals + '\n')
file.flush() | python | def print_trace(self, file=sys.stdout, base=10, compact=False):
"""
Prints a list of wires and their current values.
:param int base: the base the values are to be printed in
:param bool compact: whether to omit spaces in output lines
"""
if len(self.trace) == 0:
raise PyrtlError('error, cannot print an empty trace')
if base not in (2, 8, 10, 16):
raise PyrtlError('please choose a valid base (2,8,10,16)')
basekey = {2: 'b', 8: 'o', 10: 'd', 16: 'x'}[base]
ident_len = max(len(w) for w in self.trace)
if compact:
for w in sorted(self.trace, key=_trace_sort_key):
vals = ''.join('{0:{1}}'.format(x, basekey) for x in self.trace[w])
file.write(w.rjust(ident_len) + ' ' + vals + '\n')
else:
maxlenval = max(len('{0:{1}}'.format(x, basekey))
for w in self.trace for x in self.trace[w])
file.write(' ' * (ident_len - 3) + "--- Values in base %d ---\n" % base)
for w in sorted(self.trace, key=_trace_sort_key):
vals = ' '.join('{0:>{1}{2}}'.format(x, maxlenval, basekey) for x in self.trace[w])
file.write(w.ljust(ident_len + 1) + vals + '\n')
file.flush() | [
"def",
"print_trace",
"(",
"self",
",",
"file",
"=",
"sys",
".",
"stdout",
",",
"base",
"=",
"10",
",",
"compact",
"=",
"False",
")",
":",
"if",
"len",
"(",
"self",
".",
"trace",
")",
"==",
"0",
":",
"raise",
"PyrtlError",
"(",
"'error, cannot print an empty trace'",
")",
"if",
"base",
"not",
"in",
"(",
"2",
",",
"8",
",",
"10",
",",
"16",
")",
":",
"raise",
"PyrtlError",
"(",
"'please choose a valid base (2,8,10,16)'",
")",
"basekey",
"=",
"{",
"2",
":",
"'b'",
",",
"8",
":",
"'o'",
",",
"10",
":",
"'d'",
",",
"16",
":",
"'x'",
"}",
"[",
"base",
"]",
"ident_len",
"=",
"max",
"(",
"len",
"(",
"w",
")",
"for",
"w",
"in",
"self",
".",
"trace",
")",
"if",
"compact",
":",
"for",
"w",
"in",
"sorted",
"(",
"self",
".",
"trace",
",",
"key",
"=",
"_trace_sort_key",
")",
":",
"vals",
"=",
"''",
".",
"join",
"(",
"'{0:{1}}'",
".",
"format",
"(",
"x",
",",
"basekey",
")",
"for",
"x",
"in",
"self",
".",
"trace",
"[",
"w",
"]",
")",
"file",
".",
"write",
"(",
"w",
".",
"rjust",
"(",
"ident_len",
")",
"+",
"' '",
"+",
"vals",
"+",
"'\\n'",
")",
"else",
":",
"maxlenval",
"=",
"max",
"(",
"len",
"(",
"'{0:{1}}'",
".",
"format",
"(",
"x",
",",
"basekey",
")",
")",
"for",
"w",
"in",
"self",
".",
"trace",
"for",
"x",
"in",
"self",
".",
"trace",
"[",
"w",
"]",
")",
"file",
".",
"write",
"(",
"' '",
"*",
"(",
"ident_len",
"-",
"3",
")",
"+",
"\"--- Values in base %d ---\\n\"",
"%",
"base",
")",
"for",
"w",
"in",
"sorted",
"(",
"self",
".",
"trace",
",",
"key",
"=",
"_trace_sort_key",
")",
":",
"vals",
"=",
"' '",
".",
"join",
"(",
"'{0:>{1}{2}}'",
".",
"format",
"(",
"x",
",",
"maxlenval",
",",
"basekey",
")",
"for",
"x",
"in",
"self",
".",
"trace",
"[",
"w",
"]",
")",
"file",
".",
"write",
"(",
"w",
".",
"ljust",
"(",
"ident_len",
"+",
"1",
")",
"+",
"vals",
"+",
"'\\n'",
")",
"file",
".",
"flush",
"(",
")"
] | Prints a list of wires and their current values.
:param int base: the base the values are to be printed in
:param bool compact: whether to omit spaces in output lines | [
"Prints",
"a",
"list",
"of",
"wires",
"and",
"their",
"current",
"values",
".",
":",
"param",
"int",
"base",
":",
"the",
"base",
"the",
"values",
"are",
"to",
"be",
"printed",
"in",
":",
"param",
"bool",
"compact",
":",
"whether",
"to",
"omit",
"spaces",
"in",
"output",
"lines"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L815-L841 |
UCSBarchlab/PyRTL | pyrtl/simulation.py | SimulationTrace.print_vcd | def print_vcd(self, file=sys.stdout, include_clock=False):
""" Print the trace out as a VCD File for use in other tools.
:param file: file to open and output vcd dump to.
:param include_clock: boolean specifying if the implicit clk should be included.
Dumps the current trace to file as a "value change dump" file. The file parameter
defaults to _stdout_ and the include_clock defaults to True.
Examples ::
sim_trace.print_vcd()
sim_trace.print_vcd("my_waveform.vcd", include_clock=False)
"""
# dump header info
# file_timestamp = time.strftime("%a, %d %b %Y %H:%M:%S (UTC/GMT)", time.gmtime())
# print >>file, " ".join(["$date", file_timestamp, "$end"])
self.internal_names = _VerilogSanitizer('_vcd_tmp_')
for wire in self.wires_to_track:
self.internal_names.make_valid_string(wire.name)
def _varname(wireName):
""" Converts WireVector names to internal names """
return self.internal_names[wireName]
print(' '.join(['$timescale', '1ns', '$end']), file=file)
print(' '.join(['$scope', 'module logic', '$end']), file=file)
def print_trace_strs(time):
for wn in sorted(self.trace, key=_trace_sort_key):
print(' '.join([str(bin(self.trace[wn][time]))[1:], _varname(wn)]), file=file)
# dump variables
if include_clock:
print(' '.join(['$var', 'wire', '1', 'clk', 'clk', '$end']), file=file)
for wn in sorted(self.trace, key=_trace_sort_key):
print(' '.join(['$var', 'wire', str(self._wires[wn].bitwidth),
_varname(wn), _varname(wn), '$end']), file=file)
print(' '.join(['$upscope', '$end']), file=file)
print(' '.join(['$enddefinitions', '$end']), file=file)
print(' '.join(['$dumpvars']), file=file)
print_trace_strs(0)
print(' '.join(['$end']), file=file)
# dump values
endtime = max([len(self.trace[w]) for w in self.trace])
for timestamp in range(endtime):
print(''.join(['#', str(timestamp*10)]), file=file)
print_trace_strs(timestamp)
if include_clock:
print('b1 clk', file=file)
print('', file=file)
print(''.join(['#', str(timestamp*10+5)]), file=file)
print('b0 clk', file=file)
print('', file=file)
print(''.join(['#', str(endtime*10)]), file=file)
file.flush() | python | def print_vcd(self, file=sys.stdout, include_clock=False):
""" Print the trace out as a VCD File for use in other tools.
:param file: file to open and output vcd dump to.
:param include_clock: boolean specifying if the implicit clk should be included.
Dumps the current trace to file as a "value change dump" file. The file parameter
defaults to _stdout_ and the include_clock defaults to True.
Examples ::
sim_trace.print_vcd()
sim_trace.print_vcd("my_waveform.vcd", include_clock=False)
"""
# dump header info
# file_timestamp = time.strftime("%a, %d %b %Y %H:%M:%S (UTC/GMT)", time.gmtime())
# print >>file, " ".join(["$date", file_timestamp, "$end"])
self.internal_names = _VerilogSanitizer('_vcd_tmp_')
for wire in self.wires_to_track:
self.internal_names.make_valid_string(wire.name)
def _varname(wireName):
""" Converts WireVector names to internal names """
return self.internal_names[wireName]
print(' '.join(['$timescale', '1ns', '$end']), file=file)
print(' '.join(['$scope', 'module logic', '$end']), file=file)
def print_trace_strs(time):
for wn in sorted(self.trace, key=_trace_sort_key):
print(' '.join([str(bin(self.trace[wn][time]))[1:], _varname(wn)]), file=file)
# dump variables
if include_clock:
print(' '.join(['$var', 'wire', '1', 'clk', 'clk', '$end']), file=file)
for wn in sorted(self.trace, key=_trace_sort_key):
print(' '.join(['$var', 'wire', str(self._wires[wn].bitwidth),
_varname(wn), _varname(wn), '$end']), file=file)
print(' '.join(['$upscope', '$end']), file=file)
print(' '.join(['$enddefinitions', '$end']), file=file)
print(' '.join(['$dumpvars']), file=file)
print_trace_strs(0)
print(' '.join(['$end']), file=file)
# dump values
endtime = max([len(self.trace[w]) for w in self.trace])
for timestamp in range(endtime):
print(''.join(['#', str(timestamp*10)]), file=file)
print_trace_strs(timestamp)
if include_clock:
print('b1 clk', file=file)
print('', file=file)
print(''.join(['#', str(timestamp*10+5)]), file=file)
print('b0 clk', file=file)
print('', file=file)
print(''.join(['#', str(endtime*10)]), file=file)
file.flush() | [
"def",
"print_vcd",
"(",
"self",
",",
"file",
"=",
"sys",
".",
"stdout",
",",
"include_clock",
"=",
"False",
")",
":",
"# dump header info",
"# file_timestamp = time.strftime(\"%a, %d %b %Y %H:%M:%S (UTC/GMT)\", time.gmtime())",
"# print >>file, \" \".join([\"$date\", file_timestamp, \"$end\"])",
"self",
".",
"internal_names",
"=",
"_VerilogSanitizer",
"(",
"'_vcd_tmp_'",
")",
"for",
"wire",
"in",
"self",
".",
"wires_to_track",
":",
"self",
".",
"internal_names",
".",
"make_valid_string",
"(",
"wire",
".",
"name",
")",
"def",
"_varname",
"(",
"wireName",
")",
":",
"\"\"\" Converts WireVector names to internal names \"\"\"",
"return",
"self",
".",
"internal_names",
"[",
"wireName",
"]",
"print",
"(",
"' '",
".",
"join",
"(",
"[",
"'$timescale'",
",",
"'1ns'",
",",
"'$end'",
"]",
")",
",",
"file",
"=",
"file",
")",
"print",
"(",
"' '",
".",
"join",
"(",
"[",
"'$scope'",
",",
"'module logic'",
",",
"'$end'",
"]",
")",
",",
"file",
"=",
"file",
")",
"def",
"print_trace_strs",
"(",
"time",
")",
":",
"for",
"wn",
"in",
"sorted",
"(",
"self",
".",
"trace",
",",
"key",
"=",
"_trace_sort_key",
")",
":",
"print",
"(",
"' '",
".",
"join",
"(",
"[",
"str",
"(",
"bin",
"(",
"self",
".",
"trace",
"[",
"wn",
"]",
"[",
"time",
"]",
")",
")",
"[",
"1",
":",
"]",
",",
"_varname",
"(",
"wn",
")",
"]",
")",
",",
"file",
"=",
"file",
")",
"# dump variables",
"if",
"include_clock",
":",
"print",
"(",
"' '",
".",
"join",
"(",
"[",
"'$var'",
",",
"'wire'",
",",
"'1'",
",",
"'clk'",
",",
"'clk'",
",",
"'$end'",
"]",
")",
",",
"file",
"=",
"file",
")",
"for",
"wn",
"in",
"sorted",
"(",
"self",
".",
"trace",
",",
"key",
"=",
"_trace_sort_key",
")",
":",
"print",
"(",
"' '",
".",
"join",
"(",
"[",
"'$var'",
",",
"'wire'",
",",
"str",
"(",
"self",
".",
"_wires",
"[",
"wn",
"]",
".",
"bitwidth",
")",
",",
"_varname",
"(",
"wn",
")",
",",
"_varname",
"(",
"wn",
")",
",",
"'$end'",
"]",
")",
",",
"file",
"=",
"file",
")",
"print",
"(",
"' '",
".",
"join",
"(",
"[",
"'$upscope'",
",",
"'$end'",
"]",
")",
",",
"file",
"=",
"file",
")",
"print",
"(",
"' '",
".",
"join",
"(",
"[",
"'$enddefinitions'",
",",
"'$end'",
"]",
")",
",",
"file",
"=",
"file",
")",
"print",
"(",
"' '",
".",
"join",
"(",
"[",
"'$dumpvars'",
"]",
")",
",",
"file",
"=",
"file",
")",
"print_trace_strs",
"(",
"0",
")",
"print",
"(",
"' '",
".",
"join",
"(",
"[",
"'$end'",
"]",
")",
",",
"file",
"=",
"file",
")",
"# dump values",
"endtime",
"=",
"max",
"(",
"[",
"len",
"(",
"self",
".",
"trace",
"[",
"w",
"]",
")",
"for",
"w",
"in",
"self",
".",
"trace",
"]",
")",
"for",
"timestamp",
"in",
"range",
"(",
"endtime",
")",
":",
"print",
"(",
"''",
".",
"join",
"(",
"[",
"'#'",
",",
"str",
"(",
"timestamp",
"*",
"10",
")",
"]",
")",
",",
"file",
"=",
"file",
")",
"print_trace_strs",
"(",
"timestamp",
")",
"if",
"include_clock",
":",
"print",
"(",
"'b1 clk'",
",",
"file",
"=",
"file",
")",
"print",
"(",
"''",
",",
"file",
"=",
"file",
")",
"print",
"(",
"''",
".",
"join",
"(",
"[",
"'#'",
",",
"str",
"(",
"timestamp",
"*",
"10",
"+",
"5",
")",
"]",
")",
",",
"file",
"=",
"file",
")",
"print",
"(",
"'b0 clk'",
",",
"file",
"=",
"file",
")",
"print",
"(",
"''",
",",
"file",
"=",
"file",
")",
"print",
"(",
"''",
".",
"join",
"(",
"[",
"'#'",
",",
"str",
"(",
"endtime",
"*",
"10",
")",
"]",
")",
",",
"file",
"=",
"file",
")",
"file",
".",
"flush",
"(",
")"
] | Print the trace out as a VCD File for use in other tools.
:param file: file to open and output vcd dump to.
:param include_clock: boolean specifying if the implicit clk should be included.
Dumps the current trace to file as a "value change dump" file. The file parameter
defaults to _stdout_ and the include_clock defaults to True.
Examples ::
sim_trace.print_vcd()
sim_trace.print_vcd("my_waveform.vcd", include_clock=False) | [
"Print",
"the",
"trace",
"out",
"as",
"a",
"VCD",
"File",
"for",
"use",
"in",
"other",
"tools",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L843-L899 |
UCSBarchlab/PyRTL | pyrtl/simulation.py | SimulationTrace.render_trace | def render_trace(
self, trace_list=None, file=sys.stdout, render_cls=default_renderer(),
symbol_len=5, segment_size=5, segment_delim=' ', extra_line=True):
""" Render the trace to a file using unicode and ASCII escape sequences.
:param trace_list: A list of signals to be output in the specified order.
:param file: The place to write output, default to stdout.
:param render_cls: A class that translates traces into output bytes.
:param symbol_len: The "length" of each rendered cycle in characters.
:param segment_size: Traces are broken in the segments of this number of cycles.
:param segment_delim: The character to be output between segments.
:param extra_line: A Boolean to determin if we should print a blank line between signals.
The resulting output can be viewed directly on the terminal or looked
at with "more" or "less -R" which both should handle the ASCII escape
sequences used in rendering. render_trace takes the following optional
arguments.
"""
if _currently_in_ipython():
from IPython.display import display, HTML, Javascript # pylint: disable=import-error
from .inputoutput import trace_to_html
htmlstring = trace_to_html(self, trace_list=trace_list, sortkey=_trace_sort_key)
html_elem = HTML(htmlstring)
display(html_elem)
# print(htmlstring)
js_stuff = """
$.when(
$.getScript("https://cdnjs.cloudflare.com/ajax/libs/wavedrom/1.6.2/skins/default.js"),
$.getScript("https://cdnjs.cloudflare.com/ajax/libs/wavedrom/1.6.2/wavedrom.min.js"),
$.Deferred(function( deferred ){
$( deferred.resolve );
})).done(function(){
WaveDrom.ProcessAll();
});"""
display(Javascript(js_stuff))
else:
self.render_trace_to_text(
trace_list=trace_list, file=file, render_cls=render_cls,
symbol_len=symbol_len, segment_size=segment_size,
segment_delim=segment_delim, extra_line=extra_line) | python | def render_trace(
self, trace_list=None, file=sys.stdout, render_cls=default_renderer(),
symbol_len=5, segment_size=5, segment_delim=' ', extra_line=True):
""" Render the trace to a file using unicode and ASCII escape sequences.
:param trace_list: A list of signals to be output in the specified order.
:param file: The place to write output, default to stdout.
:param render_cls: A class that translates traces into output bytes.
:param symbol_len: The "length" of each rendered cycle in characters.
:param segment_size: Traces are broken in the segments of this number of cycles.
:param segment_delim: The character to be output between segments.
:param extra_line: A Boolean to determin if we should print a blank line between signals.
The resulting output can be viewed directly on the terminal or looked
at with "more" or "less -R" which both should handle the ASCII escape
sequences used in rendering. render_trace takes the following optional
arguments.
"""
if _currently_in_ipython():
from IPython.display import display, HTML, Javascript # pylint: disable=import-error
from .inputoutput import trace_to_html
htmlstring = trace_to_html(self, trace_list=trace_list, sortkey=_trace_sort_key)
html_elem = HTML(htmlstring)
display(html_elem)
# print(htmlstring)
js_stuff = """
$.when(
$.getScript("https://cdnjs.cloudflare.com/ajax/libs/wavedrom/1.6.2/skins/default.js"),
$.getScript("https://cdnjs.cloudflare.com/ajax/libs/wavedrom/1.6.2/wavedrom.min.js"),
$.Deferred(function( deferred ){
$( deferred.resolve );
})).done(function(){
WaveDrom.ProcessAll();
});"""
display(Javascript(js_stuff))
else:
self.render_trace_to_text(
trace_list=trace_list, file=file, render_cls=render_cls,
symbol_len=symbol_len, segment_size=segment_size,
segment_delim=segment_delim, extra_line=extra_line) | [
"def",
"render_trace",
"(",
"self",
",",
"trace_list",
"=",
"None",
",",
"file",
"=",
"sys",
".",
"stdout",
",",
"render_cls",
"=",
"default_renderer",
"(",
")",
",",
"symbol_len",
"=",
"5",
",",
"segment_size",
"=",
"5",
",",
"segment_delim",
"=",
"' '",
",",
"extra_line",
"=",
"True",
")",
":",
"if",
"_currently_in_ipython",
"(",
")",
":",
"from",
"IPython",
".",
"display",
"import",
"display",
",",
"HTML",
",",
"Javascript",
"# pylint: disable=import-error",
"from",
".",
"inputoutput",
"import",
"trace_to_html",
"htmlstring",
"=",
"trace_to_html",
"(",
"self",
",",
"trace_list",
"=",
"trace_list",
",",
"sortkey",
"=",
"_trace_sort_key",
")",
"html_elem",
"=",
"HTML",
"(",
"htmlstring",
")",
"display",
"(",
"html_elem",
")",
"# print(htmlstring)",
"js_stuff",
"=",
"\"\"\"\n $.when(\n $.getScript(\"https://cdnjs.cloudflare.com/ajax/libs/wavedrom/1.6.2/skins/default.js\"),\n $.getScript(\"https://cdnjs.cloudflare.com/ajax/libs/wavedrom/1.6.2/wavedrom.min.js\"),\n $.Deferred(function( deferred ){\n $( deferred.resolve );\n })).done(function(){\n WaveDrom.ProcessAll();\n });\"\"\"",
"display",
"(",
"Javascript",
"(",
"js_stuff",
")",
")",
"else",
":",
"self",
".",
"render_trace_to_text",
"(",
"trace_list",
"=",
"trace_list",
",",
"file",
"=",
"file",
",",
"render_cls",
"=",
"render_cls",
",",
"symbol_len",
"=",
"symbol_len",
",",
"segment_size",
"=",
"segment_size",
",",
"segment_delim",
"=",
"segment_delim",
",",
"extra_line",
"=",
"extra_line",
")"
] | Render the trace to a file using unicode and ASCII escape sequences.
:param trace_list: A list of signals to be output in the specified order.
:param file: The place to write output, default to stdout.
:param render_cls: A class that translates traces into output bytes.
:param symbol_len: The "length" of each rendered cycle in characters.
:param segment_size: Traces are broken in the segments of this number of cycles.
:param segment_delim: The character to be output between segments.
:param extra_line: A Boolean to determin if we should print a blank line between signals.
The resulting output can be viewed directly on the terminal or looked
at with "more" or "less -R" which both should handle the ASCII escape
sequences used in rendering. render_trace takes the following optional
arguments. | [
"Render",
"the",
"trace",
"to",
"a",
"file",
"using",
"unicode",
"and",
"ASCII",
"escape",
"sequences",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L901-L941 |
UCSBarchlab/PyRTL | pyrtl/rtllib/muxes.py | prioritized_mux | def prioritized_mux(selects, vals):
"""
Returns the value in the first wire for which its select bit is 1
:param [WireVector] selects: a list of WireVectors signaling whether
a wire should be chosen
:param [WireVector] vals: values to return when the corresponding select
value is 1
:return: WireVector
If none of the items are high, the last val is returned
"""
if len(selects) != len(vals):
raise pyrtl.PyrtlError("Number of select and val signals must match")
if len(vals) == 0:
raise pyrtl.PyrtlError("Must have a signal to mux")
if len(vals) == 1:
return vals[0]
else:
half = len(vals) // 2
return pyrtl.select(pyrtl.rtl_any(*selects[:half]),
truecase=prioritized_mux(selects[:half], vals[:half]),
falsecase=prioritized_mux(selects[half:], vals[half:])) | python | def prioritized_mux(selects, vals):
"""
Returns the value in the first wire for which its select bit is 1
:param [WireVector] selects: a list of WireVectors signaling whether
a wire should be chosen
:param [WireVector] vals: values to return when the corresponding select
value is 1
:return: WireVector
If none of the items are high, the last val is returned
"""
if len(selects) != len(vals):
raise pyrtl.PyrtlError("Number of select and val signals must match")
if len(vals) == 0:
raise pyrtl.PyrtlError("Must have a signal to mux")
if len(vals) == 1:
return vals[0]
else:
half = len(vals) // 2
return pyrtl.select(pyrtl.rtl_any(*selects[:half]),
truecase=prioritized_mux(selects[:half], vals[:half]),
falsecase=prioritized_mux(selects[half:], vals[half:])) | [
"def",
"prioritized_mux",
"(",
"selects",
",",
"vals",
")",
":",
"if",
"len",
"(",
"selects",
")",
"!=",
"len",
"(",
"vals",
")",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"Number of select and val signals must match\"",
")",
"if",
"len",
"(",
"vals",
")",
"==",
"0",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"Must have a signal to mux\"",
")",
"if",
"len",
"(",
"vals",
")",
"==",
"1",
":",
"return",
"vals",
"[",
"0",
"]",
"else",
":",
"half",
"=",
"len",
"(",
"vals",
")",
"//",
"2",
"return",
"pyrtl",
".",
"select",
"(",
"pyrtl",
".",
"rtl_any",
"(",
"*",
"selects",
"[",
":",
"half",
"]",
")",
",",
"truecase",
"=",
"prioritized_mux",
"(",
"selects",
"[",
":",
"half",
"]",
",",
"vals",
"[",
":",
"half",
"]",
")",
",",
"falsecase",
"=",
"prioritized_mux",
"(",
"selects",
"[",
"half",
":",
"]",
",",
"vals",
"[",
"half",
":",
"]",
")",
")"
] | Returns the value in the first wire for which its select bit is 1
:param [WireVector] selects: a list of WireVectors signaling whether
a wire should be chosen
:param [WireVector] vals: values to return when the corresponding select
value is 1
:return: WireVector
If none of the items are high, the last val is returned | [
"Returns",
"the",
"value",
"in",
"the",
"first",
"wire",
"for",
"which",
"its",
"select",
"bit",
"is",
"1"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/muxes.py#L4-L26 |
UCSBarchlab/PyRTL | pyrtl/rtllib/muxes.py | sparse_mux | def sparse_mux(sel, vals):
"""
Mux that avoids instantiating unnecessary mux_2s when possible.
:param WireVector sel: Select wire, determines what is selected on a given cycle
:param dictionary vals: dictionary of values at mux inputs (of type `{int:WireVector}`)
:return: WireVector that signifies the change
This mux supports not having a full specification. Indices that are not
specified are treated as don't-cares
It also supports a specified default value, SparseDefault
"""
import numbers
max_val = 2**len(sel) - 1
if SparseDefault in vals:
default_val = vals[SparseDefault]
del vals[SparseDefault]
for i in range(max_val + 1):
if i not in vals:
vals[i] = default_val
for key in vals.keys():
if not isinstance(key, numbers.Integral):
raise pyrtl.PyrtlError("value %s nust be either an integer or 'default'" % str(key))
if key < 0 or key > max_val:
raise pyrtl.PyrtlError("value %s is out of range of the sel wire" % str(key))
return _sparse_mux(sel, vals) | python | def sparse_mux(sel, vals):
"""
Mux that avoids instantiating unnecessary mux_2s when possible.
:param WireVector sel: Select wire, determines what is selected on a given cycle
:param dictionary vals: dictionary of values at mux inputs (of type `{int:WireVector}`)
:return: WireVector that signifies the change
This mux supports not having a full specification. Indices that are not
specified are treated as don't-cares
It also supports a specified default value, SparseDefault
"""
import numbers
max_val = 2**len(sel) - 1
if SparseDefault in vals:
default_val = vals[SparseDefault]
del vals[SparseDefault]
for i in range(max_val + 1):
if i not in vals:
vals[i] = default_val
for key in vals.keys():
if not isinstance(key, numbers.Integral):
raise pyrtl.PyrtlError("value %s nust be either an integer or 'default'" % str(key))
if key < 0 or key > max_val:
raise pyrtl.PyrtlError("value %s is out of range of the sel wire" % str(key))
return _sparse_mux(sel, vals) | [
"def",
"sparse_mux",
"(",
"sel",
",",
"vals",
")",
":",
"import",
"numbers",
"max_val",
"=",
"2",
"**",
"len",
"(",
"sel",
")",
"-",
"1",
"if",
"SparseDefault",
"in",
"vals",
":",
"default_val",
"=",
"vals",
"[",
"SparseDefault",
"]",
"del",
"vals",
"[",
"SparseDefault",
"]",
"for",
"i",
"in",
"range",
"(",
"max_val",
"+",
"1",
")",
":",
"if",
"i",
"not",
"in",
"vals",
":",
"vals",
"[",
"i",
"]",
"=",
"default_val",
"for",
"key",
"in",
"vals",
".",
"keys",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"numbers",
".",
"Integral",
")",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"value %s nust be either an integer or 'default'\"",
"%",
"str",
"(",
"key",
")",
")",
"if",
"key",
"<",
"0",
"or",
"key",
">",
"max_val",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"value %s is out of range of the sel wire\"",
"%",
"str",
"(",
"key",
")",
")",
"return",
"_sparse_mux",
"(",
"sel",
",",
"vals",
")"
] | Mux that avoids instantiating unnecessary mux_2s when possible.
:param WireVector sel: Select wire, determines what is selected on a given cycle
:param dictionary vals: dictionary of values at mux inputs (of type `{int:WireVector}`)
:return: WireVector that signifies the change
This mux supports not having a full specification. Indices that are not
specified are treated as don't-cares
It also supports a specified default value, SparseDefault | [
"Mux",
"that",
"avoids",
"instantiating",
"unnecessary",
"mux_2s",
"when",
"possible",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/muxes.py#L38-L67 |
UCSBarchlab/PyRTL | pyrtl/rtllib/muxes.py | _sparse_mux | def _sparse_mux(sel, vals):
"""
Mux that avoids instantiating unnecessary mux_2s when possible.
:param WireVector sel: Select wire, determines what is selected on a given cycle
:param {int: WireVector} vals: dictionary to store the values that are
:return: Wirevector that signifies the change
This mux supports not having a full specification. indices that are not
specified are treated as Don't Cares
"""
items = list(vals.values())
if len(vals) <= 1:
if len(vals) == 0:
raise pyrtl.PyrtlError("Needs at least one parameter for val")
return items[0]
if len(sel) == 1:
try:
false_result = vals[0]
true_result = vals[1]
except KeyError:
raise pyrtl.PyrtlError("Failed to retrieve values for smartmux. "
"The length of sel might be wrong")
else:
half = 2**(len(sel) - 1)
first_dict = {indx: wire for indx, wire in vals.items() if indx < half}
second_dict = {indx-half: wire for indx, wire in vals.items() if indx >= half}
if not len(first_dict):
return sparse_mux(sel[:-1], second_dict)
if not len(second_dict):
return sparse_mux(sel[:-1], first_dict)
false_result = sparse_mux(sel[:-1], first_dict)
true_result = sparse_mux(sel[:-1], second_dict)
if _is_equivelent(false_result, true_result):
return true_result
return pyrtl.select(sel[-1], falsecase=false_result, truecase=true_result) | python | def _sparse_mux(sel, vals):
"""
Mux that avoids instantiating unnecessary mux_2s when possible.
:param WireVector sel: Select wire, determines what is selected on a given cycle
:param {int: WireVector} vals: dictionary to store the values that are
:return: Wirevector that signifies the change
This mux supports not having a full specification. indices that are not
specified are treated as Don't Cares
"""
items = list(vals.values())
if len(vals) <= 1:
if len(vals) == 0:
raise pyrtl.PyrtlError("Needs at least one parameter for val")
return items[0]
if len(sel) == 1:
try:
false_result = vals[0]
true_result = vals[1]
except KeyError:
raise pyrtl.PyrtlError("Failed to retrieve values for smartmux. "
"The length of sel might be wrong")
else:
half = 2**(len(sel) - 1)
first_dict = {indx: wire for indx, wire in vals.items() if indx < half}
second_dict = {indx-half: wire for indx, wire in vals.items() if indx >= half}
if not len(first_dict):
return sparse_mux(sel[:-1], second_dict)
if not len(second_dict):
return sparse_mux(sel[:-1], first_dict)
false_result = sparse_mux(sel[:-1], first_dict)
true_result = sparse_mux(sel[:-1], second_dict)
if _is_equivelent(false_result, true_result):
return true_result
return pyrtl.select(sel[-1], falsecase=false_result, truecase=true_result) | [
"def",
"_sparse_mux",
"(",
"sel",
",",
"vals",
")",
":",
"items",
"=",
"list",
"(",
"vals",
".",
"values",
"(",
")",
")",
"if",
"len",
"(",
"vals",
")",
"<=",
"1",
":",
"if",
"len",
"(",
"vals",
")",
"==",
"0",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"Needs at least one parameter for val\"",
")",
"return",
"items",
"[",
"0",
"]",
"if",
"len",
"(",
"sel",
")",
"==",
"1",
":",
"try",
":",
"false_result",
"=",
"vals",
"[",
"0",
"]",
"true_result",
"=",
"vals",
"[",
"1",
"]",
"except",
"KeyError",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"Failed to retrieve values for smartmux. \"",
"\"The length of sel might be wrong\"",
")",
"else",
":",
"half",
"=",
"2",
"**",
"(",
"len",
"(",
"sel",
")",
"-",
"1",
")",
"first_dict",
"=",
"{",
"indx",
":",
"wire",
"for",
"indx",
",",
"wire",
"in",
"vals",
".",
"items",
"(",
")",
"if",
"indx",
"<",
"half",
"}",
"second_dict",
"=",
"{",
"indx",
"-",
"half",
":",
"wire",
"for",
"indx",
",",
"wire",
"in",
"vals",
".",
"items",
"(",
")",
"if",
"indx",
">=",
"half",
"}",
"if",
"not",
"len",
"(",
"first_dict",
")",
":",
"return",
"sparse_mux",
"(",
"sel",
"[",
":",
"-",
"1",
"]",
",",
"second_dict",
")",
"if",
"not",
"len",
"(",
"second_dict",
")",
":",
"return",
"sparse_mux",
"(",
"sel",
"[",
":",
"-",
"1",
"]",
",",
"first_dict",
")",
"false_result",
"=",
"sparse_mux",
"(",
"sel",
"[",
":",
"-",
"1",
"]",
",",
"first_dict",
")",
"true_result",
"=",
"sparse_mux",
"(",
"sel",
"[",
":",
"-",
"1",
"]",
",",
"second_dict",
")",
"if",
"_is_equivelent",
"(",
"false_result",
",",
"true_result",
")",
":",
"return",
"true_result",
"return",
"pyrtl",
".",
"select",
"(",
"sel",
"[",
"-",
"1",
"]",
",",
"falsecase",
"=",
"false_result",
",",
"truecase",
"=",
"true_result",
")"
] | Mux that avoids instantiating unnecessary mux_2s when possible.
:param WireVector sel: Select wire, determines what is selected on a given cycle
:param {int: WireVector} vals: dictionary to store the values that are
:return: Wirevector that signifies the change
This mux supports not having a full specification. indices that are not
specified are treated as Don't Cares | [
"Mux",
"that",
"avoids",
"instantiating",
"unnecessary",
"mux_2s",
"when",
"possible",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/muxes.py#L70-L108 |
UCSBarchlab/PyRTL | pyrtl/rtllib/muxes.py | demux | def demux(select):
"""
Demultiplexes a wire of arbitrary bitwidth
:param WireVector select: indicates which wire to set on
:return (WireVector, ...): a tuple of wires corresponding to each demultiplexed wire
"""
if len(select) == 1:
return _demux_2(select)
wires = demux(select[:-1])
sel = select[-1]
not_select = ~sel
zero_wires = tuple(not_select & w for w in wires)
one_wires = tuple(sel & w for w in wires)
return zero_wires + one_wires | python | def demux(select):
"""
Demultiplexes a wire of arbitrary bitwidth
:param WireVector select: indicates which wire to set on
:return (WireVector, ...): a tuple of wires corresponding to each demultiplexed wire
"""
if len(select) == 1:
return _demux_2(select)
wires = demux(select[:-1])
sel = select[-1]
not_select = ~sel
zero_wires = tuple(not_select & w for w in wires)
one_wires = tuple(sel & w for w in wires)
return zero_wires + one_wires | [
"def",
"demux",
"(",
"select",
")",
":",
"if",
"len",
"(",
"select",
")",
"==",
"1",
":",
"return",
"_demux_2",
"(",
"select",
")",
"wires",
"=",
"demux",
"(",
"select",
"[",
":",
"-",
"1",
"]",
")",
"sel",
"=",
"select",
"[",
"-",
"1",
"]",
"not_select",
"=",
"~",
"sel",
"zero_wires",
"=",
"tuple",
"(",
"not_select",
"&",
"w",
"for",
"w",
"in",
"wires",
")",
"one_wires",
"=",
"tuple",
"(",
"sel",
"&",
"w",
"for",
"w",
"in",
"wires",
")",
"return",
"zero_wires",
"+",
"one_wires"
] | Demultiplexes a wire of arbitrary bitwidth
:param WireVector select: indicates which wire to set on
:return (WireVector, ...): a tuple of wires corresponding to each demultiplexed wire | [
"Demultiplexes",
"a",
"wire",
"of",
"arbitrary",
"bitwidth"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/muxes.py#L190-L205 |
UCSBarchlab/PyRTL | pyrtl/rtllib/muxes.py | MultiSelector.finalize | def finalize(self):
"""
Connects the wires.
"""
self._check_finalized()
self._final = True
for dest_w, values in self.dest_instrs_info.items():
mux_vals = dict(zip(self.instructions, values))
dest_w <<= sparse_mux(self.signal_wire, mux_vals) | python | def finalize(self):
"""
Connects the wires.
"""
self._check_finalized()
self._final = True
for dest_w, values in self.dest_instrs_info.items():
mux_vals = dict(zip(self.instructions, values))
dest_w <<= sparse_mux(self.signal_wire, mux_vals) | [
"def",
"finalize",
"(",
"self",
")",
":",
"self",
".",
"_check_finalized",
"(",
")",
"self",
".",
"_final",
"=",
"True",
"for",
"dest_w",
",",
"values",
"in",
"self",
".",
"dest_instrs_info",
".",
"items",
"(",
")",
":",
"mux_vals",
"=",
"dict",
"(",
"zip",
"(",
"self",
".",
"instructions",
",",
"values",
")",
")",
"dest_w",
"<<=",
"sparse_mux",
"(",
"self",
".",
"signal_wire",
",",
"mux_vals",
")"
] | Connects the wires. | [
"Connects",
"the",
"wires",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/muxes.py#L178-L187 |
UCSBarchlab/PyRTL | pyrtl/wire.py | WireVector.bitmask | def bitmask(self):
""" A property holding a bitmask of the same length as this WireVector.
Specifically it is an integer with a number of bits set to 1 equal to the
bitwidth of the WireVector.
It is often times useful to "mask" an integer such that it fits in the
the number of bits of a WireVector. As a convenience for this, the
`bitmask` property is provided. As an example, if there was a 3-bit
WireVector `a`, a call to `a.bitmask()` should return 0b111 or 0x7."""
if "_bitmask" not in self.__dict__:
self._bitmask = (1 << len(self)) - 1
return self._bitmask | python | def bitmask(self):
""" A property holding a bitmask of the same length as this WireVector.
Specifically it is an integer with a number of bits set to 1 equal to the
bitwidth of the WireVector.
It is often times useful to "mask" an integer such that it fits in the
the number of bits of a WireVector. As a convenience for this, the
`bitmask` property is provided. As an example, if there was a 3-bit
WireVector `a`, a call to `a.bitmask()` should return 0b111 or 0x7."""
if "_bitmask" not in self.__dict__:
self._bitmask = (1 << len(self)) - 1
return self._bitmask | [
"def",
"bitmask",
"(",
"self",
")",
":",
"if",
"\"_bitmask\"",
"not",
"in",
"self",
".",
"__dict__",
":",
"self",
".",
"_bitmask",
"=",
"(",
"1",
"<<",
"len",
"(",
"self",
")",
")",
"-",
"1",
"return",
"self",
".",
"_bitmask"
] | A property holding a bitmask of the same length as this WireVector.
Specifically it is an integer with a number of bits set to 1 equal to the
bitwidth of the WireVector.
It is often times useful to "mask" an integer such that it fits in the
the number of bits of a WireVector. As a convenience for this, the
`bitmask` property is provided. As an example, if there was a 3-bit
WireVector `a`, a call to `a.bitmask()` should return 0b111 or 0x7. | [
"A",
"property",
"holding",
"a",
"bitmask",
"of",
"the",
"same",
"length",
"as",
"this",
"WireVector",
".",
"Specifically",
"it",
"is",
"an",
"integer",
"with",
"a",
"number",
"of",
"bits",
"set",
"to",
"1",
"equal",
"to",
"the",
"bitwidth",
"of",
"the",
"WireVector",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/wire.py#L427-L438 |
usrlocalben/pydux | pydux/log_middleware.py | log_middleware | def log_middleware(store):
"""log all actions to console as they are dispatched"""
def wrapper(next_):
def log_dispatch(action):
print('Dispatch Action:', action)
return next_(action)
return log_dispatch
return wrapper | python | def log_middleware(store):
"""log all actions to console as they are dispatched"""
def wrapper(next_):
def log_dispatch(action):
print('Dispatch Action:', action)
return next_(action)
return log_dispatch
return wrapper | [
"def",
"log_middleware",
"(",
"store",
")",
":",
"def",
"wrapper",
"(",
"next_",
")",
":",
"def",
"log_dispatch",
"(",
"action",
")",
":",
"print",
"(",
"'Dispatch Action:'",
",",
"action",
")",
"return",
"next_",
"(",
"action",
")",
"return",
"log_dispatch",
"return",
"wrapper"
] | log all actions to console as they are dispatched | [
"log",
"all",
"actions",
"to",
"console",
"as",
"they",
"are",
"dispatched"
] | train | https://github.com/usrlocalben/pydux/blob/943ca1c75357b9289f55f17ff2d997a66a3313a4/pydux/log_middleware.py#L6-L13 |
UCSBarchlab/PyRTL | pyrtl/compilesim.py | CompiledSimulation.inspect | def inspect(self, w):
"""Get the latest value of the wire given, if possible."""
if isinstance(w, WireVector):
w = w.name
try:
vals = self.tracer.trace[w]
except KeyError:
pass
else:
if not vals:
raise PyrtlError('No context available. Please run a simulation step')
return vals[-1]
raise PyrtlError('CompiledSimulation does not support inspecting internal WireVectors') | python | def inspect(self, w):
"""Get the latest value of the wire given, if possible."""
if isinstance(w, WireVector):
w = w.name
try:
vals = self.tracer.trace[w]
except KeyError:
pass
else:
if not vals:
raise PyrtlError('No context available. Please run a simulation step')
return vals[-1]
raise PyrtlError('CompiledSimulation does not support inspecting internal WireVectors') | [
"def",
"inspect",
"(",
"self",
",",
"w",
")",
":",
"if",
"isinstance",
"(",
"w",
",",
"WireVector",
")",
":",
"w",
"=",
"w",
".",
"name",
"try",
":",
"vals",
"=",
"self",
".",
"tracer",
".",
"trace",
"[",
"w",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"if",
"not",
"vals",
":",
"raise",
"PyrtlError",
"(",
"'No context available. Please run a simulation step'",
")",
"return",
"vals",
"[",
"-",
"1",
"]",
"raise",
"PyrtlError",
"(",
"'CompiledSimulation does not support inspecting internal WireVectors'",
")"
] | Get the latest value of the wire given, if possible. | [
"Get",
"the",
"latest",
"value",
"of",
"the",
"wire",
"given",
"if",
"possible",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/compilesim.py#L110-L122 |
UCSBarchlab/PyRTL | pyrtl/compilesim.py | CompiledSimulation.run | def run(self, inputs):
"""Run many steps of the simulation.
The argument is a list of input mappings for each step,
and its length is the number of steps to be executed.
"""
steps = len(inputs)
# create i/o arrays of the appropriate length
ibuf_type = ctypes.c_uint64*(steps*self._ibufsz)
obuf_type = ctypes.c_uint64*(steps*self._obufsz)
ibuf = ibuf_type()
obuf = obuf_type()
# these array will be passed to _crun
self._crun.argtypes = [ctypes.c_uint64, ibuf_type, obuf_type]
# build the input array
for n, inmap in enumerate(inputs):
for w in inmap:
if isinstance(w, WireVector):
name = w.name
else:
name = w
start, count = self._inputpos[name]
start += n*self._ibufsz
val = inmap[w]
if val >= 1 << self._inputbw[name]:
raise PyrtlError(
'Wire {} has value {} which cannot be represented '
'using its bitwidth'.format(name, val))
# pack input
for pos in range(start, start+count):
ibuf[pos] = val & ((1 << 64)-1)
val >>= 64
# run the simulation
self._crun(steps, ibuf, obuf)
# save traced wires
for name in self.tracer.trace:
rname = self._probe_mapping.get(name, name)
if rname in self._outputpos:
start, count = self._outputpos[rname]
buf, sz = obuf, self._obufsz
elif rname in self._inputpos:
start, count = self._inputpos[rname]
buf, sz = ibuf, self._ibufsz
else:
raise PyrtlInternalError('Untraceable wire in tracer')
res = []
for n in range(steps):
val = 0
# unpack output
for pos in reversed(range(start, start+count)):
val <<= 64
val |= buf[pos]
res.append(val)
start += sz
self.tracer.trace[name].extend(res) | python | def run(self, inputs):
"""Run many steps of the simulation.
The argument is a list of input mappings for each step,
and its length is the number of steps to be executed.
"""
steps = len(inputs)
# create i/o arrays of the appropriate length
ibuf_type = ctypes.c_uint64*(steps*self._ibufsz)
obuf_type = ctypes.c_uint64*(steps*self._obufsz)
ibuf = ibuf_type()
obuf = obuf_type()
# these array will be passed to _crun
self._crun.argtypes = [ctypes.c_uint64, ibuf_type, obuf_type]
# build the input array
for n, inmap in enumerate(inputs):
for w in inmap:
if isinstance(w, WireVector):
name = w.name
else:
name = w
start, count = self._inputpos[name]
start += n*self._ibufsz
val = inmap[w]
if val >= 1 << self._inputbw[name]:
raise PyrtlError(
'Wire {} has value {} which cannot be represented '
'using its bitwidth'.format(name, val))
# pack input
for pos in range(start, start+count):
ibuf[pos] = val & ((1 << 64)-1)
val >>= 64
# run the simulation
self._crun(steps, ibuf, obuf)
# save traced wires
for name in self.tracer.trace:
rname = self._probe_mapping.get(name, name)
if rname in self._outputpos:
start, count = self._outputpos[rname]
buf, sz = obuf, self._obufsz
elif rname in self._inputpos:
start, count = self._inputpos[rname]
buf, sz = ibuf, self._ibufsz
else:
raise PyrtlInternalError('Untraceable wire in tracer')
res = []
for n in range(steps):
val = 0
# unpack output
for pos in reversed(range(start, start+count)):
val <<= 64
val |= buf[pos]
res.append(val)
start += sz
self.tracer.trace[name].extend(res) | [
"def",
"run",
"(",
"self",
",",
"inputs",
")",
":",
"steps",
"=",
"len",
"(",
"inputs",
")",
"# create i/o arrays of the appropriate length",
"ibuf_type",
"=",
"ctypes",
".",
"c_uint64",
"*",
"(",
"steps",
"*",
"self",
".",
"_ibufsz",
")",
"obuf_type",
"=",
"ctypes",
".",
"c_uint64",
"*",
"(",
"steps",
"*",
"self",
".",
"_obufsz",
")",
"ibuf",
"=",
"ibuf_type",
"(",
")",
"obuf",
"=",
"obuf_type",
"(",
")",
"# these array will be passed to _crun",
"self",
".",
"_crun",
".",
"argtypes",
"=",
"[",
"ctypes",
".",
"c_uint64",
",",
"ibuf_type",
",",
"obuf_type",
"]",
"# build the input array",
"for",
"n",
",",
"inmap",
"in",
"enumerate",
"(",
"inputs",
")",
":",
"for",
"w",
"in",
"inmap",
":",
"if",
"isinstance",
"(",
"w",
",",
"WireVector",
")",
":",
"name",
"=",
"w",
".",
"name",
"else",
":",
"name",
"=",
"w",
"start",
",",
"count",
"=",
"self",
".",
"_inputpos",
"[",
"name",
"]",
"start",
"+=",
"n",
"*",
"self",
".",
"_ibufsz",
"val",
"=",
"inmap",
"[",
"w",
"]",
"if",
"val",
">=",
"1",
"<<",
"self",
".",
"_inputbw",
"[",
"name",
"]",
":",
"raise",
"PyrtlError",
"(",
"'Wire {} has value {} which cannot be represented '",
"'using its bitwidth'",
".",
"format",
"(",
"name",
",",
"val",
")",
")",
"# pack input",
"for",
"pos",
"in",
"range",
"(",
"start",
",",
"start",
"+",
"count",
")",
":",
"ibuf",
"[",
"pos",
"]",
"=",
"val",
"&",
"(",
"(",
"1",
"<<",
"64",
")",
"-",
"1",
")",
"val",
">>=",
"64",
"# run the simulation",
"self",
".",
"_crun",
"(",
"steps",
",",
"ibuf",
",",
"obuf",
")",
"# save traced wires",
"for",
"name",
"in",
"self",
".",
"tracer",
".",
"trace",
":",
"rname",
"=",
"self",
".",
"_probe_mapping",
".",
"get",
"(",
"name",
",",
"name",
")",
"if",
"rname",
"in",
"self",
".",
"_outputpos",
":",
"start",
",",
"count",
"=",
"self",
".",
"_outputpos",
"[",
"rname",
"]",
"buf",
",",
"sz",
"=",
"obuf",
",",
"self",
".",
"_obufsz",
"elif",
"rname",
"in",
"self",
".",
"_inputpos",
":",
"start",
",",
"count",
"=",
"self",
".",
"_inputpos",
"[",
"rname",
"]",
"buf",
",",
"sz",
"=",
"ibuf",
",",
"self",
".",
"_ibufsz",
"else",
":",
"raise",
"PyrtlInternalError",
"(",
"'Untraceable wire in tracer'",
")",
"res",
"=",
"[",
"]",
"for",
"n",
"in",
"range",
"(",
"steps",
")",
":",
"val",
"=",
"0",
"# unpack output",
"for",
"pos",
"in",
"reversed",
"(",
"range",
"(",
"start",
",",
"start",
"+",
"count",
")",
")",
":",
"val",
"<<=",
"64",
"val",
"|=",
"buf",
"[",
"pos",
"]",
"res",
".",
"append",
"(",
"val",
")",
"start",
"+=",
"sz",
"self",
".",
"tracer",
".",
"trace",
"[",
"name",
"]",
".",
"extend",
"(",
"res",
")"
] | Run many steps of the simulation.
The argument is a list of input mappings for each step,
and its length is the number of steps to be executed. | [
"Run",
"many",
"steps",
"of",
"the",
"simulation",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/compilesim.py#L131-L188 |
UCSBarchlab/PyRTL | pyrtl/compilesim.py | CompiledSimulation._traceable | def _traceable(self, wv):
"""Check if wv is able to be traced
If it is traceable due to a probe, record that probe in _probe_mapping.
"""
if isinstance(wv, (Input, Output)):
return True
for net in self.block.logic:
if net.op == 'w' and net.args[0].name == wv.name and isinstance(net.dests[0], Output):
self._probe_mapping[wv.name] = net.dests[0].name
return True
return False | python | def _traceable(self, wv):
"""Check if wv is able to be traced
If it is traceable due to a probe, record that probe in _probe_mapping.
"""
if isinstance(wv, (Input, Output)):
return True
for net in self.block.logic:
if net.op == 'w' and net.args[0].name == wv.name and isinstance(net.dests[0], Output):
self._probe_mapping[wv.name] = net.dests[0].name
return True
return False | [
"def",
"_traceable",
"(",
"self",
",",
"wv",
")",
":",
"if",
"isinstance",
"(",
"wv",
",",
"(",
"Input",
",",
"Output",
")",
")",
":",
"return",
"True",
"for",
"net",
"in",
"self",
".",
"block",
".",
"logic",
":",
"if",
"net",
".",
"op",
"==",
"'w'",
"and",
"net",
".",
"args",
"[",
"0",
"]",
".",
"name",
"==",
"wv",
".",
"name",
"and",
"isinstance",
"(",
"net",
".",
"dests",
"[",
"0",
"]",
",",
"Output",
")",
":",
"self",
".",
"_probe_mapping",
"[",
"wv",
".",
"name",
"]",
"=",
"net",
".",
"dests",
"[",
"0",
"]",
".",
"name",
"return",
"True",
"return",
"False"
] | Check if wv is able to be traced
If it is traceable due to a probe, record that probe in _probe_mapping. | [
"Check",
"if",
"wv",
"is",
"able",
"to",
"be",
"traced"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/compilesim.py#L190-L201 |
UCSBarchlab/PyRTL | pyrtl/compilesim.py | CompiledSimulation._remove_untraceable | def _remove_untraceable(self):
"""Remove from the tracer those wires that CompiledSimulation cannot track.
Create _probe_mapping for wires only traceable via probes.
"""
self._probe_mapping = {}
wvs = {wv for wv in self.tracer.wires_to_track if self._traceable(wv)}
self.tracer.wires_to_track = wvs
self.tracer._wires = {wv.name: wv for wv in wvs}
self.tracer.trace.__init__(wvs) | python | def _remove_untraceable(self):
"""Remove from the tracer those wires that CompiledSimulation cannot track.
Create _probe_mapping for wires only traceable via probes.
"""
self._probe_mapping = {}
wvs = {wv for wv in self.tracer.wires_to_track if self._traceable(wv)}
self.tracer.wires_to_track = wvs
self.tracer._wires = {wv.name: wv for wv in wvs}
self.tracer.trace.__init__(wvs) | [
"def",
"_remove_untraceable",
"(",
"self",
")",
":",
"self",
".",
"_probe_mapping",
"=",
"{",
"}",
"wvs",
"=",
"{",
"wv",
"for",
"wv",
"in",
"self",
".",
"tracer",
".",
"wires_to_track",
"if",
"self",
".",
"_traceable",
"(",
"wv",
")",
"}",
"self",
".",
"tracer",
".",
"wires_to_track",
"=",
"wvs",
"self",
".",
"tracer",
".",
"_wires",
"=",
"{",
"wv",
".",
"name",
":",
"wv",
"for",
"wv",
"in",
"wvs",
"}",
"self",
".",
"tracer",
".",
"trace",
".",
"__init__",
"(",
"wvs",
")"
] | Remove from the tracer those wires that CompiledSimulation cannot track.
Create _probe_mapping for wires only traceable via probes. | [
"Remove",
"from",
"the",
"tracer",
"those",
"wires",
"that",
"CompiledSimulation",
"cannot",
"track",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/compilesim.py#L203-L212 |
UCSBarchlab/PyRTL | pyrtl/compilesim.py | CompiledSimulation._create_dll | def _create_dll(self):
"""Create a dynamically-linked library implementing the simulation logic."""
self._dir = tempfile.mkdtemp()
with open(path.join(self._dir, 'pyrtlsim.c'), 'w') as f:
self._create_code(lambda s: f.write(s+'\n'))
if platform.system() == 'Darwin':
shared = '-dynamiclib'
else:
shared = '-shared'
subprocess.check_call([
'gcc', '-O0', '-march=native', '-std=c99', '-m64',
shared, '-fPIC',
path.join(self._dir, 'pyrtlsim.c'), '-o', path.join(self._dir, 'pyrtlsim.so'),
], shell=(platform.system() == 'Windows'))
self._dll = ctypes.CDLL(path.join(self._dir, 'pyrtlsim.so'))
self._crun = self._dll.sim_run_all
self._crun.restype = None | python | def _create_dll(self):
"""Create a dynamically-linked library implementing the simulation logic."""
self._dir = tempfile.mkdtemp()
with open(path.join(self._dir, 'pyrtlsim.c'), 'w') as f:
self._create_code(lambda s: f.write(s+'\n'))
if platform.system() == 'Darwin':
shared = '-dynamiclib'
else:
shared = '-shared'
subprocess.check_call([
'gcc', '-O0', '-march=native', '-std=c99', '-m64',
shared, '-fPIC',
path.join(self._dir, 'pyrtlsim.c'), '-o', path.join(self._dir, 'pyrtlsim.so'),
], shell=(platform.system() == 'Windows'))
self._dll = ctypes.CDLL(path.join(self._dir, 'pyrtlsim.so'))
self._crun = self._dll.sim_run_all
self._crun.restype = None | [
"def",
"_create_dll",
"(",
"self",
")",
":",
"self",
".",
"_dir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"with",
"open",
"(",
"path",
".",
"join",
"(",
"self",
".",
"_dir",
",",
"'pyrtlsim.c'",
")",
",",
"'w'",
")",
"as",
"f",
":",
"self",
".",
"_create_code",
"(",
"lambda",
"s",
":",
"f",
".",
"write",
"(",
"s",
"+",
"'\\n'",
")",
")",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Darwin'",
":",
"shared",
"=",
"'-dynamiclib'",
"else",
":",
"shared",
"=",
"'-shared'",
"subprocess",
".",
"check_call",
"(",
"[",
"'gcc'",
",",
"'-O0'",
",",
"'-march=native'",
",",
"'-std=c99'",
",",
"'-m64'",
",",
"shared",
",",
"'-fPIC'",
",",
"path",
".",
"join",
"(",
"self",
".",
"_dir",
",",
"'pyrtlsim.c'",
")",
",",
"'-o'",
",",
"path",
".",
"join",
"(",
"self",
".",
"_dir",
",",
"'pyrtlsim.so'",
")",
",",
"]",
",",
"shell",
"=",
"(",
"platform",
".",
"system",
"(",
")",
"==",
"'Windows'",
")",
")",
"self",
".",
"_dll",
"=",
"ctypes",
".",
"CDLL",
"(",
"path",
".",
"join",
"(",
"self",
".",
"_dir",
",",
"'pyrtlsim.so'",
")",
")",
"self",
".",
"_crun",
"=",
"self",
".",
"_dll",
".",
"sim_run_all",
"self",
".",
"_crun",
".",
"restype",
"=",
"None"
] | Create a dynamically-linked library implementing the simulation logic. | [
"Create",
"a",
"dynamically",
"-",
"linked",
"library",
"implementing",
"the",
"simulation",
"logic",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/compilesim.py#L214-L230 |
UCSBarchlab/PyRTL | pyrtl/compilesim.py | CompiledSimulation._makeini | def _makeini(self, w, v):
"""C initializer string for a wire with a given value."""
pieces = []
for n in range(self._limbs(w)):
pieces.append(hex(v & ((1 << 64)-1)))
v >>= 64
return ','.join(pieces).join('{}') | python | def _makeini(self, w, v):
"""C initializer string for a wire with a given value."""
pieces = []
for n in range(self._limbs(w)):
pieces.append(hex(v & ((1 << 64)-1)))
v >>= 64
return ','.join(pieces).join('{}') | [
"def",
"_makeini",
"(",
"self",
",",
"w",
",",
"v",
")",
":",
"pieces",
"=",
"[",
"]",
"for",
"n",
"in",
"range",
"(",
"self",
".",
"_limbs",
"(",
"w",
")",
")",
":",
"pieces",
".",
"append",
"(",
"hex",
"(",
"v",
"&",
"(",
"(",
"1",
"<<",
"64",
")",
"-",
"1",
")",
")",
")",
"v",
">>=",
"64",
"return",
"','",
".",
"join",
"(",
"pieces",
")",
".",
"join",
"(",
"'{}'",
")"
] | C initializer string for a wire with a given value. | [
"C",
"initializer",
"string",
"for",
"a",
"wire",
"with",
"a",
"given",
"value",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/compilesim.py#L236-L242 |
UCSBarchlab/PyRTL | pyrtl/compilesim.py | CompiledSimulation._makemask | def _makemask(self, dest, res, pos):
"""Create a bitmask.
The value being masked is of width `res`.
Limb number `pos` of `dest` is being assigned to.
"""
if (res is None or dest.bitwidth < res) and 0 < (dest.bitwidth - 64*pos) < 64:
return '&0x{:X}'.format((1 << (dest.bitwidth % 64))-1)
return '' | python | def _makemask(self, dest, res, pos):
"""Create a bitmask.
The value being masked is of width `res`.
Limb number `pos` of `dest` is being assigned to.
"""
if (res is None or dest.bitwidth < res) and 0 < (dest.bitwidth - 64*pos) < 64:
return '&0x{:X}'.format((1 << (dest.bitwidth % 64))-1)
return '' | [
"def",
"_makemask",
"(",
"self",
",",
"dest",
",",
"res",
",",
"pos",
")",
":",
"if",
"(",
"res",
"is",
"None",
"or",
"dest",
".",
"bitwidth",
"<",
"res",
")",
"and",
"0",
"<",
"(",
"dest",
".",
"bitwidth",
"-",
"64",
"*",
"pos",
")",
"<",
"64",
":",
"return",
"'&0x{:X}'",
".",
"format",
"(",
"(",
"1",
"<<",
"(",
"dest",
".",
"bitwidth",
"%",
"64",
")",
")",
"-",
"1",
")",
"return",
"''"
] | Create a bitmask.
The value being masked is of width `res`.
Limb number `pos` of `dest` is being assigned to. | [
"Create",
"a",
"bitmask",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/compilesim.py#L257-L265 |
UCSBarchlab/PyRTL | pyrtl/compilesim.py | CompiledSimulation._getarglimb | def _getarglimb(self, arg, n):
"""Get the nth limb of the given wire.
Returns '0' when the wire does not have sufficient limbs.
"""
return '{vn}[{n}]'.format(vn=self.varname[arg], n=n) if arg.bitwidth > 64*n else '0' | python | def _getarglimb(self, arg, n):
"""Get the nth limb of the given wire.
Returns '0' when the wire does not have sufficient limbs.
"""
return '{vn}[{n}]'.format(vn=self.varname[arg], n=n) if arg.bitwidth > 64*n else '0' | [
"def",
"_getarglimb",
"(",
"self",
",",
"arg",
",",
"n",
")",
":",
"return",
"'{vn}[{n}]'",
".",
"format",
"(",
"vn",
"=",
"self",
".",
"varname",
"[",
"arg",
"]",
",",
"n",
"=",
"n",
")",
"if",
"arg",
".",
"bitwidth",
">",
"64",
"*",
"n",
"else",
"'0'"
] | Get the nth limb of the given wire.
Returns '0' when the wire does not have sufficient limbs. | [
"Get",
"the",
"nth",
"limb",
"of",
"the",
"given",
"wire",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/compilesim.py#L267-L272 |
UCSBarchlab/PyRTL | pyrtl/compilesim.py | CompiledSimulation._clean_name | def _clean_name(self, prefix, obj):
"""Create a C variable name with the given prefix based on the name of obj."""
return '{}{}_{}'.format(prefix, self._uid(), ''.join(c for c in obj.name if c.isalnum())) | python | def _clean_name(self, prefix, obj):
"""Create a C variable name with the given prefix based on the name of obj."""
return '{}{}_{}'.format(prefix, self._uid(), ''.join(c for c in obj.name if c.isalnum())) | [
"def",
"_clean_name",
"(",
"self",
",",
"prefix",
",",
"obj",
")",
":",
"return",
"'{}{}_{}'",
".",
"format",
"(",
"prefix",
",",
"self",
".",
"_uid",
"(",
")",
",",
"''",
".",
"join",
"(",
"c",
"for",
"c",
"in",
"obj",
".",
"name",
"if",
"c",
".",
"isalnum",
"(",
")",
")",
")"
] | Create a C variable name with the given prefix based on the name of obj. | [
"Create",
"a",
"C",
"variable",
"name",
"with",
"the",
"given",
"prefix",
"based",
"on",
"the",
"name",
"of",
"obj",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/compilesim.py#L274-L276 |
UCSBarchlab/PyRTL | pyrtl/rtllib/multipliers.py | simple_mult | def simple_mult(A, B, start):
""" Builds a slow, small multiplier using the simple shift-and-add algorithm.
Requires very small area (it uses only a single adder), but has long delay
(worst case is len(A) cycles). start is a one-bit input to indicate inputs are ready.
done is a one-bit output signal raised when the multiplication is finished.
:param WireVector A, B: two input wires for the multiplication
:returns: Register containing the product; the "done" signal
"""
triv_result = _trivial_mult(A, B)
if triv_result is not None:
return triv_result, pyrtl.Const(1, 1)
alen = len(A)
blen = len(B)
areg = pyrtl.Register(alen)
breg = pyrtl.Register(blen + alen)
accum = pyrtl.Register(blen + alen)
done = (areg == 0) # Multiplication is finished when a becomes 0
# During multiplication, shift a right every cycle, b left every cycle
with pyrtl.conditional_assignment:
with start: # initialization
areg.next |= A
breg.next |= B
accum.next |= 0
with ~done: # don't run when there's no work to do
areg.next |= areg[1:] # right shift
breg.next |= pyrtl.concat(breg, pyrtl.Const(0, 1)) # left shift
a_0_val = areg[0].sign_extended(len(accum))
# adds to accum only when LSB of areg is 1
accum.next |= accum + (a_0_val & breg)
return accum, done | python | def simple_mult(A, B, start):
""" Builds a slow, small multiplier using the simple shift-and-add algorithm.
Requires very small area (it uses only a single adder), but has long delay
(worst case is len(A) cycles). start is a one-bit input to indicate inputs are ready.
done is a one-bit output signal raised when the multiplication is finished.
:param WireVector A, B: two input wires for the multiplication
:returns: Register containing the product; the "done" signal
"""
triv_result = _trivial_mult(A, B)
if triv_result is not None:
return triv_result, pyrtl.Const(1, 1)
alen = len(A)
blen = len(B)
areg = pyrtl.Register(alen)
breg = pyrtl.Register(blen + alen)
accum = pyrtl.Register(blen + alen)
done = (areg == 0) # Multiplication is finished when a becomes 0
# During multiplication, shift a right every cycle, b left every cycle
with pyrtl.conditional_assignment:
with start: # initialization
areg.next |= A
breg.next |= B
accum.next |= 0
with ~done: # don't run when there's no work to do
areg.next |= areg[1:] # right shift
breg.next |= pyrtl.concat(breg, pyrtl.Const(0, 1)) # left shift
a_0_val = areg[0].sign_extended(len(accum))
# adds to accum only when LSB of areg is 1
accum.next |= accum + (a_0_val & breg)
return accum, done | [
"def",
"simple_mult",
"(",
"A",
",",
"B",
",",
"start",
")",
":",
"triv_result",
"=",
"_trivial_mult",
"(",
"A",
",",
"B",
")",
"if",
"triv_result",
"is",
"not",
"None",
":",
"return",
"triv_result",
",",
"pyrtl",
".",
"Const",
"(",
"1",
",",
"1",
")",
"alen",
"=",
"len",
"(",
"A",
")",
"blen",
"=",
"len",
"(",
"B",
")",
"areg",
"=",
"pyrtl",
".",
"Register",
"(",
"alen",
")",
"breg",
"=",
"pyrtl",
".",
"Register",
"(",
"blen",
"+",
"alen",
")",
"accum",
"=",
"pyrtl",
".",
"Register",
"(",
"blen",
"+",
"alen",
")",
"done",
"=",
"(",
"areg",
"==",
"0",
")",
"# Multiplication is finished when a becomes 0",
"# During multiplication, shift a right every cycle, b left every cycle",
"with",
"pyrtl",
".",
"conditional_assignment",
":",
"with",
"start",
":",
"# initialization",
"areg",
".",
"next",
"|=",
"A",
"breg",
".",
"next",
"|=",
"B",
"accum",
".",
"next",
"|=",
"0",
"with",
"~",
"done",
":",
"# don't run when there's no work to do",
"areg",
".",
"next",
"|=",
"areg",
"[",
"1",
":",
"]",
"# right shift",
"breg",
".",
"next",
"|=",
"pyrtl",
".",
"concat",
"(",
"breg",
",",
"pyrtl",
".",
"Const",
"(",
"0",
",",
"1",
")",
")",
"# left shift",
"a_0_val",
"=",
"areg",
"[",
"0",
"]",
".",
"sign_extended",
"(",
"len",
"(",
"accum",
")",
")",
"# adds to accum only when LSB of areg is 1",
"accum",
".",
"next",
"|=",
"accum",
"+",
"(",
"a_0_val",
"&",
"breg",
")",
"return",
"accum",
",",
"done"
] | Builds a slow, small multiplier using the simple shift-and-add algorithm.
Requires very small area (it uses only a single adder), but has long delay
(worst case is len(A) cycles). start is a one-bit input to indicate inputs are ready.
done is a one-bit output signal raised when the multiplication is finished.
:param WireVector A, B: two input wires for the multiplication
:returns: Register containing the product; the "done" signal | [
"Builds",
"a",
"slow",
"small",
"multiplier",
"using",
"the",
"simple",
"shift",
"-",
"and",
"-",
"add",
"algorithm",
".",
"Requires",
"very",
"small",
"area",
"(",
"it",
"uses",
"only",
"a",
"single",
"adder",
")",
"but",
"has",
"long",
"delay",
"(",
"worst",
"case",
"is",
"len",
"(",
"A",
")",
"cycles",
")",
".",
"start",
"is",
"a",
"one",
"-",
"bit",
"input",
"to",
"indicate",
"inputs",
"are",
"ready",
".",
"done",
"is",
"a",
"one",
"-",
"bit",
"output",
"signal",
"raised",
"when",
"the",
"multiplication",
"is",
"finished",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/multipliers.py#L11-L46 |
UCSBarchlab/PyRTL | pyrtl/rtllib/multipliers.py | _trivial_mult | def _trivial_mult(A, B):
"""
turns a multiplication into an And gate if one of the
wires is a bitwidth of 1
:param A:
:param B:
:return:
"""
if len(B) == 1:
A, B = B, A # so that we can reuse the code below :)
if len(A) == 1:
a_vals = A.sign_extended(len(B))
# keep the wirevector len consistent
return pyrtl.concat_list([a_vals & B, pyrtl.Const(0)]) | python | def _trivial_mult(A, B):
"""
turns a multiplication into an And gate if one of the
wires is a bitwidth of 1
:param A:
:param B:
:return:
"""
if len(B) == 1:
A, B = B, A # so that we can reuse the code below :)
if len(A) == 1:
a_vals = A.sign_extended(len(B))
# keep the wirevector len consistent
return pyrtl.concat_list([a_vals & B, pyrtl.Const(0)]) | [
"def",
"_trivial_mult",
"(",
"A",
",",
"B",
")",
":",
"if",
"len",
"(",
"B",
")",
"==",
"1",
":",
"A",
",",
"B",
"=",
"B",
",",
"A",
"# so that we can reuse the code below :)",
"if",
"len",
"(",
"A",
")",
"==",
"1",
":",
"a_vals",
"=",
"A",
".",
"sign_extended",
"(",
"len",
"(",
"B",
")",
")",
"# keep the wirevector len consistent",
"return",
"pyrtl",
".",
"concat_list",
"(",
"[",
"a_vals",
"&",
"B",
",",
"pyrtl",
".",
"Const",
"(",
"0",
")",
"]",
")"
] | turns a multiplication into an And gate if one of the
wires is a bitwidth of 1
:param A:
:param B:
:return: | [
"turns",
"a",
"multiplication",
"into",
"an",
"And",
"gate",
"if",
"one",
"of",
"the",
"wires",
"is",
"a",
"bitwidth",
"of",
"1"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/multipliers.py#L49-L64 |
UCSBarchlab/PyRTL | pyrtl/rtllib/multipliers.py | complex_mult | def complex_mult(A, B, shifts, start):
""" Generate shift-and-add multiplier that can shift and add multiple bits per clock cycle.
Uses substantially more space than `simple_mult()` but is much faster.
:param WireVector A, B: two input wires for the multiplication
:param int shifts: number of spaces Register is to be shifted per clk cycle
(cannot be greater than the length of `A` or `B`)
:param bool start: start signal
:returns: Register containing the product; the "done" signal
"""
alen = len(A)
blen = len(B)
areg = pyrtl.Register(alen)
breg = pyrtl.Register(alen + blen)
accum = pyrtl.Register(alen + blen)
done = (areg == 0) # Multiplication is finished when a becomes 0
if (shifts > alen) or (shifts > blen):
raise pyrtl.PyrtlError("shift is larger than one or both of the parameters A or B,"
"please choose smaller shift")
# During multiplication, shift a right every cycle 'shift' times,
# shift b left every cycle 'shift' times
with pyrtl.conditional_assignment:
with start: # initialization
areg.next |= A
breg.next |= B
accum.next |= 0
with ~done: # don't run when there's no work to do
# "Multiply" shifted breg by LSB of areg by cond. adding
areg.next |= libutils._shifted_reg_next(areg, 'r', shifts) # right shift
breg.next |= libutils._shifted_reg_next(breg, 'l', shifts) # left shift
accum.next |= accum + _one_cycle_mult(areg, breg, shifts)
return accum, done | python | def complex_mult(A, B, shifts, start):
""" Generate shift-and-add multiplier that can shift and add multiple bits per clock cycle.
Uses substantially more space than `simple_mult()` but is much faster.
:param WireVector A, B: two input wires for the multiplication
:param int shifts: number of spaces Register is to be shifted per clk cycle
(cannot be greater than the length of `A` or `B`)
:param bool start: start signal
:returns: Register containing the product; the "done" signal
"""
alen = len(A)
blen = len(B)
areg = pyrtl.Register(alen)
breg = pyrtl.Register(alen + blen)
accum = pyrtl.Register(alen + blen)
done = (areg == 0) # Multiplication is finished when a becomes 0
if (shifts > alen) or (shifts > blen):
raise pyrtl.PyrtlError("shift is larger than one or both of the parameters A or B,"
"please choose smaller shift")
# During multiplication, shift a right every cycle 'shift' times,
# shift b left every cycle 'shift' times
with pyrtl.conditional_assignment:
with start: # initialization
areg.next |= A
breg.next |= B
accum.next |= 0
with ~done: # don't run when there's no work to do
# "Multiply" shifted breg by LSB of areg by cond. adding
areg.next |= libutils._shifted_reg_next(areg, 'r', shifts) # right shift
breg.next |= libutils._shifted_reg_next(breg, 'l', shifts) # left shift
accum.next |= accum + _one_cycle_mult(areg, breg, shifts)
return accum, done | [
"def",
"complex_mult",
"(",
"A",
",",
"B",
",",
"shifts",
",",
"start",
")",
":",
"alen",
"=",
"len",
"(",
"A",
")",
"blen",
"=",
"len",
"(",
"B",
")",
"areg",
"=",
"pyrtl",
".",
"Register",
"(",
"alen",
")",
"breg",
"=",
"pyrtl",
".",
"Register",
"(",
"alen",
"+",
"blen",
")",
"accum",
"=",
"pyrtl",
".",
"Register",
"(",
"alen",
"+",
"blen",
")",
"done",
"=",
"(",
"areg",
"==",
"0",
")",
"# Multiplication is finished when a becomes 0",
"if",
"(",
"shifts",
">",
"alen",
")",
"or",
"(",
"shifts",
">",
"blen",
")",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"shift is larger than one or both of the parameters A or B,\"",
"\"please choose smaller shift\"",
")",
"# During multiplication, shift a right every cycle 'shift' times,",
"# shift b left every cycle 'shift' times",
"with",
"pyrtl",
".",
"conditional_assignment",
":",
"with",
"start",
":",
"# initialization",
"areg",
".",
"next",
"|=",
"A",
"breg",
".",
"next",
"|=",
"B",
"accum",
".",
"next",
"|=",
"0",
"with",
"~",
"done",
":",
"# don't run when there's no work to do",
"# \"Multiply\" shifted breg by LSB of areg by cond. adding",
"areg",
".",
"next",
"|=",
"libutils",
".",
"_shifted_reg_next",
"(",
"areg",
",",
"'r'",
",",
"shifts",
")",
"# right shift",
"breg",
".",
"next",
"|=",
"libutils",
".",
"_shifted_reg_next",
"(",
"breg",
",",
"'l'",
",",
"shifts",
")",
"# left shift",
"accum",
".",
"next",
"|=",
"accum",
"+",
"_one_cycle_mult",
"(",
"areg",
",",
"breg",
",",
"shifts",
")",
"return",
"accum",
",",
"done"
] | Generate shift-and-add multiplier that can shift and add multiple bits per clock cycle.
Uses substantially more space than `simple_mult()` but is much faster.
:param WireVector A, B: two input wires for the multiplication
:param int shifts: number of spaces Register is to be shifted per clk cycle
(cannot be greater than the length of `A` or `B`)
:param bool start: start signal
:returns: Register containing the product; the "done" signal | [
"Generate",
"shift",
"-",
"and",
"-",
"add",
"multiplier",
"that",
"can",
"shift",
"and",
"add",
"multiple",
"bits",
"per",
"clock",
"cycle",
".",
"Uses",
"substantially",
"more",
"space",
"than",
"simple_mult",
"()",
"but",
"is",
"much",
"faster",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/multipliers.py#L67-L102 |
UCSBarchlab/PyRTL | pyrtl/rtllib/multipliers.py | _one_cycle_mult | def _one_cycle_mult(areg, breg, rem_bits, sum_sf=0, curr_bit=0):
""" returns a WireVector sum of rem_bits multiplies (in one clock cycle)
note: this method requires a lot of area because of the indexing in the else statement """
if rem_bits == 0:
return sum_sf
else:
a_curr_val = areg[curr_bit].sign_extended(len(breg))
if curr_bit == 0: # if no shift
return(_one_cycle_mult(areg, breg, rem_bits-1, # areg, breg, rem_bits
sum_sf + (a_curr_val & breg), # sum_sf
curr_bit+1)) # curr_bit
else:
return _one_cycle_mult(
areg, breg, rem_bits-1, # areg, breg, rem_bits
sum_sf + (a_curr_val &
pyrtl.concat(breg, pyrtl.Const(0, curr_bit))), # sum_sf
curr_bit+1 # curr_bit
) | python | def _one_cycle_mult(areg, breg, rem_bits, sum_sf=0, curr_bit=0):
""" returns a WireVector sum of rem_bits multiplies (in one clock cycle)
note: this method requires a lot of area because of the indexing in the else statement """
if rem_bits == 0:
return sum_sf
else:
a_curr_val = areg[curr_bit].sign_extended(len(breg))
if curr_bit == 0: # if no shift
return(_one_cycle_mult(areg, breg, rem_bits-1, # areg, breg, rem_bits
sum_sf + (a_curr_val & breg), # sum_sf
curr_bit+1)) # curr_bit
else:
return _one_cycle_mult(
areg, breg, rem_bits-1, # areg, breg, rem_bits
sum_sf + (a_curr_val &
pyrtl.concat(breg, pyrtl.Const(0, curr_bit))), # sum_sf
curr_bit+1 # curr_bit
) | [
"def",
"_one_cycle_mult",
"(",
"areg",
",",
"breg",
",",
"rem_bits",
",",
"sum_sf",
"=",
"0",
",",
"curr_bit",
"=",
"0",
")",
":",
"if",
"rem_bits",
"==",
"0",
":",
"return",
"sum_sf",
"else",
":",
"a_curr_val",
"=",
"areg",
"[",
"curr_bit",
"]",
".",
"sign_extended",
"(",
"len",
"(",
"breg",
")",
")",
"if",
"curr_bit",
"==",
"0",
":",
"# if no shift",
"return",
"(",
"_one_cycle_mult",
"(",
"areg",
",",
"breg",
",",
"rem_bits",
"-",
"1",
",",
"# areg, breg, rem_bits",
"sum_sf",
"+",
"(",
"a_curr_val",
"&",
"breg",
")",
",",
"# sum_sf",
"curr_bit",
"+",
"1",
")",
")",
"# curr_bit",
"else",
":",
"return",
"_one_cycle_mult",
"(",
"areg",
",",
"breg",
",",
"rem_bits",
"-",
"1",
",",
"# areg, breg, rem_bits",
"sum_sf",
"+",
"(",
"a_curr_val",
"&",
"pyrtl",
".",
"concat",
"(",
"breg",
",",
"pyrtl",
".",
"Const",
"(",
"0",
",",
"curr_bit",
")",
")",
")",
",",
"# sum_sf",
"curr_bit",
"+",
"1",
"# curr_bit",
")"
] | returns a WireVector sum of rem_bits multiplies (in one clock cycle)
note: this method requires a lot of area because of the indexing in the else statement | [
"returns",
"a",
"WireVector",
"sum",
"of",
"rem_bits",
"multiplies",
"(",
"in",
"one",
"clock",
"cycle",
")",
"note",
":",
"this",
"method",
"requires",
"a",
"lot",
"of",
"area",
"because",
"of",
"the",
"indexing",
"in",
"the",
"else",
"statement"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/multipliers.py#L105-L122 |
UCSBarchlab/PyRTL | pyrtl/rtllib/multipliers.py | tree_multiplier | def tree_multiplier(A, B, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone):
""" Build an fast unclocked multiplier for inputs A and B using a Wallace or Dada Tree.
:param WireVector A, B: two input wires for the multiplication
:param function reducer: Reduce the tree using either a Dada recuder or a Wallace reducer
determines whether it is a Wallace tree multiplier or a Dada tree multiplier
:param function adder_func: an adder function that will be used to do the last addition
:return WireVector: The multiplied result
Delay is order logN, while area is order N^2.
"""
"""
The two tree multipliers basically works by splitting the multiplication
into a series of many additions, and it works by applying 'reductions'.
"""
triv_res = _trivial_mult(A, B)
if triv_res is not None:
return triv_res
bits_length = (len(A) + len(B))
# create a list of lists, with slots for all the weights (bit-positions)
bits = [[] for weight in range(bits_length)]
# AND every bit of A with every bit of B (N^2 results) and store by "weight" (bit-position)
for i, a in enumerate(A):
for j, b in enumerate(B):
bits[i + j].append(a & b)
return reducer(bits, bits_length, adder_func) | python | def tree_multiplier(A, B, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone):
""" Build an fast unclocked multiplier for inputs A and B using a Wallace or Dada Tree.
:param WireVector A, B: two input wires for the multiplication
:param function reducer: Reduce the tree using either a Dada recuder or a Wallace reducer
determines whether it is a Wallace tree multiplier or a Dada tree multiplier
:param function adder_func: an adder function that will be used to do the last addition
:return WireVector: The multiplied result
Delay is order logN, while area is order N^2.
"""
"""
The two tree multipliers basically works by splitting the multiplication
into a series of many additions, and it works by applying 'reductions'.
"""
triv_res = _trivial_mult(A, B)
if triv_res is not None:
return triv_res
bits_length = (len(A) + len(B))
# create a list of lists, with slots for all the weights (bit-positions)
bits = [[] for weight in range(bits_length)]
# AND every bit of A with every bit of B (N^2 results) and store by "weight" (bit-position)
for i, a in enumerate(A):
for j, b in enumerate(B):
bits[i + j].append(a & b)
return reducer(bits, bits_length, adder_func) | [
"def",
"tree_multiplier",
"(",
"A",
",",
"B",
",",
"reducer",
"=",
"adders",
".",
"wallace_reducer",
",",
"adder_func",
"=",
"adders",
".",
"kogge_stone",
")",
":",
"\"\"\"\n The two tree multipliers basically works by splitting the multiplication\n into a series of many additions, and it works by applying 'reductions'.\n \"\"\"",
"triv_res",
"=",
"_trivial_mult",
"(",
"A",
",",
"B",
")",
"if",
"triv_res",
"is",
"not",
"None",
":",
"return",
"triv_res",
"bits_length",
"=",
"(",
"len",
"(",
"A",
")",
"+",
"len",
"(",
"B",
")",
")",
"# create a list of lists, with slots for all the weights (bit-positions)",
"bits",
"=",
"[",
"[",
"]",
"for",
"weight",
"in",
"range",
"(",
"bits_length",
")",
"]",
"# AND every bit of A with every bit of B (N^2 results) and store by \"weight\" (bit-position)",
"for",
"i",
",",
"a",
"in",
"enumerate",
"(",
"A",
")",
":",
"for",
"j",
",",
"b",
"in",
"enumerate",
"(",
"B",
")",
":",
"bits",
"[",
"i",
"+",
"j",
"]",
".",
"append",
"(",
"a",
"&",
"b",
")",
"return",
"reducer",
"(",
"bits",
",",
"bits_length",
",",
"adder_func",
")"
] | Build an fast unclocked multiplier for inputs A and B using a Wallace or Dada Tree.
:param WireVector A, B: two input wires for the multiplication
:param function reducer: Reduce the tree using either a Dada recuder or a Wallace reducer
determines whether it is a Wallace tree multiplier or a Dada tree multiplier
:param function adder_func: an adder function that will be used to do the last addition
:return WireVector: The multiplied result
Delay is order logN, while area is order N^2. | [
"Build",
"an",
"fast",
"unclocked",
"multiplier",
"for",
"inputs",
"A",
"and",
"B",
"using",
"a",
"Wallace",
"or",
"Dada",
"Tree",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/multipliers.py#L125-L155 |
UCSBarchlab/PyRTL | pyrtl/rtllib/multipliers.py | signed_tree_multiplier | def signed_tree_multiplier(A, B, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone):
"""Same as tree_multiplier, but uses two's-complement signed integers"""
if len(A) == 1 or len(B) == 1:
raise pyrtl.PyrtlError("sign bit required, one or both wires too small")
aneg, bneg = A[-1], B[-1]
a = _twos_comp_conditional(A, aneg)
b = _twos_comp_conditional(B, bneg)
res = tree_multiplier(a[:-1], b[:-1]).zero_extended(len(A) + len(B))
return _twos_comp_conditional(res, aneg ^ bneg) | python | def signed_tree_multiplier(A, B, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone):
"""Same as tree_multiplier, but uses two's-complement signed integers"""
if len(A) == 1 or len(B) == 1:
raise pyrtl.PyrtlError("sign bit required, one or both wires too small")
aneg, bneg = A[-1], B[-1]
a = _twos_comp_conditional(A, aneg)
b = _twos_comp_conditional(B, bneg)
res = tree_multiplier(a[:-1], b[:-1]).zero_extended(len(A) + len(B))
return _twos_comp_conditional(res, aneg ^ bneg) | [
"def",
"signed_tree_multiplier",
"(",
"A",
",",
"B",
",",
"reducer",
"=",
"adders",
".",
"wallace_reducer",
",",
"adder_func",
"=",
"adders",
".",
"kogge_stone",
")",
":",
"if",
"len",
"(",
"A",
")",
"==",
"1",
"or",
"len",
"(",
"B",
")",
"==",
"1",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"sign bit required, one or both wires too small\"",
")",
"aneg",
",",
"bneg",
"=",
"A",
"[",
"-",
"1",
"]",
",",
"B",
"[",
"-",
"1",
"]",
"a",
"=",
"_twos_comp_conditional",
"(",
"A",
",",
"aneg",
")",
"b",
"=",
"_twos_comp_conditional",
"(",
"B",
",",
"bneg",
")",
"res",
"=",
"tree_multiplier",
"(",
"a",
"[",
":",
"-",
"1",
"]",
",",
"b",
"[",
":",
"-",
"1",
"]",
")",
".",
"zero_extended",
"(",
"len",
"(",
"A",
")",
"+",
"len",
"(",
"B",
")",
")",
"return",
"_twos_comp_conditional",
"(",
"res",
",",
"aneg",
"^",
"bneg",
")"
] | Same as tree_multiplier, but uses two's-complement signed integers | [
"Same",
"as",
"tree_multiplier",
"but",
"uses",
"two",
"s",
"-",
"complement",
"signed",
"integers"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/multipliers.py#L158-L168 |
UCSBarchlab/PyRTL | pyrtl/rtllib/multipliers.py | _twos_comp_conditional | def _twos_comp_conditional(orig_wire, sign_bit, bw=None):
"""Returns two's complement of wire (using bitwidth bw) if sign_bit == 1"""
if bw is None:
bw = len(orig_wire)
new_wire = pyrtl.WireVector(bw)
with pyrtl.conditional_assignment:
with sign_bit:
new_wire |= ~orig_wire + 1
with pyrtl.otherwise:
new_wire |= orig_wire
return new_wire | python | def _twos_comp_conditional(orig_wire, sign_bit, bw=None):
"""Returns two's complement of wire (using bitwidth bw) if sign_bit == 1"""
if bw is None:
bw = len(orig_wire)
new_wire = pyrtl.WireVector(bw)
with pyrtl.conditional_assignment:
with sign_bit:
new_wire |= ~orig_wire + 1
with pyrtl.otherwise:
new_wire |= orig_wire
return new_wire | [
"def",
"_twos_comp_conditional",
"(",
"orig_wire",
",",
"sign_bit",
",",
"bw",
"=",
"None",
")",
":",
"if",
"bw",
"is",
"None",
":",
"bw",
"=",
"len",
"(",
"orig_wire",
")",
"new_wire",
"=",
"pyrtl",
".",
"WireVector",
"(",
"bw",
")",
"with",
"pyrtl",
".",
"conditional_assignment",
":",
"with",
"sign_bit",
":",
"new_wire",
"|=",
"~",
"orig_wire",
"+",
"1",
"with",
"pyrtl",
".",
"otherwise",
":",
"new_wire",
"|=",
"orig_wire",
"return",
"new_wire"
] | Returns two's complement of wire (using bitwidth bw) if sign_bit == 1 | [
"Returns",
"two",
"s",
"complement",
"of",
"wire",
"(",
"using",
"bitwidth",
"bw",
")",
"if",
"sign_bit",
"==",
"1"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/multipliers.py#L171-L181 |
UCSBarchlab/PyRTL | pyrtl/rtllib/multipliers.py | fused_multiply_adder | def fused_multiply_adder(mult_A, mult_B, add, signed=False, reducer=adders.wallace_reducer,
adder_func=adders.kogge_stone):
""" Generate efficient hardware for a*b+c.
Multiplies two wirevectors together and adds a third wirevector to the
multiplication result, all in
one step. By doing it this way (instead of separately), one reduces both
the area and the timing delay of the circuit.
:param Bool signed: Currently not supported (will be added in the future)
The default will likely be changed to True, so if you want the smallest
set of wires in the future, specify this as False
:param reducer: (advanced) The tree reducer to use
:param adder_func: (advanced) The adder to use to add the two results at the end
:return WireVector: The result WireVector
"""
# TODO: Specify the length of the result wirevector
return generalized_fma(((mult_A, mult_B),), (add,), signed, reducer, adder_func) | python | def fused_multiply_adder(mult_A, mult_B, add, signed=False, reducer=adders.wallace_reducer,
adder_func=adders.kogge_stone):
""" Generate efficient hardware for a*b+c.
Multiplies two wirevectors together and adds a third wirevector to the
multiplication result, all in
one step. By doing it this way (instead of separately), one reduces both
the area and the timing delay of the circuit.
:param Bool signed: Currently not supported (will be added in the future)
The default will likely be changed to True, so if you want the smallest
set of wires in the future, specify this as False
:param reducer: (advanced) The tree reducer to use
:param adder_func: (advanced) The adder to use to add the two results at the end
:return WireVector: The result WireVector
"""
# TODO: Specify the length of the result wirevector
return generalized_fma(((mult_A, mult_B),), (add,), signed, reducer, adder_func) | [
"def",
"fused_multiply_adder",
"(",
"mult_A",
",",
"mult_B",
",",
"add",
",",
"signed",
"=",
"False",
",",
"reducer",
"=",
"adders",
".",
"wallace_reducer",
",",
"adder_func",
"=",
"adders",
".",
"kogge_stone",
")",
":",
"# TODO: Specify the length of the result wirevector",
"return",
"generalized_fma",
"(",
"(",
"(",
"mult_A",
",",
"mult_B",
")",
",",
")",
",",
"(",
"add",
",",
")",
",",
"signed",
",",
"reducer",
",",
"adder_func",
")"
] | Generate efficient hardware for a*b+c.
Multiplies two wirevectors together and adds a third wirevector to the
multiplication result, all in
one step. By doing it this way (instead of separately), one reduces both
the area and the timing delay of the circuit.
:param Bool signed: Currently not supported (will be added in the future)
The default will likely be changed to True, so if you want the smallest
set of wires in the future, specify this as False
:param reducer: (advanced) The tree reducer to use
:param adder_func: (advanced) The adder to use to add the two results at the end
:return WireVector: The result WireVector | [
"Generate",
"efficient",
"hardware",
"for",
"a",
"*",
"b",
"+",
"c",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/multipliers.py#L184-L205 |
UCSBarchlab/PyRTL | pyrtl/rtllib/multipliers.py | generalized_fma | def generalized_fma(mult_pairs, add_wires, signed=False, reducer=adders.wallace_reducer,
adder_func=adders.kogge_stone):
"""Generated an opimitized fused multiply adder.
A generalized FMA unit that multiplies each pair of numbers in mult_pairs,
then adds the resulting numbers and and the values of the add wires all
together to form an answer. This is faster than separate adders and
multipliers because you avoid unnecessary adder structures for intermediate
representations.
:param mult_pairs: Either None (if there are no pairs to multiply) or
a list of pairs of wires to multiply:
[(mult1_1, mult1_2), ...]
:param add_wires: Either None (if there are no individual
items to add other than the mult_pairs), or a list of wires for adding on
top of the result of the pair multiplication.
:param Bool signed: Currently not supported (will be added in the future)
The default will likely be changed to True, so if you want the smallest
set of wires in the future, specify this as False
:param reducer: (advanced) The tree reducer to use
:param adder_func: (advanced) The adder to use to add the two results at the end
:return WireVector: The result WireVector
"""
# first need to figure out the max length
if mult_pairs: # Need to deal with the case when it is empty
mult_max = max(len(m[0]) + len(m[1]) - 1 for m in mult_pairs)
else:
mult_max = 0
if add_wires:
add_max = max(len(x) for x in add_wires)
else:
add_max = 0
longest_wire_len = max(add_max, mult_max)
bits = [[] for i in range(longest_wire_len)]
for mult_a, mult_b in mult_pairs:
for i, a in enumerate(mult_a):
for j, b in enumerate(mult_b):
bits[i + j].append(a & b)
for wire in add_wires:
for bit_loc, bit in enumerate(wire):
bits[bit_loc].append(bit)
import math
result_bitwidth = (longest_wire_len +
int(math.ceil(math.log(len(add_wires) + len(mult_pairs), 2))))
return reducer(bits, result_bitwidth, adder_func) | python | def generalized_fma(mult_pairs, add_wires, signed=False, reducer=adders.wallace_reducer,
adder_func=adders.kogge_stone):
"""Generated an opimitized fused multiply adder.
A generalized FMA unit that multiplies each pair of numbers in mult_pairs,
then adds the resulting numbers and and the values of the add wires all
together to form an answer. This is faster than separate adders and
multipliers because you avoid unnecessary adder structures for intermediate
representations.
:param mult_pairs: Either None (if there are no pairs to multiply) or
a list of pairs of wires to multiply:
[(mult1_1, mult1_2), ...]
:param add_wires: Either None (if there are no individual
items to add other than the mult_pairs), or a list of wires for adding on
top of the result of the pair multiplication.
:param Bool signed: Currently not supported (will be added in the future)
The default will likely be changed to True, so if you want the smallest
set of wires in the future, specify this as False
:param reducer: (advanced) The tree reducer to use
:param adder_func: (advanced) The adder to use to add the two results at the end
:return WireVector: The result WireVector
"""
# first need to figure out the max length
if mult_pairs: # Need to deal with the case when it is empty
mult_max = max(len(m[0]) + len(m[1]) - 1 for m in mult_pairs)
else:
mult_max = 0
if add_wires:
add_max = max(len(x) for x in add_wires)
else:
add_max = 0
longest_wire_len = max(add_max, mult_max)
bits = [[] for i in range(longest_wire_len)]
for mult_a, mult_b in mult_pairs:
for i, a in enumerate(mult_a):
for j, b in enumerate(mult_b):
bits[i + j].append(a & b)
for wire in add_wires:
for bit_loc, bit in enumerate(wire):
bits[bit_loc].append(bit)
import math
result_bitwidth = (longest_wire_len +
int(math.ceil(math.log(len(add_wires) + len(mult_pairs), 2))))
return reducer(bits, result_bitwidth, adder_func) | [
"def",
"generalized_fma",
"(",
"mult_pairs",
",",
"add_wires",
",",
"signed",
"=",
"False",
",",
"reducer",
"=",
"adders",
".",
"wallace_reducer",
",",
"adder_func",
"=",
"adders",
".",
"kogge_stone",
")",
":",
"# first need to figure out the max length",
"if",
"mult_pairs",
":",
"# Need to deal with the case when it is empty",
"mult_max",
"=",
"max",
"(",
"len",
"(",
"m",
"[",
"0",
"]",
")",
"+",
"len",
"(",
"m",
"[",
"1",
"]",
")",
"-",
"1",
"for",
"m",
"in",
"mult_pairs",
")",
"else",
":",
"mult_max",
"=",
"0",
"if",
"add_wires",
":",
"add_max",
"=",
"max",
"(",
"len",
"(",
"x",
")",
"for",
"x",
"in",
"add_wires",
")",
"else",
":",
"add_max",
"=",
"0",
"longest_wire_len",
"=",
"max",
"(",
"add_max",
",",
"mult_max",
")",
"bits",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"longest_wire_len",
")",
"]",
"for",
"mult_a",
",",
"mult_b",
"in",
"mult_pairs",
":",
"for",
"i",
",",
"a",
"in",
"enumerate",
"(",
"mult_a",
")",
":",
"for",
"j",
",",
"b",
"in",
"enumerate",
"(",
"mult_b",
")",
":",
"bits",
"[",
"i",
"+",
"j",
"]",
".",
"append",
"(",
"a",
"&",
"b",
")",
"for",
"wire",
"in",
"add_wires",
":",
"for",
"bit_loc",
",",
"bit",
"in",
"enumerate",
"(",
"wire",
")",
":",
"bits",
"[",
"bit_loc",
"]",
".",
"append",
"(",
"bit",
")",
"import",
"math",
"result_bitwidth",
"=",
"(",
"longest_wire_len",
"+",
"int",
"(",
"math",
".",
"ceil",
"(",
"math",
".",
"log",
"(",
"len",
"(",
"add_wires",
")",
"+",
"len",
"(",
"mult_pairs",
")",
",",
"2",
")",
")",
")",
")",
"return",
"reducer",
"(",
"bits",
",",
"result_bitwidth",
",",
"adder_func",
")"
] | Generated an opimitized fused multiply adder.
A generalized FMA unit that multiplies each pair of numbers in mult_pairs,
then adds the resulting numbers and and the values of the add wires all
together to form an answer. This is faster than separate adders and
multipliers because you avoid unnecessary adder structures for intermediate
representations.
:param mult_pairs: Either None (if there are no pairs to multiply) or
a list of pairs of wires to multiply:
[(mult1_1, mult1_2), ...]
:param add_wires: Either None (if there are no individual
items to add other than the mult_pairs), or a list of wires for adding on
top of the result of the pair multiplication.
:param Bool signed: Currently not supported (will be added in the future)
The default will likely be changed to True, so if you want the smallest
set of wires in the future, specify this as False
:param reducer: (advanced) The tree reducer to use
:param adder_func: (advanced) The adder to use to add the two results at the end
:return WireVector: The result WireVector | [
"Generated",
"an",
"opimitized",
"fused",
"multiply",
"adder",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/multipliers.py#L208-L258 |
UCSBarchlab/PyRTL | pyrtl/transform.py | net_transform | def net_transform(transform_func, block=None, **kwargs):
"""
Maps nets to new sets of nets according to a custom function
:param transform_func:
Function signature: func(orig_net (logicnet)) -> keep_orig_net (bool)
:return:
"""
block = working_block(block)
with set_working_block(block, True):
for net in block.logic.copy():
keep_orig_net = transform_func(net, **kwargs)
if not keep_orig_net:
block.logic.remove(net) | python | def net_transform(transform_func, block=None, **kwargs):
"""
Maps nets to new sets of nets according to a custom function
:param transform_func:
Function signature: func(orig_net (logicnet)) -> keep_orig_net (bool)
:return:
"""
block = working_block(block)
with set_working_block(block, True):
for net in block.logic.copy():
keep_orig_net = transform_func(net, **kwargs)
if not keep_orig_net:
block.logic.remove(net) | [
"def",
"net_transform",
"(",
"transform_func",
",",
"block",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"block",
"=",
"working_block",
"(",
"block",
")",
"with",
"set_working_block",
"(",
"block",
",",
"True",
")",
":",
"for",
"net",
"in",
"block",
".",
"logic",
".",
"copy",
"(",
")",
":",
"keep_orig_net",
"=",
"transform_func",
"(",
"net",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"keep_orig_net",
":",
"block",
".",
"logic",
".",
"remove",
"(",
"net",
")"
] | Maps nets to new sets of nets according to a custom function
:param transform_func:
Function signature: func(orig_net (logicnet)) -> keep_orig_net (bool)
:return: | [
"Maps",
"nets",
"to",
"new",
"sets",
"of",
"nets",
"according",
"to",
"a",
"custom",
"function"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L27-L40 |
UCSBarchlab/PyRTL | pyrtl/transform.py | all_nets | def all_nets(transform_func):
"""Decorator that wraps a net transform function"""
@functools.wraps(transform_func)
def t_res(**kwargs):
net_transform(transform_func, **kwargs)
return t_res | python | def all_nets(transform_func):
"""Decorator that wraps a net transform function"""
@functools.wraps(transform_func)
def t_res(**kwargs):
net_transform(transform_func, **kwargs)
return t_res | [
"def",
"all_nets",
"(",
"transform_func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"transform_func",
")",
"def",
"t_res",
"(",
"*",
"*",
"kwargs",
")",
":",
"net_transform",
"(",
"transform_func",
",",
"*",
"*",
"kwargs",
")",
"return",
"t_res"
] | Decorator that wraps a net transform function | [
"Decorator",
"that",
"wraps",
"a",
"net",
"transform",
"function"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L43-L48 |
UCSBarchlab/PyRTL | pyrtl/transform.py | wire_transform | def wire_transform(transform_func, select_types=WireVector,
exclude_types=(Input, Output, Register, Const), block=None):
"""
Maps Wires to new sets of nets and wires according to a custom function
:param transform_func: The function you want to run on all wires
Function signature: func(orig_wire (WireVector)) -> src_wire, dst_wire
src_wire is the src for the stuff you made in the transform func
and dst_wire is the sink
to indicate that the wire has not been changed, make src_wire and dst_wire both
the original wire
:param select_types: Type or Tuple of types of WireVectors to replace
:param exclude_types: Type or Tuple of types of WireVectors to exclude from replacement
:param block: The Block to replace wires on
"""
block = working_block(block)
for orig_wire in block.wirevector_subset(select_types, exclude_types):
new_src, new_dst = transform_func(orig_wire)
replace_wire(orig_wire, new_src, new_dst, block) | python | def wire_transform(transform_func, select_types=WireVector,
exclude_types=(Input, Output, Register, Const), block=None):
"""
Maps Wires to new sets of nets and wires according to a custom function
:param transform_func: The function you want to run on all wires
Function signature: func(orig_wire (WireVector)) -> src_wire, dst_wire
src_wire is the src for the stuff you made in the transform func
and dst_wire is the sink
to indicate that the wire has not been changed, make src_wire and dst_wire both
the original wire
:param select_types: Type or Tuple of types of WireVectors to replace
:param exclude_types: Type or Tuple of types of WireVectors to exclude from replacement
:param block: The Block to replace wires on
"""
block = working_block(block)
for orig_wire in block.wirevector_subset(select_types, exclude_types):
new_src, new_dst = transform_func(orig_wire)
replace_wire(orig_wire, new_src, new_dst, block) | [
"def",
"wire_transform",
"(",
"transform_func",
",",
"select_types",
"=",
"WireVector",
",",
"exclude_types",
"=",
"(",
"Input",
",",
"Output",
",",
"Register",
",",
"Const",
")",
",",
"block",
"=",
"None",
")",
":",
"block",
"=",
"working_block",
"(",
"block",
")",
"for",
"orig_wire",
"in",
"block",
".",
"wirevector_subset",
"(",
"select_types",
",",
"exclude_types",
")",
":",
"new_src",
",",
"new_dst",
"=",
"transform_func",
"(",
"orig_wire",
")",
"replace_wire",
"(",
"orig_wire",
",",
"new_src",
",",
"new_dst",
",",
"block",
")"
] | Maps Wires to new sets of nets and wires according to a custom function
:param transform_func: The function you want to run on all wires
Function signature: func(orig_wire (WireVector)) -> src_wire, dst_wire
src_wire is the src for the stuff you made in the transform func
and dst_wire is the sink
to indicate that the wire has not been changed, make src_wire and dst_wire both
the original wire
:param select_types: Type or Tuple of types of WireVectors to replace
:param exclude_types: Type or Tuple of types of WireVectors to exclude from replacement
:param block: The Block to replace wires on | [
"Maps",
"Wires",
"to",
"new",
"sets",
"of",
"nets",
"and",
"wires",
"according",
"to",
"a",
"custom",
"function"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L51-L70 |
UCSBarchlab/PyRTL | pyrtl/transform.py | all_wires | def all_wires(transform_func):
"""Decorator that wraps a wire transform function"""
@functools.wraps(transform_func)
def t_res(**kwargs):
wire_transform(transform_func, **kwargs)
return t_res | python | def all_wires(transform_func):
"""Decorator that wraps a wire transform function"""
@functools.wraps(transform_func)
def t_res(**kwargs):
wire_transform(transform_func, **kwargs)
return t_res | [
"def",
"all_wires",
"(",
"transform_func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"transform_func",
")",
"def",
"t_res",
"(",
"*",
"*",
"kwargs",
")",
":",
"wire_transform",
"(",
"transform_func",
",",
"*",
"*",
"kwargs",
")",
"return",
"t_res"
] | Decorator that wraps a wire transform function | [
"Decorator",
"that",
"wraps",
"a",
"wire",
"transform",
"function"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L73-L78 |
UCSBarchlab/PyRTL | pyrtl/transform.py | replace_wires | def replace_wires(wire_map, block=None):
"""
Quickly replace all wires in a block
:param {old_wire: new_wire} wire_map: mapping of old wires to
new wires
"""
block = working_block(block)
src_nets, dst_nets = block.net_connections(include_virtual_nodes=False)
for old_w, new_w in wire_map.items():
replace_wire_fast(old_w, new_w, new_w, src_nets, dst_nets, block) | python | def replace_wires(wire_map, block=None):
"""
Quickly replace all wires in a block
:param {old_wire: new_wire} wire_map: mapping of old wires to
new wires
"""
block = working_block(block)
src_nets, dst_nets = block.net_connections(include_virtual_nodes=False)
for old_w, new_w in wire_map.items():
replace_wire_fast(old_w, new_w, new_w, src_nets, dst_nets, block) | [
"def",
"replace_wires",
"(",
"wire_map",
",",
"block",
"=",
"None",
")",
":",
"block",
"=",
"working_block",
"(",
"block",
")",
"src_nets",
",",
"dst_nets",
"=",
"block",
".",
"net_connections",
"(",
"include_virtual_nodes",
"=",
"False",
")",
"for",
"old_w",
",",
"new_w",
"in",
"wire_map",
".",
"items",
"(",
")",
":",
"replace_wire_fast",
"(",
"old_w",
",",
"new_w",
",",
"new_w",
",",
"src_nets",
",",
"dst_nets",
",",
"block",
")"
] | Quickly replace all wires in a block
:param {old_wire: new_wire} wire_map: mapping of old wires to
new wires | [
"Quickly",
"replace",
"all",
"wires",
"in",
"a",
"block"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L109-L119 |
UCSBarchlab/PyRTL | pyrtl/transform.py | clone_wire | def clone_wire(old_wire, name=None):
"""
Makes a copy of any existing wire
:param old_wire: The wire to clone
:param name: a name fo rhte new wire
Note that this function is mainly intended to be used when the
two wires are from different blocks. Making two wires with the
same name in the same block is not allowed
"""
if isinstance(old_wire, Const):
return Const(old_wire.val, old_wire.bitwidth)
else:
if name is None:
return old_wire.__class__(old_wire.bitwidth, name=old_wire.name)
return old_wire.__class__(old_wire.bitwidth, name=name) | python | def clone_wire(old_wire, name=None):
"""
Makes a copy of any existing wire
:param old_wire: The wire to clone
:param name: a name fo rhte new wire
Note that this function is mainly intended to be used when the
two wires are from different blocks. Making two wires with the
same name in the same block is not allowed
"""
if isinstance(old_wire, Const):
return Const(old_wire.val, old_wire.bitwidth)
else:
if name is None:
return old_wire.__class__(old_wire.bitwidth, name=old_wire.name)
return old_wire.__class__(old_wire.bitwidth, name=name) | [
"def",
"clone_wire",
"(",
"old_wire",
",",
"name",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"old_wire",
",",
"Const",
")",
":",
"return",
"Const",
"(",
"old_wire",
".",
"val",
",",
"old_wire",
".",
"bitwidth",
")",
"else",
":",
"if",
"name",
"is",
"None",
":",
"return",
"old_wire",
".",
"__class__",
"(",
"old_wire",
".",
"bitwidth",
",",
"name",
"=",
"old_wire",
".",
"name",
")",
"return",
"old_wire",
".",
"__class__",
"(",
"old_wire",
".",
"bitwidth",
",",
"name",
"=",
"name",
")"
] | Makes a copy of any existing wire
:param old_wire: The wire to clone
:param name: a name fo rhte new wire
Note that this function is mainly intended to be used when the
two wires are from different blocks. Making two wires with the
same name in the same block is not allowed | [
"Makes",
"a",
"copy",
"of",
"any",
"existing",
"wire"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L166-L182 |
UCSBarchlab/PyRTL | pyrtl/transform.py | copy_block | def copy_block(block=None, update_working_block=True):
"""
Makes a copy of an existing block
:param block: The block to clone. (defaults to the working block)
:return: The resulting block
"""
block_in = working_block(block)
block_out, temp_wv_map = _clone_block_and_wires(block_in)
mems = {}
for net in block_in.logic:
_copy_net(block_out, net, temp_wv_map, mems)
block_out.mem_map = mems
if update_working_block:
set_working_block(block_out)
return block_out | python | def copy_block(block=None, update_working_block=True):
"""
Makes a copy of an existing block
:param block: The block to clone. (defaults to the working block)
:return: The resulting block
"""
block_in = working_block(block)
block_out, temp_wv_map = _clone_block_and_wires(block_in)
mems = {}
for net in block_in.logic:
_copy_net(block_out, net, temp_wv_map, mems)
block_out.mem_map = mems
if update_working_block:
set_working_block(block_out)
return block_out | [
"def",
"copy_block",
"(",
"block",
"=",
"None",
",",
"update_working_block",
"=",
"True",
")",
":",
"block_in",
"=",
"working_block",
"(",
"block",
")",
"block_out",
",",
"temp_wv_map",
"=",
"_clone_block_and_wires",
"(",
"block_in",
")",
"mems",
"=",
"{",
"}",
"for",
"net",
"in",
"block_in",
".",
"logic",
":",
"_copy_net",
"(",
"block_out",
",",
"net",
",",
"temp_wv_map",
",",
"mems",
")",
"block_out",
".",
"mem_map",
"=",
"mems",
"if",
"update_working_block",
":",
"set_working_block",
"(",
"block_out",
")",
"return",
"block_out"
] | Makes a copy of an existing block
:param block: The block to clone. (defaults to the working block)
:return: The resulting block | [
"Makes",
"a",
"copy",
"of",
"an",
"existing",
"block"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L185-L201 |
UCSBarchlab/PyRTL | pyrtl/transform.py | _clone_block_and_wires | def _clone_block_and_wires(block_in):
"""
This is a generic function to copy the WireVectors for another round of
synthesis This does not split a WireVector with multiple wires.
:param block_in: The block to change
:param synth_name: a name to prepend to all new copies of a wire
:return: the resulting block and a WireVector map
"""
block_in.sanity_check() # make sure that everything is valid
block_out = block_in.__class__()
temp_wv_map = {}
with set_working_block(block_out, no_sanity_check=True):
for wirevector in block_in.wirevector_subset():
new_wv = clone_wire(wirevector)
temp_wv_map[wirevector] = new_wv
return block_out, temp_wv_map | python | def _clone_block_and_wires(block_in):
"""
This is a generic function to copy the WireVectors for another round of
synthesis This does not split a WireVector with multiple wires.
:param block_in: The block to change
:param synth_name: a name to prepend to all new copies of a wire
:return: the resulting block and a WireVector map
"""
block_in.sanity_check() # make sure that everything is valid
block_out = block_in.__class__()
temp_wv_map = {}
with set_working_block(block_out, no_sanity_check=True):
for wirevector in block_in.wirevector_subset():
new_wv = clone_wire(wirevector)
temp_wv_map[wirevector] = new_wv
return block_out, temp_wv_map | [
"def",
"_clone_block_and_wires",
"(",
"block_in",
")",
":",
"block_in",
".",
"sanity_check",
"(",
")",
"# make sure that everything is valid",
"block_out",
"=",
"block_in",
".",
"__class__",
"(",
")",
"temp_wv_map",
"=",
"{",
"}",
"with",
"set_working_block",
"(",
"block_out",
",",
"no_sanity_check",
"=",
"True",
")",
":",
"for",
"wirevector",
"in",
"block_in",
".",
"wirevector_subset",
"(",
")",
":",
"new_wv",
"=",
"clone_wire",
"(",
"wirevector",
")",
"temp_wv_map",
"[",
"wirevector",
"]",
"=",
"new_wv",
"return",
"block_out",
",",
"temp_wv_map"
] | This is a generic function to copy the WireVectors for another round of
synthesis This does not split a WireVector with multiple wires.
:param block_in: The block to change
:param synth_name: a name to prepend to all new copies of a wire
:return: the resulting block and a WireVector map | [
"This",
"is",
"a",
"generic",
"function",
"to",
"copy",
"the",
"WireVectors",
"for",
"another",
"round",
"of",
"synthesis",
"This",
"does",
"not",
"split",
"a",
"WireVector",
"with",
"multiple",
"wires",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L204-L221 |
UCSBarchlab/PyRTL | pyrtl/transform.py | _copy_net | def _copy_net(block_out, net, temp_wv_net, mem_map):
"""This function makes a copy of all nets passed to it for synth uses
"""
new_args = tuple(temp_wv_net[a_arg] for a_arg in net.args)
new_dests = tuple(temp_wv_net[a_dest] for a_dest in net.dests)
if net.op in "m@": # special stuff for copying memories
new_param = _get_new_block_mem_instance(net.op_param, mem_map, block_out)
else:
new_param = net.op_param
new_net = LogicNet(net.op, new_param, args=new_args, dests=new_dests)
block_out.add_net(new_net) | python | def _copy_net(block_out, net, temp_wv_net, mem_map):
"""This function makes a copy of all nets passed to it for synth uses
"""
new_args = tuple(temp_wv_net[a_arg] for a_arg in net.args)
new_dests = tuple(temp_wv_net[a_dest] for a_dest in net.dests)
if net.op in "m@": # special stuff for copying memories
new_param = _get_new_block_mem_instance(net.op_param, mem_map, block_out)
else:
new_param = net.op_param
new_net = LogicNet(net.op, new_param, args=new_args, dests=new_dests)
block_out.add_net(new_net) | [
"def",
"_copy_net",
"(",
"block_out",
",",
"net",
",",
"temp_wv_net",
",",
"mem_map",
")",
":",
"new_args",
"=",
"tuple",
"(",
"temp_wv_net",
"[",
"a_arg",
"]",
"for",
"a_arg",
"in",
"net",
".",
"args",
")",
"new_dests",
"=",
"tuple",
"(",
"temp_wv_net",
"[",
"a_dest",
"]",
"for",
"a_dest",
"in",
"net",
".",
"dests",
")",
"if",
"net",
".",
"op",
"in",
"\"m@\"",
":",
"# special stuff for copying memories",
"new_param",
"=",
"_get_new_block_mem_instance",
"(",
"net",
".",
"op_param",
",",
"mem_map",
",",
"block_out",
")",
"else",
":",
"new_param",
"=",
"net",
".",
"op_param",
"new_net",
"=",
"LogicNet",
"(",
"net",
".",
"op",
",",
"new_param",
",",
"args",
"=",
"new_args",
",",
"dests",
"=",
"new_dests",
")",
"block_out",
".",
"add_net",
"(",
"new_net",
")"
] | This function makes a copy of all nets passed to it for synth uses | [
"This",
"function",
"makes",
"a",
"copy",
"of",
"all",
"nets",
"passed",
"to",
"it",
"for",
"synth",
"uses"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L224-L235 |
UCSBarchlab/PyRTL | pyrtl/transform.py | _get_new_block_mem_instance | def _get_new_block_mem_instance(op_param, mem_map, block_out):
""" gets the instance of the memory in the new block that is
associated with a memory in a old block
"""
memid, old_mem = op_param
if old_mem not in mem_map:
new_mem = old_mem._make_copy(block_out)
new_mem.id = old_mem.id
mem_map[old_mem] = new_mem
return memid, mem_map[old_mem] | python | def _get_new_block_mem_instance(op_param, mem_map, block_out):
""" gets the instance of the memory in the new block that is
associated with a memory in a old block
"""
memid, old_mem = op_param
if old_mem not in mem_map:
new_mem = old_mem._make_copy(block_out)
new_mem.id = old_mem.id
mem_map[old_mem] = new_mem
return memid, mem_map[old_mem] | [
"def",
"_get_new_block_mem_instance",
"(",
"op_param",
",",
"mem_map",
",",
"block_out",
")",
":",
"memid",
",",
"old_mem",
"=",
"op_param",
"if",
"old_mem",
"not",
"in",
"mem_map",
":",
"new_mem",
"=",
"old_mem",
".",
"_make_copy",
"(",
"block_out",
")",
"new_mem",
".",
"id",
"=",
"old_mem",
".",
"id",
"mem_map",
"[",
"old_mem",
"]",
"=",
"new_mem",
"return",
"memid",
",",
"mem_map",
"[",
"old_mem",
"]"
] | gets the instance of the memory in the new block that is
associated with a memory in a old block | [
"gets",
"the",
"instance",
"of",
"the",
"memory",
"in",
"the",
"new",
"block",
"that",
"is",
"associated",
"with",
"a",
"memory",
"in",
"a",
"old",
"block"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L238-L247 |
UCSBarchlab/PyRTL | pyrtl/helperfuncs.py | probe | def probe(w, name=None):
""" Print useful information about a WireVector when in debug mode.
:param w: WireVector from which to get info
:param name: optional name for probe (defaults to an autogenerated name)
:return: original WireVector w
Probe can be inserted into a existing design easily as it returns the
original wire unmodified. For example ``y <<= x[0:3] + 4`` could be turned
into ``y <<= probe(x)[0:3] + 4`` to give visibility into both the origin of
``x`` (including the line that WireVector was originally created) and
the run-time values of ``x`` (which will be named and thus show up by
default in a trace. Likewise ``y <<= probe(x[0:3]) + 4``,
``y <<= probe(x[0:3] + 4)``, and ``probe(y) <<= x[0:3] + 4`` are all
valid uses of `probe`.
Note: `probe` does actually add a wire to the working block of w (which can
confuse various post-processing transforms such as output to verilog).
"""
if not isinstance(w, WireVector):
raise PyrtlError('Only WireVectors can be probed')
if name is None:
name = '(%s: %s)' % (probeIndexer.make_valid_string(), w.name)
print("Probe: " + name + ' ' + get_stack(w))
p = Output(name=name)
p <<= w # late assigns len from w automatically
return w | python | def probe(w, name=None):
""" Print useful information about a WireVector when in debug mode.
:param w: WireVector from which to get info
:param name: optional name for probe (defaults to an autogenerated name)
:return: original WireVector w
Probe can be inserted into a existing design easily as it returns the
original wire unmodified. For example ``y <<= x[0:3] + 4`` could be turned
into ``y <<= probe(x)[0:3] + 4`` to give visibility into both the origin of
``x`` (including the line that WireVector was originally created) and
the run-time values of ``x`` (which will be named and thus show up by
default in a trace. Likewise ``y <<= probe(x[0:3]) + 4``,
``y <<= probe(x[0:3] + 4)``, and ``probe(y) <<= x[0:3] + 4`` are all
valid uses of `probe`.
Note: `probe` does actually add a wire to the working block of w (which can
confuse various post-processing transforms such as output to verilog).
"""
if not isinstance(w, WireVector):
raise PyrtlError('Only WireVectors can be probed')
if name is None:
name = '(%s: %s)' % (probeIndexer.make_valid_string(), w.name)
print("Probe: " + name + ' ' + get_stack(w))
p = Output(name=name)
p <<= w # late assigns len from w automatically
return w | [
"def",
"probe",
"(",
"w",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"w",
",",
"WireVector",
")",
":",
"raise",
"PyrtlError",
"(",
"'Only WireVectors can be probed'",
")",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"'(%s: %s)'",
"%",
"(",
"probeIndexer",
".",
"make_valid_string",
"(",
")",
",",
"w",
".",
"name",
")",
"print",
"(",
"\"Probe: \"",
"+",
"name",
"+",
"' '",
"+",
"get_stack",
"(",
"w",
")",
")",
"p",
"=",
"Output",
"(",
"name",
"=",
"name",
")",
"p",
"<<=",
"w",
"# late assigns len from w automatically",
"return",
"w"
] | Print useful information about a WireVector when in debug mode.
:param w: WireVector from which to get info
:param name: optional name for probe (defaults to an autogenerated name)
:return: original WireVector w
Probe can be inserted into a existing design easily as it returns the
original wire unmodified. For example ``y <<= x[0:3] + 4`` could be turned
into ``y <<= probe(x)[0:3] + 4`` to give visibility into both the origin of
``x`` (including the line that WireVector was originally created) and
the run-time values of ``x`` (which will be named and thus show up by
default in a trace. Likewise ``y <<= probe(x[0:3]) + 4``,
``y <<= probe(x[0:3] + 4)``, and ``probe(y) <<= x[0:3] + 4`` are all
valid uses of `probe`.
Note: `probe` does actually add a wire to the working block of w (which can
confuse various post-processing transforms such as output to verilog). | [
"Print",
"useful",
"information",
"about",
"a",
"WireVector",
"when",
"in",
"debug",
"mode",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/helperfuncs.py#L24-L52 |
UCSBarchlab/PyRTL | pyrtl/helperfuncs.py | rtl_assert | def rtl_assert(w, exp, block=None):
""" Add hardware assertions to be checked on the RTL design.
:param w: should be a WireVector
:param Exception exp: Exception to throw when assertion fails
:param Block block: block to which the assertion should be added (default to working block)
:return: the Output wire for the assertion (can be ignored in most cases)
If at any time during execution the wire w is not `true` (i.e. asserted low)
then simulation will raise exp.
"""
block = working_block(block)
if not isinstance(w, WireVector):
raise PyrtlError('Only WireVectors can be asserted with rtl_assert')
if len(w) != 1:
raise PyrtlError('rtl_assert checks only a WireVector of bitwidth 1')
if not isinstance(exp, Exception):
raise PyrtlError('the second argument to rtl_assert must be an instance of Exception')
if isinstance(exp, KeyError):
raise PyrtlError('the second argument to rtl_assert cannot be a KeyError')
if w not in block.wirevector_set:
raise PyrtlError('assertion wire not part of the block to which it is being added')
if w not in block.wirevector_set:
raise PyrtlError('assertion not a known wirevector in the target block')
if w in block.rtl_assert_dict:
raise PyrtlInternalError('assertion conflicts with existing registered assertion')
assert_wire = Output(bitwidth=1, name=assertIndexer.make_valid_string(), block=block)
assert_wire <<= w
block.rtl_assert_dict[assert_wire] = exp
return assert_wire | python | def rtl_assert(w, exp, block=None):
""" Add hardware assertions to be checked on the RTL design.
:param w: should be a WireVector
:param Exception exp: Exception to throw when assertion fails
:param Block block: block to which the assertion should be added (default to working block)
:return: the Output wire for the assertion (can be ignored in most cases)
If at any time during execution the wire w is not `true` (i.e. asserted low)
then simulation will raise exp.
"""
block = working_block(block)
if not isinstance(w, WireVector):
raise PyrtlError('Only WireVectors can be asserted with rtl_assert')
if len(w) != 1:
raise PyrtlError('rtl_assert checks only a WireVector of bitwidth 1')
if not isinstance(exp, Exception):
raise PyrtlError('the second argument to rtl_assert must be an instance of Exception')
if isinstance(exp, KeyError):
raise PyrtlError('the second argument to rtl_assert cannot be a KeyError')
if w not in block.wirevector_set:
raise PyrtlError('assertion wire not part of the block to which it is being added')
if w not in block.wirevector_set:
raise PyrtlError('assertion not a known wirevector in the target block')
if w in block.rtl_assert_dict:
raise PyrtlInternalError('assertion conflicts with existing registered assertion')
assert_wire = Output(bitwidth=1, name=assertIndexer.make_valid_string(), block=block)
assert_wire <<= w
block.rtl_assert_dict[assert_wire] = exp
return assert_wire | [
"def",
"rtl_assert",
"(",
"w",
",",
"exp",
",",
"block",
"=",
"None",
")",
":",
"block",
"=",
"working_block",
"(",
"block",
")",
"if",
"not",
"isinstance",
"(",
"w",
",",
"WireVector",
")",
":",
"raise",
"PyrtlError",
"(",
"'Only WireVectors can be asserted with rtl_assert'",
")",
"if",
"len",
"(",
"w",
")",
"!=",
"1",
":",
"raise",
"PyrtlError",
"(",
"'rtl_assert checks only a WireVector of bitwidth 1'",
")",
"if",
"not",
"isinstance",
"(",
"exp",
",",
"Exception",
")",
":",
"raise",
"PyrtlError",
"(",
"'the second argument to rtl_assert must be an instance of Exception'",
")",
"if",
"isinstance",
"(",
"exp",
",",
"KeyError",
")",
":",
"raise",
"PyrtlError",
"(",
"'the second argument to rtl_assert cannot be a KeyError'",
")",
"if",
"w",
"not",
"in",
"block",
".",
"wirevector_set",
":",
"raise",
"PyrtlError",
"(",
"'assertion wire not part of the block to which it is being added'",
")",
"if",
"w",
"not",
"in",
"block",
".",
"wirevector_set",
":",
"raise",
"PyrtlError",
"(",
"'assertion not a known wirevector in the target block'",
")",
"if",
"w",
"in",
"block",
".",
"rtl_assert_dict",
":",
"raise",
"PyrtlInternalError",
"(",
"'assertion conflicts with existing registered assertion'",
")",
"assert_wire",
"=",
"Output",
"(",
"bitwidth",
"=",
"1",
",",
"name",
"=",
"assertIndexer",
".",
"make_valid_string",
"(",
")",
",",
"block",
"=",
"block",
")",
"assert_wire",
"<<=",
"w",
"block",
".",
"rtl_assert_dict",
"[",
"assert_wire",
"]",
"=",
"exp",
"return",
"assert_wire"
] | Add hardware assertions to be checked on the RTL design.
:param w: should be a WireVector
:param Exception exp: Exception to throw when assertion fails
:param Block block: block to which the assertion should be added (default to working block)
:return: the Output wire for the assertion (can be ignored in most cases)
If at any time during execution the wire w is not `true` (i.e. asserted low)
then simulation will raise exp. | [
"Add",
"hardware",
"assertions",
"to",
"be",
"checked",
"on",
"the",
"RTL",
"design",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/helperfuncs.py#L58-L90 |
UCSBarchlab/PyRTL | pyrtl/helperfuncs.py | check_rtl_assertions | def check_rtl_assertions(sim):
""" Checks the values in sim to see if any registers assertions fail.
:param sim: Simulation in which to check the assertions
:return: None
"""
for (w, exp) in sim.block.rtl_assert_dict.items():
try:
value = sim.inspect(w)
if not value:
raise exp
except KeyError:
pass | python | def check_rtl_assertions(sim):
""" Checks the values in sim to see if any registers assertions fail.
:param sim: Simulation in which to check the assertions
:return: None
"""
for (w, exp) in sim.block.rtl_assert_dict.items():
try:
value = sim.inspect(w)
if not value:
raise exp
except KeyError:
pass | [
"def",
"check_rtl_assertions",
"(",
"sim",
")",
":",
"for",
"(",
"w",
",",
"exp",
")",
"in",
"sim",
".",
"block",
".",
"rtl_assert_dict",
".",
"items",
"(",
")",
":",
"try",
":",
"value",
"=",
"sim",
".",
"inspect",
"(",
"w",
")",
"if",
"not",
"value",
":",
"raise",
"exp",
"except",
"KeyError",
":",
"pass"
] | Checks the values in sim to see if any registers assertions fail.
:param sim: Simulation in which to check the assertions
:return: None | [
"Checks",
"the",
"values",
"in",
"sim",
"to",
"see",
"if",
"any",
"registers",
"assertions",
"fail",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/helperfuncs.py#L93-L106 |
UCSBarchlab/PyRTL | pyrtl/helperfuncs.py | wirevector_list | def wirevector_list(names, bitwidth=None, wvtype=WireVector):
""" Allocate and return a list of WireVectors.
:param names: Names for the WireVectors. Can be a list or single comma/space-separated string
:param bitwidth: The desired bitwidth for the resulting WireVectors.
:param WireVector wvtype: Which WireVector type to create.
:return: List of WireVectors.
Additionally, the ``names`` string can also contain an additional bitwidth specification
separated by a ``/`` in the name. This cannot be used in combination with a ``bitwidth``
value other than ``1``.
Examples: ::
wirevector_list(['name1', 'name2', 'name3'])
wirevector_list('name1, name2, name3')
wirevector_list('input1 input2 input3', bitwidth=8, wvtype=pyrtl.wire.Input)
wirevector_list('output1, output2 output3', bitwidth=3, wvtype=pyrtl.wire.Output)
wirevector_list('two_bits/2, four_bits/4, eight_bits/8')
wirevector_list(['name1', 'name2', 'name3'], bitwidth=[2, 4, 8])
"""
if isinstance(names, str):
names = names.replace(',', ' ').split()
if any('/' in name for name in names) and bitwidth is not None:
raise PyrtlError('only one of optional "/" or bitwidth parameter allowed')
if bitwidth is None:
bitwidth = 1
if isinstance(bitwidth, numbers.Integral):
bitwidth = [bitwidth]*len(names)
if len(bitwidth) != len(names):
raise ValueError('number of names ' + str(len(names))
+ ' should match number of bitwidths ' + str(len(bitwidth)))
wirelist = []
for fullname, bw in zip(names, bitwidth):
try:
name, bw = fullname.split('/')
except ValueError:
name, bw = fullname, bw
wirelist.append(wvtype(bitwidth=int(bw), name=name))
return wirelist | python | def wirevector_list(names, bitwidth=None, wvtype=WireVector):
""" Allocate and return a list of WireVectors.
:param names: Names for the WireVectors. Can be a list or single comma/space-separated string
:param bitwidth: The desired bitwidth for the resulting WireVectors.
:param WireVector wvtype: Which WireVector type to create.
:return: List of WireVectors.
Additionally, the ``names`` string can also contain an additional bitwidth specification
separated by a ``/`` in the name. This cannot be used in combination with a ``bitwidth``
value other than ``1``.
Examples: ::
wirevector_list(['name1', 'name2', 'name3'])
wirevector_list('name1, name2, name3')
wirevector_list('input1 input2 input3', bitwidth=8, wvtype=pyrtl.wire.Input)
wirevector_list('output1, output2 output3', bitwidth=3, wvtype=pyrtl.wire.Output)
wirevector_list('two_bits/2, four_bits/4, eight_bits/8')
wirevector_list(['name1', 'name2', 'name3'], bitwidth=[2, 4, 8])
"""
if isinstance(names, str):
names = names.replace(',', ' ').split()
if any('/' in name for name in names) and bitwidth is not None:
raise PyrtlError('only one of optional "/" or bitwidth parameter allowed')
if bitwidth is None:
bitwidth = 1
if isinstance(bitwidth, numbers.Integral):
bitwidth = [bitwidth]*len(names)
if len(bitwidth) != len(names):
raise ValueError('number of names ' + str(len(names))
+ ' should match number of bitwidths ' + str(len(bitwidth)))
wirelist = []
for fullname, bw in zip(names, bitwidth):
try:
name, bw = fullname.split('/')
except ValueError:
name, bw = fullname, bw
wirelist.append(wvtype(bitwidth=int(bw), name=name))
return wirelist | [
"def",
"wirevector_list",
"(",
"names",
",",
"bitwidth",
"=",
"None",
",",
"wvtype",
"=",
"WireVector",
")",
":",
"if",
"isinstance",
"(",
"names",
",",
"str",
")",
":",
"names",
"=",
"names",
".",
"replace",
"(",
"','",
",",
"' '",
")",
".",
"split",
"(",
")",
"if",
"any",
"(",
"'/'",
"in",
"name",
"for",
"name",
"in",
"names",
")",
"and",
"bitwidth",
"is",
"not",
"None",
":",
"raise",
"PyrtlError",
"(",
"'only one of optional \"/\" or bitwidth parameter allowed'",
")",
"if",
"bitwidth",
"is",
"None",
":",
"bitwidth",
"=",
"1",
"if",
"isinstance",
"(",
"bitwidth",
",",
"numbers",
".",
"Integral",
")",
":",
"bitwidth",
"=",
"[",
"bitwidth",
"]",
"*",
"len",
"(",
"names",
")",
"if",
"len",
"(",
"bitwidth",
")",
"!=",
"len",
"(",
"names",
")",
":",
"raise",
"ValueError",
"(",
"'number of names '",
"+",
"str",
"(",
"len",
"(",
"names",
")",
")",
"+",
"' should match number of bitwidths '",
"+",
"str",
"(",
"len",
"(",
"bitwidth",
")",
")",
")",
"wirelist",
"=",
"[",
"]",
"for",
"fullname",
",",
"bw",
"in",
"zip",
"(",
"names",
",",
"bitwidth",
")",
":",
"try",
":",
"name",
",",
"bw",
"=",
"fullname",
".",
"split",
"(",
"'/'",
")",
"except",
"ValueError",
":",
"name",
",",
"bw",
"=",
"fullname",
",",
"bw",
"wirelist",
".",
"append",
"(",
"wvtype",
"(",
"bitwidth",
"=",
"int",
"(",
"bw",
")",
",",
"name",
"=",
"name",
")",
")",
"return",
"wirelist"
] | Allocate and return a list of WireVectors.
:param names: Names for the WireVectors. Can be a list or single comma/space-separated string
:param bitwidth: The desired bitwidth for the resulting WireVectors.
:param WireVector wvtype: Which WireVector type to create.
:return: List of WireVectors.
Additionally, the ``names`` string can also contain an additional bitwidth specification
separated by a ``/`` in the name. This cannot be used in combination with a ``bitwidth``
value other than ``1``.
Examples: ::
wirevector_list(['name1', 'name2', 'name3'])
wirevector_list('name1, name2, name3')
wirevector_list('input1 input2 input3', bitwidth=8, wvtype=pyrtl.wire.Input)
wirevector_list('output1, output2 output3', bitwidth=3, wvtype=pyrtl.wire.Output)
wirevector_list('two_bits/2, four_bits/4, eight_bits/8')
wirevector_list(['name1', 'name2', 'name3'], bitwidth=[2, 4, 8]) | [
"Allocate",
"and",
"return",
"a",
"list",
"of",
"WireVectors",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/helperfuncs.py#L154-L197 |
UCSBarchlab/PyRTL | pyrtl/helperfuncs.py | val_to_signed_integer | def val_to_signed_integer(value, bitwidth):
""" Return value as intrepreted as a signed integer under twos complement.
:param value: a python integer holding the value to convert
:param bitwidth: the length of the integer in bits to assume for conversion
Given an unsigned integer (not a wirevector!) covert that to a signed
integer. This is useful for printing and interpreting values which are
negative numbers in twos complement. ::
val_to_signed_integer(0xff, 8) == -1
"""
if isinstance(value, WireVector) or isinstance(bitwidth, WireVector):
raise PyrtlError('inputs must not be wirevectors')
if bitwidth < 1:
raise PyrtlError('bitwidth must be a positive integer')
neg_mask = 1 << (bitwidth - 1)
neg_part = value & neg_mask
pos_mask = neg_mask - 1
pos_part = value & pos_mask
return pos_part - neg_part | python | def val_to_signed_integer(value, bitwidth):
""" Return value as intrepreted as a signed integer under twos complement.
:param value: a python integer holding the value to convert
:param bitwidth: the length of the integer in bits to assume for conversion
Given an unsigned integer (not a wirevector!) covert that to a signed
integer. This is useful for printing and interpreting values which are
negative numbers in twos complement. ::
val_to_signed_integer(0xff, 8) == -1
"""
if isinstance(value, WireVector) or isinstance(bitwidth, WireVector):
raise PyrtlError('inputs must not be wirevectors')
if bitwidth < 1:
raise PyrtlError('bitwidth must be a positive integer')
neg_mask = 1 << (bitwidth - 1)
neg_part = value & neg_mask
pos_mask = neg_mask - 1
pos_part = value & pos_mask
return pos_part - neg_part | [
"def",
"val_to_signed_integer",
"(",
"value",
",",
"bitwidth",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"WireVector",
")",
"or",
"isinstance",
"(",
"bitwidth",
",",
"WireVector",
")",
":",
"raise",
"PyrtlError",
"(",
"'inputs must not be wirevectors'",
")",
"if",
"bitwidth",
"<",
"1",
":",
"raise",
"PyrtlError",
"(",
"'bitwidth must be a positive integer'",
")",
"neg_mask",
"=",
"1",
"<<",
"(",
"bitwidth",
"-",
"1",
")",
"neg_part",
"=",
"value",
"&",
"neg_mask",
"pos_mask",
"=",
"neg_mask",
"-",
"1",
"pos_part",
"=",
"value",
"&",
"pos_mask",
"return",
"pos_part",
"-",
"neg_part"
] | Return value as intrepreted as a signed integer under twos complement.
:param value: a python integer holding the value to convert
:param bitwidth: the length of the integer in bits to assume for conversion
Given an unsigned integer (not a wirevector!) covert that to a signed
integer. This is useful for printing and interpreting values which are
negative numbers in twos complement. ::
val_to_signed_integer(0xff, 8) == -1 | [
"Return",
"value",
"as",
"intrepreted",
"as",
"a",
"signed",
"integer",
"under",
"twos",
"complement",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/helperfuncs.py#L200-L223 |
UCSBarchlab/PyRTL | pyrtl/helperfuncs.py | formatted_str_to_val | def formatted_str_to_val(data, format, enum_set=None):
""" Return an unsigned integer representation of the data given format specified.
:param data: a string holding the value to convert
:param format: a string holding a format which will be used to convert the data string
:param enum_set: an iterable of enums which are used as part of the converstion process
Given a string (not a wirevector!) covert that to an unsigned integer ready for input
to the simulation enviornment. This helps deal with signed/unsigned numbers (simulation
assumes the values have been converted via two's complement already), but it also takes
hex, binary, and enum types as inputs. It is easiest to see how it works with some
examples. ::
formatted_str_to_val('2', 's3') == 2 # 0b010
formatted_str_to_val('-1', 's3') == 7 # 0b111
formatted_str_to_val('101', 'b3') == 5
formatted_str_to_val('5', 'u3') == 5
formatted_str_to_val('-3', 's3') == 5
formatted_str_to_val('a', 'x3') == 10
class Ctl(Enum):
ADD = 5
SUB = 12
formatted_str_to_val('ADD', 'e3/Ctl', [Ctl]) == 5
formatted_str_to_val('SUB', 'e3/Ctl', [Ctl]) == 12
"""
type = format[0]
bitwidth = int(format[1:].split('/')[0])
bitmask = (1 << bitwidth)-1
if type == 's':
rval = int(data) & bitmask
elif type == 'x':
rval = int(data, 16)
elif type == 'b':
rval = int(data, 2)
elif type == 'u':
rval = int(data)
if rval < 0:
raise PyrtlError('unsigned format requested, but negative value provided')
elif type == 'e':
enumname = format.split('/')[1]
enum_inst_list = [e for e in enum_set if e.__name__ == enumname]
if len(enum_inst_list) == 0:
raise PyrtlError('enum "{}" not found in passed enum_set "{}"'
.format(enumname, enum_set))
rval = getattr(enum_inst_list[0], data).value
else:
raise PyrtlError('unknown format type {}'.format(format))
return rval | python | def formatted_str_to_val(data, format, enum_set=None):
""" Return an unsigned integer representation of the data given format specified.
:param data: a string holding the value to convert
:param format: a string holding a format which will be used to convert the data string
:param enum_set: an iterable of enums which are used as part of the converstion process
Given a string (not a wirevector!) covert that to an unsigned integer ready for input
to the simulation enviornment. This helps deal with signed/unsigned numbers (simulation
assumes the values have been converted via two's complement already), but it also takes
hex, binary, and enum types as inputs. It is easiest to see how it works with some
examples. ::
formatted_str_to_val('2', 's3') == 2 # 0b010
formatted_str_to_val('-1', 's3') == 7 # 0b111
formatted_str_to_val('101', 'b3') == 5
formatted_str_to_val('5', 'u3') == 5
formatted_str_to_val('-3', 's3') == 5
formatted_str_to_val('a', 'x3') == 10
class Ctl(Enum):
ADD = 5
SUB = 12
formatted_str_to_val('ADD', 'e3/Ctl', [Ctl]) == 5
formatted_str_to_val('SUB', 'e3/Ctl', [Ctl]) == 12
"""
type = format[0]
bitwidth = int(format[1:].split('/')[0])
bitmask = (1 << bitwidth)-1
if type == 's':
rval = int(data) & bitmask
elif type == 'x':
rval = int(data, 16)
elif type == 'b':
rval = int(data, 2)
elif type == 'u':
rval = int(data)
if rval < 0:
raise PyrtlError('unsigned format requested, but negative value provided')
elif type == 'e':
enumname = format.split('/')[1]
enum_inst_list = [e for e in enum_set if e.__name__ == enumname]
if len(enum_inst_list) == 0:
raise PyrtlError('enum "{}" not found in passed enum_set "{}"'
.format(enumname, enum_set))
rval = getattr(enum_inst_list[0], data).value
else:
raise PyrtlError('unknown format type {}'.format(format))
return rval | [
"def",
"formatted_str_to_val",
"(",
"data",
",",
"format",
",",
"enum_set",
"=",
"None",
")",
":",
"type",
"=",
"format",
"[",
"0",
"]",
"bitwidth",
"=",
"int",
"(",
"format",
"[",
"1",
":",
"]",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]",
")",
"bitmask",
"=",
"(",
"1",
"<<",
"bitwidth",
")",
"-",
"1",
"if",
"type",
"==",
"'s'",
":",
"rval",
"=",
"int",
"(",
"data",
")",
"&",
"bitmask",
"elif",
"type",
"==",
"'x'",
":",
"rval",
"=",
"int",
"(",
"data",
",",
"16",
")",
"elif",
"type",
"==",
"'b'",
":",
"rval",
"=",
"int",
"(",
"data",
",",
"2",
")",
"elif",
"type",
"==",
"'u'",
":",
"rval",
"=",
"int",
"(",
"data",
")",
"if",
"rval",
"<",
"0",
":",
"raise",
"PyrtlError",
"(",
"'unsigned format requested, but negative value provided'",
")",
"elif",
"type",
"==",
"'e'",
":",
"enumname",
"=",
"format",
".",
"split",
"(",
"'/'",
")",
"[",
"1",
"]",
"enum_inst_list",
"=",
"[",
"e",
"for",
"e",
"in",
"enum_set",
"if",
"e",
".",
"__name__",
"==",
"enumname",
"]",
"if",
"len",
"(",
"enum_inst_list",
")",
"==",
"0",
":",
"raise",
"PyrtlError",
"(",
"'enum \"{}\" not found in passed enum_set \"{}\"'",
".",
"format",
"(",
"enumname",
",",
"enum_set",
")",
")",
"rval",
"=",
"getattr",
"(",
"enum_inst_list",
"[",
"0",
"]",
",",
"data",
")",
".",
"value",
"else",
":",
"raise",
"PyrtlError",
"(",
"'unknown format type {}'",
".",
"format",
"(",
"format",
")",
")",
"return",
"rval"
] | Return an unsigned integer representation of the data given format specified.
:param data: a string holding the value to convert
:param format: a string holding a format which will be used to convert the data string
:param enum_set: an iterable of enums which are used as part of the converstion process
Given a string (not a wirevector!) covert that to an unsigned integer ready for input
to the simulation enviornment. This helps deal with signed/unsigned numbers (simulation
assumes the values have been converted via two's complement already), but it also takes
hex, binary, and enum types as inputs. It is easiest to see how it works with some
examples. ::
formatted_str_to_val('2', 's3') == 2 # 0b010
formatted_str_to_val('-1', 's3') == 7 # 0b111
formatted_str_to_val('101', 'b3') == 5
formatted_str_to_val('5', 'u3') == 5
formatted_str_to_val('-3', 's3') == 5
formatted_str_to_val('a', 'x3') == 10
class Ctl(Enum):
ADD = 5
SUB = 12
formatted_str_to_val('ADD', 'e3/Ctl', [Ctl]) == 5
formatted_str_to_val('SUB', 'e3/Ctl', [Ctl]) == 12 | [
"Return",
"an",
"unsigned",
"integer",
"representation",
"of",
"the",
"data",
"given",
"format",
"specified",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/helperfuncs.py#L226-L274 |
UCSBarchlab/PyRTL | pyrtl/helperfuncs.py | val_to_formatted_str | def val_to_formatted_str(val, format, enum_set=None):
""" Return a string representation of the value given format specified.
:param val: a string holding an unsigned integer to convert
:param format: a string holding a format which will be used to convert the data string
:param enum_set: an iterable of enums which are used as part of the converstion process
Given an unsigned integer (not a wirevector!) covert that to a strong ready for output
to a human to interpret. This helps deal with signed/unsigned numbers (simulation
operates on values that have been converted via two's complement), but it also generates
hex, binary, and enum types as outputs. It is easiest to see how it works with some
examples. ::
formatted_str_to_val(2, 's3') == '2'
formatted_str_to_val(7, 's3') == '-1'
formatted_str_to_val(5, 'b3') == '101'
formatted_str_to_val(5, 'u3') == '5'
formatted_str_to_val(5, 's3') == '-3'
formatted_str_to_val(10, 'x3') == 'a'
class Ctl(Enum):
ADD = 5
SUB = 12
formatted_str_to_val('ADD', 'e3/Ctl', [Ctl]) == 5
formatted_str_to_val('SUB', 'e3/Ctl', [Ctl]) == 12
"""
type = format[0]
bitwidth = int(format[1:].split('/')[0])
bitmask = (1 << bitwidth)-1
if type == 's':
rval = str(val_to_signed_integer(val, bitwidth))
elif type == 'x':
rval = hex(val)[2:] # cuts off '0x' at the start
elif type == 'b':
rval = bin(val)[2:] # cuts off '0b' at the start
elif type == 'u':
rval = str(int(val)) # nothing fancy
elif type == 'e':
enumname = format.split('/')[1]
enum_inst_list = [e for e in enum_set if e.__name__ == enumname]
if len(enum_inst_list) == 0:
raise PyrtlError('enum "{}" not found in passed enum_set "{}"'
.format(enumname, enum_set))
rval = enum_inst_list[0](val).name
else:
raise PyrtlError('unknown format type {}'.format(format))
return rval | python | def val_to_formatted_str(val, format, enum_set=None):
""" Return a string representation of the value given format specified.
:param val: a string holding an unsigned integer to convert
:param format: a string holding a format which will be used to convert the data string
:param enum_set: an iterable of enums which are used as part of the converstion process
Given an unsigned integer (not a wirevector!) covert that to a strong ready for output
to a human to interpret. This helps deal with signed/unsigned numbers (simulation
operates on values that have been converted via two's complement), but it also generates
hex, binary, and enum types as outputs. It is easiest to see how it works with some
examples. ::
formatted_str_to_val(2, 's3') == '2'
formatted_str_to_val(7, 's3') == '-1'
formatted_str_to_val(5, 'b3') == '101'
formatted_str_to_val(5, 'u3') == '5'
formatted_str_to_val(5, 's3') == '-3'
formatted_str_to_val(10, 'x3') == 'a'
class Ctl(Enum):
ADD = 5
SUB = 12
formatted_str_to_val('ADD', 'e3/Ctl', [Ctl]) == 5
formatted_str_to_val('SUB', 'e3/Ctl', [Ctl]) == 12
"""
type = format[0]
bitwidth = int(format[1:].split('/')[0])
bitmask = (1 << bitwidth)-1
if type == 's':
rval = str(val_to_signed_integer(val, bitwidth))
elif type == 'x':
rval = hex(val)[2:] # cuts off '0x' at the start
elif type == 'b':
rval = bin(val)[2:] # cuts off '0b' at the start
elif type == 'u':
rval = str(int(val)) # nothing fancy
elif type == 'e':
enumname = format.split('/')[1]
enum_inst_list = [e for e in enum_set if e.__name__ == enumname]
if len(enum_inst_list) == 0:
raise PyrtlError('enum "{}" not found in passed enum_set "{}"'
.format(enumname, enum_set))
rval = enum_inst_list[0](val).name
else:
raise PyrtlError('unknown format type {}'.format(format))
return rval | [
"def",
"val_to_formatted_str",
"(",
"val",
",",
"format",
",",
"enum_set",
"=",
"None",
")",
":",
"type",
"=",
"format",
"[",
"0",
"]",
"bitwidth",
"=",
"int",
"(",
"format",
"[",
"1",
":",
"]",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]",
")",
"bitmask",
"=",
"(",
"1",
"<<",
"bitwidth",
")",
"-",
"1",
"if",
"type",
"==",
"'s'",
":",
"rval",
"=",
"str",
"(",
"val_to_signed_integer",
"(",
"val",
",",
"bitwidth",
")",
")",
"elif",
"type",
"==",
"'x'",
":",
"rval",
"=",
"hex",
"(",
"val",
")",
"[",
"2",
":",
"]",
"# cuts off '0x' at the start",
"elif",
"type",
"==",
"'b'",
":",
"rval",
"=",
"bin",
"(",
"val",
")",
"[",
"2",
":",
"]",
"# cuts off '0b' at the start",
"elif",
"type",
"==",
"'u'",
":",
"rval",
"=",
"str",
"(",
"int",
"(",
"val",
")",
")",
"# nothing fancy",
"elif",
"type",
"==",
"'e'",
":",
"enumname",
"=",
"format",
".",
"split",
"(",
"'/'",
")",
"[",
"1",
"]",
"enum_inst_list",
"=",
"[",
"e",
"for",
"e",
"in",
"enum_set",
"if",
"e",
".",
"__name__",
"==",
"enumname",
"]",
"if",
"len",
"(",
"enum_inst_list",
")",
"==",
"0",
":",
"raise",
"PyrtlError",
"(",
"'enum \"{}\" not found in passed enum_set \"{}\"'",
".",
"format",
"(",
"enumname",
",",
"enum_set",
")",
")",
"rval",
"=",
"enum_inst_list",
"[",
"0",
"]",
"(",
"val",
")",
".",
"name",
"else",
":",
"raise",
"PyrtlError",
"(",
"'unknown format type {}'",
".",
"format",
"(",
"format",
")",
")",
"return",
"rval"
] | Return a string representation of the value given format specified.
:param val: a string holding an unsigned integer to convert
:param format: a string holding a format which will be used to convert the data string
:param enum_set: an iterable of enums which are used as part of the converstion process
Given an unsigned integer (not a wirevector!) covert that to a strong ready for output
to a human to interpret. This helps deal with signed/unsigned numbers (simulation
operates on values that have been converted via two's complement), but it also generates
hex, binary, and enum types as outputs. It is easiest to see how it works with some
examples. ::
formatted_str_to_val(2, 's3') == '2'
formatted_str_to_val(7, 's3') == '-1'
formatted_str_to_val(5, 'b3') == '101'
formatted_str_to_val(5, 'u3') == '5'
formatted_str_to_val(5, 's3') == '-3'
formatted_str_to_val(10, 'x3') == 'a'
class Ctl(Enum):
ADD = 5
SUB = 12
formatted_str_to_val('ADD', 'e3/Ctl', [Ctl]) == 5
formatted_str_to_val('SUB', 'e3/Ctl', [Ctl]) == 12 | [
"Return",
"a",
"string",
"representation",
"of",
"the",
"value",
"given",
"format",
"specified",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/helperfuncs.py#L277-L323 |
UCSBarchlab/PyRTL | pyrtl/helperfuncs.py | _NetCount.shrank | def shrank(self, block=None, percent_diff=0, abs_diff=1):
"""
Returns whether a block has less nets than before
:param Block block: block to check (if changed)
:param Number percent_diff: percentage difference threshold
:param int abs_diff: absolute difference threshold
:return: boolean
This function checks whether the change in the number of
nets is greater than the percentage and absolute difference
thresholds.
"""
if block is None:
block = self.block
cur_nets = len(block.logic)
net_goal = self.prev_nets * (1 - percent_diff) - abs_diff
less_nets = (cur_nets <= net_goal)
self.prev_nets = cur_nets
return less_nets | python | def shrank(self, block=None, percent_diff=0, abs_diff=1):
"""
Returns whether a block has less nets than before
:param Block block: block to check (if changed)
:param Number percent_diff: percentage difference threshold
:param int abs_diff: absolute difference threshold
:return: boolean
This function checks whether the change in the number of
nets is greater than the percentage and absolute difference
thresholds.
"""
if block is None:
block = self.block
cur_nets = len(block.logic)
net_goal = self.prev_nets * (1 - percent_diff) - abs_diff
less_nets = (cur_nets <= net_goal)
self.prev_nets = cur_nets
return less_nets | [
"def",
"shrank",
"(",
"self",
",",
"block",
"=",
"None",
",",
"percent_diff",
"=",
"0",
",",
"abs_diff",
"=",
"1",
")",
":",
"if",
"block",
"is",
"None",
":",
"block",
"=",
"self",
".",
"block",
"cur_nets",
"=",
"len",
"(",
"block",
".",
"logic",
")",
"net_goal",
"=",
"self",
".",
"prev_nets",
"*",
"(",
"1",
"-",
"percent_diff",
")",
"-",
"abs_diff",
"less_nets",
"=",
"(",
"cur_nets",
"<=",
"net_goal",
")",
"self",
".",
"prev_nets",
"=",
"cur_nets",
"return",
"less_nets"
] | Returns whether a block has less nets than before
:param Block block: block to check (if changed)
:param Number percent_diff: percentage difference threshold
:param int abs_diff: absolute difference threshold
:return: boolean
This function checks whether the change in the number of
nets is greater than the percentage and absolute difference
thresholds. | [
"Returns",
"whether",
"a",
"block",
"has",
"less",
"nets",
"than",
"before"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/helperfuncs.py#L463-L482 |
UCSBarchlab/PyRTL | pyrtl/rtllib/adders.py | kogge_stone | def kogge_stone(a, b, cin=0):
"""
Creates a Kogge-Stone adder given two inputs
:param WireVector a, b: The two WireVectors to add up (bitwidths don't need to match)
:param cin: An optimal carry in WireVector or value
:return: a Wirevector representing the output of the adder
The Kogge-Stone adder is a fast tree-based adder with O(log(n))
propagation delay, useful for performance critical designs. However,
it has O(n log(n)) area usage, and large fan out.
"""
a, b = libutils.match_bitwidth(a, b)
prop_orig = a ^ b
prop_bits = [i for i in prop_orig]
gen_bits = [i for i in a & b]
prop_dist = 1
# creation of the carry calculation
while prop_dist < len(a):
for i in reversed(range(prop_dist, len(a))):
prop_old = prop_bits[i]
gen_bits[i] = gen_bits[i] | (prop_old & gen_bits[i - prop_dist])
if i >= prop_dist * 2: # to prevent creating unnecessary nets and wires
prop_bits[i] = prop_old & prop_bits[i - prop_dist]
prop_dist *= 2
# assembling the result of the addition
# preparing the cin (and conveniently shifting the gen bits)
gen_bits.insert(0, pyrtl.as_wires(cin))
return pyrtl.concat_list(gen_bits) ^ prop_orig | python | def kogge_stone(a, b, cin=0):
"""
Creates a Kogge-Stone adder given two inputs
:param WireVector a, b: The two WireVectors to add up (bitwidths don't need to match)
:param cin: An optimal carry in WireVector or value
:return: a Wirevector representing the output of the adder
The Kogge-Stone adder is a fast tree-based adder with O(log(n))
propagation delay, useful for performance critical designs. However,
it has O(n log(n)) area usage, and large fan out.
"""
a, b = libutils.match_bitwidth(a, b)
prop_orig = a ^ b
prop_bits = [i for i in prop_orig]
gen_bits = [i for i in a & b]
prop_dist = 1
# creation of the carry calculation
while prop_dist < len(a):
for i in reversed(range(prop_dist, len(a))):
prop_old = prop_bits[i]
gen_bits[i] = gen_bits[i] | (prop_old & gen_bits[i - prop_dist])
if i >= prop_dist * 2: # to prevent creating unnecessary nets and wires
prop_bits[i] = prop_old & prop_bits[i - prop_dist]
prop_dist *= 2
# assembling the result of the addition
# preparing the cin (and conveniently shifting the gen bits)
gen_bits.insert(0, pyrtl.as_wires(cin))
return pyrtl.concat_list(gen_bits) ^ prop_orig | [
"def",
"kogge_stone",
"(",
"a",
",",
"b",
",",
"cin",
"=",
"0",
")",
":",
"a",
",",
"b",
"=",
"libutils",
".",
"match_bitwidth",
"(",
"a",
",",
"b",
")",
"prop_orig",
"=",
"a",
"^",
"b",
"prop_bits",
"=",
"[",
"i",
"for",
"i",
"in",
"prop_orig",
"]",
"gen_bits",
"=",
"[",
"i",
"for",
"i",
"in",
"a",
"&",
"b",
"]",
"prop_dist",
"=",
"1",
"# creation of the carry calculation",
"while",
"prop_dist",
"<",
"len",
"(",
"a",
")",
":",
"for",
"i",
"in",
"reversed",
"(",
"range",
"(",
"prop_dist",
",",
"len",
"(",
"a",
")",
")",
")",
":",
"prop_old",
"=",
"prop_bits",
"[",
"i",
"]",
"gen_bits",
"[",
"i",
"]",
"=",
"gen_bits",
"[",
"i",
"]",
"|",
"(",
"prop_old",
"&",
"gen_bits",
"[",
"i",
"-",
"prop_dist",
"]",
")",
"if",
"i",
">=",
"prop_dist",
"*",
"2",
":",
"# to prevent creating unnecessary nets and wires",
"prop_bits",
"[",
"i",
"]",
"=",
"prop_old",
"&",
"prop_bits",
"[",
"i",
"-",
"prop_dist",
"]",
"prop_dist",
"*=",
"2",
"# assembling the result of the addition",
"# preparing the cin (and conveniently shifting the gen bits)",
"gen_bits",
".",
"insert",
"(",
"0",
",",
"pyrtl",
".",
"as_wires",
"(",
"cin",
")",
")",
"return",
"pyrtl",
".",
"concat_list",
"(",
"gen_bits",
")",
"^",
"prop_orig"
] | Creates a Kogge-Stone adder given two inputs
:param WireVector a, b: The two WireVectors to add up (bitwidths don't need to match)
:param cin: An optimal carry in WireVector or value
:return: a Wirevector representing the output of the adder
The Kogge-Stone adder is a fast tree-based adder with O(log(n))
propagation delay, useful for performance critical designs. However,
it has O(n log(n)) area usage, and large fan out. | [
"Creates",
"a",
"Kogge",
"-",
"Stone",
"adder",
"given",
"two",
"inputs"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/adders.py#L6-L37 |
UCSBarchlab/PyRTL | pyrtl/rtllib/adders.py | carrysave_adder | def carrysave_adder(a, b, c, final_adder=ripple_add):
"""
Adds three wirevectors up in an efficient manner
:param WireVector a, b, c : the three wires to add up
:param function final_adder : The adder to use to do the final addition
:return: a wirevector with length 2 longer than the largest input
"""
a, b, c = libutils.match_bitwidth(a, b, c)
partial_sum = a ^ b ^ c
shift_carry = (a | b) & (a | c) & (b | c)
return pyrtl.concat(final_adder(partial_sum[1:], shift_carry), partial_sum[0]) | python | def carrysave_adder(a, b, c, final_adder=ripple_add):
"""
Adds three wirevectors up in an efficient manner
:param WireVector a, b, c : the three wires to add up
:param function final_adder : The adder to use to do the final addition
:return: a wirevector with length 2 longer than the largest input
"""
a, b, c = libutils.match_bitwidth(a, b, c)
partial_sum = a ^ b ^ c
shift_carry = (a | b) & (a | c) & (b | c)
return pyrtl.concat(final_adder(partial_sum[1:], shift_carry), partial_sum[0]) | [
"def",
"carrysave_adder",
"(",
"a",
",",
"b",
",",
"c",
",",
"final_adder",
"=",
"ripple_add",
")",
":",
"a",
",",
"b",
",",
"c",
"=",
"libutils",
".",
"match_bitwidth",
"(",
"a",
",",
"b",
",",
"c",
")",
"partial_sum",
"=",
"a",
"^",
"b",
"^",
"c",
"shift_carry",
"=",
"(",
"a",
"|",
"b",
")",
"&",
"(",
"a",
"|",
"c",
")",
"&",
"(",
"b",
"|",
"c",
")",
"return",
"pyrtl",
".",
"concat",
"(",
"final_adder",
"(",
"partial_sum",
"[",
"1",
":",
"]",
",",
"shift_carry",
")",
",",
"partial_sum",
"[",
"0",
"]",
")"
] | Adds three wirevectors up in an efficient manner
:param WireVector a, b, c : the three wires to add up
:param function final_adder : The adder to use to do the final addition
:return: a wirevector with length 2 longer than the largest input | [
"Adds",
"three",
"wirevectors",
"up",
"in",
"an",
"efficient",
"manner",
":",
"param",
"WireVector",
"a",
"b",
"c",
":",
"the",
"three",
"wires",
"to",
"add",
"up",
":",
"param",
"function",
"final_adder",
":",
"The",
"adder",
"to",
"use",
"to",
"do",
"the",
"final",
"addition",
":",
"return",
":",
"a",
"wirevector",
"with",
"length",
"2",
"longer",
"than",
"the",
"largest",
"input"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/adders.py#L84-L94 |
UCSBarchlab/PyRTL | pyrtl/rtllib/adders.py | cla_adder | def cla_adder(a, b, cin=0, la_unit_len=4):
"""
Carry Lookahead Adder
:param int la_unit_len: the length of input that every unit processes
A Carry LookAhead Adder is an adder that is faster than
a ripple carry adder, as it calculates the carry bits faster.
It is not as fast as a Kogge-Stone adder, but uses less area.
"""
a, b = pyrtl.match_bitwidth(a, b)
if len(a) <= la_unit_len:
sum, cout = _cla_adder_unit(a, b, cin)
return pyrtl.concat(cout, sum)
else:
sum, cout = _cla_adder_unit(a[0:la_unit_len], b[0:la_unit_len], cin)
msbits = cla_adder(a[la_unit_len:], b[la_unit_len:], cout, la_unit_len)
return pyrtl.concat(msbits, sum) | python | def cla_adder(a, b, cin=0, la_unit_len=4):
"""
Carry Lookahead Adder
:param int la_unit_len: the length of input that every unit processes
A Carry LookAhead Adder is an adder that is faster than
a ripple carry adder, as it calculates the carry bits faster.
It is not as fast as a Kogge-Stone adder, but uses less area.
"""
a, b = pyrtl.match_bitwidth(a, b)
if len(a) <= la_unit_len:
sum, cout = _cla_adder_unit(a, b, cin)
return pyrtl.concat(cout, sum)
else:
sum, cout = _cla_adder_unit(a[0:la_unit_len], b[0:la_unit_len], cin)
msbits = cla_adder(a[la_unit_len:], b[la_unit_len:], cout, la_unit_len)
return pyrtl.concat(msbits, sum) | [
"def",
"cla_adder",
"(",
"a",
",",
"b",
",",
"cin",
"=",
"0",
",",
"la_unit_len",
"=",
"4",
")",
":",
"a",
",",
"b",
"=",
"pyrtl",
".",
"match_bitwidth",
"(",
"a",
",",
"b",
")",
"if",
"len",
"(",
"a",
")",
"<=",
"la_unit_len",
":",
"sum",
",",
"cout",
"=",
"_cla_adder_unit",
"(",
"a",
",",
"b",
",",
"cin",
")",
"return",
"pyrtl",
".",
"concat",
"(",
"cout",
",",
"sum",
")",
"else",
":",
"sum",
",",
"cout",
"=",
"_cla_adder_unit",
"(",
"a",
"[",
"0",
":",
"la_unit_len",
"]",
",",
"b",
"[",
"0",
":",
"la_unit_len",
"]",
",",
"cin",
")",
"msbits",
"=",
"cla_adder",
"(",
"a",
"[",
"la_unit_len",
":",
"]",
",",
"b",
"[",
"la_unit_len",
":",
"]",
",",
"cout",
",",
"la_unit_len",
")",
"return",
"pyrtl",
".",
"concat",
"(",
"msbits",
",",
"sum",
")"
] | Carry Lookahead Adder
:param int la_unit_len: the length of input that every unit processes
A Carry LookAhead Adder is an adder that is faster than
a ripple carry adder, as it calculates the carry bits faster.
It is not as fast as a Kogge-Stone adder, but uses less area. | [
"Carry",
"Lookahead",
"Adder",
":",
"param",
"int",
"la_unit_len",
":",
"the",
"length",
"of",
"input",
"that",
"every",
"unit",
"processes"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/adders.py#L97-L113 |
UCSBarchlab/PyRTL | pyrtl/rtllib/adders.py | _cla_adder_unit | def _cla_adder_unit(a, b, cin):
"""
Carry generation and propogation signals will be calculated only using
the inputs; their values don't rely on the sum. Every unit generates
a cout signal which is used as cin for the next unit.
"""
gen = a & b
prop = a ^ b
assert(len(prop) == len(gen))
carry = [gen[0] | prop[0] & cin]
sum_bit = prop[0] ^ cin
cur_gen = gen[0]
cur_prop = prop[0]
for i in range(1, len(prop)):
cur_gen = gen[i] | (prop[i] & cur_gen)
cur_prop = cur_prop & prop[i]
sum_bit = pyrtl.concat(prop[i] ^ carry[i - 1], sum_bit)
carry.append(gen[i] | (prop[i] & carry[i-1]))
cout = cur_gen | (cur_prop & cin)
return sum_bit, cout | python | def _cla_adder_unit(a, b, cin):
"""
Carry generation and propogation signals will be calculated only using
the inputs; their values don't rely on the sum. Every unit generates
a cout signal which is used as cin for the next unit.
"""
gen = a & b
prop = a ^ b
assert(len(prop) == len(gen))
carry = [gen[0] | prop[0] & cin]
sum_bit = prop[0] ^ cin
cur_gen = gen[0]
cur_prop = prop[0]
for i in range(1, len(prop)):
cur_gen = gen[i] | (prop[i] & cur_gen)
cur_prop = cur_prop & prop[i]
sum_bit = pyrtl.concat(prop[i] ^ carry[i - 1], sum_bit)
carry.append(gen[i] | (prop[i] & carry[i-1]))
cout = cur_gen | (cur_prop & cin)
return sum_bit, cout | [
"def",
"_cla_adder_unit",
"(",
"a",
",",
"b",
",",
"cin",
")",
":",
"gen",
"=",
"a",
"&",
"b",
"prop",
"=",
"a",
"^",
"b",
"assert",
"(",
"len",
"(",
"prop",
")",
"==",
"len",
"(",
"gen",
")",
")",
"carry",
"=",
"[",
"gen",
"[",
"0",
"]",
"|",
"prop",
"[",
"0",
"]",
"&",
"cin",
"]",
"sum_bit",
"=",
"prop",
"[",
"0",
"]",
"^",
"cin",
"cur_gen",
"=",
"gen",
"[",
"0",
"]",
"cur_prop",
"=",
"prop",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"prop",
")",
")",
":",
"cur_gen",
"=",
"gen",
"[",
"i",
"]",
"|",
"(",
"prop",
"[",
"i",
"]",
"&",
"cur_gen",
")",
"cur_prop",
"=",
"cur_prop",
"&",
"prop",
"[",
"i",
"]",
"sum_bit",
"=",
"pyrtl",
".",
"concat",
"(",
"prop",
"[",
"i",
"]",
"^",
"carry",
"[",
"i",
"-",
"1",
"]",
",",
"sum_bit",
")",
"carry",
".",
"append",
"(",
"gen",
"[",
"i",
"]",
"|",
"(",
"prop",
"[",
"i",
"]",
"&",
"carry",
"[",
"i",
"-",
"1",
"]",
")",
")",
"cout",
"=",
"cur_gen",
"|",
"(",
"cur_prop",
"&",
"cin",
")",
"return",
"sum_bit",
",",
"cout"
] | Carry generation and propogation signals will be calculated only using
the inputs; their values don't rely on the sum. Every unit generates
a cout signal which is used as cin for the next unit. | [
"Carry",
"generation",
"and",
"propogation",
"signals",
"will",
"be",
"calculated",
"only",
"using",
"the",
"inputs",
";",
"their",
"values",
"don",
"t",
"rely",
"on",
"the",
"sum",
".",
"Every",
"unit",
"generates",
"a",
"cout",
"signal",
"which",
"is",
"used",
"as",
"cin",
"for",
"the",
"next",
"unit",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/adders.py#L116-L137 |
UCSBarchlab/PyRTL | pyrtl/rtllib/adders.py | wallace_reducer | def wallace_reducer(wire_array_2, result_bitwidth, final_adder=kogge_stone):
"""
The reduction and final adding part of a dada tree. Useful for adding many numbers together
The use of single bitwidth wires is to allow for additional flexibility
:param [[Wirevector]] wire_array_2: An array of arrays of single bitwidth
wirevectors
:param int result_bitwidth: The bitwidth you want for the resulting wire.
Used to eliminate unnessary wires.
:param final_adder: The adder used for the final addition
:return: wirevector of length result_wirevector
"""
# verification that the wires are actually wirevectors of length 1
for wire_set in wire_array_2:
for a_wire in wire_set:
if not isinstance(a_wire, pyrtl.WireVector) or len(a_wire) != 1:
raise pyrtl.PyrtlError(
"The item {} is not a valid element for the wire_array_2. "
"It must be a WireVector of bitwidth 1".format(a_wire))
while not all(len(i) <= 2 for i in wire_array_2):
deferred = [[] for weight in range(result_bitwidth + 1)]
for i, w_array in enumerate(wire_array_2): # Start with low weights and start reducing
while len(w_array) >= 3:
cout, sum = _one_bit_add_no_concat(*(w_array.pop(0) for j in range(3)))
deferred[i].append(sum)
deferred[i + 1].append(cout)
if len(w_array) == 2:
cout, sum = half_adder(*w_array)
deferred[i].append(sum)
deferred[i + 1].append(cout)
else:
deferred[i].extend(w_array)
wire_array_2 = deferred[:result_bitwidth]
# At this stage in the multiplication we have only 2 wire vectors left.
# now we need to add them up
result = _sparse_adder(wire_array_2, final_adder)
if len(result) > result_bitwidth:
return result[:result_bitwidth]
else:
return result | python | def wallace_reducer(wire_array_2, result_bitwidth, final_adder=kogge_stone):
"""
The reduction and final adding part of a dada tree. Useful for adding many numbers together
The use of single bitwidth wires is to allow for additional flexibility
:param [[Wirevector]] wire_array_2: An array of arrays of single bitwidth
wirevectors
:param int result_bitwidth: The bitwidth you want for the resulting wire.
Used to eliminate unnessary wires.
:param final_adder: The adder used for the final addition
:return: wirevector of length result_wirevector
"""
# verification that the wires are actually wirevectors of length 1
for wire_set in wire_array_2:
for a_wire in wire_set:
if not isinstance(a_wire, pyrtl.WireVector) or len(a_wire) != 1:
raise pyrtl.PyrtlError(
"The item {} is not a valid element for the wire_array_2. "
"It must be a WireVector of bitwidth 1".format(a_wire))
while not all(len(i) <= 2 for i in wire_array_2):
deferred = [[] for weight in range(result_bitwidth + 1)]
for i, w_array in enumerate(wire_array_2): # Start with low weights and start reducing
while len(w_array) >= 3:
cout, sum = _one_bit_add_no_concat(*(w_array.pop(0) for j in range(3)))
deferred[i].append(sum)
deferred[i + 1].append(cout)
if len(w_array) == 2:
cout, sum = half_adder(*w_array)
deferred[i].append(sum)
deferred[i + 1].append(cout)
else:
deferred[i].extend(w_array)
wire_array_2 = deferred[:result_bitwidth]
# At this stage in the multiplication we have only 2 wire vectors left.
# now we need to add them up
result = _sparse_adder(wire_array_2, final_adder)
if len(result) > result_bitwidth:
return result[:result_bitwidth]
else:
return result | [
"def",
"wallace_reducer",
"(",
"wire_array_2",
",",
"result_bitwidth",
",",
"final_adder",
"=",
"kogge_stone",
")",
":",
"# verification that the wires are actually wirevectors of length 1",
"for",
"wire_set",
"in",
"wire_array_2",
":",
"for",
"a_wire",
"in",
"wire_set",
":",
"if",
"not",
"isinstance",
"(",
"a_wire",
",",
"pyrtl",
".",
"WireVector",
")",
"or",
"len",
"(",
"a_wire",
")",
"!=",
"1",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"The item {} is not a valid element for the wire_array_2. \"",
"\"It must be a WireVector of bitwidth 1\"",
".",
"format",
"(",
"a_wire",
")",
")",
"while",
"not",
"all",
"(",
"len",
"(",
"i",
")",
"<=",
"2",
"for",
"i",
"in",
"wire_array_2",
")",
":",
"deferred",
"=",
"[",
"[",
"]",
"for",
"weight",
"in",
"range",
"(",
"result_bitwidth",
"+",
"1",
")",
"]",
"for",
"i",
",",
"w_array",
"in",
"enumerate",
"(",
"wire_array_2",
")",
":",
"# Start with low weights and start reducing",
"while",
"len",
"(",
"w_array",
")",
">=",
"3",
":",
"cout",
",",
"sum",
"=",
"_one_bit_add_no_concat",
"(",
"*",
"(",
"w_array",
".",
"pop",
"(",
"0",
")",
"for",
"j",
"in",
"range",
"(",
"3",
")",
")",
")",
"deferred",
"[",
"i",
"]",
".",
"append",
"(",
"sum",
")",
"deferred",
"[",
"i",
"+",
"1",
"]",
".",
"append",
"(",
"cout",
")",
"if",
"len",
"(",
"w_array",
")",
"==",
"2",
":",
"cout",
",",
"sum",
"=",
"half_adder",
"(",
"*",
"w_array",
")",
"deferred",
"[",
"i",
"]",
".",
"append",
"(",
"sum",
")",
"deferred",
"[",
"i",
"+",
"1",
"]",
".",
"append",
"(",
"cout",
")",
"else",
":",
"deferred",
"[",
"i",
"]",
".",
"extend",
"(",
"w_array",
")",
"wire_array_2",
"=",
"deferred",
"[",
":",
"result_bitwidth",
"]",
"# At this stage in the multiplication we have only 2 wire vectors left.",
"# now we need to add them up",
"result",
"=",
"_sparse_adder",
"(",
"wire_array_2",
",",
"final_adder",
")",
"if",
"len",
"(",
"result",
")",
">",
"result_bitwidth",
":",
"return",
"result",
"[",
":",
"result_bitwidth",
"]",
"else",
":",
"return",
"result"
] | The reduction and final adding part of a dada tree. Useful for adding many numbers together
The use of single bitwidth wires is to allow for additional flexibility
:param [[Wirevector]] wire_array_2: An array of arrays of single bitwidth
wirevectors
:param int result_bitwidth: The bitwidth you want for the resulting wire.
Used to eliminate unnessary wires.
:param final_adder: The adder used for the final addition
:return: wirevector of length result_wirevector | [
"The",
"reduction",
"and",
"final",
"adding",
"part",
"of",
"a",
"dada",
"tree",
".",
"Useful",
"for",
"adding",
"many",
"numbers",
"together",
"The",
"use",
"of",
"single",
"bitwidth",
"wires",
"is",
"to",
"allow",
"for",
"additional",
"flexibility"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/adders.py#L140-L182 |
UCSBarchlab/PyRTL | pyrtl/rtllib/adders.py | dada_reducer | def dada_reducer(wire_array_2, result_bitwidth, final_adder=kogge_stone):
"""
The reduction and final adding part of a dada tree. Useful for adding many numbers together
The use of single bitwidth wires is to allow for additional flexibility
:param [[Wirevector]] wire_array_2: An array of arrays of single bitwidth
wirevectors
:param int result_bitwidth: The bitwidth you want for the resulting wire.
Used to eliminate unnessary wires.
:param final_adder: The adder used for the final addition
:return: wirevector of length result_wirevector
"""
import math
# verification that the wires are actually wirevectors of length 1
for wire_set in wire_array_2:
for a_wire in wire_set:
if not isinstance(a_wire, pyrtl.WireVector) or len(a_wire) != 1:
raise pyrtl.PyrtlError(
"The item {} is not a valid element for the wire_array_2. "
"It must be a WireVector of bitwidth 1".format(a_wire))
max_width = max(len(i) for i in wire_array_2)
reduction_schedule = [2]
while reduction_schedule[-1] <= max_width:
reduction_schedule.append(int(reduction_schedule[-1]*3/2))
for reduction_target in reversed(reduction_schedule[:-1]):
deferred = [[] for weight in range(result_bitwidth + 1)]
last_round = (max(len(i) for i in wire_array_2) == 3)
for i, w_array in enumerate(wire_array_2): # Start with low weights and start reducing
while len(w_array) + len(deferred[i]) > reduction_target:
if len(w_array) + len(deferred[i]) - reduction_target >= 2:
cout, sum = _one_bit_add_no_concat(*(w_array.pop(0) for j in range(3)))
deferred[i].append(sum)
deferred[i + 1].append(cout)
else:
# if (last_round and len(deferred[i]) % 3 == 1) or (len(deferred[i]) % 3 == 2):
# if not(last_round and len(wire_array_2[i + 1]) < 3):
cout, sum = half_adder(*(w_array.pop(0) for j in range(2)))
deferred[i].append(sum)
deferred[i + 1].append(cout)
deferred[i].extend(w_array)
if len(deferred[i]) > reduction_target:
raise pyrtl.PyrtlError("Expected that the code would be able to reduce more wires")
wire_array_2 = deferred[:result_bitwidth]
# At this stage in the multiplication we have only 2 wire vectors left.
# now we need to add them up
result = _sparse_adder(wire_array_2, final_adder)
if len(result) > result_bitwidth:
return result[:result_bitwidth]
else:
return result | python | def dada_reducer(wire_array_2, result_bitwidth, final_adder=kogge_stone):
"""
The reduction and final adding part of a dada tree. Useful for adding many numbers together
The use of single bitwidth wires is to allow for additional flexibility
:param [[Wirevector]] wire_array_2: An array of arrays of single bitwidth
wirevectors
:param int result_bitwidth: The bitwidth you want for the resulting wire.
Used to eliminate unnessary wires.
:param final_adder: The adder used for the final addition
:return: wirevector of length result_wirevector
"""
import math
# verification that the wires are actually wirevectors of length 1
for wire_set in wire_array_2:
for a_wire in wire_set:
if not isinstance(a_wire, pyrtl.WireVector) or len(a_wire) != 1:
raise pyrtl.PyrtlError(
"The item {} is not a valid element for the wire_array_2. "
"It must be a WireVector of bitwidth 1".format(a_wire))
max_width = max(len(i) for i in wire_array_2)
reduction_schedule = [2]
while reduction_schedule[-1] <= max_width:
reduction_schedule.append(int(reduction_schedule[-1]*3/2))
for reduction_target in reversed(reduction_schedule[:-1]):
deferred = [[] for weight in range(result_bitwidth + 1)]
last_round = (max(len(i) for i in wire_array_2) == 3)
for i, w_array in enumerate(wire_array_2): # Start with low weights and start reducing
while len(w_array) + len(deferred[i]) > reduction_target:
if len(w_array) + len(deferred[i]) - reduction_target >= 2:
cout, sum = _one_bit_add_no_concat(*(w_array.pop(0) for j in range(3)))
deferred[i].append(sum)
deferred[i + 1].append(cout)
else:
# if (last_round and len(deferred[i]) % 3 == 1) or (len(deferred[i]) % 3 == 2):
# if not(last_round and len(wire_array_2[i + 1]) < 3):
cout, sum = half_adder(*(w_array.pop(0) for j in range(2)))
deferred[i].append(sum)
deferred[i + 1].append(cout)
deferred[i].extend(w_array)
if len(deferred[i]) > reduction_target:
raise pyrtl.PyrtlError("Expected that the code would be able to reduce more wires")
wire_array_2 = deferred[:result_bitwidth]
# At this stage in the multiplication we have only 2 wire vectors left.
# now we need to add them up
result = _sparse_adder(wire_array_2, final_adder)
if len(result) > result_bitwidth:
return result[:result_bitwidth]
else:
return result | [
"def",
"dada_reducer",
"(",
"wire_array_2",
",",
"result_bitwidth",
",",
"final_adder",
"=",
"kogge_stone",
")",
":",
"import",
"math",
"# verification that the wires are actually wirevectors of length 1",
"for",
"wire_set",
"in",
"wire_array_2",
":",
"for",
"a_wire",
"in",
"wire_set",
":",
"if",
"not",
"isinstance",
"(",
"a_wire",
",",
"pyrtl",
".",
"WireVector",
")",
"or",
"len",
"(",
"a_wire",
")",
"!=",
"1",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"The item {} is not a valid element for the wire_array_2. \"",
"\"It must be a WireVector of bitwidth 1\"",
".",
"format",
"(",
"a_wire",
")",
")",
"max_width",
"=",
"max",
"(",
"len",
"(",
"i",
")",
"for",
"i",
"in",
"wire_array_2",
")",
"reduction_schedule",
"=",
"[",
"2",
"]",
"while",
"reduction_schedule",
"[",
"-",
"1",
"]",
"<=",
"max_width",
":",
"reduction_schedule",
".",
"append",
"(",
"int",
"(",
"reduction_schedule",
"[",
"-",
"1",
"]",
"*",
"3",
"/",
"2",
")",
")",
"for",
"reduction_target",
"in",
"reversed",
"(",
"reduction_schedule",
"[",
":",
"-",
"1",
"]",
")",
":",
"deferred",
"=",
"[",
"[",
"]",
"for",
"weight",
"in",
"range",
"(",
"result_bitwidth",
"+",
"1",
")",
"]",
"last_round",
"=",
"(",
"max",
"(",
"len",
"(",
"i",
")",
"for",
"i",
"in",
"wire_array_2",
")",
"==",
"3",
")",
"for",
"i",
",",
"w_array",
"in",
"enumerate",
"(",
"wire_array_2",
")",
":",
"# Start with low weights and start reducing",
"while",
"len",
"(",
"w_array",
")",
"+",
"len",
"(",
"deferred",
"[",
"i",
"]",
")",
">",
"reduction_target",
":",
"if",
"len",
"(",
"w_array",
")",
"+",
"len",
"(",
"deferred",
"[",
"i",
"]",
")",
"-",
"reduction_target",
">=",
"2",
":",
"cout",
",",
"sum",
"=",
"_one_bit_add_no_concat",
"(",
"*",
"(",
"w_array",
".",
"pop",
"(",
"0",
")",
"for",
"j",
"in",
"range",
"(",
"3",
")",
")",
")",
"deferred",
"[",
"i",
"]",
".",
"append",
"(",
"sum",
")",
"deferred",
"[",
"i",
"+",
"1",
"]",
".",
"append",
"(",
"cout",
")",
"else",
":",
"# if (last_round and len(deferred[i]) % 3 == 1) or (len(deferred[i]) % 3 == 2):",
"# if not(last_round and len(wire_array_2[i + 1]) < 3):",
"cout",
",",
"sum",
"=",
"half_adder",
"(",
"*",
"(",
"w_array",
".",
"pop",
"(",
"0",
")",
"for",
"j",
"in",
"range",
"(",
"2",
")",
")",
")",
"deferred",
"[",
"i",
"]",
".",
"append",
"(",
"sum",
")",
"deferred",
"[",
"i",
"+",
"1",
"]",
".",
"append",
"(",
"cout",
")",
"deferred",
"[",
"i",
"]",
".",
"extend",
"(",
"w_array",
")",
"if",
"len",
"(",
"deferred",
"[",
"i",
"]",
")",
">",
"reduction_target",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"Expected that the code would be able to reduce more wires\"",
")",
"wire_array_2",
"=",
"deferred",
"[",
":",
"result_bitwidth",
"]",
"# At this stage in the multiplication we have only 2 wire vectors left.",
"# now we need to add them up",
"result",
"=",
"_sparse_adder",
"(",
"wire_array_2",
",",
"final_adder",
")",
"if",
"len",
"(",
"result",
")",
">",
"result_bitwidth",
":",
"return",
"result",
"[",
":",
"result_bitwidth",
"]",
"else",
":",
"return",
"result"
] | The reduction and final adding part of a dada tree. Useful for adding many numbers together
The use of single bitwidth wires is to allow for additional flexibility
:param [[Wirevector]] wire_array_2: An array of arrays of single bitwidth
wirevectors
:param int result_bitwidth: The bitwidth you want for the resulting wire.
Used to eliminate unnessary wires.
:param final_adder: The adder used for the final addition
:return: wirevector of length result_wirevector | [
"The",
"reduction",
"and",
"final",
"adding",
"part",
"of",
"a",
"dada",
"tree",
".",
"Useful",
"for",
"adding",
"many",
"numbers",
"together",
"The",
"use",
"of",
"single",
"bitwidth",
"wires",
"is",
"to",
"allow",
"for",
"additional",
"flexibility"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/adders.py#L185-L237 |
UCSBarchlab/PyRTL | pyrtl/rtllib/adders.py | fast_group_adder | def fast_group_adder(wires_to_add, reducer=wallace_reducer, final_adder=kogge_stone):
"""
A generalization of the carry save adder, this is designed to add many numbers
together in a both area and time efficient manner. Uses a tree reducer
to achieve this performance
:param [WireVector] wires_to_add: an array of wirevectors to add
:param reducer: the tree reducer to use
:param final_adder: The two value adder to use at the end
:return: a wirevector with the result of the addition
The length of the result is:
max(len(w) for w in wires_to_add) + ceil(len(wires_to_add))
"""
import math
longest_wire_len = max(len(w) for w in wires_to_add)
result_bitwidth = longest_wire_len + int(math.ceil(math.log(len(wires_to_add), 2)))
bits = [[] for i in range(longest_wire_len)]
for wire in wires_to_add:
for bit_loc, bit in enumerate(wire):
bits[bit_loc].append(bit)
return reducer(bits, result_bitwidth, final_adder) | python | def fast_group_adder(wires_to_add, reducer=wallace_reducer, final_adder=kogge_stone):
"""
A generalization of the carry save adder, this is designed to add many numbers
together in a both area and time efficient manner. Uses a tree reducer
to achieve this performance
:param [WireVector] wires_to_add: an array of wirevectors to add
:param reducer: the tree reducer to use
:param final_adder: The two value adder to use at the end
:return: a wirevector with the result of the addition
The length of the result is:
max(len(w) for w in wires_to_add) + ceil(len(wires_to_add))
"""
import math
longest_wire_len = max(len(w) for w in wires_to_add)
result_bitwidth = longest_wire_len + int(math.ceil(math.log(len(wires_to_add), 2)))
bits = [[] for i in range(longest_wire_len)]
for wire in wires_to_add:
for bit_loc, bit in enumerate(wire):
bits[bit_loc].append(bit)
return reducer(bits, result_bitwidth, final_adder) | [
"def",
"fast_group_adder",
"(",
"wires_to_add",
",",
"reducer",
"=",
"wallace_reducer",
",",
"final_adder",
"=",
"kogge_stone",
")",
":",
"import",
"math",
"longest_wire_len",
"=",
"max",
"(",
"len",
"(",
"w",
")",
"for",
"w",
"in",
"wires_to_add",
")",
"result_bitwidth",
"=",
"longest_wire_len",
"+",
"int",
"(",
"math",
".",
"ceil",
"(",
"math",
".",
"log",
"(",
"len",
"(",
"wires_to_add",
")",
",",
"2",
")",
")",
")",
"bits",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"longest_wire_len",
")",
"]",
"for",
"wire",
"in",
"wires_to_add",
":",
"for",
"bit_loc",
",",
"bit",
"in",
"enumerate",
"(",
"wire",
")",
":",
"bits",
"[",
"bit_loc",
"]",
".",
"append",
"(",
"bit",
")",
"return",
"reducer",
"(",
"bits",
",",
"result_bitwidth",
",",
"final_adder",
")"
] | A generalization of the carry save adder, this is designed to add many numbers
together in a both area and time efficient manner. Uses a tree reducer
to achieve this performance
:param [WireVector] wires_to_add: an array of wirevectors to add
:param reducer: the tree reducer to use
:param final_adder: The two value adder to use at the end
:return: a wirevector with the result of the addition
The length of the result is:
max(len(w) for w in wires_to_add) + ceil(len(wires_to_add)) | [
"A",
"generalization",
"of",
"the",
"carry",
"save",
"adder",
"this",
"is",
"designed",
"to",
"add",
"many",
"numbers",
"together",
"in",
"a",
"both",
"area",
"and",
"time",
"efficient",
"manner",
".",
"Uses",
"a",
"tree",
"reducer",
"to",
"achieve",
"this",
"performance"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/adders.py#L258-L282 |
UCSBarchlab/PyRTL | pyrtl/memory.py | MemBlock._build | def _build(self, addr, data, enable):
""" Builds a write port. """
if self.max_write_ports is not None:
self.write_ports += 1
if self.write_ports > self.max_write_ports:
raise PyrtlError('maximum number of write ports (%d) exceeded' %
self.max_write_ports)
writeport_net = LogicNet(
op='@',
op_param=(self.id, self),
args=(addr, data, enable),
dests=tuple())
working_block().add_net(writeport_net)
self.writeport_nets.append(writeport_net) | python | def _build(self, addr, data, enable):
""" Builds a write port. """
if self.max_write_ports is not None:
self.write_ports += 1
if self.write_ports > self.max_write_ports:
raise PyrtlError('maximum number of write ports (%d) exceeded' %
self.max_write_ports)
writeport_net = LogicNet(
op='@',
op_param=(self.id, self),
args=(addr, data, enable),
dests=tuple())
working_block().add_net(writeport_net)
self.writeport_nets.append(writeport_net) | [
"def",
"_build",
"(",
"self",
",",
"addr",
",",
"data",
",",
"enable",
")",
":",
"if",
"self",
".",
"max_write_ports",
"is",
"not",
"None",
":",
"self",
".",
"write_ports",
"+=",
"1",
"if",
"self",
".",
"write_ports",
">",
"self",
".",
"max_write_ports",
":",
"raise",
"PyrtlError",
"(",
"'maximum number of write ports (%d) exceeded'",
"%",
"self",
".",
"max_write_ports",
")",
"writeport_net",
"=",
"LogicNet",
"(",
"op",
"=",
"'@'",
",",
"op_param",
"=",
"(",
"self",
".",
"id",
",",
"self",
")",
",",
"args",
"=",
"(",
"addr",
",",
"data",
",",
"enable",
")",
",",
"dests",
"=",
"tuple",
"(",
")",
")",
"working_block",
"(",
")",
".",
"add_net",
"(",
"writeport_net",
")",
"self",
".",
"writeport_nets",
".",
"append",
"(",
"writeport_net",
")"
] | Builds a write port. | [
"Builds",
"a",
"write",
"port",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/memory.py#L236-L249 |
UCSBarchlab/PyRTL | pyrtl/rtllib/aes.py | AES.encryption | def encryption(self, plaintext, key):
"""
Builds a single cycle AES Encryption circuit
:param WireVector plaintext: text to encrypt
:param WireVector key: AES key to use to encrypt
:return: a WireVector containing the ciphertext
"""
if len(plaintext) != self._key_len:
raise pyrtl.PyrtlError("Ciphertext length is invalid")
if len(key) != self._key_len:
raise pyrtl.PyrtlError("key length is invalid")
key_list = self._key_gen(key)
t = self._add_round_key(plaintext, key_list[0])
for round in range(1, 11):
t = self._sub_bytes(t)
t = self._shift_rows(t)
if round != 10:
t = self._mix_columns(t)
t = self._add_round_key(t, key_list[round])
return t | python | def encryption(self, plaintext, key):
"""
Builds a single cycle AES Encryption circuit
:param WireVector plaintext: text to encrypt
:param WireVector key: AES key to use to encrypt
:return: a WireVector containing the ciphertext
"""
if len(plaintext) != self._key_len:
raise pyrtl.PyrtlError("Ciphertext length is invalid")
if len(key) != self._key_len:
raise pyrtl.PyrtlError("key length is invalid")
key_list = self._key_gen(key)
t = self._add_round_key(plaintext, key_list[0])
for round in range(1, 11):
t = self._sub_bytes(t)
t = self._shift_rows(t)
if round != 10:
t = self._mix_columns(t)
t = self._add_round_key(t, key_list[round])
return t | [
"def",
"encryption",
"(",
"self",
",",
"plaintext",
",",
"key",
")",
":",
"if",
"len",
"(",
"plaintext",
")",
"!=",
"self",
".",
"_key_len",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"Ciphertext length is invalid\"",
")",
"if",
"len",
"(",
"key",
")",
"!=",
"self",
".",
"_key_len",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"key length is invalid\"",
")",
"key_list",
"=",
"self",
".",
"_key_gen",
"(",
"key",
")",
"t",
"=",
"self",
".",
"_add_round_key",
"(",
"plaintext",
",",
"key_list",
"[",
"0",
"]",
")",
"for",
"round",
"in",
"range",
"(",
"1",
",",
"11",
")",
":",
"t",
"=",
"self",
".",
"_sub_bytes",
"(",
"t",
")",
"t",
"=",
"self",
".",
"_shift_rows",
"(",
"t",
")",
"if",
"round",
"!=",
"10",
":",
"t",
"=",
"self",
".",
"_mix_columns",
"(",
"t",
")",
"t",
"=",
"self",
".",
"_add_round_key",
"(",
"t",
",",
"key_list",
"[",
"round",
"]",
")",
"return",
"t"
] | Builds a single cycle AES Encryption circuit
:param WireVector plaintext: text to encrypt
:param WireVector key: AES key to use to encrypt
:return: a WireVector containing the ciphertext | [
"Builds",
"a",
"single",
"cycle",
"AES",
"Encryption",
"circuit"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/aes.py#L53-L76 |
UCSBarchlab/PyRTL | pyrtl/rtllib/aes.py | AES.encrypt_state_m | def encrypt_state_m(self, plaintext_in, key_in, reset):
"""
Builds a multiple cycle AES Encryption state machine circuit
:param reset: a one bit signal telling the state machine
to reset and accept the current plaintext and key
:return ready, cipher_text: ready is a one bit signal showing
that the encryption result (cipher_text) has been calculated.
"""
if len(key_in) != len(plaintext_in):
raise pyrtl.PyrtlError("AES key and plaintext should be the same length")
plain_text, key = (pyrtl.Register(len(plaintext_in)) for i in range(2))
key_exp_in, add_round_in = (pyrtl.WireVector(len(plaintext_in)) for i in range(2))
counter = pyrtl.Register(4, 'counter')
round = pyrtl.WireVector(4, 'round')
counter.next <<= round
sub_out = self._sub_bytes(plain_text)
shift_out = self._shift_rows(sub_out)
mix_out = self._mix_columns(shift_out)
key_out = self._key_expansion(key, counter)
add_round_out = self._add_round_key(add_round_in, key_exp_in)
with pyrtl.conditional_assignment:
with reset == 1:
round |= 0
key_exp_in |= key_in # to lower the number of cycles
plain_text.next |= add_round_out
key.next |= key_in
add_round_in |= plaintext_in
with counter == 10: # keep everything the same
round |= counter
plain_text.next |= plain_text
with pyrtl.otherwise: # running through AES
round |= counter + 1
key_exp_in |= key_out
plain_text.next |= add_round_out
key.next |= key_out
with counter == 9:
add_round_in |= shift_out
with pyrtl.otherwise:
add_round_in |= mix_out
ready = (counter == 10)
return ready, plain_text | python | def encrypt_state_m(self, plaintext_in, key_in, reset):
"""
Builds a multiple cycle AES Encryption state machine circuit
:param reset: a one bit signal telling the state machine
to reset and accept the current plaintext and key
:return ready, cipher_text: ready is a one bit signal showing
that the encryption result (cipher_text) has been calculated.
"""
if len(key_in) != len(plaintext_in):
raise pyrtl.PyrtlError("AES key and plaintext should be the same length")
plain_text, key = (pyrtl.Register(len(plaintext_in)) for i in range(2))
key_exp_in, add_round_in = (pyrtl.WireVector(len(plaintext_in)) for i in range(2))
counter = pyrtl.Register(4, 'counter')
round = pyrtl.WireVector(4, 'round')
counter.next <<= round
sub_out = self._sub_bytes(plain_text)
shift_out = self._shift_rows(sub_out)
mix_out = self._mix_columns(shift_out)
key_out = self._key_expansion(key, counter)
add_round_out = self._add_round_key(add_round_in, key_exp_in)
with pyrtl.conditional_assignment:
with reset == 1:
round |= 0
key_exp_in |= key_in # to lower the number of cycles
plain_text.next |= add_round_out
key.next |= key_in
add_round_in |= plaintext_in
with counter == 10: # keep everything the same
round |= counter
plain_text.next |= plain_text
with pyrtl.otherwise: # running through AES
round |= counter + 1
key_exp_in |= key_out
plain_text.next |= add_round_out
key.next |= key_out
with counter == 9:
add_round_in |= shift_out
with pyrtl.otherwise:
add_round_in |= mix_out
ready = (counter == 10)
return ready, plain_text | [
"def",
"encrypt_state_m",
"(",
"self",
",",
"plaintext_in",
",",
"key_in",
",",
"reset",
")",
":",
"if",
"len",
"(",
"key_in",
")",
"!=",
"len",
"(",
"plaintext_in",
")",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"AES key and plaintext should be the same length\"",
")",
"plain_text",
",",
"key",
"=",
"(",
"pyrtl",
".",
"Register",
"(",
"len",
"(",
"plaintext_in",
")",
")",
"for",
"i",
"in",
"range",
"(",
"2",
")",
")",
"key_exp_in",
",",
"add_round_in",
"=",
"(",
"pyrtl",
".",
"WireVector",
"(",
"len",
"(",
"plaintext_in",
")",
")",
"for",
"i",
"in",
"range",
"(",
"2",
")",
")",
"counter",
"=",
"pyrtl",
".",
"Register",
"(",
"4",
",",
"'counter'",
")",
"round",
"=",
"pyrtl",
".",
"WireVector",
"(",
"4",
",",
"'round'",
")",
"counter",
".",
"next",
"<<=",
"round",
"sub_out",
"=",
"self",
".",
"_sub_bytes",
"(",
"plain_text",
")",
"shift_out",
"=",
"self",
".",
"_shift_rows",
"(",
"sub_out",
")",
"mix_out",
"=",
"self",
".",
"_mix_columns",
"(",
"shift_out",
")",
"key_out",
"=",
"self",
".",
"_key_expansion",
"(",
"key",
",",
"counter",
")",
"add_round_out",
"=",
"self",
".",
"_add_round_key",
"(",
"add_round_in",
",",
"key_exp_in",
")",
"with",
"pyrtl",
".",
"conditional_assignment",
":",
"with",
"reset",
"==",
"1",
":",
"round",
"|=",
"0",
"key_exp_in",
"|=",
"key_in",
"# to lower the number of cycles",
"plain_text",
".",
"next",
"|=",
"add_round_out",
"key",
".",
"next",
"|=",
"key_in",
"add_round_in",
"|=",
"plaintext_in",
"with",
"counter",
"==",
"10",
":",
"# keep everything the same",
"round",
"|=",
"counter",
"plain_text",
".",
"next",
"|=",
"plain_text",
"with",
"pyrtl",
".",
"otherwise",
":",
"# running through AES",
"round",
"|=",
"counter",
"+",
"1",
"key_exp_in",
"|=",
"key_out",
"plain_text",
".",
"next",
"|=",
"add_round_out",
"key",
".",
"next",
"|=",
"key_out",
"with",
"counter",
"==",
"9",
":",
"add_round_in",
"|=",
"shift_out",
"with",
"pyrtl",
".",
"otherwise",
":",
"add_round_in",
"|=",
"mix_out",
"ready",
"=",
"(",
"counter",
"==",
"10",
")",
"return",
"ready",
",",
"plain_text"
] | Builds a multiple cycle AES Encryption state machine circuit
:param reset: a one bit signal telling the state machine
to reset and accept the current plaintext and key
:return ready, cipher_text: ready is a one bit signal showing
that the encryption result (cipher_text) has been calculated. | [
"Builds",
"a",
"multiple",
"cycle",
"AES",
"Encryption",
"state",
"machine",
"circuit"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/aes.py#L78-L125 |
UCSBarchlab/PyRTL | pyrtl/rtllib/aes.py | AES.decryption | def decryption(self, ciphertext, key):
"""
Builds a single cycle AES Decryption circuit
:param WireVector ciphertext: data to decrypt
:param WireVector key: AES key to use to encrypt (AES is symmetric)
:return: a WireVector containing the plaintext
"""
if len(ciphertext) != self._key_len:
raise pyrtl.PyrtlError("Ciphertext length is invalid")
if len(key) != self._key_len:
raise pyrtl.PyrtlError("key length is invalid")
key_list = self._key_gen(key)
t = self._add_round_key(ciphertext, key_list[10])
for round in range(1, 11):
t = self._inv_shift_rows(t)
t = self._sub_bytes(t, True)
t = self._add_round_key(t, key_list[10 - round])
if round != 10:
t = self._mix_columns(t, True)
return t | python | def decryption(self, ciphertext, key):
"""
Builds a single cycle AES Decryption circuit
:param WireVector ciphertext: data to decrypt
:param WireVector key: AES key to use to encrypt (AES is symmetric)
:return: a WireVector containing the plaintext
"""
if len(ciphertext) != self._key_len:
raise pyrtl.PyrtlError("Ciphertext length is invalid")
if len(key) != self._key_len:
raise pyrtl.PyrtlError("key length is invalid")
key_list = self._key_gen(key)
t = self._add_round_key(ciphertext, key_list[10])
for round in range(1, 11):
t = self._inv_shift_rows(t)
t = self._sub_bytes(t, True)
t = self._add_round_key(t, key_list[10 - round])
if round != 10:
t = self._mix_columns(t, True)
return t | [
"def",
"decryption",
"(",
"self",
",",
"ciphertext",
",",
"key",
")",
":",
"if",
"len",
"(",
"ciphertext",
")",
"!=",
"self",
".",
"_key_len",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"Ciphertext length is invalid\"",
")",
"if",
"len",
"(",
"key",
")",
"!=",
"self",
".",
"_key_len",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"key length is invalid\"",
")",
"key_list",
"=",
"self",
".",
"_key_gen",
"(",
"key",
")",
"t",
"=",
"self",
".",
"_add_round_key",
"(",
"ciphertext",
",",
"key_list",
"[",
"10",
"]",
")",
"for",
"round",
"in",
"range",
"(",
"1",
",",
"11",
")",
":",
"t",
"=",
"self",
".",
"_inv_shift_rows",
"(",
"t",
")",
"t",
"=",
"self",
".",
"_sub_bytes",
"(",
"t",
",",
"True",
")",
"t",
"=",
"self",
".",
"_add_round_key",
"(",
"t",
",",
"key_list",
"[",
"10",
"-",
"round",
"]",
")",
"if",
"round",
"!=",
"10",
":",
"t",
"=",
"self",
".",
"_mix_columns",
"(",
"t",
",",
"True",
")",
"return",
"t"
] | Builds a single cycle AES Decryption circuit
:param WireVector ciphertext: data to decrypt
:param WireVector key: AES key to use to encrypt (AES is symmetric)
:return: a WireVector containing the plaintext | [
"Builds",
"a",
"single",
"cycle",
"AES",
"Decryption",
"circuit"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/aes.py#L127-L149 |
UCSBarchlab/PyRTL | pyrtl/rtllib/aes.py | AES.decryption_statem | def decryption_statem(self, ciphertext_in, key_in, reset):
"""
Builds a multiple cycle AES Decryption state machine circuit
:param reset: a one bit signal telling the state machine
to reset and accept the current plaintext and key
:return ready, plain_text: ready is a one bit signal showing
that the decryption result (plain_text) has been calculated.
"""
if len(key_in) != len(ciphertext_in):
raise pyrtl.PyrtlError("AES key and ciphertext should be the same length")
cipher_text, key = (pyrtl.Register(len(ciphertext_in)) for i in range(2))
key_exp_in, add_round_in = (pyrtl.WireVector(len(ciphertext_in)) for i in range(2))
# this is not part of the state machine as we need the keys in
# reverse order...
reversed_key_list = reversed(self._key_gen(key_exp_in))
counter = pyrtl.Register(4, 'counter')
round = pyrtl.WireVector(4)
counter.next <<= round
inv_shift = self._inv_shift_rows(cipher_text)
inv_sub = self._sub_bytes(inv_shift, True)
key_out = pyrtl.mux(round, *reversed_key_list, default=0)
add_round_out = self._add_round_key(add_round_in, key_out)
inv_mix_out = self._mix_columns(add_round_out, True)
with pyrtl.conditional_assignment:
with reset == 1:
round |= 0
key.next |= key_in
key_exp_in |= key_in # to lower the number of cycles needed
cipher_text.next |= add_round_out
add_round_in |= ciphertext_in
with counter == 10: # keep everything the same
round |= counter
cipher_text.next |= cipher_text
with pyrtl.otherwise: # running through AES
round |= counter + 1
key.next |= key
key_exp_in |= key
add_round_in |= inv_sub
with counter == 9:
cipher_text.next |= add_round_out
with pyrtl.otherwise:
cipher_text.next |= inv_mix_out
ready = (counter == 10)
return ready, cipher_text | python | def decryption_statem(self, ciphertext_in, key_in, reset):
"""
Builds a multiple cycle AES Decryption state machine circuit
:param reset: a one bit signal telling the state machine
to reset and accept the current plaintext and key
:return ready, plain_text: ready is a one bit signal showing
that the decryption result (plain_text) has been calculated.
"""
if len(key_in) != len(ciphertext_in):
raise pyrtl.PyrtlError("AES key and ciphertext should be the same length")
cipher_text, key = (pyrtl.Register(len(ciphertext_in)) for i in range(2))
key_exp_in, add_round_in = (pyrtl.WireVector(len(ciphertext_in)) for i in range(2))
# this is not part of the state machine as we need the keys in
# reverse order...
reversed_key_list = reversed(self._key_gen(key_exp_in))
counter = pyrtl.Register(4, 'counter')
round = pyrtl.WireVector(4)
counter.next <<= round
inv_shift = self._inv_shift_rows(cipher_text)
inv_sub = self._sub_bytes(inv_shift, True)
key_out = pyrtl.mux(round, *reversed_key_list, default=0)
add_round_out = self._add_round_key(add_round_in, key_out)
inv_mix_out = self._mix_columns(add_round_out, True)
with pyrtl.conditional_assignment:
with reset == 1:
round |= 0
key.next |= key_in
key_exp_in |= key_in # to lower the number of cycles needed
cipher_text.next |= add_round_out
add_round_in |= ciphertext_in
with counter == 10: # keep everything the same
round |= counter
cipher_text.next |= cipher_text
with pyrtl.otherwise: # running through AES
round |= counter + 1
key.next |= key
key_exp_in |= key
add_round_in |= inv_sub
with counter == 9:
cipher_text.next |= add_round_out
with pyrtl.otherwise:
cipher_text.next |= inv_mix_out
ready = (counter == 10)
return ready, cipher_text | [
"def",
"decryption_statem",
"(",
"self",
",",
"ciphertext_in",
",",
"key_in",
",",
"reset",
")",
":",
"if",
"len",
"(",
"key_in",
")",
"!=",
"len",
"(",
"ciphertext_in",
")",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"AES key and ciphertext should be the same length\"",
")",
"cipher_text",
",",
"key",
"=",
"(",
"pyrtl",
".",
"Register",
"(",
"len",
"(",
"ciphertext_in",
")",
")",
"for",
"i",
"in",
"range",
"(",
"2",
")",
")",
"key_exp_in",
",",
"add_round_in",
"=",
"(",
"pyrtl",
".",
"WireVector",
"(",
"len",
"(",
"ciphertext_in",
")",
")",
"for",
"i",
"in",
"range",
"(",
"2",
")",
")",
"# this is not part of the state machine as we need the keys in",
"# reverse order...",
"reversed_key_list",
"=",
"reversed",
"(",
"self",
".",
"_key_gen",
"(",
"key_exp_in",
")",
")",
"counter",
"=",
"pyrtl",
".",
"Register",
"(",
"4",
",",
"'counter'",
")",
"round",
"=",
"pyrtl",
".",
"WireVector",
"(",
"4",
")",
"counter",
".",
"next",
"<<=",
"round",
"inv_shift",
"=",
"self",
".",
"_inv_shift_rows",
"(",
"cipher_text",
")",
"inv_sub",
"=",
"self",
".",
"_sub_bytes",
"(",
"inv_shift",
",",
"True",
")",
"key_out",
"=",
"pyrtl",
".",
"mux",
"(",
"round",
",",
"*",
"reversed_key_list",
",",
"default",
"=",
"0",
")",
"add_round_out",
"=",
"self",
".",
"_add_round_key",
"(",
"add_round_in",
",",
"key_out",
")",
"inv_mix_out",
"=",
"self",
".",
"_mix_columns",
"(",
"add_round_out",
",",
"True",
")",
"with",
"pyrtl",
".",
"conditional_assignment",
":",
"with",
"reset",
"==",
"1",
":",
"round",
"|=",
"0",
"key",
".",
"next",
"|=",
"key_in",
"key_exp_in",
"|=",
"key_in",
"# to lower the number of cycles needed",
"cipher_text",
".",
"next",
"|=",
"add_round_out",
"add_round_in",
"|=",
"ciphertext_in",
"with",
"counter",
"==",
"10",
":",
"# keep everything the same",
"round",
"|=",
"counter",
"cipher_text",
".",
"next",
"|=",
"cipher_text",
"with",
"pyrtl",
".",
"otherwise",
":",
"# running through AES",
"round",
"|=",
"counter",
"+",
"1",
"key",
".",
"next",
"|=",
"key",
"key_exp_in",
"|=",
"key",
"add_round_in",
"|=",
"inv_sub",
"with",
"counter",
"==",
"9",
":",
"cipher_text",
".",
"next",
"|=",
"add_round_out",
"with",
"pyrtl",
".",
"otherwise",
":",
"cipher_text",
".",
"next",
"|=",
"inv_mix_out",
"ready",
"=",
"(",
"counter",
"==",
"10",
")",
"return",
"ready",
",",
"cipher_text"
] | Builds a multiple cycle AES Decryption state machine circuit
:param reset: a one bit signal telling the state machine
to reset and accept the current plaintext and key
:return ready, plain_text: ready is a one bit signal showing
that the decryption result (plain_text) has been calculated. | [
"Builds",
"a",
"multiple",
"cycle",
"AES",
"Decryption",
"state",
"machine",
"circuit"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/aes.py#L151-L205 |
UCSBarchlab/PyRTL | pyrtl/rtllib/aes.py | AES._g | def _g(self, word, key_expand_round):
"""
One-byte left circular rotation, substitution of each byte
"""
import numbers
self._build_memories_if_not_exists()
a = libutils.partition_wire(word, 8)
sub = [self.sbox[a[index]] for index in (3, 0, 1, 2)]
if isinstance(key_expand_round, numbers.Number):
rcon_data = self._rcon_data[key_expand_round + 1] # int value
else:
rcon_data = self.rcon[key_expand_round + 1]
sub[3] = sub[3] ^ rcon_data
return pyrtl.concat_list(sub) | python | def _g(self, word, key_expand_round):
"""
One-byte left circular rotation, substitution of each byte
"""
import numbers
self._build_memories_if_not_exists()
a = libutils.partition_wire(word, 8)
sub = [self.sbox[a[index]] for index in (3, 0, 1, 2)]
if isinstance(key_expand_round, numbers.Number):
rcon_data = self._rcon_data[key_expand_round + 1] # int value
else:
rcon_data = self.rcon[key_expand_round + 1]
sub[3] = sub[3] ^ rcon_data
return pyrtl.concat_list(sub) | [
"def",
"_g",
"(",
"self",
",",
"word",
",",
"key_expand_round",
")",
":",
"import",
"numbers",
"self",
".",
"_build_memories_if_not_exists",
"(",
")",
"a",
"=",
"libutils",
".",
"partition_wire",
"(",
"word",
",",
"8",
")",
"sub",
"=",
"[",
"self",
".",
"sbox",
"[",
"a",
"[",
"index",
"]",
"]",
"for",
"index",
"in",
"(",
"3",
",",
"0",
",",
"1",
",",
"2",
")",
"]",
"if",
"isinstance",
"(",
"key_expand_round",
",",
"numbers",
".",
"Number",
")",
":",
"rcon_data",
"=",
"self",
".",
"_rcon_data",
"[",
"key_expand_round",
"+",
"1",
"]",
"# int value",
"else",
":",
"rcon_data",
"=",
"self",
".",
"rcon",
"[",
"key_expand_round",
"+",
"1",
"]",
"sub",
"[",
"3",
"]",
"=",
"sub",
"[",
"3",
"]",
"^",
"rcon_data",
"return",
"pyrtl",
".",
"concat_list",
"(",
"sub",
")"
] | One-byte left circular rotation, substitution of each byte | [
"One",
"-",
"byte",
"left",
"circular",
"rotation",
"substitution",
"of",
"each",
"byte"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/aes.py#L223-L236 |
usrlocalben/pydux | pydux/extend.py | extend | def extend(*args):
"""shallow dictionary merge
Args:
a: dict to extend
b: dict to apply to a
Returns:
new instance of the same type as _a_, with _a_ and _b_ merged.
"""
if not args:
return {}
first = args[0]
rest = args[1:]
out = type(first)(first)
for each in rest:
out.update(each)
return out | python | def extend(*args):
"""shallow dictionary merge
Args:
a: dict to extend
b: dict to apply to a
Returns:
new instance of the same type as _a_, with _a_ and _b_ merged.
"""
if not args:
return {}
first = args[0]
rest = args[1:]
out = type(first)(first)
for each in rest:
out.update(each)
return out | [
"def",
"extend",
"(",
"*",
"args",
")",
":",
"if",
"not",
"args",
":",
"return",
"{",
"}",
"first",
"=",
"args",
"[",
"0",
"]",
"rest",
"=",
"args",
"[",
"1",
":",
"]",
"out",
"=",
"type",
"(",
"first",
")",
"(",
"first",
")",
"for",
"each",
"in",
"rest",
":",
"out",
".",
"update",
"(",
"each",
")",
"return",
"out"
] | shallow dictionary merge
Args:
a: dict to extend
b: dict to apply to a
Returns:
new instance of the same type as _a_, with _a_ and _b_ merged. | [
"shallow",
"dictionary",
"merge"
] | train | https://github.com/usrlocalben/pydux/blob/943ca1c75357b9289f55f17ff2d997a66a3313a4/pydux/extend.py#L1-L19 |
UCSBarchlab/PyRTL | pyrtl/inputoutput.py | input_from_blif | def input_from_blif(blif, block=None, merge_io_vectors=True):
""" Read an open blif file or string as input, updating the block appropriately
Assumes the blif has been flattened and their is only a single module.
Assumes that there is only one single shared clock and reset
Assumes that output is generated by Yosys with formals in a particular order
Ignores reset signal (which it assumes is input only to the flip flops)
"""
import pyparsing
import six
from pyparsing import (Word, Literal, OneOrMore, ZeroOrMore,
Suppress, Group, Keyword)
block = working_block(block)
try:
blif_string = blif.read()
except AttributeError:
if isinstance(blif, six.string_types):
blif_string = blif
else:
raise PyrtlError('input_blif expecting either open file or string')
def SKeyword(x):
return Suppress(Keyword(x))
def SLiteral(x):
return Suppress(Literal(x))
def twire(x):
""" find or make wire named x and return it """
s = block.get_wirevector_by_name(x)
if s is None:
s = WireVector(bitwidth=1, name=x)
return s
# Begin BLIF language definition
signal_start = pyparsing.alphas + '$:[]_<>\\\/'
signal_middle = pyparsing.alphas + pyparsing.nums + '$:[]_<>\\\/.'
signal_id = Word(signal_start, signal_middle)
header = SKeyword('.model') + signal_id('model_name')
input_list = Group(SKeyword('.inputs') + OneOrMore(signal_id))('input_list')
output_list = Group(SKeyword('.outputs') + OneOrMore(signal_id))('output_list')
cover_atom = Word('01-')
cover_list = Group(ZeroOrMore(cover_atom))('cover_list')
namesignal_list = Group(OneOrMore(signal_id))('namesignal_list')
name_def = Group(SKeyword('.names') + namesignal_list + cover_list)('name_def')
# asynchronous Flip-flop
dffas_formal = (SLiteral('C=') + signal_id('C') +
SLiteral('R=') + signal_id('R') +
SLiteral('D=') + signal_id('D') +
SLiteral('Q=') + signal_id('Q'))
dffas_keyword = SKeyword('$_DFF_PN0_') | SKeyword('$_DFF_PP0_')
dffas_def = Group(SKeyword('.subckt') + dffas_keyword + dffas_formal)('dffas_def')
# synchronous Flip-flop
dffs_def = Group(SKeyword('.latch') +
signal_id('D') +
signal_id('Q') +
SLiteral('re') +
signal_id('C'))('dffs_def')
command_def = name_def | dffas_def | dffs_def
command_list = Group(OneOrMore(command_def))('command_list')
footer = SKeyword('.end')
model_def = Group(header + input_list + output_list + command_list + footer)
model_list = OneOrMore(model_def)
parser = model_list.ignore(pyparsing.pythonStyleComment)
# Begin actually reading and parsing the BLIF file
result = parser.parseString(blif_string, parseAll=True)
# Blif file with multiple models (currently only handles one flattened models)
assert(len(result) == 1)
clk_set = set([])
ff_clk_set = set([])
def extract_inputs(model):
start_names = [re.sub(r'\[([0-9]+)\]$', '', x) for x in model['input_list']]
name_counts = collections.Counter(start_names)
for input_name in name_counts:
bitwidth = name_counts[input_name]
if input_name == 'clk':
clk_set.add(input_name)
elif not merge_io_vectors or bitwidth == 1:
block.add_wirevector(Input(bitwidth=1, name=input_name))
else:
wire_in = Input(bitwidth=bitwidth, name=input_name, block=block)
for i in range(bitwidth):
bit_name = input_name + '[' + str(i) + ']'
bit_wire = WireVector(bitwidth=1, name=bit_name, block=block)
bit_wire <<= wire_in[i]
def extract_outputs(model):
start_names = [re.sub(r'\[([0-9]+)\]$', '', x) for x in model['output_list']]
name_counts = collections.Counter(start_names)
for output_name in name_counts:
bitwidth = name_counts[output_name]
if not merge_io_vectors or bitwidth == 1:
block.add_wirevector(Output(bitwidth=1, name=output_name))
else:
wire_out = Output(bitwidth=bitwidth, name=output_name, block=block)
bit_list = []
for i in range(bitwidth):
bit_name = output_name + '[' + str(i) + ']'
bit_wire = WireVector(bitwidth=1, name=bit_name, block=block)
bit_list.append(bit_wire)
wire_out <<= concat(*bit_list)
def extract_commands(model):
# for each "command" (dff or net) in the model
for command in model['command_list']:
# if it is a net (specified as a cover)
if command.getName() == 'name_def':
extract_cover(command)
# else if the command is a d flop flop
elif command.getName() == 'dffas_def' or command.getName() == 'dffs_def':
extract_flop(command)
else:
raise PyrtlError('unknown command type')
def extract_cover(command):
netio = command['namesignal_list']
if len(command['cover_list']) == 0:
output_wire = twire(netio[0])
output_wire <<= Const(0, bitwidth=1, block=block) # const "FALSE"
elif command['cover_list'].asList() == ['1']:
output_wire = twire(netio[0])
output_wire <<= Const(1, bitwidth=1, block=block) # const "TRUE"
elif command['cover_list'].asList() == ['1', '1']:
# Populate clock list if one input is already a clock
if(netio[1] in clk_set):
clk_set.add(netio[0])
elif(netio[0] in clk_set):
clk_set.add(netio[1])
else:
output_wire = twire(netio[1])
output_wire <<= twire(netio[0]) # simple wire
elif command['cover_list'].asList() == ['0', '1']:
output_wire = twire(netio[1])
output_wire <<= ~ twire(netio[0]) # not gate
elif command['cover_list'].asList() == ['11', '1']:
output_wire = twire(netio[2])
output_wire <<= twire(netio[0]) & twire(netio[1]) # and gate
elif command['cover_list'].asList() == ['00', '1']:
output_wire = twire(netio[2])
output_wire <<= ~ (twire(netio[0]) | twire(netio[1])) # nor gate
elif command['cover_list'].asList() == ['1-', '1', '-1', '1']:
output_wire = twire(netio[2])
output_wire <<= twire(netio[0]) | twire(netio[1]) # or gate
elif command['cover_list'].asList() == ['10', '1', '01', '1']:
output_wire = twire(netio[2])
output_wire <<= twire(netio[0]) ^ twire(netio[1]) # xor gate
elif command['cover_list'].asList() == ['1-0', '1', '-11', '1']:
output_wire = twire(netio[3])
output_wire <<= (twire(netio[0]) & ~ twire(netio[2])) \
| (twire(netio[1]) & twire(netio[2])) # mux
elif command['cover_list'].asList() == ['-00', '1', '0-0', '1']:
output_wire = twire(netio[3])
output_wire <<= (~twire(netio[1]) & ~twire(netio[2])) \
| (~twire(netio[0]) & ~twire(netio[2]))
else:
raise PyrtlError('Blif file with unknown logic cover set "%s"'
'(currently gates are hard coded)' % command['cover_list'])
def extract_flop(command):
if(command['C'] not in ff_clk_set):
ff_clk_set.add(command['C'])
# Create register and assign next state to D and output to Q
regname = command['Q'] + '_reg'
flop = Register(bitwidth=1, name=regname)
flop.next <<= twire(command['D'])
flop_output = twire(command['Q'])
flop_output <<= flop
for model in result:
extract_inputs(model)
extract_outputs(model)
extract_commands(model) | python | def input_from_blif(blif, block=None, merge_io_vectors=True):
""" Read an open blif file or string as input, updating the block appropriately
Assumes the blif has been flattened and their is only a single module.
Assumes that there is only one single shared clock and reset
Assumes that output is generated by Yosys with formals in a particular order
Ignores reset signal (which it assumes is input only to the flip flops)
"""
import pyparsing
import six
from pyparsing import (Word, Literal, OneOrMore, ZeroOrMore,
Suppress, Group, Keyword)
block = working_block(block)
try:
blif_string = blif.read()
except AttributeError:
if isinstance(blif, six.string_types):
blif_string = blif
else:
raise PyrtlError('input_blif expecting either open file or string')
def SKeyword(x):
return Suppress(Keyword(x))
def SLiteral(x):
return Suppress(Literal(x))
def twire(x):
""" find or make wire named x and return it """
s = block.get_wirevector_by_name(x)
if s is None:
s = WireVector(bitwidth=1, name=x)
return s
# Begin BLIF language definition
signal_start = pyparsing.alphas + '$:[]_<>\\\/'
signal_middle = pyparsing.alphas + pyparsing.nums + '$:[]_<>\\\/.'
signal_id = Word(signal_start, signal_middle)
header = SKeyword('.model') + signal_id('model_name')
input_list = Group(SKeyword('.inputs') + OneOrMore(signal_id))('input_list')
output_list = Group(SKeyword('.outputs') + OneOrMore(signal_id))('output_list')
cover_atom = Word('01-')
cover_list = Group(ZeroOrMore(cover_atom))('cover_list')
namesignal_list = Group(OneOrMore(signal_id))('namesignal_list')
name_def = Group(SKeyword('.names') + namesignal_list + cover_list)('name_def')
# asynchronous Flip-flop
dffas_formal = (SLiteral('C=') + signal_id('C') +
SLiteral('R=') + signal_id('R') +
SLiteral('D=') + signal_id('D') +
SLiteral('Q=') + signal_id('Q'))
dffas_keyword = SKeyword('$_DFF_PN0_') | SKeyword('$_DFF_PP0_')
dffas_def = Group(SKeyword('.subckt') + dffas_keyword + dffas_formal)('dffas_def')
# synchronous Flip-flop
dffs_def = Group(SKeyword('.latch') +
signal_id('D') +
signal_id('Q') +
SLiteral('re') +
signal_id('C'))('dffs_def')
command_def = name_def | dffas_def | dffs_def
command_list = Group(OneOrMore(command_def))('command_list')
footer = SKeyword('.end')
model_def = Group(header + input_list + output_list + command_list + footer)
model_list = OneOrMore(model_def)
parser = model_list.ignore(pyparsing.pythonStyleComment)
# Begin actually reading and parsing the BLIF file
result = parser.parseString(blif_string, parseAll=True)
# Blif file with multiple models (currently only handles one flattened models)
assert(len(result) == 1)
clk_set = set([])
ff_clk_set = set([])
def extract_inputs(model):
start_names = [re.sub(r'\[([0-9]+)\]$', '', x) for x in model['input_list']]
name_counts = collections.Counter(start_names)
for input_name in name_counts:
bitwidth = name_counts[input_name]
if input_name == 'clk':
clk_set.add(input_name)
elif not merge_io_vectors or bitwidth == 1:
block.add_wirevector(Input(bitwidth=1, name=input_name))
else:
wire_in = Input(bitwidth=bitwidth, name=input_name, block=block)
for i in range(bitwidth):
bit_name = input_name + '[' + str(i) + ']'
bit_wire = WireVector(bitwidth=1, name=bit_name, block=block)
bit_wire <<= wire_in[i]
def extract_outputs(model):
start_names = [re.sub(r'\[([0-9]+)\]$', '', x) for x in model['output_list']]
name_counts = collections.Counter(start_names)
for output_name in name_counts:
bitwidth = name_counts[output_name]
if not merge_io_vectors or bitwidth == 1:
block.add_wirevector(Output(bitwidth=1, name=output_name))
else:
wire_out = Output(bitwidth=bitwidth, name=output_name, block=block)
bit_list = []
for i in range(bitwidth):
bit_name = output_name + '[' + str(i) + ']'
bit_wire = WireVector(bitwidth=1, name=bit_name, block=block)
bit_list.append(bit_wire)
wire_out <<= concat(*bit_list)
def extract_commands(model):
# for each "command" (dff or net) in the model
for command in model['command_list']:
# if it is a net (specified as a cover)
if command.getName() == 'name_def':
extract_cover(command)
# else if the command is a d flop flop
elif command.getName() == 'dffas_def' or command.getName() == 'dffs_def':
extract_flop(command)
else:
raise PyrtlError('unknown command type')
def extract_cover(command):
netio = command['namesignal_list']
if len(command['cover_list']) == 0:
output_wire = twire(netio[0])
output_wire <<= Const(0, bitwidth=1, block=block) # const "FALSE"
elif command['cover_list'].asList() == ['1']:
output_wire = twire(netio[0])
output_wire <<= Const(1, bitwidth=1, block=block) # const "TRUE"
elif command['cover_list'].asList() == ['1', '1']:
# Populate clock list if one input is already a clock
if(netio[1] in clk_set):
clk_set.add(netio[0])
elif(netio[0] in clk_set):
clk_set.add(netio[1])
else:
output_wire = twire(netio[1])
output_wire <<= twire(netio[0]) # simple wire
elif command['cover_list'].asList() == ['0', '1']:
output_wire = twire(netio[1])
output_wire <<= ~ twire(netio[0]) # not gate
elif command['cover_list'].asList() == ['11', '1']:
output_wire = twire(netio[2])
output_wire <<= twire(netio[0]) & twire(netio[1]) # and gate
elif command['cover_list'].asList() == ['00', '1']:
output_wire = twire(netio[2])
output_wire <<= ~ (twire(netio[0]) | twire(netio[1])) # nor gate
elif command['cover_list'].asList() == ['1-', '1', '-1', '1']:
output_wire = twire(netio[2])
output_wire <<= twire(netio[0]) | twire(netio[1]) # or gate
elif command['cover_list'].asList() == ['10', '1', '01', '1']:
output_wire = twire(netio[2])
output_wire <<= twire(netio[0]) ^ twire(netio[1]) # xor gate
elif command['cover_list'].asList() == ['1-0', '1', '-11', '1']:
output_wire = twire(netio[3])
output_wire <<= (twire(netio[0]) & ~ twire(netio[2])) \
| (twire(netio[1]) & twire(netio[2])) # mux
elif command['cover_list'].asList() == ['-00', '1', '0-0', '1']:
output_wire = twire(netio[3])
output_wire <<= (~twire(netio[1]) & ~twire(netio[2])) \
| (~twire(netio[0]) & ~twire(netio[2]))
else:
raise PyrtlError('Blif file with unknown logic cover set "%s"'
'(currently gates are hard coded)' % command['cover_list'])
def extract_flop(command):
if(command['C'] not in ff_clk_set):
ff_clk_set.add(command['C'])
# Create register and assign next state to D and output to Q
regname = command['Q'] + '_reg'
flop = Register(bitwidth=1, name=regname)
flop.next <<= twire(command['D'])
flop_output = twire(command['Q'])
flop_output <<= flop
for model in result:
extract_inputs(model)
extract_outputs(model)
extract_commands(model) | [
"def",
"input_from_blif",
"(",
"blif",
",",
"block",
"=",
"None",
",",
"merge_io_vectors",
"=",
"True",
")",
":",
"import",
"pyparsing",
"import",
"six",
"from",
"pyparsing",
"import",
"(",
"Word",
",",
"Literal",
",",
"OneOrMore",
",",
"ZeroOrMore",
",",
"Suppress",
",",
"Group",
",",
"Keyword",
")",
"block",
"=",
"working_block",
"(",
"block",
")",
"try",
":",
"blif_string",
"=",
"blif",
".",
"read",
"(",
")",
"except",
"AttributeError",
":",
"if",
"isinstance",
"(",
"blif",
",",
"six",
".",
"string_types",
")",
":",
"blif_string",
"=",
"blif",
"else",
":",
"raise",
"PyrtlError",
"(",
"'input_blif expecting either open file or string'",
")",
"def",
"SKeyword",
"(",
"x",
")",
":",
"return",
"Suppress",
"(",
"Keyword",
"(",
"x",
")",
")",
"def",
"SLiteral",
"(",
"x",
")",
":",
"return",
"Suppress",
"(",
"Literal",
"(",
"x",
")",
")",
"def",
"twire",
"(",
"x",
")",
":",
"\"\"\" find or make wire named x and return it \"\"\"",
"s",
"=",
"block",
".",
"get_wirevector_by_name",
"(",
"x",
")",
"if",
"s",
"is",
"None",
":",
"s",
"=",
"WireVector",
"(",
"bitwidth",
"=",
"1",
",",
"name",
"=",
"x",
")",
"return",
"s",
"# Begin BLIF language definition",
"signal_start",
"=",
"pyparsing",
".",
"alphas",
"+",
"'$:[]_<>\\\\\\/'",
"signal_middle",
"=",
"pyparsing",
".",
"alphas",
"+",
"pyparsing",
".",
"nums",
"+",
"'$:[]_<>\\\\\\/.'",
"signal_id",
"=",
"Word",
"(",
"signal_start",
",",
"signal_middle",
")",
"header",
"=",
"SKeyword",
"(",
"'.model'",
")",
"+",
"signal_id",
"(",
"'model_name'",
")",
"input_list",
"=",
"Group",
"(",
"SKeyword",
"(",
"'.inputs'",
")",
"+",
"OneOrMore",
"(",
"signal_id",
")",
")",
"(",
"'input_list'",
")",
"output_list",
"=",
"Group",
"(",
"SKeyword",
"(",
"'.outputs'",
")",
"+",
"OneOrMore",
"(",
"signal_id",
")",
")",
"(",
"'output_list'",
")",
"cover_atom",
"=",
"Word",
"(",
"'01-'",
")",
"cover_list",
"=",
"Group",
"(",
"ZeroOrMore",
"(",
"cover_atom",
")",
")",
"(",
"'cover_list'",
")",
"namesignal_list",
"=",
"Group",
"(",
"OneOrMore",
"(",
"signal_id",
")",
")",
"(",
"'namesignal_list'",
")",
"name_def",
"=",
"Group",
"(",
"SKeyword",
"(",
"'.names'",
")",
"+",
"namesignal_list",
"+",
"cover_list",
")",
"(",
"'name_def'",
")",
"# asynchronous Flip-flop",
"dffas_formal",
"=",
"(",
"SLiteral",
"(",
"'C='",
")",
"+",
"signal_id",
"(",
"'C'",
")",
"+",
"SLiteral",
"(",
"'R='",
")",
"+",
"signal_id",
"(",
"'R'",
")",
"+",
"SLiteral",
"(",
"'D='",
")",
"+",
"signal_id",
"(",
"'D'",
")",
"+",
"SLiteral",
"(",
"'Q='",
")",
"+",
"signal_id",
"(",
"'Q'",
")",
")",
"dffas_keyword",
"=",
"SKeyword",
"(",
"'$_DFF_PN0_'",
")",
"|",
"SKeyword",
"(",
"'$_DFF_PP0_'",
")",
"dffas_def",
"=",
"Group",
"(",
"SKeyword",
"(",
"'.subckt'",
")",
"+",
"dffas_keyword",
"+",
"dffas_formal",
")",
"(",
"'dffas_def'",
")",
"# synchronous Flip-flop",
"dffs_def",
"=",
"Group",
"(",
"SKeyword",
"(",
"'.latch'",
")",
"+",
"signal_id",
"(",
"'D'",
")",
"+",
"signal_id",
"(",
"'Q'",
")",
"+",
"SLiteral",
"(",
"'re'",
")",
"+",
"signal_id",
"(",
"'C'",
")",
")",
"(",
"'dffs_def'",
")",
"command_def",
"=",
"name_def",
"|",
"dffas_def",
"|",
"dffs_def",
"command_list",
"=",
"Group",
"(",
"OneOrMore",
"(",
"command_def",
")",
")",
"(",
"'command_list'",
")",
"footer",
"=",
"SKeyword",
"(",
"'.end'",
")",
"model_def",
"=",
"Group",
"(",
"header",
"+",
"input_list",
"+",
"output_list",
"+",
"command_list",
"+",
"footer",
")",
"model_list",
"=",
"OneOrMore",
"(",
"model_def",
")",
"parser",
"=",
"model_list",
".",
"ignore",
"(",
"pyparsing",
".",
"pythonStyleComment",
")",
"# Begin actually reading and parsing the BLIF file",
"result",
"=",
"parser",
".",
"parseString",
"(",
"blif_string",
",",
"parseAll",
"=",
"True",
")",
"# Blif file with multiple models (currently only handles one flattened models)",
"assert",
"(",
"len",
"(",
"result",
")",
"==",
"1",
")",
"clk_set",
"=",
"set",
"(",
"[",
"]",
")",
"ff_clk_set",
"=",
"set",
"(",
"[",
"]",
")",
"def",
"extract_inputs",
"(",
"model",
")",
":",
"start_names",
"=",
"[",
"re",
".",
"sub",
"(",
"r'\\[([0-9]+)\\]$'",
",",
"''",
",",
"x",
")",
"for",
"x",
"in",
"model",
"[",
"'input_list'",
"]",
"]",
"name_counts",
"=",
"collections",
".",
"Counter",
"(",
"start_names",
")",
"for",
"input_name",
"in",
"name_counts",
":",
"bitwidth",
"=",
"name_counts",
"[",
"input_name",
"]",
"if",
"input_name",
"==",
"'clk'",
":",
"clk_set",
".",
"add",
"(",
"input_name",
")",
"elif",
"not",
"merge_io_vectors",
"or",
"bitwidth",
"==",
"1",
":",
"block",
".",
"add_wirevector",
"(",
"Input",
"(",
"bitwidth",
"=",
"1",
",",
"name",
"=",
"input_name",
")",
")",
"else",
":",
"wire_in",
"=",
"Input",
"(",
"bitwidth",
"=",
"bitwidth",
",",
"name",
"=",
"input_name",
",",
"block",
"=",
"block",
")",
"for",
"i",
"in",
"range",
"(",
"bitwidth",
")",
":",
"bit_name",
"=",
"input_name",
"+",
"'['",
"+",
"str",
"(",
"i",
")",
"+",
"']'",
"bit_wire",
"=",
"WireVector",
"(",
"bitwidth",
"=",
"1",
",",
"name",
"=",
"bit_name",
",",
"block",
"=",
"block",
")",
"bit_wire",
"<<=",
"wire_in",
"[",
"i",
"]",
"def",
"extract_outputs",
"(",
"model",
")",
":",
"start_names",
"=",
"[",
"re",
".",
"sub",
"(",
"r'\\[([0-9]+)\\]$'",
",",
"''",
",",
"x",
")",
"for",
"x",
"in",
"model",
"[",
"'output_list'",
"]",
"]",
"name_counts",
"=",
"collections",
".",
"Counter",
"(",
"start_names",
")",
"for",
"output_name",
"in",
"name_counts",
":",
"bitwidth",
"=",
"name_counts",
"[",
"output_name",
"]",
"if",
"not",
"merge_io_vectors",
"or",
"bitwidth",
"==",
"1",
":",
"block",
".",
"add_wirevector",
"(",
"Output",
"(",
"bitwidth",
"=",
"1",
",",
"name",
"=",
"output_name",
")",
")",
"else",
":",
"wire_out",
"=",
"Output",
"(",
"bitwidth",
"=",
"bitwidth",
",",
"name",
"=",
"output_name",
",",
"block",
"=",
"block",
")",
"bit_list",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"bitwidth",
")",
":",
"bit_name",
"=",
"output_name",
"+",
"'['",
"+",
"str",
"(",
"i",
")",
"+",
"']'",
"bit_wire",
"=",
"WireVector",
"(",
"bitwidth",
"=",
"1",
",",
"name",
"=",
"bit_name",
",",
"block",
"=",
"block",
")",
"bit_list",
".",
"append",
"(",
"bit_wire",
")",
"wire_out",
"<<=",
"concat",
"(",
"*",
"bit_list",
")",
"def",
"extract_commands",
"(",
"model",
")",
":",
"# for each \"command\" (dff or net) in the model",
"for",
"command",
"in",
"model",
"[",
"'command_list'",
"]",
":",
"# if it is a net (specified as a cover)",
"if",
"command",
".",
"getName",
"(",
")",
"==",
"'name_def'",
":",
"extract_cover",
"(",
"command",
")",
"# else if the command is a d flop flop",
"elif",
"command",
".",
"getName",
"(",
")",
"==",
"'dffas_def'",
"or",
"command",
".",
"getName",
"(",
")",
"==",
"'dffs_def'",
":",
"extract_flop",
"(",
"command",
")",
"else",
":",
"raise",
"PyrtlError",
"(",
"'unknown command type'",
")",
"def",
"extract_cover",
"(",
"command",
")",
":",
"netio",
"=",
"command",
"[",
"'namesignal_list'",
"]",
"if",
"len",
"(",
"command",
"[",
"'cover_list'",
"]",
")",
"==",
"0",
":",
"output_wire",
"=",
"twire",
"(",
"netio",
"[",
"0",
"]",
")",
"output_wire",
"<<=",
"Const",
"(",
"0",
",",
"bitwidth",
"=",
"1",
",",
"block",
"=",
"block",
")",
"# const \"FALSE\"",
"elif",
"command",
"[",
"'cover_list'",
"]",
".",
"asList",
"(",
")",
"==",
"[",
"'1'",
"]",
":",
"output_wire",
"=",
"twire",
"(",
"netio",
"[",
"0",
"]",
")",
"output_wire",
"<<=",
"Const",
"(",
"1",
",",
"bitwidth",
"=",
"1",
",",
"block",
"=",
"block",
")",
"# const \"TRUE\"",
"elif",
"command",
"[",
"'cover_list'",
"]",
".",
"asList",
"(",
")",
"==",
"[",
"'1'",
",",
"'1'",
"]",
":",
"# Populate clock list if one input is already a clock",
"if",
"(",
"netio",
"[",
"1",
"]",
"in",
"clk_set",
")",
":",
"clk_set",
".",
"add",
"(",
"netio",
"[",
"0",
"]",
")",
"elif",
"(",
"netio",
"[",
"0",
"]",
"in",
"clk_set",
")",
":",
"clk_set",
".",
"add",
"(",
"netio",
"[",
"1",
"]",
")",
"else",
":",
"output_wire",
"=",
"twire",
"(",
"netio",
"[",
"1",
"]",
")",
"output_wire",
"<<=",
"twire",
"(",
"netio",
"[",
"0",
"]",
")",
"# simple wire",
"elif",
"command",
"[",
"'cover_list'",
"]",
".",
"asList",
"(",
")",
"==",
"[",
"'0'",
",",
"'1'",
"]",
":",
"output_wire",
"=",
"twire",
"(",
"netio",
"[",
"1",
"]",
")",
"output_wire",
"<<=",
"~",
"twire",
"(",
"netio",
"[",
"0",
"]",
")",
"# not gate",
"elif",
"command",
"[",
"'cover_list'",
"]",
".",
"asList",
"(",
")",
"==",
"[",
"'11'",
",",
"'1'",
"]",
":",
"output_wire",
"=",
"twire",
"(",
"netio",
"[",
"2",
"]",
")",
"output_wire",
"<<=",
"twire",
"(",
"netio",
"[",
"0",
"]",
")",
"&",
"twire",
"(",
"netio",
"[",
"1",
"]",
")",
"# and gate",
"elif",
"command",
"[",
"'cover_list'",
"]",
".",
"asList",
"(",
")",
"==",
"[",
"'00'",
",",
"'1'",
"]",
":",
"output_wire",
"=",
"twire",
"(",
"netio",
"[",
"2",
"]",
")",
"output_wire",
"<<=",
"~",
"(",
"twire",
"(",
"netio",
"[",
"0",
"]",
")",
"|",
"twire",
"(",
"netio",
"[",
"1",
"]",
")",
")",
"# nor gate",
"elif",
"command",
"[",
"'cover_list'",
"]",
".",
"asList",
"(",
")",
"==",
"[",
"'1-'",
",",
"'1'",
",",
"'-1'",
",",
"'1'",
"]",
":",
"output_wire",
"=",
"twire",
"(",
"netio",
"[",
"2",
"]",
")",
"output_wire",
"<<=",
"twire",
"(",
"netio",
"[",
"0",
"]",
")",
"|",
"twire",
"(",
"netio",
"[",
"1",
"]",
")",
"# or gate",
"elif",
"command",
"[",
"'cover_list'",
"]",
".",
"asList",
"(",
")",
"==",
"[",
"'10'",
",",
"'1'",
",",
"'01'",
",",
"'1'",
"]",
":",
"output_wire",
"=",
"twire",
"(",
"netio",
"[",
"2",
"]",
")",
"output_wire",
"<<=",
"twire",
"(",
"netio",
"[",
"0",
"]",
")",
"^",
"twire",
"(",
"netio",
"[",
"1",
"]",
")",
"# xor gate",
"elif",
"command",
"[",
"'cover_list'",
"]",
".",
"asList",
"(",
")",
"==",
"[",
"'1-0'",
",",
"'1'",
",",
"'-11'",
",",
"'1'",
"]",
":",
"output_wire",
"=",
"twire",
"(",
"netio",
"[",
"3",
"]",
")",
"output_wire",
"<<=",
"(",
"twire",
"(",
"netio",
"[",
"0",
"]",
")",
"&",
"~",
"twire",
"(",
"netio",
"[",
"2",
"]",
")",
")",
"|",
"(",
"twire",
"(",
"netio",
"[",
"1",
"]",
")",
"&",
"twire",
"(",
"netio",
"[",
"2",
"]",
")",
")",
"# mux",
"elif",
"command",
"[",
"'cover_list'",
"]",
".",
"asList",
"(",
")",
"==",
"[",
"'-00'",
",",
"'1'",
",",
"'0-0'",
",",
"'1'",
"]",
":",
"output_wire",
"=",
"twire",
"(",
"netio",
"[",
"3",
"]",
")",
"output_wire",
"<<=",
"(",
"~",
"twire",
"(",
"netio",
"[",
"1",
"]",
")",
"&",
"~",
"twire",
"(",
"netio",
"[",
"2",
"]",
")",
")",
"|",
"(",
"~",
"twire",
"(",
"netio",
"[",
"0",
"]",
")",
"&",
"~",
"twire",
"(",
"netio",
"[",
"2",
"]",
")",
")",
"else",
":",
"raise",
"PyrtlError",
"(",
"'Blif file with unknown logic cover set \"%s\"'",
"'(currently gates are hard coded)'",
"%",
"command",
"[",
"'cover_list'",
"]",
")",
"def",
"extract_flop",
"(",
"command",
")",
":",
"if",
"(",
"command",
"[",
"'C'",
"]",
"not",
"in",
"ff_clk_set",
")",
":",
"ff_clk_set",
".",
"add",
"(",
"command",
"[",
"'C'",
"]",
")",
"# Create register and assign next state to D and output to Q",
"regname",
"=",
"command",
"[",
"'Q'",
"]",
"+",
"'_reg'",
"flop",
"=",
"Register",
"(",
"bitwidth",
"=",
"1",
",",
"name",
"=",
"regname",
")",
"flop",
".",
"next",
"<<=",
"twire",
"(",
"command",
"[",
"'D'",
"]",
")",
"flop_output",
"=",
"twire",
"(",
"command",
"[",
"'Q'",
"]",
")",
"flop_output",
"<<=",
"flop",
"for",
"model",
"in",
"result",
":",
"extract_inputs",
"(",
"model",
")",
"extract_outputs",
"(",
"model",
")",
"extract_commands",
"(",
"model",
")"
] | Read an open blif file or string as input, updating the block appropriately
Assumes the blif has been flattened and their is only a single module.
Assumes that there is only one single shared clock and reset
Assumes that output is generated by Yosys with formals in a particular order
Ignores reset signal (which it assumes is input only to the flip flops) | [
"Read",
"an",
"open",
"blif",
"file",
"or",
"string",
"as",
"input",
"updating",
"the",
"block",
"appropriately"
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/inputoutput.py#L26-L206 |
UCSBarchlab/PyRTL | pyrtl/inputoutput.py | output_to_firrtl | def output_to_firrtl(open_file, rom_blocks=None, block=None):
""" Output the block as firrtl code to the output file.
Output_to_firrtl(open_file, rom_block, block)
If rom is intialized in pyrtl code, you can pass in the rom_blocks as a list [rom1, rom2, ...]
"""
block = working_block(block)
f = open_file
# write out all the implicit stuff
f.write("circuit Example : \n")
f.write(" module Example : \n")
f.write(" input clock : Clock\n input reset : UInt<1>\n")
# write out IO signals, wires and registers
wireRegDefs = ""
for wire in list(block.wirevector_subset()):
if type(wire) == Input:
f.write(" input %s : UInt<%d>\n" % (wire.name, wire.bitwidth))
elif type(wire) == Output:
f.write(" output %s : UInt<%d>\n" % (wire.name, wire.bitwidth))
elif type(wire) == WireVector:
wireRegDefs += " wire {} : UInt<{}>\n".format(wire.name, wire.bitwidth)
elif type(wire) == Register:
wireRegDefs += " reg {} : UInt<{}>, clock\n".format(wire.name, wire.bitwidth)
elif type(wire) == Const:
# some const is in the form like const_0_1'b1, is this legal operation?
wire.name = wire.name.split("'").pop(0)
wireRegDefs += " node {} = UInt<{}>({})\n".format(wire.name, wire.bitwidth, wire.val)
else:
return 1
f.write(wireRegDefs)
f.write("\n")
# write "Main"
node_cntr = 0
initializedMem = []
for log_net in list(block.logic_subset()):
if log_net.op == '&':
f.write(" %s <= and(%s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[1].name))
elif log_net.op == '|':
f.write(" %s <= or(%s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[1].name))
elif log_net.op == '^':
f.write(" %s <= xor(%s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[1].name))
elif log_net.op == 'n':
f.write(" node T_%d = and(%s, %s)\n" % (node_cntr, log_net.args[0].name,
log_net.args[1].name))
f.write(" %s <= not(T_%d)\n" % (log_net.dests[0].name, node_cntr))
node_cntr += 1
elif log_net.op == '~':
f.write(" %s <= not(%s)\n" % (log_net.dests[0].name, log_net.args[0].name))
elif log_net.op == '+':
f.write(" %s <= add(%s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[1].name))
elif log_net.op == '-':
f.write(" %s <= sub(%s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[1].name))
elif log_net.op == '*':
f.write(" %s <= mul(%s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[1].name))
elif log_net.op == '=':
f.write(" %s <= eq(%s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[1].name))
elif log_net.op == '<':
f.write(" %s <= lt(%s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[1].name))
elif log_net.op == '>':
f.write(" %s <= gt(%s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[1].name))
elif log_net.op == 'w':
f.write(" %s <= %s\n" % (log_net.dests[0].name, log_net.args[0].name))
elif log_net.op == 'x':
f.write(" %s <= mux(%s, %s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[2].name, log_net.args[1].name))
elif log_net.op == 'c':
f.write(" %s <= cat(%s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[1].name))
elif log_net.op == 's':
selEnd = log_net.op_param[0]
if len(log_net.op_param) < 2:
selBegin = selEnd
else:
selBegin = log_net.op_param[len(log_net.op_param)-1]
f.write(" %s <= bits(%s, %s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
selBegin, selEnd))
elif log_net.op == 'r':
f.write(" %s <= mux(reset, UInt<%s>(0), %s)\n" %
(log_net.dests[0].name, log_net.dests[0].bitwidth, log_net.args[0].name))
elif log_net.op == 'm':
# if there are rom blocks, need to be initialized
if rom_blocks is not None:
if not log_net.op_param[0] in initializedMem:
initializedMem.append(log_net.op_param[0])
# find corresponding rom block according to memid
curr_rom = next((x for x in rom_blocks if x.id == log_net.op_param[0]), None)
f.write(" wire %s : UInt<%s>[%s]\n" %
(log_net.op_param[1].name, log_net.op_param[1].bitwidth,
2**log_net.op_param[1].addrwidth))
# if rom data is a function, calculate the data first
if callable(curr_rom.data):
romdata = [curr_rom.data(i) for i in range(2**curr_rom.addrwidth)]
curr_rom.data = romdata
# write rom block initialization data
for i in range(len(curr_rom.data)):
f.write(" %s[%s] <= UInt<%s>(%s)\n" %
(log_net.op_param[1].name, i, log_net.op_param[1].bitwidth,
curr_rom.data[i]))
# write the connection
f.write(" %s <= %s[%s]\n" % (log_net.dests[0].name, log_net.op_param[1].name,
log_net.args[0].name))
else:
if not log_net.op_param[0] in initializedMem:
initializedMem.append(log_net.op_param[0])
f.write(" cmem %s_%s : UInt<%s>[%s]\n" %
(log_net.op_param[1].name, log_net.op_param[0],
log_net.op_param[1].bitwidth, 2**log_net.op_param[1].addrwidth))
f.write(" infer mport T_%d = %s_%s[%s], clock\n" %
(node_cntr, log_net.op_param[1].name, log_net.op_param[0],
log_net.args[0].name))
f.write(" %s <= T_%d\n" % (log_net.dests[0].name, node_cntr))
node_cntr += 1
elif log_net.op == '@':
if not log_net.op_param[0] in initializedMem:
initializedMem.append(log_net.op_param[0])
f.write(" cmem %s_%s : UInt<%s>[%s]\n" %
(log_net.op_param[1].name, log_net.op_param[0],
log_net.op_param[1].bitwidth, 2**log_net.op_param[1].addrwidth))
f.write(" when %s :\n" % log_net.args[2].name)
f.write(" infer mport T_%d = %s_%s[%s], clock\n" %
(node_cntr, log_net.op_param[1].name, log_net.op_param[0],
log_net.args[0].name))
f.write(" T_%d <= %s\n" % (node_cntr, log_net.args[1].name))
f.write(" skip\n")
node_cntr += 1
else:
pass
f.close()
return 0 | python | def output_to_firrtl(open_file, rom_blocks=None, block=None):
""" Output the block as firrtl code to the output file.
Output_to_firrtl(open_file, rom_block, block)
If rom is intialized in pyrtl code, you can pass in the rom_blocks as a list [rom1, rom2, ...]
"""
block = working_block(block)
f = open_file
# write out all the implicit stuff
f.write("circuit Example : \n")
f.write(" module Example : \n")
f.write(" input clock : Clock\n input reset : UInt<1>\n")
# write out IO signals, wires and registers
wireRegDefs = ""
for wire in list(block.wirevector_subset()):
if type(wire) == Input:
f.write(" input %s : UInt<%d>\n" % (wire.name, wire.bitwidth))
elif type(wire) == Output:
f.write(" output %s : UInt<%d>\n" % (wire.name, wire.bitwidth))
elif type(wire) == WireVector:
wireRegDefs += " wire {} : UInt<{}>\n".format(wire.name, wire.bitwidth)
elif type(wire) == Register:
wireRegDefs += " reg {} : UInt<{}>, clock\n".format(wire.name, wire.bitwidth)
elif type(wire) == Const:
# some const is in the form like const_0_1'b1, is this legal operation?
wire.name = wire.name.split("'").pop(0)
wireRegDefs += " node {} = UInt<{}>({})\n".format(wire.name, wire.bitwidth, wire.val)
else:
return 1
f.write(wireRegDefs)
f.write("\n")
# write "Main"
node_cntr = 0
initializedMem = []
for log_net in list(block.logic_subset()):
if log_net.op == '&':
f.write(" %s <= and(%s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[1].name))
elif log_net.op == '|':
f.write(" %s <= or(%s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[1].name))
elif log_net.op == '^':
f.write(" %s <= xor(%s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[1].name))
elif log_net.op == 'n':
f.write(" node T_%d = and(%s, %s)\n" % (node_cntr, log_net.args[0].name,
log_net.args[1].name))
f.write(" %s <= not(T_%d)\n" % (log_net.dests[0].name, node_cntr))
node_cntr += 1
elif log_net.op == '~':
f.write(" %s <= not(%s)\n" % (log_net.dests[0].name, log_net.args[0].name))
elif log_net.op == '+':
f.write(" %s <= add(%s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[1].name))
elif log_net.op == '-':
f.write(" %s <= sub(%s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[1].name))
elif log_net.op == '*':
f.write(" %s <= mul(%s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[1].name))
elif log_net.op == '=':
f.write(" %s <= eq(%s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[1].name))
elif log_net.op == '<':
f.write(" %s <= lt(%s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[1].name))
elif log_net.op == '>':
f.write(" %s <= gt(%s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[1].name))
elif log_net.op == 'w':
f.write(" %s <= %s\n" % (log_net.dests[0].name, log_net.args[0].name))
elif log_net.op == 'x':
f.write(" %s <= mux(%s, %s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[2].name, log_net.args[1].name))
elif log_net.op == 'c':
f.write(" %s <= cat(%s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
log_net.args[1].name))
elif log_net.op == 's':
selEnd = log_net.op_param[0]
if len(log_net.op_param) < 2:
selBegin = selEnd
else:
selBegin = log_net.op_param[len(log_net.op_param)-1]
f.write(" %s <= bits(%s, %s, %s)\n" % (log_net.dests[0].name, log_net.args[0].name,
selBegin, selEnd))
elif log_net.op == 'r':
f.write(" %s <= mux(reset, UInt<%s>(0), %s)\n" %
(log_net.dests[0].name, log_net.dests[0].bitwidth, log_net.args[0].name))
elif log_net.op == 'm':
# if there are rom blocks, need to be initialized
if rom_blocks is not None:
if not log_net.op_param[0] in initializedMem:
initializedMem.append(log_net.op_param[0])
# find corresponding rom block according to memid
curr_rom = next((x for x in rom_blocks if x.id == log_net.op_param[0]), None)
f.write(" wire %s : UInt<%s>[%s]\n" %
(log_net.op_param[1].name, log_net.op_param[1].bitwidth,
2**log_net.op_param[1].addrwidth))
# if rom data is a function, calculate the data first
if callable(curr_rom.data):
romdata = [curr_rom.data(i) for i in range(2**curr_rom.addrwidth)]
curr_rom.data = romdata
# write rom block initialization data
for i in range(len(curr_rom.data)):
f.write(" %s[%s] <= UInt<%s>(%s)\n" %
(log_net.op_param[1].name, i, log_net.op_param[1].bitwidth,
curr_rom.data[i]))
# write the connection
f.write(" %s <= %s[%s]\n" % (log_net.dests[0].name, log_net.op_param[1].name,
log_net.args[0].name))
else:
if not log_net.op_param[0] in initializedMem:
initializedMem.append(log_net.op_param[0])
f.write(" cmem %s_%s : UInt<%s>[%s]\n" %
(log_net.op_param[1].name, log_net.op_param[0],
log_net.op_param[1].bitwidth, 2**log_net.op_param[1].addrwidth))
f.write(" infer mport T_%d = %s_%s[%s], clock\n" %
(node_cntr, log_net.op_param[1].name, log_net.op_param[0],
log_net.args[0].name))
f.write(" %s <= T_%d\n" % (log_net.dests[0].name, node_cntr))
node_cntr += 1
elif log_net.op == '@':
if not log_net.op_param[0] in initializedMem:
initializedMem.append(log_net.op_param[0])
f.write(" cmem %s_%s : UInt<%s>[%s]\n" %
(log_net.op_param[1].name, log_net.op_param[0],
log_net.op_param[1].bitwidth, 2**log_net.op_param[1].addrwidth))
f.write(" when %s :\n" % log_net.args[2].name)
f.write(" infer mport T_%d = %s_%s[%s], clock\n" %
(node_cntr, log_net.op_param[1].name, log_net.op_param[0],
log_net.args[0].name))
f.write(" T_%d <= %s\n" % (node_cntr, log_net.args[1].name))
f.write(" skip\n")
node_cntr += 1
else:
pass
f.close()
return 0 | [
"def",
"output_to_firrtl",
"(",
"open_file",
",",
"rom_blocks",
"=",
"None",
",",
"block",
"=",
"None",
")",
":",
"block",
"=",
"working_block",
"(",
"block",
")",
"f",
"=",
"open_file",
"# write out all the implicit stuff",
"f",
".",
"write",
"(",
"\"circuit Example : \\n\"",
")",
"f",
".",
"write",
"(",
"\" module Example : \\n\"",
")",
"f",
".",
"write",
"(",
"\" input clock : Clock\\n input reset : UInt<1>\\n\"",
")",
"# write out IO signals, wires and registers",
"wireRegDefs",
"=",
"\"\"",
"for",
"wire",
"in",
"list",
"(",
"block",
".",
"wirevector_subset",
"(",
")",
")",
":",
"if",
"type",
"(",
"wire",
")",
"==",
"Input",
":",
"f",
".",
"write",
"(",
"\" input %s : UInt<%d>\\n\"",
"%",
"(",
"wire",
".",
"name",
",",
"wire",
".",
"bitwidth",
")",
")",
"elif",
"type",
"(",
"wire",
")",
"==",
"Output",
":",
"f",
".",
"write",
"(",
"\" output %s : UInt<%d>\\n\"",
"%",
"(",
"wire",
".",
"name",
",",
"wire",
".",
"bitwidth",
")",
")",
"elif",
"type",
"(",
"wire",
")",
"==",
"WireVector",
":",
"wireRegDefs",
"+=",
"\" wire {} : UInt<{}>\\n\"",
".",
"format",
"(",
"wire",
".",
"name",
",",
"wire",
".",
"bitwidth",
")",
"elif",
"type",
"(",
"wire",
")",
"==",
"Register",
":",
"wireRegDefs",
"+=",
"\" reg {} : UInt<{}>, clock\\n\"",
".",
"format",
"(",
"wire",
".",
"name",
",",
"wire",
".",
"bitwidth",
")",
"elif",
"type",
"(",
"wire",
")",
"==",
"Const",
":",
"# some const is in the form like const_0_1'b1, is this legal operation?",
"wire",
".",
"name",
"=",
"wire",
".",
"name",
".",
"split",
"(",
"\"'\"",
")",
".",
"pop",
"(",
"0",
")",
"wireRegDefs",
"+=",
"\" node {} = UInt<{}>({})\\n\"",
".",
"format",
"(",
"wire",
".",
"name",
",",
"wire",
".",
"bitwidth",
",",
"wire",
".",
"val",
")",
"else",
":",
"return",
"1",
"f",
".",
"write",
"(",
"wireRegDefs",
")",
"f",
".",
"write",
"(",
"\"\\n\"",
")",
"# write \"Main\"",
"node_cntr",
"=",
"0",
"initializedMem",
"=",
"[",
"]",
"for",
"log_net",
"in",
"list",
"(",
"block",
".",
"logic_subset",
"(",
")",
")",
":",
"if",
"log_net",
".",
"op",
"==",
"'&'",
":",
"f",
".",
"write",
"(",
"\" %s <= and(%s, %s)\\n\"",
"%",
"(",
"log_net",
".",
"dests",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"1",
"]",
".",
"name",
")",
")",
"elif",
"log_net",
".",
"op",
"==",
"'|'",
":",
"f",
".",
"write",
"(",
"\" %s <= or(%s, %s)\\n\"",
"%",
"(",
"log_net",
".",
"dests",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"1",
"]",
".",
"name",
")",
")",
"elif",
"log_net",
".",
"op",
"==",
"'^'",
":",
"f",
".",
"write",
"(",
"\" %s <= xor(%s, %s)\\n\"",
"%",
"(",
"log_net",
".",
"dests",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"1",
"]",
".",
"name",
")",
")",
"elif",
"log_net",
".",
"op",
"==",
"'n'",
":",
"f",
".",
"write",
"(",
"\" node T_%d = and(%s, %s)\\n\"",
"%",
"(",
"node_cntr",
",",
"log_net",
".",
"args",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"1",
"]",
".",
"name",
")",
")",
"f",
".",
"write",
"(",
"\" %s <= not(T_%d)\\n\"",
"%",
"(",
"log_net",
".",
"dests",
"[",
"0",
"]",
".",
"name",
",",
"node_cntr",
")",
")",
"node_cntr",
"+=",
"1",
"elif",
"log_net",
".",
"op",
"==",
"'~'",
":",
"f",
".",
"write",
"(",
"\" %s <= not(%s)\\n\"",
"%",
"(",
"log_net",
".",
"dests",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"0",
"]",
".",
"name",
")",
")",
"elif",
"log_net",
".",
"op",
"==",
"'+'",
":",
"f",
".",
"write",
"(",
"\" %s <= add(%s, %s)\\n\"",
"%",
"(",
"log_net",
".",
"dests",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"1",
"]",
".",
"name",
")",
")",
"elif",
"log_net",
".",
"op",
"==",
"'-'",
":",
"f",
".",
"write",
"(",
"\" %s <= sub(%s, %s)\\n\"",
"%",
"(",
"log_net",
".",
"dests",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"1",
"]",
".",
"name",
")",
")",
"elif",
"log_net",
".",
"op",
"==",
"'*'",
":",
"f",
".",
"write",
"(",
"\" %s <= mul(%s, %s)\\n\"",
"%",
"(",
"log_net",
".",
"dests",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"1",
"]",
".",
"name",
")",
")",
"elif",
"log_net",
".",
"op",
"==",
"'='",
":",
"f",
".",
"write",
"(",
"\" %s <= eq(%s, %s)\\n\"",
"%",
"(",
"log_net",
".",
"dests",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"1",
"]",
".",
"name",
")",
")",
"elif",
"log_net",
".",
"op",
"==",
"'<'",
":",
"f",
".",
"write",
"(",
"\" %s <= lt(%s, %s)\\n\"",
"%",
"(",
"log_net",
".",
"dests",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"1",
"]",
".",
"name",
")",
")",
"elif",
"log_net",
".",
"op",
"==",
"'>'",
":",
"f",
".",
"write",
"(",
"\" %s <= gt(%s, %s)\\n\"",
"%",
"(",
"log_net",
".",
"dests",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"1",
"]",
".",
"name",
")",
")",
"elif",
"log_net",
".",
"op",
"==",
"'w'",
":",
"f",
".",
"write",
"(",
"\" %s <= %s\\n\"",
"%",
"(",
"log_net",
".",
"dests",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"0",
"]",
".",
"name",
")",
")",
"elif",
"log_net",
".",
"op",
"==",
"'x'",
":",
"f",
".",
"write",
"(",
"\" %s <= mux(%s, %s, %s)\\n\"",
"%",
"(",
"log_net",
".",
"dests",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"2",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"1",
"]",
".",
"name",
")",
")",
"elif",
"log_net",
".",
"op",
"==",
"'c'",
":",
"f",
".",
"write",
"(",
"\" %s <= cat(%s, %s)\\n\"",
"%",
"(",
"log_net",
".",
"dests",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"1",
"]",
".",
"name",
")",
")",
"elif",
"log_net",
".",
"op",
"==",
"'s'",
":",
"selEnd",
"=",
"log_net",
".",
"op_param",
"[",
"0",
"]",
"if",
"len",
"(",
"log_net",
".",
"op_param",
")",
"<",
"2",
":",
"selBegin",
"=",
"selEnd",
"else",
":",
"selBegin",
"=",
"log_net",
".",
"op_param",
"[",
"len",
"(",
"log_net",
".",
"op_param",
")",
"-",
"1",
"]",
"f",
".",
"write",
"(",
"\" %s <= bits(%s, %s, %s)\\n\"",
"%",
"(",
"log_net",
".",
"dests",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"0",
"]",
".",
"name",
",",
"selBegin",
",",
"selEnd",
")",
")",
"elif",
"log_net",
".",
"op",
"==",
"'r'",
":",
"f",
".",
"write",
"(",
"\" %s <= mux(reset, UInt<%s>(0), %s)\\n\"",
"%",
"(",
"log_net",
".",
"dests",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"dests",
"[",
"0",
"]",
".",
"bitwidth",
",",
"log_net",
".",
"args",
"[",
"0",
"]",
".",
"name",
")",
")",
"elif",
"log_net",
".",
"op",
"==",
"'m'",
":",
"# if there are rom blocks, need to be initialized",
"if",
"rom_blocks",
"is",
"not",
"None",
":",
"if",
"not",
"log_net",
".",
"op_param",
"[",
"0",
"]",
"in",
"initializedMem",
":",
"initializedMem",
".",
"append",
"(",
"log_net",
".",
"op_param",
"[",
"0",
"]",
")",
"# find corresponding rom block according to memid",
"curr_rom",
"=",
"next",
"(",
"(",
"x",
"for",
"x",
"in",
"rom_blocks",
"if",
"x",
".",
"id",
"==",
"log_net",
".",
"op_param",
"[",
"0",
"]",
")",
",",
"None",
")",
"f",
".",
"write",
"(",
"\" wire %s : UInt<%s>[%s]\\n\"",
"%",
"(",
"log_net",
".",
"op_param",
"[",
"1",
"]",
".",
"name",
",",
"log_net",
".",
"op_param",
"[",
"1",
"]",
".",
"bitwidth",
",",
"2",
"**",
"log_net",
".",
"op_param",
"[",
"1",
"]",
".",
"addrwidth",
")",
")",
"# if rom data is a function, calculate the data first",
"if",
"callable",
"(",
"curr_rom",
".",
"data",
")",
":",
"romdata",
"=",
"[",
"curr_rom",
".",
"data",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"2",
"**",
"curr_rom",
".",
"addrwidth",
")",
"]",
"curr_rom",
".",
"data",
"=",
"romdata",
"# write rom block initialization data",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"curr_rom",
".",
"data",
")",
")",
":",
"f",
".",
"write",
"(",
"\" %s[%s] <= UInt<%s>(%s)\\n\"",
"%",
"(",
"log_net",
".",
"op_param",
"[",
"1",
"]",
".",
"name",
",",
"i",
",",
"log_net",
".",
"op_param",
"[",
"1",
"]",
".",
"bitwidth",
",",
"curr_rom",
".",
"data",
"[",
"i",
"]",
")",
")",
"# write the connection",
"f",
".",
"write",
"(",
"\" %s <= %s[%s]\\n\"",
"%",
"(",
"log_net",
".",
"dests",
"[",
"0",
"]",
".",
"name",
",",
"log_net",
".",
"op_param",
"[",
"1",
"]",
".",
"name",
",",
"log_net",
".",
"args",
"[",
"0",
"]",
".",
"name",
")",
")",
"else",
":",
"if",
"not",
"log_net",
".",
"op_param",
"[",
"0",
"]",
"in",
"initializedMem",
":",
"initializedMem",
".",
"append",
"(",
"log_net",
".",
"op_param",
"[",
"0",
"]",
")",
"f",
".",
"write",
"(",
"\" cmem %s_%s : UInt<%s>[%s]\\n\"",
"%",
"(",
"log_net",
".",
"op_param",
"[",
"1",
"]",
".",
"name",
",",
"log_net",
".",
"op_param",
"[",
"0",
"]",
",",
"log_net",
".",
"op_param",
"[",
"1",
"]",
".",
"bitwidth",
",",
"2",
"**",
"log_net",
".",
"op_param",
"[",
"1",
"]",
".",
"addrwidth",
")",
")",
"f",
".",
"write",
"(",
"\" infer mport T_%d = %s_%s[%s], clock\\n\"",
"%",
"(",
"node_cntr",
",",
"log_net",
".",
"op_param",
"[",
"1",
"]",
".",
"name",
",",
"log_net",
".",
"op_param",
"[",
"0",
"]",
",",
"log_net",
".",
"args",
"[",
"0",
"]",
".",
"name",
")",
")",
"f",
".",
"write",
"(",
"\" %s <= T_%d\\n\"",
"%",
"(",
"log_net",
".",
"dests",
"[",
"0",
"]",
".",
"name",
",",
"node_cntr",
")",
")",
"node_cntr",
"+=",
"1",
"elif",
"log_net",
".",
"op",
"==",
"'@'",
":",
"if",
"not",
"log_net",
".",
"op_param",
"[",
"0",
"]",
"in",
"initializedMem",
":",
"initializedMem",
".",
"append",
"(",
"log_net",
".",
"op_param",
"[",
"0",
"]",
")",
"f",
".",
"write",
"(",
"\" cmem %s_%s : UInt<%s>[%s]\\n\"",
"%",
"(",
"log_net",
".",
"op_param",
"[",
"1",
"]",
".",
"name",
",",
"log_net",
".",
"op_param",
"[",
"0",
"]",
",",
"log_net",
".",
"op_param",
"[",
"1",
"]",
".",
"bitwidth",
",",
"2",
"**",
"log_net",
".",
"op_param",
"[",
"1",
"]",
".",
"addrwidth",
")",
")",
"f",
".",
"write",
"(",
"\" when %s :\\n\"",
"%",
"log_net",
".",
"args",
"[",
"2",
"]",
".",
"name",
")",
"f",
".",
"write",
"(",
"\" infer mport T_%d = %s_%s[%s], clock\\n\"",
"%",
"(",
"node_cntr",
",",
"log_net",
".",
"op_param",
"[",
"1",
"]",
".",
"name",
",",
"log_net",
".",
"op_param",
"[",
"0",
"]",
",",
"log_net",
".",
"args",
"[",
"0",
"]",
".",
"name",
")",
")",
"f",
".",
"write",
"(",
"\" T_%d <= %s\\n\"",
"%",
"(",
"node_cntr",
",",
"log_net",
".",
"args",
"[",
"1",
"]",
".",
"name",
")",
")",
"f",
".",
"write",
"(",
"\" skip\\n\"",
")",
"node_cntr",
"+=",
"1",
"else",
":",
"pass",
"f",
".",
"close",
"(",
")",
"return",
"0"
] | Output the block as firrtl code to the output file.
Output_to_firrtl(open_file, rom_block, block)
If rom is intialized in pyrtl code, you can pass in the rom_blocks as a list [rom1, rom2, ...] | [
"Output",
"the",
"block",
"as",
"firrtl",
"code",
"to",
"the",
"output",
"file",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/inputoutput.py#L215-L359 |
UCSBarchlab/PyRTL | pyrtl/inputoutput.py | _trivialgraph_default_namer | def _trivialgraph_default_namer(thing, is_edge=True):
""" Returns a "good" string for thing in printed graphs. """
if is_edge:
if thing.name is None or thing.name.startswith('tmp'):
return ''
else:
return '/'.join([thing.name, str(len(thing))])
elif isinstance(thing, Const):
return str(thing.val)
elif isinstance(thing, WireVector):
return thing.name or '??'
else:
try:
return thing.op + str(thing.op_param or '')
except AttributeError:
raise PyrtlError('no naming rule for "%s"' % str(thing)) | python | def _trivialgraph_default_namer(thing, is_edge=True):
""" Returns a "good" string for thing in printed graphs. """
if is_edge:
if thing.name is None or thing.name.startswith('tmp'):
return ''
else:
return '/'.join([thing.name, str(len(thing))])
elif isinstance(thing, Const):
return str(thing.val)
elif isinstance(thing, WireVector):
return thing.name or '??'
else:
try:
return thing.op + str(thing.op_param or '')
except AttributeError:
raise PyrtlError('no naming rule for "%s"' % str(thing)) | [
"def",
"_trivialgraph_default_namer",
"(",
"thing",
",",
"is_edge",
"=",
"True",
")",
":",
"if",
"is_edge",
":",
"if",
"thing",
".",
"name",
"is",
"None",
"or",
"thing",
".",
"name",
".",
"startswith",
"(",
"'tmp'",
")",
":",
"return",
"''",
"else",
":",
"return",
"'/'",
".",
"join",
"(",
"[",
"thing",
".",
"name",
",",
"str",
"(",
"len",
"(",
"thing",
")",
")",
"]",
")",
"elif",
"isinstance",
"(",
"thing",
",",
"Const",
")",
":",
"return",
"str",
"(",
"thing",
".",
"val",
")",
"elif",
"isinstance",
"(",
"thing",
",",
"WireVector",
")",
":",
"return",
"thing",
".",
"name",
"or",
"'??'",
"else",
":",
"try",
":",
"return",
"thing",
".",
"op",
"+",
"str",
"(",
"thing",
".",
"op_param",
"or",
"''",
")",
"except",
"AttributeError",
":",
"raise",
"PyrtlError",
"(",
"'no naming rule for \"%s\"'",
"%",
"str",
"(",
"thing",
")",
")"
] | Returns a "good" string for thing in printed graphs. | [
"Returns",
"a",
"good",
"string",
"for",
"thing",
"in",
"printed",
"graphs",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/inputoutput.py#L362-L377 |
UCSBarchlab/PyRTL | pyrtl/inputoutput.py | net_graph | def net_graph(block=None, split_state=False):
""" Return a graph representation of the current block.
Graph has the following form:
{ node1: { nodeA: edge1A, nodeB: edge1B},
node2: { nodeB: edge2B, nodeC: edge2C},
...
}
aka: edge = graph[source][dest]
Each node can be either a logic net or a WireVector (e.g. an Input, and Output, a
Const or even an undriven WireVector (which acts as a source or sink in the network)
Each edge is a WireVector or derived type (Input, Output, Register, etc.)
Note that inputs, consts, and outputs will be both "node" and "edge".
WireVectors that are not connected to any nets are not returned as part
of the graph.
"""
# FIXME: make it not try to add unused wires (issue #204)
block = working_block(block)
from .wire import Register
# self.sanity_check()
graph = {}
# add all of the nodes
for net in block.logic:
graph[net] = {}
wire_src_dict, wire_dst_dict = block.net_connections()
dest_set = set(wire_src_dict.keys())
arg_set = set(wire_dst_dict.keys())
dangle_set = dest_set.symmetric_difference(arg_set)
for w in dangle_set:
graph[w] = {}
if split_state:
for w in block.wirevector_subset(Register):
graph[w] = {}
# add all of the edges
for w in (dest_set & arg_set):
try:
_from = wire_src_dict[w]
except Exception:
_from = w
if split_state and isinstance(w, Register):
_from = w
try:
_to_list = wire_dst_dict[w]
except Exception:
_to_list = [w]
for _to in _to_list:
graph[_from][_to] = w
return graph | python | def net_graph(block=None, split_state=False):
""" Return a graph representation of the current block.
Graph has the following form:
{ node1: { nodeA: edge1A, nodeB: edge1B},
node2: { nodeB: edge2B, nodeC: edge2C},
...
}
aka: edge = graph[source][dest]
Each node can be either a logic net or a WireVector (e.g. an Input, and Output, a
Const or even an undriven WireVector (which acts as a source or sink in the network)
Each edge is a WireVector or derived type (Input, Output, Register, etc.)
Note that inputs, consts, and outputs will be both "node" and "edge".
WireVectors that are not connected to any nets are not returned as part
of the graph.
"""
# FIXME: make it not try to add unused wires (issue #204)
block = working_block(block)
from .wire import Register
# self.sanity_check()
graph = {}
# add all of the nodes
for net in block.logic:
graph[net] = {}
wire_src_dict, wire_dst_dict = block.net_connections()
dest_set = set(wire_src_dict.keys())
arg_set = set(wire_dst_dict.keys())
dangle_set = dest_set.symmetric_difference(arg_set)
for w in dangle_set:
graph[w] = {}
if split_state:
for w in block.wirevector_subset(Register):
graph[w] = {}
# add all of the edges
for w in (dest_set & arg_set):
try:
_from = wire_src_dict[w]
except Exception:
_from = w
if split_state and isinstance(w, Register):
_from = w
try:
_to_list = wire_dst_dict[w]
except Exception:
_to_list = [w]
for _to in _to_list:
graph[_from][_to] = w
return graph | [
"def",
"net_graph",
"(",
"block",
"=",
"None",
",",
"split_state",
"=",
"False",
")",
":",
"# FIXME: make it not try to add unused wires (issue #204)",
"block",
"=",
"working_block",
"(",
"block",
")",
"from",
".",
"wire",
"import",
"Register",
"# self.sanity_check()",
"graph",
"=",
"{",
"}",
"# add all of the nodes",
"for",
"net",
"in",
"block",
".",
"logic",
":",
"graph",
"[",
"net",
"]",
"=",
"{",
"}",
"wire_src_dict",
",",
"wire_dst_dict",
"=",
"block",
".",
"net_connections",
"(",
")",
"dest_set",
"=",
"set",
"(",
"wire_src_dict",
".",
"keys",
"(",
")",
")",
"arg_set",
"=",
"set",
"(",
"wire_dst_dict",
".",
"keys",
"(",
")",
")",
"dangle_set",
"=",
"dest_set",
".",
"symmetric_difference",
"(",
"arg_set",
")",
"for",
"w",
"in",
"dangle_set",
":",
"graph",
"[",
"w",
"]",
"=",
"{",
"}",
"if",
"split_state",
":",
"for",
"w",
"in",
"block",
".",
"wirevector_subset",
"(",
"Register",
")",
":",
"graph",
"[",
"w",
"]",
"=",
"{",
"}",
"# add all of the edges",
"for",
"w",
"in",
"(",
"dest_set",
"&",
"arg_set",
")",
":",
"try",
":",
"_from",
"=",
"wire_src_dict",
"[",
"w",
"]",
"except",
"Exception",
":",
"_from",
"=",
"w",
"if",
"split_state",
"and",
"isinstance",
"(",
"w",
",",
"Register",
")",
":",
"_from",
"=",
"w",
"try",
":",
"_to_list",
"=",
"wire_dst_dict",
"[",
"w",
"]",
"except",
"Exception",
":",
"_to_list",
"=",
"[",
"w",
"]",
"for",
"_to",
"in",
"_to_list",
":",
"graph",
"[",
"_from",
"]",
"[",
"_to",
"]",
"=",
"w",
"return",
"graph"
] | Return a graph representation of the current block.
Graph has the following form:
{ node1: { nodeA: edge1A, nodeB: edge1B},
node2: { nodeB: edge2B, nodeC: edge2C},
...
}
aka: edge = graph[source][dest]
Each node can be either a logic net or a WireVector (e.g. an Input, and Output, a
Const or even an undriven WireVector (which acts as a source or sink in the network)
Each edge is a WireVector or derived type (Input, Output, Register, etc.)
Note that inputs, consts, and outputs will be both "node" and "edge".
WireVectors that are not connected to any nets are not returned as part
of the graph. | [
"Return",
"a",
"graph",
"representation",
"of",
"the",
"current",
"block",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/inputoutput.py#L380-L435 |
UCSBarchlab/PyRTL | pyrtl/inputoutput.py | output_to_trivialgraph | def output_to_trivialgraph(file, namer=_trivialgraph_default_namer, block=None):
""" Walk the block and output it in trivial graph format to the open file. """
graph = net_graph(block)
node_index_map = {} # map node -> index
# print the list of nodes
for index, node in enumerate(graph):
print('%d %s' % (index, namer(node, is_edge=False)), file=file)
node_index_map[node] = index
print('#', file=file)
# print the list of edges
for _from in graph:
for _to in graph[_from]:
from_index = node_index_map[_from]
to_index = node_index_map[_to]
edge = graph[_from][_to]
print('%d %d %s' % (from_index, to_index, namer(edge)), file=file) | python | def output_to_trivialgraph(file, namer=_trivialgraph_default_namer, block=None):
""" Walk the block and output it in trivial graph format to the open file. """
graph = net_graph(block)
node_index_map = {} # map node -> index
# print the list of nodes
for index, node in enumerate(graph):
print('%d %s' % (index, namer(node, is_edge=False)), file=file)
node_index_map[node] = index
print('#', file=file)
# print the list of edges
for _from in graph:
for _to in graph[_from]:
from_index = node_index_map[_from]
to_index = node_index_map[_to]
edge = graph[_from][_to]
print('%d %d %s' % (from_index, to_index, namer(edge)), file=file) | [
"def",
"output_to_trivialgraph",
"(",
"file",
",",
"namer",
"=",
"_trivialgraph_default_namer",
",",
"block",
"=",
"None",
")",
":",
"graph",
"=",
"net_graph",
"(",
"block",
")",
"node_index_map",
"=",
"{",
"}",
"# map node -> index",
"# print the list of nodes",
"for",
"index",
",",
"node",
"in",
"enumerate",
"(",
"graph",
")",
":",
"print",
"(",
"'%d %s'",
"%",
"(",
"index",
",",
"namer",
"(",
"node",
",",
"is_edge",
"=",
"False",
")",
")",
",",
"file",
"=",
"file",
")",
"node_index_map",
"[",
"node",
"]",
"=",
"index",
"print",
"(",
"'#'",
",",
"file",
"=",
"file",
")",
"# print the list of edges",
"for",
"_from",
"in",
"graph",
":",
"for",
"_to",
"in",
"graph",
"[",
"_from",
"]",
":",
"from_index",
"=",
"node_index_map",
"[",
"_from",
"]",
"to_index",
"=",
"node_index_map",
"[",
"_to",
"]",
"edge",
"=",
"graph",
"[",
"_from",
"]",
"[",
"_to",
"]",
"print",
"(",
"'%d %d %s'",
"%",
"(",
"from_index",
",",
"to_index",
",",
"namer",
"(",
"edge",
")",
")",
",",
"file",
"=",
"file",
")"
] | Walk the block and output it in trivial graph format to the open file. | [
"Walk",
"the",
"block",
"and",
"output",
"it",
"in",
"trivial",
"graph",
"format",
"to",
"the",
"open",
"file",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/inputoutput.py#L438-L456 |
UCSBarchlab/PyRTL | pyrtl/inputoutput.py | _graphviz_default_namer | def _graphviz_default_namer(thing, is_edge=True, is_to_splitmerge=False):
""" Returns a "good" graphviz label for thing. """
if is_edge:
if (thing.name is None or
thing.name.startswith('tmp') or
isinstance(thing, (Input, Output, Const, Register))):
name = ''
else:
name = '/'.join([thing.name, str(len(thing))])
penwidth = 2 if len(thing) == 1 else 6
arrowhead = 'none' if is_to_splitmerge else 'normal'
return '[label="%s", penwidth="%d", arrowhead="%s"]' % (name, penwidth, arrowhead)
elif isinstance(thing, Const):
return '[label="%d", shape=circle, fillcolor=lightgrey]' % thing.val
elif isinstance(thing, (Input, Output)):
return '[label="%s", shape=circle, fillcolor=none]' % thing.name
elif isinstance(thing, Register):
return '[label="%s", shape=square, fillcolor=gold]' % thing.name
elif isinstance(thing, WireVector):
return '[label="", shape=circle, fillcolor=none]'
else:
try:
if thing.op == '&':
return '[label="and"]'
elif thing.op == '|':
return '[label="or"]'
elif thing.op == '^':
return '[label="xor"]'
elif thing.op == '~':
return '[label="not"]'
elif thing.op == 'x':
return '[label="mux"]'
elif thing.op in 'sc':
return '[label="", height=.1, width=.1]'
elif thing.op == 'r':
name = thing.dests[0].name or ''
return '[label="%s.next", shape=square, fillcolor=gold]' % name
elif thing.op == 'w':
return '[label="buf"]'
else:
return '[label="%s"]' % (thing.op + str(thing.op_param or ''))
except AttributeError:
raise PyrtlError('no naming rule for "%s"' % str(thing)) | python | def _graphviz_default_namer(thing, is_edge=True, is_to_splitmerge=False):
""" Returns a "good" graphviz label for thing. """
if is_edge:
if (thing.name is None or
thing.name.startswith('tmp') or
isinstance(thing, (Input, Output, Const, Register))):
name = ''
else:
name = '/'.join([thing.name, str(len(thing))])
penwidth = 2 if len(thing) == 1 else 6
arrowhead = 'none' if is_to_splitmerge else 'normal'
return '[label="%s", penwidth="%d", arrowhead="%s"]' % (name, penwidth, arrowhead)
elif isinstance(thing, Const):
return '[label="%d", shape=circle, fillcolor=lightgrey]' % thing.val
elif isinstance(thing, (Input, Output)):
return '[label="%s", shape=circle, fillcolor=none]' % thing.name
elif isinstance(thing, Register):
return '[label="%s", shape=square, fillcolor=gold]' % thing.name
elif isinstance(thing, WireVector):
return '[label="", shape=circle, fillcolor=none]'
else:
try:
if thing.op == '&':
return '[label="and"]'
elif thing.op == '|':
return '[label="or"]'
elif thing.op == '^':
return '[label="xor"]'
elif thing.op == '~':
return '[label="not"]'
elif thing.op == 'x':
return '[label="mux"]'
elif thing.op in 'sc':
return '[label="", height=.1, width=.1]'
elif thing.op == 'r':
name = thing.dests[0].name or ''
return '[label="%s.next", shape=square, fillcolor=gold]' % name
elif thing.op == 'w':
return '[label="buf"]'
else:
return '[label="%s"]' % (thing.op + str(thing.op_param or ''))
except AttributeError:
raise PyrtlError('no naming rule for "%s"' % str(thing)) | [
"def",
"_graphviz_default_namer",
"(",
"thing",
",",
"is_edge",
"=",
"True",
",",
"is_to_splitmerge",
"=",
"False",
")",
":",
"if",
"is_edge",
":",
"if",
"(",
"thing",
".",
"name",
"is",
"None",
"or",
"thing",
".",
"name",
".",
"startswith",
"(",
"'tmp'",
")",
"or",
"isinstance",
"(",
"thing",
",",
"(",
"Input",
",",
"Output",
",",
"Const",
",",
"Register",
")",
")",
")",
":",
"name",
"=",
"''",
"else",
":",
"name",
"=",
"'/'",
".",
"join",
"(",
"[",
"thing",
".",
"name",
",",
"str",
"(",
"len",
"(",
"thing",
")",
")",
"]",
")",
"penwidth",
"=",
"2",
"if",
"len",
"(",
"thing",
")",
"==",
"1",
"else",
"6",
"arrowhead",
"=",
"'none'",
"if",
"is_to_splitmerge",
"else",
"'normal'",
"return",
"'[label=\"%s\", penwidth=\"%d\", arrowhead=\"%s\"]'",
"%",
"(",
"name",
",",
"penwidth",
",",
"arrowhead",
")",
"elif",
"isinstance",
"(",
"thing",
",",
"Const",
")",
":",
"return",
"'[label=\"%d\", shape=circle, fillcolor=lightgrey]'",
"%",
"thing",
".",
"val",
"elif",
"isinstance",
"(",
"thing",
",",
"(",
"Input",
",",
"Output",
")",
")",
":",
"return",
"'[label=\"%s\", shape=circle, fillcolor=none]'",
"%",
"thing",
".",
"name",
"elif",
"isinstance",
"(",
"thing",
",",
"Register",
")",
":",
"return",
"'[label=\"%s\", shape=square, fillcolor=gold]'",
"%",
"thing",
".",
"name",
"elif",
"isinstance",
"(",
"thing",
",",
"WireVector",
")",
":",
"return",
"'[label=\"\", shape=circle, fillcolor=none]'",
"else",
":",
"try",
":",
"if",
"thing",
".",
"op",
"==",
"'&'",
":",
"return",
"'[label=\"and\"]'",
"elif",
"thing",
".",
"op",
"==",
"'|'",
":",
"return",
"'[label=\"or\"]'",
"elif",
"thing",
".",
"op",
"==",
"'^'",
":",
"return",
"'[label=\"xor\"]'",
"elif",
"thing",
".",
"op",
"==",
"'~'",
":",
"return",
"'[label=\"not\"]'",
"elif",
"thing",
".",
"op",
"==",
"'x'",
":",
"return",
"'[label=\"mux\"]'",
"elif",
"thing",
".",
"op",
"in",
"'sc'",
":",
"return",
"'[label=\"\", height=.1, width=.1]'",
"elif",
"thing",
".",
"op",
"==",
"'r'",
":",
"name",
"=",
"thing",
".",
"dests",
"[",
"0",
"]",
".",
"name",
"or",
"''",
"return",
"'[label=\"%s.next\", shape=square, fillcolor=gold]'",
"%",
"name",
"elif",
"thing",
".",
"op",
"==",
"'w'",
":",
"return",
"'[label=\"buf\"]'",
"else",
":",
"return",
"'[label=\"%s\"]'",
"%",
"(",
"thing",
".",
"op",
"+",
"str",
"(",
"thing",
".",
"op_param",
"or",
"''",
")",
")",
"except",
"AttributeError",
":",
"raise",
"PyrtlError",
"(",
"'no naming rule for \"%s\"'",
"%",
"str",
"(",
"thing",
")",
")"
] | Returns a "good" graphviz label for thing. | [
"Returns",
"a",
"good",
"graphviz",
"label",
"for",
"thing",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/inputoutput.py#L459-L502 |
UCSBarchlab/PyRTL | pyrtl/inputoutput.py | output_to_graphviz | def output_to_graphviz(file, namer=_graphviz_default_namer, block=None):
""" Walk the block and output it in graphviz format to the open file. """
print(block_to_graphviz_string(block, namer), file=file) | python | def output_to_graphviz(file, namer=_graphviz_default_namer, block=None):
""" Walk the block and output it in graphviz format to the open file. """
print(block_to_graphviz_string(block, namer), file=file) | [
"def",
"output_to_graphviz",
"(",
"file",
",",
"namer",
"=",
"_graphviz_default_namer",
",",
"block",
"=",
"None",
")",
":",
"print",
"(",
"block_to_graphviz_string",
"(",
"block",
",",
"namer",
")",
",",
"file",
"=",
"file",
")"
] | Walk the block and output it in graphviz format to the open file. | [
"Walk",
"the",
"block",
"and",
"output",
"it",
"in",
"graphviz",
"format",
"to",
"the",
"open",
"file",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/inputoutput.py#L505-L507 |
UCSBarchlab/PyRTL | pyrtl/inputoutput.py | block_to_graphviz_string | def block_to_graphviz_string(block=None, namer=_graphviz_default_namer):
""" Return a graphviz string for the block. """
graph = net_graph(block, split_state=True)
node_index_map = {} # map node -> index
rstring = """\
digraph g {\n
graph [splines="spline"];
node [shape=circle, style=filled, fillcolor=lightblue1,
fontcolor=grey, fontname=helvetica, penwidth=0,
fixedsize=true];
edge [labelfloat=false, penwidth=2, color=deepskyblue, arrowsize=.5];
"""
# print the list of nodes
for index, node in enumerate(graph):
label = namer(node, is_edge=False)
rstring += ' n%s %s;\n' % (index, label)
node_index_map[node] = index
# print the list of edges
for _from in graph:
for _to in graph[_from]:
from_index = node_index_map[_from]
to_index = node_index_map[_to]
edge = graph[_from][_to]
is_to_splitmerge = True if hasattr(_to, 'op') and _to.op in 'cs' else False
label = namer(edge, is_to_splitmerge=is_to_splitmerge)
rstring += ' n%d -> n%d %s;\n' % (from_index, to_index, label)
rstring += '}\n'
return rstring | python | def block_to_graphviz_string(block=None, namer=_graphviz_default_namer):
""" Return a graphviz string for the block. """
graph = net_graph(block, split_state=True)
node_index_map = {} # map node -> index
rstring = """\
digraph g {\n
graph [splines="spline"];
node [shape=circle, style=filled, fillcolor=lightblue1,
fontcolor=grey, fontname=helvetica, penwidth=0,
fixedsize=true];
edge [labelfloat=false, penwidth=2, color=deepskyblue, arrowsize=.5];
"""
# print the list of nodes
for index, node in enumerate(graph):
label = namer(node, is_edge=False)
rstring += ' n%s %s;\n' % (index, label)
node_index_map[node] = index
# print the list of edges
for _from in graph:
for _to in graph[_from]:
from_index = node_index_map[_from]
to_index = node_index_map[_to]
edge = graph[_from][_to]
is_to_splitmerge = True if hasattr(_to, 'op') and _to.op in 'cs' else False
label = namer(edge, is_to_splitmerge=is_to_splitmerge)
rstring += ' n%d -> n%d %s;\n' % (from_index, to_index, label)
rstring += '}\n'
return rstring | [
"def",
"block_to_graphviz_string",
"(",
"block",
"=",
"None",
",",
"namer",
"=",
"_graphviz_default_namer",
")",
":",
"graph",
"=",
"net_graph",
"(",
"block",
",",
"split_state",
"=",
"True",
")",
"node_index_map",
"=",
"{",
"}",
"# map node -> index",
"rstring",
"=",
"\"\"\"\\\n digraph g {\\n\n graph [splines=\"spline\"];\n node [shape=circle, style=filled, fillcolor=lightblue1,\n fontcolor=grey, fontname=helvetica, penwidth=0,\n fixedsize=true];\n edge [labelfloat=false, penwidth=2, color=deepskyblue, arrowsize=.5];\n \"\"\"",
"# print the list of nodes",
"for",
"index",
",",
"node",
"in",
"enumerate",
"(",
"graph",
")",
":",
"label",
"=",
"namer",
"(",
"node",
",",
"is_edge",
"=",
"False",
")",
"rstring",
"+=",
"' n%s %s;\\n'",
"%",
"(",
"index",
",",
"label",
")",
"node_index_map",
"[",
"node",
"]",
"=",
"index",
"# print the list of edges",
"for",
"_from",
"in",
"graph",
":",
"for",
"_to",
"in",
"graph",
"[",
"_from",
"]",
":",
"from_index",
"=",
"node_index_map",
"[",
"_from",
"]",
"to_index",
"=",
"node_index_map",
"[",
"_to",
"]",
"edge",
"=",
"graph",
"[",
"_from",
"]",
"[",
"_to",
"]",
"is_to_splitmerge",
"=",
"True",
"if",
"hasattr",
"(",
"_to",
",",
"'op'",
")",
"and",
"_to",
".",
"op",
"in",
"'cs'",
"else",
"False",
"label",
"=",
"namer",
"(",
"edge",
",",
"is_to_splitmerge",
"=",
"is_to_splitmerge",
")",
"rstring",
"+=",
"' n%d -> n%d %s;\\n'",
"%",
"(",
"from_index",
",",
"to_index",
",",
"label",
")",
"rstring",
"+=",
"'}\\n'",
"return",
"rstring"
] | Return a graphviz string for the block. | [
"Return",
"a",
"graphviz",
"string",
"for",
"the",
"block",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/inputoutput.py#L510-L541 |
UCSBarchlab/PyRTL | pyrtl/inputoutput.py | block_to_svg | def block_to_svg(block=None):
""" Return an SVG for the block. """
block = working_block(block)
try:
from graphviz import Source
return Source(block_to_graphviz_string())._repr_svg_()
except ImportError:
raise PyrtlError('need graphviz installed (try "pip install graphviz")') | python | def block_to_svg(block=None):
""" Return an SVG for the block. """
block = working_block(block)
try:
from graphviz import Source
return Source(block_to_graphviz_string())._repr_svg_()
except ImportError:
raise PyrtlError('need graphviz installed (try "pip install graphviz")') | [
"def",
"block_to_svg",
"(",
"block",
"=",
"None",
")",
":",
"block",
"=",
"working_block",
"(",
"block",
")",
"try",
":",
"from",
"graphviz",
"import",
"Source",
"return",
"Source",
"(",
"block_to_graphviz_string",
"(",
")",
")",
".",
"_repr_svg_",
"(",
")",
"except",
"ImportError",
":",
"raise",
"PyrtlError",
"(",
"'need graphviz installed (try \"pip install graphviz\")'",
")"
] | Return an SVG for the block. | [
"Return",
"an",
"SVG",
"for",
"the",
"block",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/inputoutput.py#L544-L551 |
UCSBarchlab/PyRTL | pyrtl/inputoutput.py | trace_to_html | def trace_to_html(simtrace, trace_list=None, sortkey=None):
""" Return a HTML block showing the trace. """
from .simulation import SimulationTrace, _trace_sort_key
if not isinstance(simtrace, SimulationTrace):
raise PyrtlError('first arguement must be of type SimulationTrace')
trace = simtrace.trace
if sortkey is None:
sortkey = _trace_sort_key
if trace_list is None:
trace_list = sorted(trace, key=sortkey)
wave_template = (
"""\
<script type="WaveDrom">
{ signal : [
%s
]}
</script>
"""
)
def extract(w):
wavelist = []
datalist = []
last = None
for i, value in enumerate(trace[w]):
if last == value:
wavelist.append('.')
else:
if len(w) == 1:
wavelist.append(str(value))
else:
wavelist.append('=')
datalist.append(value)
last = value
wavestring = ''.join(wavelist)
datastring = ', '.join(['"%d"' % data for data in datalist])
if len(w) == 1:
return bool_signal_template % (w, wavestring)
else:
return int_signal_template % (w, wavestring, datastring)
bool_signal_template = '{ name: "%s", wave: "%s" },'
int_signal_template = '{ name: "%s", wave: "%s", data: [%s] },'
signals = [extract(w) for w in trace_list]
all_signals = '\n'.join(signals)
wave = wave_template % all_signals
# print(wave)
return wave | python | def trace_to_html(simtrace, trace_list=None, sortkey=None):
""" Return a HTML block showing the trace. """
from .simulation import SimulationTrace, _trace_sort_key
if not isinstance(simtrace, SimulationTrace):
raise PyrtlError('first arguement must be of type SimulationTrace')
trace = simtrace.trace
if sortkey is None:
sortkey = _trace_sort_key
if trace_list is None:
trace_list = sorted(trace, key=sortkey)
wave_template = (
"""\
<script type="WaveDrom">
{ signal : [
%s
]}
</script>
"""
)
def extract(w):
wavelist = []
datalist = []
last = None
for i, value in enumerate(trace[w]):
if last == value:
wavelist.append('.')
else:
if len(w) == 1:
wavelist.append(str(value))
else:
wavelist.append('=')
datalist.append(value)
last = value
wavestring = ''.join(wavelist)
datastring = ', '.join(['"%d"' % data for data in datalist])
if len(w) == 1:
return bool_signal_template % (w, wavestring)
else:
return int_signal_template % (w, wavestring, datastring)
bool_signal_template = '{ name: "%s", wave: "%s" },'
int_signal_template = '{ name: "%s", wave: "%s", data: [%s] },'
signals = [extract(w) for w in trace_list]
all_signals = '\n'.join(signals)
wave = wave_template % all_signals
# print(wave)
return wave | [
"def",
"trace_to_html",
"(",
"simtrace",
",",
"trace_list",
"=",
"None",
",",
"sortkey",
"=",
"None",
")",
":",
"from",
".",
"simulation",
"import",
"SimulationTrace",
",",
"_trace_sort_key",
"if",
"not",
"isinstance",
"(",
"simtrace",
",",
"SimulationTrace",
")",
":",
"raise",
"PyrtlError",
"(",
"'first arguement must be of type SimulationTrace'",
")",
"trace",
"=",
"simtrace",
".",
"trace",
"if",
"sortkey",
"is",
"None",
":",
"sortkey",
"=",
"_trace_sort_key",
"if",
"trace_list",
"is",
"None",
":",
"trace_list",
"=",
"sorted",
"(",
"trace",
",",
"key",
"=",
"sortkey",
")",
"wave_template",
"=",
"(",
"\"\"\"\\\n <script type=\"WaveDrom\">\n { signal : [\n %s\n ]}\n </script>\n\n \"\"\"",
")",
"def",
"extract",
"(",
"w",
")",
":",
"wavelist",
"=",
"[",
"]",
"datalist",
"=",
"[",
"]",
"last",
"=",
"None",
"for",
"i",
",",
"value",
"in",
"enumerate",
"(",
"trace",
"[",
"w",
"]",
")",
":",
"if",
"last",
"==",
"value",
":",
"wavelist",
".",
"append",
"(",
"'.'",
")",
"else",
":",
"if",
"len",
"(",
"w",
")",
"==",
"1",
":",
"wavelist",
".",
"append",
"(",
"str",
"(",
"value",
")",
")",
"else",
":",
"wavelist",
".",
"append",
"(",
"'='",
")",
"datalist",
".",
"append",
"(",
"value",
")",
"last",
"=",
"value",
"wavestring",
"=",
"''",
".",
"join",
"(",
"wavelist",
")",
"datastring",
"=",
"', '",
".",
"join",
"(",
"[",
"'\"%d\"'",
"%",
"data",
"for",
"data",
"in",
"datalist",
"]",
")",
"if",
"len",
"(",
"w",
")",
"==",
"1",
":",
"return",
"bool_signal_template",
"%",
"(",
"w",
",",
"wavestring",
")",
"else",
":",
"return",
"int_signal_template",
"%",
"(",
"w",
",",
"wavestring",
",",
"datastring",
")",
"bool_signal_template",
"=",
"'{ name: \"%s\", wave: \"%s\" },'",
"int_signal_template",
"=",
"'{ name: \"%s\", wave: \"%s\", data: [%s] },'",
"signals",
"=",
"[",
"extract",
"(",
"w",
")",
"for",
"w",
"in",
"trace_list",
"]",
"all_signals",
"=",
"'\\n'",
".",
"join",
"(",
"signals",
")",
"wave",
"=",
"wave_template",
"%",
"all_signals",
"# print(wave)",
"return",
"wave"
] | Return a HTML block showing the trace. | [
"Return",
"a",
"HTML",
"block",
"showing",
"the",
"trace",
"."
] | train | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/inputoutput.py#L554-L607 |
usrlocalben/pydux | pydux/create_store.py | create_store | def create_store(reducer, initial_state=None, enhancer=None):
"""
redux in a nutshell.
observable has been omitted.
Args:
reducer: root reducer function for the state tree
initial_state: optional initial state data
enhancer: optional enhancer function for middleware etc.
Returns:
a Pydux store
"""
if enhancer is not None:
if not hasattr(enhancer, '__call__'):
raise TypeError('Expected the enhancer to be a function.')
return enhancer(create_store)(reducer, initial_state)
if not hasattr(reducer, '__call__'):
raise TypeError('Expected the reducer to be a function.')
# single-element arrays for r/w closure
current_reducer = [reducer]
current_state = [initial_state]
current_listeners = [[]]
next_listeners = [current_listeners[0]]
is_dispatching = [False]
def ensure_can_mutate_next_listeners():
if next_listeners[0] == current_listeners[0]:
next_listeners[0] = current_listeners[0][:]
def get_state():
return current_state[0]
def subscribe(listener):
if not hasattr(listener, '__call__'):
raise TypeError('Expected listener to be a function.')
is_subscribed = [True] # r/w closure
ensure_can_mutate_next_listeners()
next_listeners[0].append(listener)
def unsubcribe():
if not is_subscribed[0]:
return
is_subscribed[0] = False
ensure_can_mutate_next_listeners()
index = next_listeners[0].index(listener)
next_listeners[0].pop(index)
return unsubcribe
def dispatch(action):
if not isinstance(action, dict):
raise TypeError('Actions must be a dict. '
'Use custom middleware for async actions.')
if action.get('type') is None:
raise ValueError('Actions must have a non-None "type" property. '
'Have you misspelled a constant?')
if is_dispatching[0]:
raise Exception('Reducers may not dispatch actions.')
try:
is_dispatching[0] = True
current_state[0] = current_reducer[0](current_state[0], action)
finally:
is_dispatching[0] = False
listeners = current_listeners[0] = next_listeners[0]
for listener in listeners:
listener()
return action
def replace_reducer(next_reducer):
if not hasattr(next_reducer, '__call__'):
raise TypeError('Expected next_reducer to be a function')
current_reducer[0] = next_reducer
dispatch({'type': ActionTypes.INIT})
dispatch({'type': ActionTypes.INIT})
return StoreDict(
dispatch=dispatch,
subscribe=subscribe,
get_state=get_state,
replace_reducer=replace_reducer,
) | python | def create_store(reducer, initial_state=None, enhancer=None):
"""
redux in a nutshell.
observable has been omitted.
Args:
reducer: root reducer function for the state tree
initial_state: optional initial state data
enhancer: optional enhancer function for middleware etc.
Returns:
a Pydux store
"""
if enhancer is not None:
if not hasattr(enhancer, '__call__'):
raise TypeError('Expected the enhancer to be a function.')
return enhancer(create_store)(reducer, initial_state)
if not hasattr(reducer, '__call__'):
raise TypeError('Expected the reducer to be a function.')
# single-element arrays for r/w closure
current_reducer = [reducer]
current_state = [initial_state]
current_listeners = [[]]
next_listeners = [current_listeners[0]]
is_dispatching = [False]
def ensure_can_mutate_next_listeners():
if next_listeners[0] == current_listeners[0]:
next_listeners[0] = current_listeners[0][:]
def get_state():
return current_state[0]
def subscribe(listener):
if not hasattr(listener, '__call__'):
raise TypeError('Expected listener to be a function.')
is_subscribed = [True] # r/w closure
ensure_can_mutate_next_listeners()
next_listeners[0].append(listener)
def unsubcribe():
if not is_subscribed[0]:
return
is_subscribed[0] = False
ensure_can_mutate_next_listeners()
index = next_listeners[0].index(listener)
next_listeners[0].pop(index)
return unsubcribe
def dispatch(action):
if not isinstance(action, dict):
raise TypeError('Actions must be a dict. '
'Use custom middleware for async actions.')
if action.get('type') is None:
raise ValueError('Actions must have a non-None "type" property. '
'Have you misspelled a constant?')
if is_dispatching[0]:
raise Exception('Reducers may not dispatch actions.')
try:
is_dispatching[0] = True
current_state[0] = current_reducer[0](current_state[0], action)
finally:
is_dispatching[0] = False
listeners = current_listeners[0] = next_listeners[0]
for listener in listeners:
listener()
return action
def replace_reducer(next_reducer):
if not hasattr(next_reducer, '__call__'):
raise TypeError('Expected next_reducer to be a function')
current_reducer[0] = next_reducer
dispatch({'type': ActionTypes.INIT})
dispatch({'type': ActionTypes.INIT})
return StoreDict(
dispatch=dispatch,
subscribe=subscribe,
get_state=get_state,
replace_reducer=replace_reducer,
) | [
"def",
"create_store",
"(",
"reducer",
",",
"initial_state",
"=",
"None",
",",
"enhancer",
"=",
"None",
")",
":",
"if",
"enhancer",
"is",
"not",
"None",
":",
"if",
"not",
"hasattr",
"(",
"enhancer",
",",
"'__call__'",
")",
":",
"raise",
"TypeError",
"(",
"'Expected the enhancer to be a function.'",
")",
"return",
"enhancer",
"(",
"create_store",
")",
"(",
"reducer",
",",
"initial_state",
")",
"if",
"not",
"hasattr",
"(",
"reducer",
",",
"'__call__'",
")",
":",
"raise",
"TypeError",
"(",
"'Expected the reducer to be a function.'",
")",
"# single-element arrays for r/w closure",
"current_reducer",
"=",
"[",
"reducer",
"]",
"current_state",
"=",
"[",
"initial_state",
"]",
"current_listeners",
"=",
"[",
"[",
"]",
"]",
"next_listeners",
"=",
"[",
"current_listeners",
"[",
"0",
"]",
"]",
"is_dispatching",
"=",
"[",
"False",
"]",
"def",
"ensure_can_mutate_next_listeners",
"(",
")",
":",
"if",
"next_listeners",
"[",
"0",
"]",
"==",
"current_listeners",
"[",
"0",
"]",
":",
"next_listeners",
"[",
"0",
"]",
"=",
"current_listeners",
"[",
"0",
"]",
"[",
":",
"]",
"def",
"get_state",
"(",
")",
":",
"return",
"current_state",
"[",
"0",
"]",
"def",
"subscribe",
"(",
"listener",
")",
":",
"if",
"not",
"hasattr",
"(",
"listener",
",",
"'__call__'",
")",
":",
"raise",
"TypeError",
"(",
"'Expected listener to be a function.'",
")",
"is_subscribed",
"=",
"[",
"True",
"]",
"# r/w closure",
"ensure_can_mutate_next_listeners",
"(",
")",
"next_listeners",
"[",
"0",
"]",
".",
"append",
"(",
"listener",
")",
"def",
"unsubcribe",
"(",
")",
":",
"if",
"not",
"is_subscribed",
"[",
"0",
"]",
":",
"return",
"is_subscribed",
"[",
"0",
"]",
"=",
"False",
"ensure_can_mutate_next_listeners",
"(",
")",
"index",
"=",
"next_listeners",
"[",
"0",
"]",
".",
"index",
"(",
"listener",
")",
"next_listeners",
"[",
"0",
"]",
".",
"pop",
"(",
"index",
")",
"return",
"unsubcribe",
"def",
"dispatch",
"(",
"action",
")",
":",
"if",
"not",
"isinstance",
"(",
"action",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"'Actions must be a dict. '",
"'Use custom middleware for async actions.'",
")",
"if",
"action",
".",
"get",
"(",
"'type'",
")",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Actions must have a non-None \"type\" property. '",
"'Have you misspelled a constant?'",
")",
"if",
"is_dispatching",
"[",
"0",
"]",
":",
"raise",
"Exception",
"(",
"'Reducers may not dispatch actions.'",
")",
"try",
":",
"is_dispatching",
"[",
"0",
"]",
"=",
"True",
"current_state",
"[",
"0",
"]",
"=",
"current_reducer",
"[",
"0",
"]",
"(",
"current_state",
"[",
"0",
"]",
",",
"action",
")",
"finally",
":",
"is_dispatching",
"[",
"0",
"]",
"=",
"False",
"listeners",
"=",
"current_listeners",
"[",
"0",
"]",
"=",
"next_listeners",
"[",
"0",
"]",
"for",
"listener",
"in",
"listeners",
":",
"listener",
"(",
")",
"return",
"action",
"def",
"replace_reducer",
"(",
"next_reducer",
")",
":",
"if",
"not",
"hasattr",
"(",
"next_reducer",
",",
"'__call__'",
")",
":",
"raise",
"TypeError",
"(",
"'Expected next_reducer to be a function'",
")",
"current_reducer",
"[",
"0",
"]",
"=",
"next_reducer",
"dispatch",
"(",
"{",
"'type'",
":",
"ActionTypes",
".",
"INIT",
"}",
")",
"dispatch",
"(",
"{",
"'type'",
":",
"ActionTypes",
".",
"INIT",
"}",
")",
"return",
"StoreDict",
"(",
"dispatch",
"=",
"dispatch",
",",
"subscribe",
"=",
"subscribe",
",",
"get_state",
"=",
"get_state",
",",
"replace_reducer",
"=",
"replace_reducer",
",",
")"
] | redux in a nutshell.
observable has been omitted.
Args:
reducer: root reducer function for the state tree
initial_state: optional initial state data
enhancer: optional enhancer function for middleware etc.
Returns:
a Pydux store | [
"redux",
"in",
"a",
"nutshell",
"."
] | train | https://github.com/usrlocalben/pydux/blob/943ca1c75357b9289f55f17ff2d997a66a3313a4/pydux/create_store.py#L30-L124 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.