id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
27,400
cjdrake/pyeda
pyeda/parsing/dimacs.py
_sat
def _sat(lexer, varname): """Return a DIMACS SAT.""" _expect_token(lexer, {KW_p}) fmt = _expect_token(lexer, {KW_sat, KW_satx, KW_sate, KW_satex}).value nvars = _expect_token(lexer, {IntegerToken}).value return _sat_formula(lexer, varname, fmt, nvars)
python
def _sat(lexer, varname): _expect_token(lexer, {KW_p}) fmt = _expect_token(lexer, {KW_sat, KW_satx, KW_sate, KW_satex}).value nvars = _expect_token(lexer, {IntegerToken}).value return _sat_formula(lexer, varname, fmt, nvars)
[ "def", "_sat", "(", "lexer", ",", "varname", ")", ":", "_expect_token", "(", "lexer", ",", "{", "KW_p", "}", ")", "fmt", "=", "_expect_token", "(", "lexer", ",", "{", "KW_sat", ",", "KW_satx", ",", "KW_sate", ",", "KW_satex", "}", ")", ".", "value", ...
Return a DIMACS SAT.
[ "Return", "a", "DIMACS", "SAT", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L377-L382
27,401
cjdrake/pyeda
pyeda/parsing/dimacs.py
_sat_formula
def _sat_formula(lexer, varname, fmt, nvars): """Return a DIMACS SAT formula.""" types = {IntegerToken, LPAREN} | _SAT_TOKS[fmt] tok = _expect_token(lexer, types) # INT if isinstance(tok, IntegerToken): index = tok.value if not 0 < index <= nvars: fstr = "formula literal {} outside valid range: (0, {}]" raise Error(fstr.format(index, nvars)) return ('var', (varname, ), (index, )) # '-' elif isinstance(tok, OP_not): tok = _expect_token(lexer, {IntegerToken, LPAREN}) # '-' INT if isinstance(tok, IntegerToken): index = tok.value if not 0 < index <= nvars: fstr = "formula literal {} outside valid range: (0, {}]" raise Error(fstr.format(index, nvars)) return ('not', ('var', (varname, ), (index, ))) # '-' '(' FORMULA ')' else: formula = _sat_formula(lexer, varname, fmt, nvars) _expect_token(lexer, {RPAREN}) return ('not', formula) # '(' FORMULA ')' elif isinstance(tok, LPAREN): formula = _sat_formula(lexer, varname, fmt, nvars) _expect_token(lexer, {RPAREN}) return formula # OP '(' FORMULAS ')' else: _expect_token(lexer, {LPAREN}) formulas = _formulas(lexer, varname, fmt, nvars) _expect_token(lexer, {RPAREN}) return (tok.ASTOP, ) + formulas
python
def _sat_formula(lexer, varname, fmt, nvars): types = {IntegerToken, LPAREN} | _SAT_TOKS[fmt] tok = _expect_token(lexer, types) # INT if isinstance(tok, IntegerToken): index = tok.value if not 0 < index <= nvars: fstr = "formula literal {} outside valid range: (0, {}]" raise Error(fstr.format(index, nvars)) return ('var', (varname, ), (index, )) # '-' elif isinstance(tok, OP_not): tok = _expect_token(lexer, {IntegerToken, LPAREN}) # '-' INT if isinstance(tok, IntegerToken): index = tok.value if not 0 < index <= nvars: fstr = "formula literal {} outside valid range: (0, {}]" raise Error(fstr.format(index, nvars)) return ('not', ('var', (varname, ), (index, ))) # '-' '(' FORMULA ')' else: formula = _sat_formula(lexer, varname, fmt, nvars) _expect_token(lexer, {RPAREN}) return ('not', formula) # '(' FORMULA ')' elif isinstance(tok, LPAREN): formula = _sat_formula(lexer, varname, fmt, nvars) _expect_token(lexer, {RPAREN}) return formula # OP '(' FORMULAS ')' else: _expect_token(lexer, {LPAREN}) formulas = _formulas(lexer, varname, fmt, nvars) _expect_token(lexer, {RPAREN}) return (tok.ASTOP, ) + formulas
[ "def", "_sat_formula", "(", "lexer", ",", "varname", ",", "fmt", ",", "nvars", ")", ":", "types", "=", "{", "IntegerToken", ",", "LPAREN", "}", "|", "_SAT_TOKS", "[", "fmt", "]", "tok", "=", "_expect_token", "(", "lexer", ",", "types", ")", "# INT", ...
Return a DIMACS SAT formula.
[ "Return", "a", "DIMACS", "SAT", "formula", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L385-L421
27,402
cjdrake/pyeda
pyeda/parsing/dimacs.py
_formulas
def _formulas(lexer, varname, fmt, nvars): """Return a tuple of DIMACS SAT formulas.""" types = {IntegerToken, LPAREN} | _SAT_TOKS[fmt] tok = lexer.peek_token() if any(isinstance(tok, t) for t in types): first = _sat_formula(lexer, varname, fmt, nvars) rest = _formulas(lexer, varname, fmt, nvars) return (first, ) + rest # null else: return tuple()
python
def _formulas(lexer, varname, fmt, nvars): types = {IntegerToken, LPAREN} | _SAT_TOKS[fmt] tok = lexer.peek_token() if any(isinstance(tok, t) for t in types): first = _sat_formula(lexer, varname, fmt, nvars) rest = _formulas(lexer, varname, fmt, nvars) return (first, ) + rest # null else: return tuple()
[ "def", "_formulas", "(", "lexer", ",", "varname", ",", "fmt", ",", "nvars", ")", ":", "types", "=", "{", "IntegerToken", ",", "LPAREN", "}", "|", "_SAT_TOKS", "[", "fmt", "]", "tok", "=", "lexer", ".", "peek_token", "(", ")", "if", "any", "(", "isi...
Return a tuple of DIMACS SAT formulas.
[ "Return", "a", "tuple", "of", "DIMACS", "SAT", "formulas", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L424-L434
27,403
cjdrake/pyeda
pyeda/parsing/dimacs.py
CNFLexer.keyword
def keyword(self, text): """Push a keyword onto the token queue.""" cls = self.KEYWORDS[text] self.push_token(cls(text, self.lineno, self.offset))
python
def keyword(self, text): cls = self.KEYWORDS[text] self.push_token(cls(text, self.lineno, self.offset))
[ "def", "keyword", "(", "self", ",", "text", ")", ":", "cls", "=", "self", ".", "KEYWORDS", "[", "text", "]", "self", ".", "push_token", "(", "cls", "(", "text", ",", "self", ".", "lineno", ",", "self", ".", "offset", ")", ")" ]
Push a keyword onto the token queue.
[ "Push", "a", "keyword", "onto", "the", "token", "queue", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L91-L94
27,404
cjdrake/pyeda
pyeda/parsing/dimacs.py
CNFLexer.operator
def operator(self, text): """Push an operator onto the token queue.""" cls = self.OPERATORS[text] self.push_token(cls(text, self.lineno, self.offset))
python
def operator(self, text): cls = self.OPERATORS[text] self.push_token(cls(text, self.lineno, self.offset))
[ "def", "operator", "(", "self", ",", "text", ")", ":", "cls", "=", "self", ".", "OPERATORS", "[", "text", "]", "self", ".", "push_token", "(", "cls", "(", "text", ",", "self", ".", "lineno", ",", "self", ".", "offset", ")", ")" ]
Push an operator onto the token queue.
[ "Push", "an", "operator", "onto", "the", "token", "queue", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L96-L99
27,405
cjdrake/pyeda
pyeda/parsing/dimacs.py
SATLexer.punct
def punct(self, text): """Push punctuation onto the token queue.""" cls = self.PUNCTUATION[text] self.push_token(cls(text, self.lineno, self.offset))
python
def punct(self, text): cls = self.PUNCTUATION[text] self.push_token(cls(text, self.lineno, self.offset))
[ "def", "punct", "(", "self", ",", "text", ")", ":", "cls", "=", "self", ".", "PUNCTUATION", "[", "text", "]", "self", ".", "push_token", "(", "cls", "(", "text", ",", "self", ".", "lineno", ",", "self", ".", "offset", ")", ")" ]
Push punctuation onto the token queue.
[ "Push", "punctuation", "onto", "the", "token", "queue", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L266-L269
27,406
cjdrake/pyeda
pyeda/parsing/pla.py
parse
def parse(s): """ Parse an input string in PLA format, and return an intermediate representation dict. Parameters ---------- s : str String containing a PLA. Returns ------- A dict with all PLA information: =============== ============ ================================= Key Value type Value description =============== ============ ================================= ninputs int Number of inputs noutputs int Number of outputs input_labels list Input variable names output_labels list Output function names intype int Cover type: {F, R, FD, FR, DR, FDR} cover set Implicant table =============== ============ ================================= """ d = dict(ninputs=None, noutputs=None, input_labels=None, output_labels=None, intype=None, cover=set()) lines = [line.strip() for line in s.splitlines()] for i, line in enumerate(lines, start=1): # skip comments if not line or _COMMENT.match(line): continue # .i m_in = _NINS.match(line) if m_in: if d['ninputs'] is None: d['ninputs'] = int(m_in.group(1)) continue else: raise Error(".i declared more than once") # .o m_out = _NOUTS.match(line) if m_out: if d['noutputs'] is None: d['noutputs'] = int(m_out.group(1)) continue else: raise Error(".o declared more than once") # ignore .p m_prod = _PROD.match(line) if m_prod: continue # .ilb m_ilb = _ILB.match(line) if m_ilb: if d['input_labels'] is None: d['input_labels'] = m_ilb.group(1).split() continue else: raise Error(".ilb declared more than once") # .ob m_ob = _OB.match(line) if m_ob: if d['output_labels'] is None: d['output_labels'] = m_ob.group(1).split() continue else: raise Error(".ob declared more than once") # .type m_type = _TYPE.match(line) if m_type: if d['intype'] is None: d['intype'] = _TYPES[m_type.group(1)] continue else: raise Error(".type declared more tha once") # cube m_cube = _CUBE.match(line) if m_cube: inputs, outputs = m_cube.groups() invec = tuple(_INCODE[c] for c in inputs) outvec = tuple(_OUTCODE[c] for c in outputs) d['cover'].add((invec, outvec)) continue # ignore .e m_end = _END.match(line) if m_end: continue raise Error("syntax error on line {}: {}".format(i, line)) return d
python
def parse(s): d = dict(ninputs=None, noutputs=None, input_labels=None, output_labels=None, intype=None, cover=set()) lines = [line.strip() for line in s.splitlines()] for i, line in enumerate(lines, start=1): # skip comments if not line or _COMMENT.match(line): continue # .i m_in = _NINS.match(line) if m_in: if d['ninputs'] is None: d['ninputs'] = int(m_in.group(1)) continue else: raise Error(".i declared more than once") # .o m_out = _NOUTS.match(line) if m_out: if d['noutputs'] is None: d['noutputs'] = int(m_out.group(1)) continue else: raise Error(".o declared more than once") # ignore .p m_prod = _PROD.match(line) if m_prod: continue # .ilb m_ilb = _ILB.match(line) if m_ilb: if d['input_labels'] is None: d['input_labels'] = m_ilb.group(1).split() continue else: raise Error(".ilb declared more than once") # .ob m_ob = _OB.match(line) if m_ob: if d['output_labels'] is None: d['output_labels'] = m_ob.group(1).split() continue else: raise Error(".ob declared more than once") # .type m_type = _TYPE.match(line) if m_type: if d['intype'] is None: d['intype'] = _TYPES[m_type.group(1)] continue else: raise Error(".type declared more tha once") # cube m_cube = _CUBE.match(line) if m_cube: inputs, outputs = m_cube.groups() invec = tuple(_INCODE[c] for c in inputs) outvec = tuple(_OUTCODE[c] for c in outputs) d['cover'].add((invec, outvec)) continue # ignore .e m_end = _END.match(line) if m_end: continue raise Error("syntax error on line {}: {}".format(i, line)) return d
[ "def", "parse", "(", "s", ")", ":", "d", "=", "dict", "(", "ninputs", "=", "None", ",", "noutputs", "=", "None", ",", "input_labels", "=", "None", ",", "output_labels", "=", "None", ",", "intype", "=", "None", ",", "cover", "=", "set", "(", ")", ...
Parse an input string in PLA format, and return an intermediate representation dict. Parameters ---------- s : str String containing a PLA. Returns ------- A dict with all PLA information: =============== ============ ================================= Key Value type Value description =============== ============ ================================= ninputs int Number of inputs noutputs int Number of outputs input_labels list Input variable names output_labels list Output function names intype int Cover type: {F, R, FD, FR, DR, FDR} cover set Implicant table =============== ============ =================================
[ "Parse", "an", "input", "string", "in", "PLA", "format", "and", "return", "an", "intermediate", "representation", "dict", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/pla.py#L50-L151
27,407
cjdrake/pyeda
pyeda/parsing/lex.py
action
def action(toktype): """Return a parser action property.""" def outer(func): """Return a function that pushes a token onto the token queue.""" def inner(lexer, text): """Push a token onto the token queue.""" value = func(lexer, text) lexer.tokens.append(toktype(value, lexer.lineno, lexer.offset)) return inner return outer
python
def action(toktype): def outer(func): """Return a function that pushes a token onto the token queue.""" def inner(lexer, text): """Push a token onto the token queue.""" value = func(lexer, text) lexer.tokens.append(toktype(value, lexer.lineno, lexer.offset)) return inner return outer
[ "def", "action", "(", "toktype", ")", ":", "def", "outer", "(", "func", ")", ":", "\"\"\"Return a function that pushes a token onto the token queue.\"\"\"", "def", "inner", "(", "lexer", ",", "text", ")", ":", "\"\"\"Push a token onto the token queue.\"\"\"", "value", "...
Return a parser action property.
[ "Return", "a", "parser", "action", "property", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/lex.py#L174-L183
27,408
cjdrake/pyeda
pyeda/parsing/lex.py
RegexLexer._compile_rules
def _compile_rules(self): """Compile the rules into the internal lexer state.""" for state, table in self.RULES.items(): patterns = list() actions = list() nextstates = list() for i, row in enumerate(table): if len(row) == 2: pattern, _action = row nextstate = None elif len(row) == 3: pattern, _action, nextstate = row else: fstr = "invalid RULES: state {}, row {}" raise CompileError(fstr.format(state, i)) patterns.append(pattern) actions.append(_action) nextstates.append(nextstate) reobj = re.compile('|'.join("(" + p + ")" for p in patterns)) self._rules[state] = (reobj, actions, nextstates)
python
def _compile_rules(self): for state, table in self.RULES.items(): patterns = list() actions = list() nextstates = list() for i, row in enumerate(table): if len(row) == 2: pattern, _action = row nextstate = None elif len(row) == 3: pattern, _action, nextstate = row else: fstr = "invalid RULES: state {}, row {}" raise CompileError(fstr.format(state, i)) patterns.append(pattern) actions.append(_action) nextstates.append(nextstate) reobj = re.compile('|'.join("(" + p + ")" for p in patterns)) self._rules[state] = (reobj, actions, nextstates)
[ "def", "_compile_rules", "(", "self", ")", ":", "for", "state", ",", "table", "in", "self", ".", "RULES", ".", "items", "(", ")", ":", "patterns", "=", "list", "(", ")", "actions", "=", "list", "(", ")", "nextstates", "=", "list", "(", ")", "for", ...
Compile the rules into the internal lexer state.
[ "Compile", "the", "rules", "into", "the", "internal", "lexer", "state", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/lex.py#L83-L102
27,409
cjdrake/pyeda
pyeda/parsing/lex.py
RegexLexer._iter_tokens
def _iter_tokens(self): """Iterate through all tokens in the input string.""" reobj, actions, nextstates = self._rules[self.states[-1]] mobj = reobj.match(self.string, self.pos) while mobj is not None: text = mobj.group(0) idx = mobj.lastindex - 1 nextstate = nextstates[idx] # Take action actions[idx](self, text) while self.tokens: yield self.pop_token() if nextstate and nextstate != self.states[-1]: self.states[-1] = nextstate # Update position variables self.pos = mobj.end() lines = text.split('\n') nlines = len(lines) - 1 if nlines == 0: self.offset = self.offset + len(lines[0]) else: self.lineno = self.lineno + nlines self.offset = 1 + len(lines[-1]) reobj, actions, nextstates = self._rules[self.states[-1]] mobj = reobj.match(self.string, self.pos) if self.pos != len(self.string): msg = "unexpected character" text = self.string[self.pos] raise RunError(msg, self.lineno, self.offset, text) yield EndToken("", self.lineno, self.offset)
python
def _iter_tokens(self): reobj, actions, nextstates = self._rules[self.states[-1]] mobj = reobj.match(self.string, self.pos) while mobj is not None: text = mobj.group(0) idx = mobj.lastindex - 1 nextstate = nextstates[idx] # Take action actions[idx](self, text) while self.tokens: yield self.pop_token() if nextstate and nextstate != self.states[-1]: self.states[-1] = nextstate # Update position variables self.pos = mobj.end() lines = text.split('\n') nlines = len(lines) - 1 if nlines == 0: self.offset = self.offset + len(lines[0]) else: self.lineno = self.lineno + nlines self.offset = 1 + len(lines[-1]) reobj, actions, nextstates = self._rules[self.states[-1]] mobj = reobj.match(self.string, self.pos) if self.pos != len(self.string): msg = "unexpected character" text = self.string[self.pos] raise RunError(msg, self.lineno, self.offset, text) yield EndToken("", self.lineno, self.offset)
[ "def", "_iter_tokens", "(", "self", ")", ":", "reobj", ",", "actions", ",", "nextstates", "=", "self", ".", "_rules", "[", "self", ".", "states", "[", "-", "1", "]", "]", "mobj", "=", "reobj", ".", "match", "(", "self", ".", "string", ",", "self", ...
Iterate through all tokens in the input string.
[ "Iterate", "through", "all", "tokens", "in", "the", "input", "string", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/lex.py#L104-L138
27,410
cjdrake/pyeda
pyeda/util.py
parity
def parity(num: int) -> int: """Return the parity of a non-negative integer. For example, here are the parities of the first ten integers: >>> [parity(n) for n in range(10)] [0, 1, 1, 0, 1, 0, 0, 1, 1, 0] This function is undefined for negative integers: >>> parity(-1) Traceback (most recent call last): ... ValueError: expected num >= 0 """ if num < 0: raise ValueError("expected num >= 0") par = 0 while num: par ^= (num & 1) num >>= 1 return par
python
def parity(num: int) -> int: if num < 0: raise ValueError("expected num >= 0") par = 0 while num: par ^= (num & 1) num >>= 1 return par
[ "def", "parity", "(", "num", ":", "int", ")", "->", "int", ":", "if", "num", "<", "0", ":", "raise", "ValueError", "(", "\"expected num >= 0\"", ")", "par", "=", "0", "while", "num", ":", "par", "^=", "(", "num", "&", "1", ")", "num", ">>=", "1",...
Return the parity of a non-negative integer. For example, here are the parities of the first ten integers: >>> [parity(n) for n in range(10)] [0, 1, 1, 0, 1, 0, 0, 1, 1, 0] This function is undefined for negative integers: >>> parity(-1) Traceback (most recent call last): ... ValueError: expected num >= 0
[ "Return", "the", "parity", "of", "a", "non", "-", "negative", "integer", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/util.py#L56-L77
27,411
cjdrake/pyeda
pyeda/util.py
cached_property
def cached_property(func): """Return a cached property calculated by the input function. Unlike the ``property`` decorator builtin, this decorator will cache the return value in order to avoid repeated calculations. This is particularly useful when the property involves some non-trivial computation. For example, consider a class that models a right triangle. The hypotenuse ``c`` will only be calculated once. .. code-block:: python import math class RightTriangle: def __init__(self, a, b): self.a = a self.b = b @cached_property def c(self): return math.sqrt(self.a**2 + self.b**2) """ def get(self): """this docstring will be over-written by func.__doc__""" try: return self._property_cache[func] except AttributeError: self._property_cache = dict() prop = self._property_cache[func] = func(self) return prop except KeyError: prop = self._property_cache[func] = func(self) return prop get.__doc__ = func.__doc__ return property(get)
python
def cached_property(func): def get(self): """this docstring will be over-written by func.__doc__""" try: return self._property_cache[func] except AttributeError: self._property_cache = dict() prop = self._property_cache[func] = func(self) return prop except KeyError: prop = self._property_cache[func] = func(self) return prop get.__doc__ = func.__doc__ return property(get)
[ "def", "cached_property", "(", "func", ")", ":", "def", "get", "(", "self", ")", ":", "\"\"\"this docstring will be over-written by func.__doc__\"\"\"", "try", ":", "return", "self", ".", "_property_cache", "[", "func", "]", "except", "AttributeError", ":", "self", ...
Return a cached property calculated by the input function. Unlike the ``property`` decorator builtin, this decorator will cache the return value in order to avoid repeated calculations. This is particularly useful when the property involves some non-trivial computation. For example, consider a class that models a right triangle. The hypotenuse ``c`` will only be calculated once. .. code-block:: python import math class RightTriangle: def __init__(self, a, b): self.a = a self.b = b @cached_property def c(self): return math.sqrt(self.a**2 + self.b**2)
[ "Return", "a", "cached", "property", "calculated", "by", "the", "input", "function", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/util.py#L80-L116
27,412
cjdrake/pyeda
pyeda/boolalg/boolfunc.py
var
def var(name, index=None): """Return a unique Variable instance. .. note:: Do **NOT** call this function directly. Instead, use one of the concrete implementations: * :func:`pyeda.boolalg.bdd.bddvar` * :func:`pyeda.boolalg.expr.exprvar`, * :func:`pyeda.boolalg.table.ttvar`. """ tname = type(name) if tname is str: names = (name, ) elif tname is tuple: names = name else: fstr = "expected name to be a str or tuple, got {0.__name__}" raise TypeError(fstr.format(tname)) if not names: raise ValueError("expected at least one name") for name in names: tname = type(name) if tname is not str: fstr = "expected name to be a str, got {0.__name__}" raise TypeError(fstr.format(tname)) if index is None: indices = tuple() else: tindex = type(index) if tindex is int: indices = (index, ) elif tindex is tuple: indices = index else: fstr = "expected index to be an int or tuple, got {0.__name__}" raise TypeError(fstr.format(tindex)) for index in indices: tindex = type(index) if tindex is not int: fstr = "expected index to be an int, got {0.__name__}" raise TypeError(fstr.format(tindex)) if index < 0: fstr = "expected index to be >= 0, got {}" raise ValueError(fstr.format(index)) try: v = VARIABLES[(names, indices)] except KeyError: v = Variable(names, indices) VARIABLES[(names, indices)] = v return v
python
def var(name, index=None): tname = type(name) if tname is str: names = (name, ) elif tname is tuple: names = name else: fstr = "expected name to be a str or tuple, got {0.__name__}" raise TypeError(fstr.format(tname)) if not names: raise ValueError("expected at least one name") for name in names: tname = type(name) if tname is not str: fstr = "expected name to be a str, got {0.__name__}" raise TypeError(fstr.format(tname)) if index is None: indices = tuple() else: tindex = type(index) if tindex is int: indices = (index, ) elif tindex is tuple: indices = index else: fstr = "expected index to be an int or tuple, got {0.__name__}" raise TypeError(fstr.format(tindex)) for index in indices: tindex = type(index) if tindex is not int: fstr = "expected index to be an int, got {0.__name__}" raise TypeError(fstr.format(tindex)) if index < 0: fstr = "expected index to be >= 0, got {}" raise ValueError(fstr.format(index)) try: v = VARIABLES[(names, indices)] except KeyError: v = Variable(names, indices) VARIABLES[(names, indices)] = v return v
[ "def", "var", "(", "name", ",", "index", "=", "None", ")", ":", "tname", "=", "type", "(", "name", ")", "if", "tname", "is", "str", ":", "names", "=", "(", "name", ",", ")", "elif", "tname", "is", "tuple", ":", "names", "=", "name", "else", ":"...
Return a unique Variable instance. .. note:: Do **NOT** call this function directly. Instead, use one of the concrete implementations: * :func:`pyeda.boolalg.bdd.bddvar` * :func:`pyeda.boolalg.expr.exprvar`, * :func:`pyeda.boolalg.table.ttvar`.
[ "Return", "a", "unique", "Variable", "instance", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/boolfunc.py#L65-L120
27,413
cjdrake/pyeda
pyeda/boolalg/boolfunc.py
Function.iter_cofactors
def iter_cofactors(self, vs=None): r"""Iterate through the cofactors of a function over N variables. The *vs* argument is a sequence of :math:`N` Boolean variables. The *cofactor* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with respect to variable :math:`x_i` is: :math:`f_{x_i} = f(x_1, x_2, \dots, 1, \dots, x_n)` The *cofactor* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with respect to variable :math:`x_i'` is: :math:`f_{x_i'} = f(x_1, x_2, \dots, 0, \dots, x_n)` """ vs = self._expect_vars(vs) for point in iter_points(vs): yield self.restrict(point)
python
def iter_cofactors(self, vs=None): r"""Iterate through the cofactors of a function over N variables. The *vs* argument is a sequence of :math:`N` Boolean variables. The *cofactor* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with respect to variable :math:`x_i` is: :math:`f_{x_i} = f(x_1, x_2, \dots, 1, \dots, x_n)` The *cofactor* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with respect to variable :math:`x_i'` is: :math:`f_{x_i'} = f(x_1, x_2, \dots, 0, \dots, x_n)` """ vs = self._expect_vars(vs) for point in iter_points(vs): yield self.restrict(point)
[ "def", "iter_cofactors", "(", "self", ",", "vs", "=", "None", ")", ":", "vs", "=", "self", ".", "_expect_vars", "(", "vs", ")", "for", "point", "in", "iter_points", "(", "vs", ")", ":", "yield", "self", ".", "restrict", "(", "point", ")" ]
r"""Iterate through the cofactors of a function over N variables. The *vs* argument is a sequence of :math:`N` Boolean variables. The *cofactor* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with respect to variable :math:`x_i` is: :math:`f_{x_i} = f(x_1, x_2, \dots, 1, \dots, x_n)` The *cofactor* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with respect to variable :math:`x_i'` is: :math:`f_{x_i'} = f(x_1, x_2, \dots, 0, \dots, x_n)`
[ "r", "Iterate", "through", "the", "cofactors", "of", "a", "function", "over", "N", "variables", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/boolfunc.py#L633-L648
27,414
cjdrake/pyeda
pyeda/boolalg/boolfunc.py
Function.smoothing
def smoothing(self, vs=None): r"""Return the smoothing of a function over a sequence of N variables. The *vs* argument is a sequence of :math:`N` Boolean variables. The *smoothing* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with respect to variable :math:`x_i` is: :math:`S_{x_i}(f) = f_{x_i} + f_{x_i'}` This is the same as the existential quantification operator: :math:`\exists \{x_1, x_2, \dots\} \: f` """ return functools.reduce(operator.or_, self.iter_cofactors(vs))
python
def smoothing(self, vs=None): r"""Return the smoothing of a function over a sequence of N variables. The *vs* argument is a sequence of :math:`N` Boolean variables. The *smoothing* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with respect to variable :math:`x_i` is: :math:`S_{x_i}(f) = f_{x_i} + f_{x_i'}` This is the same as the existential quantification operator: :math:`\exists \{x_1, x_2, \dots\} \: f` """ return functools.reduce(operator.or_, self.iter_cofactors(vs))
[ "def", "smoothing", "(", "self", ",", "vs", "=", "None", ")", ":", "return", "functools", ".", "reduce", "(", "operator", ".", "or_", ",", "self", ".", "iter_cofactors", "(", "vs", ")", ")" ]
r"""Return the smoothing of a function over a sequence of N variables. The *vs* argument is a sequence of :math:`N` Boolean variables. The *smoothing* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with respect to variable :math:`x_i` is: :math:`S_{x_i}(f) = f_{x_i} + f_{x_i'}` This is the same as the existential quantification operator: :math:`\exists \{x_1, x_2, \dots\} \: f`
[ "r", "Return", "the", "smoothing", "of", "a", "function", "over", "a", "sequence", "of", "N", "variables", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/boolfunc.py#L665-L677
27,415
cjdrake/pyeda
pyeda/boolalg/boolfunc.py
Function.consensus
def consensus(self, vs=None): r"""Return the consensus of a function over a sequence of N variables. The *vs* argument is a sequence of :math:`N` Boolean variables. The *consensus* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with respect to variable :math:`x_i` is: :math:`C_{x_i}(f) = f_{x_i} \cdot f_{x_i'}` This is the same as the universal quantification operator: :math:`\forall \{x_1, x_2, \dots\} \: f` """ return functools.reduce(operator.and_, self.iter_cofactors(vs))
python
def consensus(self, vs=None): r"""Return the consensus of a function over a sequence of N variables. The *vs* argument is a sequence of :math:`N` Boolean variables. The *consensus* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with respect to variable :math:`x_i` is: :math:`C_{x_i}(f) = f_{x_i} \cdot f_{x_i'}` This is the same as the universal quantification operator: :math:`\forall \{x_1, x_2, \dots\} \: f` """ return functools.reduce(operator.and_, self.iter_cofactors(vs))
[ "def", "consensus", "(", "self", ",", "vs", "=", "None", ")", ":", "return", "functools", ".", "reduce", "(", "operator", ".", "and_", ",", "self", ".", "iter_cofactors", "(", "vs", ")", ")" ]
r"""Return the consensus of a function over a sequence of N variables. The *vs* argument is a sequence of :math:`N` Boolean variables. The *consensus* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with respect to variable :math:`x_i` is: :math:`C_{x_i}(f) = f_{x_i} \cdot f_{x_i'}` This is the same as the universal quantification operator: :math:`\forall \{x_1, x_2, \dots\} \: f`
[ "r", "Return", "the", "consensus", "of", "a", "function", "over", "a", "sequence", "of", "N", "variables", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/boolfunc.py#L679-L691
27,416
cjdrake/pyeda
pyeda/boolalg/boolfunc.py
Function.derivative
def derivative(self, vs=None): r"""Return the derivative of a function over a sequence of N variables. The *vs* argument is a sequence of :math:`N` Boolean variables. The *derivative* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with respect to variable :math:`x_i` is: :math:`\frac{\partial}{\partial x_i} f = f_{x_i} \oplus f_{x_i'}` This is also known as the Boolean *difference*. """ return functools.reduce(operator.xor, self.iter_cofactors(vs))
python
def derivative(self, vs=None): r"""Return the derivative of a function over a sequence of N variables. The *vs* argument is a sequence of :math:`N` Boolean variables. The *derivative* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with respect to variable :math:`x_i` is: :math:`\frac{\partial}{\partial x_i} f = f_{x_i} \oplus f_{x_i'}` This is also known as the Boolean *difference*. """ return functools.reduce(operator.xor, self.iter_cofactors(vs))
[ "def", "derivative", "(", "self", ",", "vs", "=", "None", ")", ":", "return", "functools", ".", "reduce", "(", "operator", ".", "xor", ",", "self", ".", "iter_cofactors", "(", "vs", ")", ")" ]
r"""Return the derivative of a function over a sequence of N variables. The *vs* argument is a sequence of :math:`N` Boolean variables. The *derivative* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with respect to variable :math:`x_i` is: :math:`\frac{\partial}{\partial x_i} f = f_{x_i} \oplus f_{x_i'}` This is also known as the Boolean *difference*.
[ "r", "Return", "the", "derivative", "of", "a", "function", "over", "a", "sequence", "of", "N", "variables", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/boolfunc.py#L693-L704
27,417
cjdrake/pyeda
pyeda/boolalg/boolfunc.py
Function._expect_vars
def _expect_vars(vs=None): """Verify the input type and return a list of Variables.""" if vs is None: return list() elif isinstance(vs, Variable): return [vs] else: checked = list() # Will raise TypeError if vs is not iterable for v in vs: if isinstance(v, Variable): checked.append(v) else: fstr = "expected Variable, got {0.__name__}" raise TypeError(fstr.format(type(v))) return checked
python
def _expect_vars(vs=None): if vs is None: return list() elif isinstance(vs, Variable): return [vs] else: checked = list() # Will raise TypeError if vs is not iterable for v in vs: if isinstance(v, Variable): checked.append(v) else: fstr = "expected Variable, got {0.__name__}" raise TypeError(fstr.format(type(v))) return checked
[ "def", "_expect_vars", "(", "vs", "=", "None", ")", ":", "if", "vs", "is", "None", ":", "return", "list", "(", ")", "elif", "isinstance", "(", "vs", ",", "Variable", ")", ":", "return", "[", "vs", "]", "else", ":", "checked", "=", "list", "(", ")...
Verify the input type and return a list of Variables.
[ "Verify", "the", "input", "type", "and", "return", "a", "list", "of", "Variables", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/boolfunc.py#L739-L754
27,418
cjdrake/pyeda
pyeda/logic/sudoku.py
SudokuSolver.solve
def solve(self, grid): """Return a solution point for a Sudoku grid.""" soln = self.S.satisfy_one(assumptions=self._parse_grid(grid)) return self.S.soln2point(soln, self.litmap)
python
def solve(self, grid): soln = self.S.satisfy_one(assumptions=self._parse_grid(grid)) return self.S.soln2point(soln, self.litmap)
[ "def", "solve", "(", "self", ",", "grid", ")", ":", "soln", "=", "self", ".", "S", ".", "satisfy_one", "(", "assumptions", "=", "self", ".", "_parse_grid", "(", "grid", ")", ")", "return", "self", ".", "S", ".", "soln2point", "(", "soln", ",", "sel...
Return a solution point for a Sudoku grid.
[ "Return", "a", "solution", "point", "for", "a", "Sudoku", "grid", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/sudoku.py#L38-L41
27,419
cjdrake/pyeda
pyeda/logic/sudoku.py
SudokuSolver._parse_grid
def _parse_grid(self, grid): """Return the input constraints for a Sudoku grid.""" chars = [c for c in grid if c in DIGITS or c in "0."] if len(chars) != 9**2: raise ValueError("expected 9x9 grid") return [self.litmap[self.X[i // 9 + 1, i % 9 + 1, int(c)]] for i, c in enumerate(chars) if c in DIGITS]
python
def _parse_grid(self, grid): chars = [c for c in grid if c in DIGITS or c in "0."] if len(chars) != 9**2: raise ValueError("expected 9x9 grid") return [self.litmap[self.X[i // 9 + 1, i % 9 + 1, int(c)]] for i, c in enumerate(chars) if c in DIGITS]
[ "def", "_parse_grid", "(", "self", ",", "grid", ")", ":", "chars", "=", "[", "c", "for", "c", "in", "grid", "if", "c", "in", "DIGITS", "or", "c", "in", "\"0.\"", "]", "if", "len", "(", "chars", ")", "!=", "9", "**", "2", ":", "raise", "ValueErr...
Return the input constraints for a Sudoku grid.
[ "Return", "the", "input", "constraints", "for", "a", "Sudoku", "grid", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/sudoku.py#L47-L53
27,420
cjdrake/pyeda
pyeda/logic/sudoku.py
SudokuSolver._soln2str
def _soln2str(self, soln, fancy=False): """Convert a Sudoku solution point to a string.""" chars = list() for r in range(1, 10): for c in range(1, 10): if fancy and c in (4, 7): chars.append("|") chars.append(self._get_val(soln, r, c)) if fancy and r != 9: chars.append("\n") if r in (3, 6): chars.append("---+---+---\n") return "".join(chars)
python
def _soln2str(self, soln, fancy=False): chars = list() for r in range(1, 10): for c in range(1, 10): if fancy and c in (4, 7): chars.append("|") chars.append(self._get_val(soln, r, c)) if fancy and r != 9: chars.append("\n") if r in (3, 6): chars.append("---+---+---\n") return "".join(chars)
[ "def", "_soln2str", "(", "self", ",", "soln", ",", "fancy", "=", "False", ")", ":", "chars", "=", "list", "(", ")", "for", "r", "in", "range", "(", "1", ",", "10", ")", ":", "for", "c", "in", "range", "(", "1", ",", "10", ")", ":", "if", "f...
Convert a Sudoku solution point to a string.
[ "Convert", "a", "Sudoku", "solution", "point", "to", "a", "string", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/sudoku.py#L55-L67
27,421
cjdrake/pyeda
pyeda/logic/sudoku.py
SudokuSolver._get_val
def _get_val(self, soln, r, c): """Return the string value for a solution coordinate.""" for v in range(1, 10): if soln[self.X[r, c, v]]: return DIGITS[v-1] return "X"
python
def _get_val(self, soln, r, c): for v in range(1, 10): if soln[self.X[r, c, v]]: return DIGITS[v-1] return "X"
[ "def", "_get_val", "(", "self", ",", "soln", ",", "r", ",", "c", ")", ":", "for", "v", "in", "range", "(", "1", ",", "10", ")", ":", "if", "soln", "[", "self", ".", "X", "[", "r", ",", "c", ",", "v", "]", "]", ":", "return", "DIGITS", "["...
Return the string value for a solution coordinate.
[ "Return", "the", "string", "value", "for", "a", "solution", "coordinate", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/sudoku.py#L69-L74
27,422
cjdrake/pyeda
pyeda/boolalg/table.py
ttvar
def ttvar(name, index=None): """Return a TruthTable variable. Parameters ---------- name : str The variable's identifier string. index : int or tuple[int], optional One or more integer suffixes for variables that are part of a multi-dimensional bit-vector, eg x[1], x[1][2][3] """ bvar = boolfunc.var(name, index) try: var = _VARS[bvar.uniqid] except KeyError: var = _VARS[bvar.uniqid] = TTVariable(bvar) return var
python
def ttvar(name, index=None): bvar = boolfunc.var(name, index) try: var = _VARS[bvar.uniqid] except KeyError: var = _VARS[bvar.uniqid] = TTVariable(bvar) return var
[ "def", "ttvar", "(", "name", ",", "index", "=", "None", ")", ":", "bvar", "=", "boolfunc", ".", "var", "(", "name", ",", "index", ")", "try", ":", "var", "=", "_VARS", "[", "bvar", ".", "uniqid", "]", "except", "KeyError", ":", "var", "=", "_VARS...
Return a TruthTable variable. Parameters ---------- name : str The variable's identifier string. index : int or tuple[int], optional One or more integer suffixes for variables that are part of a multi-dimensional bit-vector, eg x[1], x[1][2][3]
[ "Return", "a", "TruthTable", "variable", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/table.py#L43-L59
27,423
cjdrake/pyeda
pyeda/boolalg/table.py
expr2truthtable
def expr2truthtable(expr): """Convert an expression into a truth table.""" inputs = [ttvar(v.names, v.indices) for v in expr.inputs] return truthtable(inputs, expr.iter_image())
python
def expr2truthtable(expr): inputs = [ttvar(v.names, v.indices) for v in expr.inputs] return truthtable(inputs, expr.iter_image())
[ "def", "expr2truthtable", "(", "expr", ")", ":", "inputs", "=", "[", "ttvar", "(", "v", ".", "names", ",", "v", ".", "indices", ")", "for", "v", "in", "expr", ".", "inputs", "]", "return", "truthtable", "(", "inputs", ",", "expr", ".", "iter_image", ...
Convert an expression into a truth table.
[ "Convert", "an", "expression", "into", "a", "truth", "table", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/table.py#L99-L102
27,424
cjdrake/pyeda
pyeda/boolalg/table.py
truthtable2expr
def truthtable2expr(tt, conj=False): """Convert a truth table into an expression.""" if conj: outer, inner = (And, Or) nums = tt.pcdata.iter_zeros() else: outer, inner = (Or, And) nums = tt.pcdata.iter_ones() inputs = [exprvar(v.names, v.indices) for v in tt.inputs] terms = [boolfunc.num2term(num, inputs, conj) for num in nums] return outer(*[inner(*term) for term in terms])
python
def truthtable2expr(tt, conj=False): if conj: outer, inner = (And, Or) nums = tt.pcdata.iter_zeros() else: outer, inner = (Or, And) nums = tt.pcdata.iter_ones() inputs = [exprvar(v.names, v.indices) for v in tt.inputs] terms = [boolfunc.num2term(num, inputs, conj) for num in nums] return outer(*[inner(*term) for term in terms])
[ "def", "truthtable2expr", "(", "tt", ",", "conj", "=", "False", ")", ":", "if", "conj", ":", "outer", ",", "inner", "=", "(", "And", ",", "Or", ")", "nums", "=", "tt", ".", "pcdata", ".", "iter_zeros", "(", ")", "else", ":", "outer", ",", "inner"...
Convert a truth table into an expression.
[ "Convert", "a", "truth", "table", "into", "an", "expression", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/table.py#L105-L115
27,425
cjdrake/pyeda
pyeda/boolalg/table.py
_bin_zfill
def _bin_zfill(num, width=None): """Convert a base-10 number to a binary string. Parameters num: int width: int, optional Zero-extend the string to this width. Examples -------- >>> _bin_zfill(42) '101010' >>> _bin_zfill(42, 8) '00101010' """ s = bin(num)[2:] return s if width is None else s.zfill(width)
python
def _bin_zfill(num, width=None): s = bin(num)[2:] return s if width is None else s.zfill(width)
[ "def", "_bin_zfill", "(", "num", ",", "width", "=", "None", ")", ":", "s", "=", "bin", "(", "num", ")", "[", "2", ":", "]", "return", "s", "if", "width", "is", "None", "else", "s", ".", "zfill", "(", "width", ")" ]
Convert a base-10 number to a binary string. Parameters num: int width: int, optional Zero-extend the string to this width. Examples -------- >>> _bin_zfill(42) '101010' >>> _bin_zfill(42, 8) '00101010'
[ "Convert", "a", "base", "-", "10", "number", "to", "a", "binary", "string", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/table.py#L481-L497
27,426
cjdrake/pyeda
pyeda/boolalg/table.py
PCData.zero_mask
def zero_mask(self): """Return a mask to determine whether an array chunk has any zeros.""" accum = 0 for i in range(self.data.itemsize): accum += (0x55 << (i << 3)) return accum
python
def zero_mask(self): accum = 0 for i in range(self.data.itemsize): accum += (0x55 << (i << 3)) return accum
[ "def", "zero_mask", "(", "self", ")", ":", "accum", "=", "0", "for", "i", "in", "range", "(", "self", ".", "data", ".", "itemsize", ")", ":", "accum", "+=", "(", "0x55", "<<", "(", "i", "<<", "3", ")", ")", "return", "accum" ]
Return a mask to determine whether an array chunk has any zeros.
[ "Return", "a", "mask", "to", "determine", "whether", "an", "array", "chunk", "has", "any", "zeros", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/table.py#L161-L166
27,427
cjdrake/pyeda
pyeda/boolalg/table.py
PCData.one_mask
def one_mask(self): """Return a mask to determine whether an array chunk has any ones.""" accum = 0 for i in range(self.data.itemsize): accum += (0xAA << (i << 3)) return accum
python
def one_mask(self): accum = 0 for i in range(self.data.itemsize): accum += (0xAA << (i << 3)) return accum
[ "def", "one_mask", "(", "self", ")", ":", "accum", "=", "0", "for", "i", "in", "range", "(", "self", ".", "data", ".", "itemsize", ")", ":", "accum", "+=", "(", "0xAA", "<<", "(", "i", "<<", "3", ")", ")", "return", "accum" ]
Return a mask to determine whether an array chunk has any ones.
[ "Return", "a", "mask", "to", "determine", "whether", "an", "array", "chunk", "has", "any", "ones", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/table.py#L169-L174
27,428
cjdrake/pyeda
pyeda/boolalg/table.py
PCData.iter_zeros
def iter_zeros(self): """Iterate through the indices of all zero items.""" num = quotient = 0 while num < self._len: chunk = self.data[quotient] if chunk & self.zero_mask: remainder = 0 while remainder < self.width and num < self._len: item = (chunk >> remainder) & 3 if item == PC_ZERO: yield num remainder += 2 num += 1 else: num += (self.width >> 1) quotient += 1
python
def iter_zeros(self): num = quotient = 0 while num < self._len: chunk = self.data[quotient] if chunk & self.zero_mask: remainder = 0 while remainder < self.width and num < self._len: item = (chunk >> remainder) & 3 if item == PC_ZERO: yield num remainder += 2 num += 1 else: num += (self.width >> 1) quotient += 1
[ "def", "iter_zeros", "(", "self", ")", ":", "num", "=", "quotient", "=", "0", "while", "num", "<", "self", ".", "_len", ":", "chunk", "=", "self", ".", "data", "[", "quotient", "]", "if", "chunk", "&", "self", ".", "zero_mask", ":", "remainder", "=...
Iterate through the indices of all zero items.
[ "Iterate", "through", "the", "indices", "of", "all", "zero", "items", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/table.py#L176-L191
27,429
cjdrake/pyeda
pyeda/boolalg/table.py
PCData.find_one
def find_one(self): """ Return the first index of an entry that is either one or DC. If no item is found, return None. """ num = quotient = 0 while num < self._len: chunk = self.data[quotient] if chunk & self.one_mask: remainder = 0 while remainder < self.width and num < self._len: item = (chunk >> remainder) & 3 if item == PC_ONE: return num remainder += 2 num += 1 else: num += (self.width >> 1) quotient += 1 return None
python
def find_one(self): num = quotient = 0 while num < self._len: chunk = self.data[quotient] if chunk & self.one_mask: remainder = 0 while remainder < self.width and num < self._len: item = (chunk >> remainder) & 3 if item == PC_ONE: return num remainder += 2 num += 1 else: num += (self.width >> 1) quotient += 1 return None
[ "def", "find_one", "(", "self", ")", ":", "num", "=", "quotient", "=", "0", "while", "num", "<", "self", ".", "_len", ":", "chunk", "=", "self", ".", "data", "[", "quotient", "]", "if", "chunk", "&", "self", ".", "one_mask", ":", "remainder", "=", ...
Return the first index of an entry that is either one or DC. If no item is found, return None.
[ "Return", "the", "first", "index", "of", "an", "entry", "that", "is", "either", "one", "or", "DC", ".", "If", "no", "item", "is", "found", "return", "None", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/table.py#L193-L212
27,430
cjdrake/pyeda
pyeda/boolalg/table.py
TruthTable.is_neg_unate
def is_neg_unate(self, vs=None): r"""Return whether a function is negative unate. A function :math:`f(x_1, x_2, ..., x_i, ..., x_n)` is *negative unate* in variable :math:`x_i` if :math:`f_{x_i'} \geq f_{xi}`. """ vs = self._expect_vars(vs) basis = self.support - set(vs) maxcov = [PC_ONE] * (1 << len(basis)) # Test whether table entries are monotonically decreasing for cf in self.iter_cofactors(vs): for i, item in enumerate(cf.pcdata): if maxcov[i] == PC_ZERO and item == PC_ONE: return False maxcov[i] = item return True
python
def is_neg_unate(self, vs=None): r"""Return whether a function is negative unate. A function :math:`f(x_1, x_2, ..., x_i, ..., x_n)` is *negative unate* in variable :math:`x_i` if :math:`f_{x_i'} \geq f_{xi}`. """ vs = self._expect_vars(vs) basis = self.support - set(vs) maxcov = [PC_ONE] * (1 << len(basis)) # Test whether table entries are monotonically decreasing for cf in self.iter_cofactors(vs): for i, item in enumerate(cf.pcdata): if maxcov[i] == PC_ZERO and item == PC_ONE: return False maxcov[i] = item return True
[ "def", "is_neg_unate", "(", "self", ",", "vs", "=", "None", ")", ":", "vs", "=", "self", ".", "_expect_vars", "(", "vs", ")", "basis", "=", "self", ".", "support", "-", "set", "(", "vs", ")", "maxcov", "=", "[", "PC_ONE", "]", "*", "(", "1", "<...
r"""Return whether a function is negative unate. A function :math:`f(x_1, x_2, ..., x_i, ..., x_n)` is *negative unate* in variable :math:`x_i` if :math:`f_{x_i'} \geq f_{xi}`.
[ "r", "Return", "whether", "a", "function", "is", "negative", "unate", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/table.py#L389-L404
27,431
cjdrake/pyeda
pyeda/boolalg/table.py
TruthTable._iter_restrict
def _iter_restrict(self, zeros, ones): """Iterate through indices of all table entries that vary.""" inputs = list(self.inputs) unmapped = dict() for i, v in enumerate(self.inputs): if v in zeros: inputs[i] = 0 elif v in ones: inputs[i] = 1 else: unmapped[v] = i vs = sorted(unmapped.keys()) for num in range(1 << len(vs)): for v, val in boolfunc.num2point(num, vs).items(): inputs[unmapped[v]] = val yield sum((val << i) for i, val in enumerate(inputs))
python
def _iter_restrict(self, zeros, ones): inputs = list(self.inputs) unmapped = dict() for i, v in enumerate(self.inputs): if v in zeros: inputs[i] = 0 elif v in ones: inputs[i] = 1 else: unmapped[v] = i vs = sorted(unmapped.keys()) for num in range(1 << len(vs)): for v, val in boolfunc.num2point(num, vs).items(): inputs[unmapped[v]] = val yield sum((val << i) for i, val in enumerate(inputs))
[ "def", "_iter_restrict", "(", "self", ",", "zeros", ",", "ones", ")", ":", "inputs", "=", "list", "(", "self", ".", "inputs", ")", "unmapped", "=", "dict", "(", ")", "for", "i", ",", "v", "in", "enumerate", "(", "self", ".", "inputs", ")", ":", "...
Iterate through indices of all table entries that vary.
[ "Iterate", "through", "indices", "of", "all", "table", "entries", "that", "vary", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/table.py#L432-L447
27,432
cjdrake/pyeda
pyeda/boolalg/bdd.py
bddvar
def bddvar(name, index=None): r"""Return a unique BDD variable. A Boolean *variable* is an abstract numerical quantity that may assume any value in the set :math:`B = \{0, 1\}`. The ``bddvar`` function returns a unique Boolean variable instance represented by a binary decision diagram. Variable instances may be used to symbolically construct larger BDDs. A variable is defined by one or more *names*, and zero or more *indices*. Multiple names establish hierarchical namespaces, and multiple indices group several related variables. If the ``name`` parameter is a single ``str``, it will be converted to ``(name, )``. The ``index`` parameter is optional; when empty, it will be converted to an empty tuple ``()``. If the ``index`` parameter is a single ``int``, it will be converted to ``(index, )``. Given identical names and indices, the ``bddvar`` function will always return the same variable: >>> bddvar('a', 0) is bddvar('a', 0) True To create several single-letter variables: >>> a, b, c, d = map(bddvar, 'abcd') To create variables with multiple names (inner-most first): >>> fifo_push = bddvar(('push', 'fifo')) >>> fifo_pop = bddvar(('pop', 'fifo')) .. seealso:: For creating arrays of variables with incremental indices, use the :func:`pyeda.boolalg.bfarray.bddvars` function. """ bvar = boolfunc.var(name, index) try: var = _VARS[bvar.uniqid] except KeyError: var = _VARS[bvar.uniqid] = BDDVariable(bvar) _BDDS[var.node] = var return var
python
def bddvar(name, index=None): r"""Return a unique BDD variable. A Boolean *variable* is an abstract numerical quantity that may assume any value in the set :math:`B = \{0, 1\}`. The ``bddvar`` function returns a unique Boolean variable instance represented by a binary decision diagram. Variable instances may be used to symbolically construct larger BDDs. A variable is defined by one or more *names*, and zero or more *indices*. Multiple names establish hierarchical namespaces, and multiple indices group several related variables. If the ``name`` parameter is a single ``str``, it will be converted to ``(name, )``. The ``index`` parameter is optional; when empty, it will be converted to an empty tuple ``()``. If the ``index`` parameter is a single ``int``, it will be converted to ``(index, )``. Given identical names and indices, the ``bddvar`` function will always return the same variable: >>> bddvar('a', 0) is bddvar('a', 0) True To create several single-letter variables: >>> a, b, c, d = map(bddvar, 'abcd') To create variables with multiple names (inner-most first): >>> fifo_push = bddvar(('push', 'fifo')) >>> fifo_pop = bddvar(('pop', 'fifo')) .. seealso:: For creating arrays of variables with incremental indices, use the :func:`pyeda.boolalg.bfarray.bddvars` function. """ bvar = boolfunc.var(name, index) try: var = _VARS[bvar.uniqid] except KeyError: var = _VARS[bvar.uniqid] = BDDVariable(bvar) _BDDS[var.node] = var return var
[ "def", "bddvar", "(", "name", ",", "index", "=", "None", ")", ":", "bvar", "=", "boolfunc", ".", "var", "(", "name", ",", "index", ")", "try", ":", "var", "=", "_VARS", "[", "bvar", ".", "uniqid", "]", "except", "KeyError", ":", "var", "=", "_VAR...
r"""Return a unique BDD variable. A Boolean *variable* is an abstract numerical quantity that may assume any value in the set :math:`B = \{0, 1\}`. The ``bddvar`` function returns a unique Boolean variable instance represented by a binary decision diagram. Variable instances may be used to symbolically construct larger BDDs. A variable is defined by one or more *names*, and zero or more *indices*. Multiple names establish hierarchical namespaces, and multiple indices group several related variables. If the ``name`` parameter is a single ``str``, it will be converted to ``(name, )``. The ``index`` parameter is optional; when empty, it will be converted to an empty tuple ``()``. If the ``index`` parameter is a single ``int``, it will be converted to ``(index, )``. Given identical names and indices, the ``bddvar`` function will always return the same variable: >>> bddvar('a', 0) is bddvar('a', 0) True To create several single-letter variables: >>> a, b, c, d = map(bddvar, 'abcd') To create variables with multiple names (inner-most first): >>> fifo_push = bddvar(('push', 'fifo')) >>> fifo_pop = bddvar(('pop', 'fifo')) .. seealso:: For creating arrays of variables with incremental indices, use the :func:`pyeda.boolalg.bfarray.bddvars` function.
[ "r", "Return", "a", "unique", "BDD", "variable", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L68-L113
27,433
cjdrake/pyeda
pyeda/boolalg/bdd.py
_expr2bddnode
def _expr2bddnode(expr): """Convert an expression into a BDD node.""" if expr.is_zero(): return BDDNODEZERO elif expr.is_one(): return BDDNODEONE else: top = expr.top # Register this variable _ = bddvar(top.names, top.indices) root = top.uniqid lo = _expr2bddnode(expr.restrict({top: 0})) hi = _expr2bddnode(expr.restrict({top: 1})) return _bddnode(root, lo, hi)
python
def _expr2bddnode(expr): if expr.is_zero(): return BDDNODEZERO elif expr.is_one(): return BDDNODEONE else: top = expr.top # Register this variable _ = bddvar(top.names, top.indices) root = top.uniqid lo = _expr2bddnode(expr.restrict({top: 0})) hi = _expr2bddnode(expr.restrict({top: 1})) return _bddnode(root, lo, hi)
[ "def", "_expr2bddnode", "(", "expr", ")", ":", "if", "expr", ".", "is_zero", "(", ")", ":", "return", "BDDNODEZERO", "elif", "expr", ".", "is_one", "(", ")", ":", "return", "BDDNODEONE", "else", ":", "top", "=", "expr", ".", "top", "# Register this varia...
Convert an expression into a BDD node.
[ "Convert", "an", "expression", "into", "a", "BDD", "node", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L116-L131
27,434
cjdrake/pyeda
pyeda/boolalg/bdd.py
bdd2expr
def bdd2expr(bdd, conj=False): """Convert a binary decision diagram into an expression. This function will always return an expression in two-level form. If *conj* is ``False``, return a sum of products (SOP). Otherwise, return a product of sums (POS). For example:: >>> a, b = map(bddvar, 'ab') >>> bdd2expr(~a | b) Or(~a, And(a, b)) """ if conj: outer, inner = (And, Or) paths = _iter_all_paths(bdd.node, BDDNODEZERO) else: outer, inner = (Or, And) paths = _iter_all_paths(bdd.node, BDDNODEONE) terms = list() for path in paths: expr_point = {exprvar(v.names, v.indices): val for v, val in _path2point(path).items()} terms.append(boolfunc.point2term(expr_point, conj)) return outer(*[inner(*term) for term in terms])
python
def bdd2expr(bdd, conj=False): if conj: outer, inner = (And, Or) paths = _iter_all_paths(bdd.node, BDDNODEZERO) else: outer, inner = (Or, And) paths = _iter_all_paths(bdd.node, BDDNODEONE) terms = list() for path in paths: expr_point = {exprvar(v.names, v.indices): val for v, val in _path2point(path).items()} terms.append(boolfunc.point2term(expr_point, conj)) return outer(*[inner(*term) for term in terms])
[ "def", "bdd2expr", "(", "bdd", ",", "conj", "=", "False", ")", ":", "if", "conj", ":", "outer", ",", "inner", "=", "(", "And", ",", "Or", ")", "paths", "=", "_iter_all_paths", "(", "bdd", ".", "node", ",", "BDDNODEZERO", ")", "else", ":", "outer", ...
Convert a binary decision diagram into an expression. This function will always return an expression in two-level form. If *conj* is ``False``, return a sum of products (SOP). Otherwise, return a product of sums (POS). For example:: >>> a, b = map(bddvar, 'ab') >>> bdd2expr(~a | b) Or(~a, And(a, b))
[ "Convert", "a", "binary", "decision", "diagram", "into", "an", "expression", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L139-L163
27,435
cjdrake/pyeda
pyeda/boolalg/bdd.py
upoint2bddpoint
def upoint2bddpoint(upoint): """Convert an untyped point into a BDD point. .. seealso:: For definitions of points and untyped points, see the :mod:`pyeda.boolalg.boolfunc` module. """ point = dict() for uniqid in upoint[0]: point[_VARS[uniqid]] = 0 for uniqid in upoint[1]: point[_VARS[uniqid]] = 1 return point
python
def upoint2bddpoint(upoint): point = dict() for uniqid in upoint[0]: point[_VARS[uniqid]] = 0 for uniqid in upoint[1]: point[_VARS[uniqid]] = 1 return point
[ "def", "upoint2bddpoint", "(", "upoint", ")", ":", "point", "=", "dict", "(", ")", "for", "uniqid", "in", "upoint", "[", "0", "]", ":", "point", "[", "_VARS", "[", "uniqid", "]", "]", "=", "0", "for", "uniqid", "in", "upoint", "[", "1", "]", ":",...
Convert an untyped point into a BDD point. .. seealso:: For definitions of points and untyped points, see the :mod:`pyeda.boolalg.boolfunc` module.
[ "Convert", "an", "untyped", "point", "into", "a", "BDD", "point", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L166-L178
27,436
cjdrake/pyeda
pyeda/boolalg/bdd.py
_bddnode
def _bddnode(root, lo, hi): """Return a unique BDD node.""" if lo is hi: node = lo else: key = (root, lo, hi) try: node = _NODES[key] except KeyError: node = _NODES[key] = BDDNode(*key) return node
python
def _bddnode(root, lo, hi): if lo is hi: node = lo else: key = (root, lo, hi) try: node = _NODES[key] except KeyError: node = _NODES[key] = BDDNode(*key) return node
[ "def", "_bddnode", "(", "root", ",", "lo", ",", "hi", ")", ":", "if", "lo", "is", "hi", ":", "node", "=", "lo", "else", ":", "key", "=", "(", "root", ",", "lo", ",", "hi", ")", "try", ":", "node", "=", "_NODES", "[", "key", "]", "except", "...
Return a unique BDD node.
[ "Return", "a", "unique", "BDD", "node", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L198-L208
27,437
cjdrake/pyeda
pyeda/boolalg/bdd.py
_bdd
def _bdd(node): """Return a unique BDD.""" try: bdd = _BDDS[node] except KeyError: bdd = _BDDS[node] = BinaryDecisionDiagram(node) return bdd
python
def _bdd(node): try: bdd = _BDDS[node] except KeyError: bdd = _BDDS[node] = BinaryDecisionDiagram(node) return bdd
[ "def", "_bdd", "(", "node", ")", ":", "try", ":", "bdd", "=", "_BDDS", "[", "node", "]", "except", "KeyError", ":", "bdd", "=", "_BDDS", "[", "node", "]", "=", "BinaryDecisionDiagram", "(", "node", ")", "return", "bdd" ]
Return a unique BDD.
[ "Return", "a", "unique", "BDD", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L211-L217
27,438
cjdrake/pyeda
pyeda/boolalg/bdd.py
_path2point
def _path2point(path): """Convert a BDD path to a BDD point.""" return {_VARS[node.root]: int(node.hi is path[i+1]) for i, node in enumerate(path[:-1])}
python
def _path2point(path): return {_VARS[node.root]: int(node.hi is path[i+1]) for i, node in enumerate(path[:-1])}
[ "def", "_path2point", "(", "path", ")", ":", "return", "{", "_VARS", "[", "node", ".", "root", "]", ":", "int", "(", "node", ".", "hi", "is", "path", "[", "i", "+", "1", "]", ")", "for", "i", ",", "node", "in", "enumerate", "(", "path", "[", ...
Convert a BDD path to a BDD point.
[ "Convert", "a", "BDD", "path", "to", "a", "BDD", "point", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L220-L223
27,439
cjdrake/pyeda
pyeda/boolalg/bdd.py
_find_path
def _find_path(start, end, path=tuple()): """Return the path from start to end. If no path exists, return None. """ path = path + (start, ) if start is end: return path else: ret = None if start.lo is not None: ret = _find_path(start.lo, end, path) if ret is None and start.hi is not None: ret = _find_path(start.hi, end, path) return ret
python
def _find_path(start, end, path=tuple()): path = path + (start, ) if start is end: return path else: ret = None if start.lo is not None: ret = _find_path(start.lo, end, path) if ret is None and start.hi is not None: ret = _find_path(start.hi, end, path) return ret
[ "def", "_find_path", "(", "start", ",", "end", ",", "path", "=", "tuple", "(", ")", ")", ":", "path", "=", "path", "+", "(", "start", ",", ")", "if", "start", "is", "end", ":", "return", "path", "else", ":", "ret", "=", "None", "if", "start", "...
Return the path from start to end. If no path exists, return None.
[ "Return", "the", "path", "from", "start", "to", "end", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L507-L521
27,440
cjdrake/pyeda
pyeda/boolalg/bdd.py
_iter_all_paths
def _iter_all_paths(start, end, rand=False, path=tuple()): """Iterate through all paths from start to end.""" path = path + (start, ) if start is end: yield path else: nodes = [start.lo, start.hi] if rand: # pragma: no cover random.shuffle(nodes) for node in nodes: if node is not None: yield from _iter_all_paths(node, end, rand, path)
python
def _iter_all_paths(start, end, rand=False, path=tuple()): path = path + (start, ) if start is end: yield path else: nodes = [start.lo, start.hi] if rand: # pragma: no cover random.shuffle(nodes) for node in nodes: if node is not None: yield from _iter_all_paths(node, end, rand, path)
[ "def", "_iter_all_paths", "(", "start", ",", "end", ",", "rand", "=", "False", ",", "path", "=", "tuple", "(", ")", ")", ":", "path", "=", "path", "+", "(", "start", ",", ")", "if", "start", "is", "end", ":", "yield", "path", "else", ":", "nodes"...
Iterate through all paths from start to end.
[ "Iterate", "through", "all", "paths", "from", "start", "to", "end", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L524-L535
27,441
cjdrake/pyeda
pyeda/boolalg/bdd.py
_dfs_preorder
def _dfs_preorder(node, visited): """Iterate through nodes in DFS pre-order.""" if node not in visited: visited.add(node) yield node if node.lo is not None: yield from _dfs_preorder(node.lo, visited) if node.hi is not None: yield from _dfs_preorder(node.hi, visited)
python
def _dfs_preorder(node, visited): if node not in visited: visited.add(node) yield node if node.lo is not None: yield from _dfs_preorder(node.lo, visited) if node.hi is not None: yield from _dfs_preorder(node.hi, visited)
[ "def", "_dfs_preorder", "(", "node", ",", "visited", ")", ":", "if", "node", "not", "in", "visited", ":", "visited", ".", "add", "(", "node", ")", "yield", "node", "if", "node", ".", "lo", "is", "not", "None", ":", "yield", "from", "_dfs_preorder", "...
Iterate through nodes in DFS pre-order.
[ "Iterate", "through", "nodes", "in", "DFS", "pre", "-", "order", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L538-L546
27,442
cjdrake/pyeda
pyeda/boolalg/bdd.py
_dfs_postorder
def _dfs_postorder(node, visited): """Iterate through nodes in DFS post-order.""" if node.lo is not None: yield from _dfs_postorder(node.lo, visited) if node.hi is not None: yield from _dfs_postorder(node.hi, visited) if node not in visited: visited.add(node) yield node
python
def _dfs_postorder(node, visited): if node.lo is not None: yield from _dfs_postorder(node.lo, visited) if node.hi is not None: yield from _dfs_postorder(node.hi, visited) if node not in visited: visited.add(node) yield node
[ "def", "_dfs_postorder", "(", "node", ",", "visited", ")", ":", "if", "node", ".", "lo", "is", "not", "None", ":", "yield", "from", "_dfs_postorder", "(", "node", ".", "lo", ",", "visited", ")", "if", "node", ".", "hi", "is", "not", "None", ":", "y...
Iterate through nodes in DFS post-order.
[ "Iterate", "through", "nodes", "in", "DFS", "post", "-", "order", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L549-L557
27,443
cjdrake/pyeda
pyeda/boolalg/bdd.py
_bfs
def _bfs(node, visited): """Iterate through nodes in BFS order.""" queue = collections.deque() queue.appendleft(node) while queue: node = queue.pop() if node not in visited: if node.lo is not None: queue.appendleft(node.lo) if node.hi is not None: queue.appendleft(node.hi) visited.add(node) yield node
python
def _bfs(node, visited): queue = collections.deque() queue.appendleft(node) while queue: node = queue.pop() if node not in visited: if node.lo is not None: queue.appendleft(node.lo) if node.hi is not None: queue.appendleft(node.hi) visited.add(node) yield node
[ "def", "_bfs", "(", "node", ",", "visited", ")", ":", "queue", "=", "collections", ".", "deque", "(", ")", "queue", ".", "appendleft", "(", "node", ")", "while", "queue", ":", "node", "=", "queue", ".", "pop", "(", ")", "if", "node", "not", "in", ...
Iterate through nodes in BFS order.
[ "Iterate", "through", "nodes", "in", "BFS", "order", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L560-L572
27,444
cjdrake/pyeda
pyeda/parsing/boolexpr.py
parse
def parse(s): """ Parse a Boolean expression string, and return an expression abstract syntax tree. Parameters ---------- s : str String containing a Boolean expression. See ``pyeda.parsing.boolexpr.GRAMMAR`` for details. Examples -------- >>> parse("a | b ^ c & d") ('or', ('var', ('a',), ()), ('xor', ('var', ('b',), ()), ('and', ('var', ('c',), ()), ('var', ('d',), ())))) >>> parse("p => q") ('implies', ('var', ('p',), ()), ('var', ('q',), ())) Returns ------- An ast tuple, defined recursively: ast := ('const', bool) | ('var', names, indices) | ('not', ast) | ('implies', ast, ast) | ('ite', ast, ast, ast) | (func, ast, ...) bool := 0 | 1 names := (name, ...) indices := (index, ...) func := 'or' | 'and' | 'nor' | 'nand' | 'xor' | 'xnor' | 'equal' | 'unequal' | 'onehot0' | 'onehot' | 'majority' | 'achillesheel' """ lexer = iter(BoolExprLexer(s)) try: expr = _expr(lexer) except lex.RunError as exc: fstr = ("{0.args[0]}: " "(line: {0.lineno}, offset: {0.offset}, text: {0.text})") raise Error(fstr.format(exc)) # Check for end of buffer _expect_token(lexer, {EndToken}) return expr
python
def parse(s): lexer = iter(BoolExprLexer(s)) try: expr = _expr(lexer) except lex.RunError as exc: fstr = ("{0.args[0]}: " "(line: {0.lineno}, offset: {0.offset}, text: {0.text})") raise Error(fstr.format(exc)) # Check for end of buffer _expect_token(lexer, {EndToken}) return expr
[ "def", "parse", "(", "s", ")", ":", "lexer", "=", "iter", "(", "BoolExprLexer", "(", "s", ")", ")", "try", ":", "expr", "=", "_expr", "(", "lexer", ")", "except", "lex", ".", "RunError", "as", "exc", ":", "fstr", "=", "(", "\"{0.args[0]}: \"", "\"(...
Parse a Boolean expression string, and return an expression abstract syntax tree. Parameters ---------- s : str String containing a Boolean expression. See ``pyeda.parsing.boolexpr.GRAMMAR`` for details. Examples -------- >>> parse("a | b ^ c & d") ('or', ('var', ('a',), ()), ('xor', ('var', ('b',), ()), ('and', ('var', ('c',), ()), ('var', ('d',), ())))) >>> parse("p => q") ('implies', ('var', ('p',), ()), ('var', ('q',), ())) Returns ------- An ast tuple, defined recursively: ast := ('const', bool) | ('var', names, indices) | ('not', ast) | ('implies', ast, ast) | ('ite', ast, ast, ast) | (func, ast, ...) bool := 0 | 1 names := (name, ...) indices := (index, ...) func := 'or' | 'and' | 'nor' | 'nand' | 'xor' | 'xnor' | 'equal' | 'unequal' | 'onehot0' | 'onehot' | 'majority' | 'achillesheel'
[ "Parse", "a", "Boolean", "expression", "string", "and", "return", "an", "expression", "abstract", "syntax", "tree", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L340-L393
27,445
cjdrake/pyeda
pyeda/parsing/boolexpr.py
_ite
def _ite(lexer): """Return an ITE expression.""" s = _impl(lexer) tok = next(lexer) # IMPL '?' ITE ':' ITE if isinstance(tok, OP_question): d1 = _ite(lexer) _expect_token(lexer, {OP_colon}) d0 = _ite(lexer) return ('ite', s, d1, d0) # IMPL else: lexer.unpop_token(tok) return s
python
def _ite(lexer): s = _impl(lexer) tok = next(lexer) # IMPL '?' ITE ':' ITE if isinstance(tok, OP_question): d1 = _ite(lexer) _expect_token(lexer, {OP_colon}) d0 = _ite(lexer) return ('ite', s, d1, d0) # IMPL else: lexer.unpop_token(tok) return s
[ "def", "_ite", "(", "lexer", ")", ":", "s", "=", "_impl", "(", "lexer", ")", "tok", "=", "next", "(", "lexer", ")", "# IMPL '?' ITE ':' ITE", "if", "isinstance", "(", "tok", ",", "OP_question", ")", ":", "d1", "=", "_ite", "(", "lexer", ")", "_expect...
Return an ITE expression.
[ "Return", "an", "ITE", "expression", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L410-L424
27,446
cjdrake/pyeda
pyeda/parsing/boolexpr.py
_impl
def _impl(lexer): """Return an Implies expression.""" p = _sumterm(lexer) tok = next(lexer) # SUMTERM '=>' IMPL if isinstance(tok, OP_rarrow): q = _impl(lexer) return ('implies', p, q) # SUMTERM '<=>' IMPL elif isinstance(tok, OP_lrarrow): q = _impl(lexer) return ('equal', p, q) # SUMTERM else: lexer.unpop_token(tok) return p
python
def _impl(lexer): p = _sumterm(lexer) tok = next(lexer) # SUMTERM '=>' IMPL if isinstance(tok, OP_rarrow): q = _impl(lexer) return ('implies', p, q) # SUMTERM '<=>' IMPL elif isinstance(tok, OP_lrarrow): q = _impl(lexer) return ('equal', p, q) # SUMTERM else: lexer.unpop_token(tok) return p
[ "def", "_impl", "(", "lexer", ")", ":", "p", "=", "_sumterm", "(", "lexer", ")", "tok", "=", "next", "(", "lexer", ")", "# SUMTERM '=>' IMPL", "if", "isinstance", "(", "tok", ",", "OP_rarrow", ")", ":", "q", "=", "_impl", "(", "lexer", ")", "return",...
Return an Implies expression.
[ "Return", "an", "Implies", "expression", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L427-L443
27,447
cjdrake/pyeda
pyeda/parsing/boolexpr.py
_sumterm
def _sumterm(lexer): """Return a sum term expresssion.""" xorterm = _xorterm(lexer) sumterm_prime = _sumterm_prime(lexer) if sumterm_prime is None: return xorterm else: return ('or', xorterm, sumterm_prime)
python
def _sumterm(lexer): xorterm = _xorterm(lexer) sumterm_prime = _sumterm_prime(lexer) if sumterm_prime is None: return xorterm else: return ('or', xorterm, sumterm_prime)
[ "def", "_sumterm", "(", "lexer", ")", ":", "xorterm", "=", "_xorterm", "(", "lexer", ")", "sumterm_prime", "=", "_sumterm_prime", "(", "lexer", ")", "if", "sumterm_prime", "is", "None", ":", "return", "xorterm", "else", ":", "return", "(", "'or'", ",", "...
Return a sum term expresssion.
[ "Return", "a", "sum", "term", "expresssion", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L446-L453
27,448
cjdrake/pyeda
pyeda/parsing/boolexpr.py
_sumterm_prime
def _sumterm_prime(lexer): """Return a sum term' expression, eliminates left recursion.""" tok = next(lexer) # '|' XORTERM SUMTERM' if isinstance(tok, OP_or): xorterm = _xorterm(lexer) sumterm_prime = _sumterm_prime(lexer) if sumterm_prime is None: return xorterm else: return ('or', xorterm, sumterm_prime) # null else: lexer.unpop_token(tok) return None
python
def _sumterm_prime(lexer): tok = next(lexer) # '|' XORTERM SUMTERM' if isinstance(tok, OP_or): xorterm = _xorterm(lexer) sumterm_prime = _sumterm_prime(lexer) if sumterm_prime is None: return xorterm else: return ('or', xorterm, sumterm_prime) # null else: lexer.unpop_token(tok) return None
[ "def", "_sumterm_prime", "(", "lexer", ")", ":", "tok", "=", "next", "(", "lexer", ")", "# '|' XORTERM SUMTERM'", "if", "isinstance", "(", "tok", ",", "OP_or", ")", ":", "xorterm", "=", "_xorterm", "(", "lexer", ")", "sumterm_prime", "=", "_sumterm_prime", ...
Return a sum term' expression, eliminates left recursion.
[ "Return", "a", "sum", "term", "expression", "eliminates", "left", "recursion", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L456-L470
27,449
cjdrake/pyeda
pyeda/parsing/boolexpr.py
_xorterm
def _xorterm(lexer): """Return an xor term expresssion.""" prodterm = _prodterm(lexer) xorterm_prime = _xorterm_prime(lexer) if xorterm_prime is None: return prodterm else: return ('xor', prodterm, xorterm_prime)
python
def _xorterm(lexer): prodterm = _prodterm(lexer) xorterm_prime = _xorterm_prime(lexer) if xorterm_prime is None: return prodterm else: return ('xor', prodterm, xorterm_prime)
[ "def", "_xorterm", "(", "lexer", ")", ":", "prodterm", "=", "_prodterm", "(", "lexer", ")", "xorterm_prime", "=", "_xorterm_prime", "(", "lexer", ")", "if", "xorterm_prime", "is", "None", ":", "return", "prodterm", "else", ":", "return", "(", "'xor'", ",",...
Return an xor term expresssion.
[ "Return", "an", "xor", "term", "expresssion", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L473-L480
27,450
cjdrake/pyeda
pyeda/parsing/boolexpr.py
_xorterm_prime
def _xorterm_prime(lexer): """Return an xor term' expression, eliminates left recursion.""" tok = next(lexer) # '^' PRODTERM XORTERM' if isinstance(tok, OP_xor): prodterm = _prodterm(lexer) xorterm_prime = _xorterm_prime(lexer) if xorterm_prime is None: return prodterm else: return ('xor', prodterm, xorterm_prime) # null else: lexer.unpop_token(tok) return None
python
def _xorterm_prime(lexer): tok = next(lexer) # '^' PRODTERM XORTERM' if isinstance(tok, OP_xor): prodterm = _prodterm(lexer) xorterm_prime = _xorterm_prime(lexer) if xorterm_prime is None: return prodterm else: return ('xor', prodterm, xorterm_prime) # null else: lexer.unpop_token(tok) return None
[ "def", "_xorterm_prime", "(", "lexer", ")", ":", "tok", "=", "next", "(", "lexer", ")", "# '^' PRODTERM XORTERM'", "if", "isinstance", "(", "tok", ",", "OP_xor", ")", ":", "prodterm", "=", "_prodterm", "(", "lexer", ")", "xorterm_prime", "=", "_xorterm_prime...
Return an xor term' expression, eliminates left recursion.
[ "Return", "an", "xor", "term", "expression", "eliminates", "left", "recursion", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L483-L497
27,451
cjdrake/pyeda
pyeda/parsing/boolexpr.py
_prodterm
def _prodterm(lexer): """Return a product term expression.""" factor = _factor(lexer) prodterm_prime = _prodterm_prime(lexer) if prodterm_prime is None: return factor else: return ('and', factor, prodterm_prime)
python
def _prodterm(lexer): factor = _factor(lexer) prodterm_prime = _prodterm_prime(lexer) if prodterm_prime is None: return factor else: return ('and', factor, prodterm_prime)
[ "def", "_prodterm", "(", "lexer", ")", ":", "factor", "=", "_factor", "(", "lexer", ")", "prodterm_prime", "=", "_prodterm_prime", "(", "lexer", ")", "if", "prodterm_prime", "is", "None", ":", "return", "factor", "else", ":", "return", "(", "'and'", ",", ...
Return a product term expression.
[ "Return", "a", "product", "term", "expression", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L500-L507
27,452
cjdrake/pyeda
pyeda/parsing/boolexpr.py
_prodterm_prime
def _prodterm_prime(lexer): """Return a product term' expression, eliminates left recursion.""" tok = next(lexer) # '&' FACTOR PRODTERM' if isinstance(tok, OP_and): factor = _factor(lexer) prodterm_prime = _prodterm_prime(lexer) if prodterm_prime is None: return factor else: return ('and', factor, prodterm_prime) # null else: lexer.unpop_token(tok) return None
python
def _prodterm_prime(lexer): tok = next(lexer) # '&' FACTOR PRODTERM' if isinstance(tok, OP_and): factor = _factor(lexer) prodterm_prime = _prodterm_prime(lexer) if prodterm_prime is None: return factor else: return ('and', factor, prodterm_prime) # null else: lexer.unpop_token(tok) return None
[ "def", "_prodterm_prime", "(", "lexer", ")", ":", "tok", "=", "next", "(", "lexer", ")", "# '&' FACTOR PRODTERM'", "if", "isinstance", "(", "tok", ",", "OP_and", ")", ":", "factor", "=", "_factor", "(", "lexer", ")", "prodterm_prime", "=", "_prodterm_prime",...
Return a product term' expression, eliminates left recursion.
[ "Return", "a", "product", "term", "expression", "eliminates", "left", "recursion", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L510-L524
27,453
cjdrake/pyeda
pyeda/parsing/boolexpr.py
_factor
def _factor(lexer): """Return a factor expression.""" tok = _expect_token(lexer, FACTOR_TOKS) # '~' F toktype = type(tok) if toktype is OP_not: return ('not', _factor(lexer)) # '(' EXPR ')' elif toktype is LPAREN: expr = _expr(lexer) _expect_token(lexer, {RPAREN}) return expr # OPN '(' ... ')' elif any(toktype is t for t in OPN_TOKS): op = tok.ASTOP _expect_token(lexer, {LPAREN}) tok = next(lexer) # OPN '(' ')' if isinstance(tok, RPAREN): xs = tuple() # OPN '(' XS ')' else: lexer.unpop_token(tok) xs = _args(lexer) _expect_token(lexer, {RPAREN}) return (op, ) + xs # ITE '(' EXPR ',' EXPR ',' EXPR ')' elif toktype is KW_ite: _expect_token(lexer, {LPAREN}) s = _expr(lexer) _expect_token(lexer, {COMMA}) d1 = _expr(lexer) _expect_token(lexer, {COMMA}) d0 = _expr(lexer) _expect_token(lexer, {RPAREN}) return ('ite', s, d1, d0) # Implies '(' EXPR ',' EXPR ')' elif toktype is KW_implies: _expect_token(lexer, {LPAREN}) p = _expr(lexer) _expect_token(lexer, {COMMA}) q = _expr(lexer) _expect_token(lexer, {RPAREN}) return ('implies', p, q) # Not '(' EXPR ')' elif toktype is KW_not: _expect_token(lexer, {LPAREN}) x = _expr(lexer) _expect_token(lexer, {RPAREN}) return ('not', x) # VARIABLE elif toktype is NameToken: lexer.unpop_token(tok) return _variable(lexer) # '0' | '1' else: if tok.value not in {0, 1}: raise Error("unexpected token: " + str(tok)) return ('const', tok.value)
python
def _factor(lexer): tok = _expect_token(lexer, FACTOR_TOKS) # '~' F toktype = type(tok) if toktype is OP_not: return ('not', _factor(lexer)) # '(' EXPR ')' elif toktype is LPAREN: expr = _expr(lexer) _expect_token(lexer, {RPAREN}) return expr # OPN '(' ... ')' elif any(toktype is t for t in OPN_TOKS): op = tok.ASTOP _expect_token(lexer, {LPAREN}) tok = next(lexer) # OPN '(' ')' if isinstance(tok, RPAREN): xs = tuple() # OPN '(' XS ')' else: lexer.unpop_token(tok) xs = _args(lexer) _expect_token(lexer, {RPAREN}) return (op, ) + xs # ITE '(' EXPR ',' EXPR ',' EXPR ')' elif toktype is KW_ite: _expect_token(lexer, {LPAREN}) s = _expr(lexer) _expect_token(lexer, {COMMA}) d1 = _expr(lexer) _expect_token(lexer, {COMMA}) d0 = _expr(lexer) _expect_token(lexer, {RPAREN}) return ('ite', s, d1, d0) # Implies '(' EXPR ',' EXPR ')' elif toktype is KW_implies: _expect_token(lexer, {LPAREN}) p = _expr(lexer) _expect_token(lexer, {COMMA}) q = _expr(lexer) _expect_token(lexer, {RPAREN}) return ('implies', p, q) # Not '(' EXPR ')' elif toktype is KW_not: _expect_token(lexer, {LPAREN}) x = _expr(lexer) _expect_token(lexer, {RPAREN}) return ('not', x) # VARIABLE elif toktype is NameToken: lexer.unpop_token(tok) return _variable(lexer) # '0' | '1' else: if tok.value not in {0, 1}: raise Error("unexpected token: " + str(tok)) return ('const', tok.value)
[ "def", "_factor", "(", "lexer", ")", ":", "tok", "=", "_expect_token", "(", "lexer", ",", "FACTOR_TOKS", ")", "# '~' F", "toktype", "=", "type", "(", "tok", ")", "if", "toktype", "is", "OP_not", ":", "return", "(", "'not'", ",", "_factor", "(", "lexer"...
Return a factor expression.
[ "Return", "a", "factor", "expression", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L527-L585
27,454
cjdrake/pyeda
pyeda/parsing/boolexpr.py
_zom_arg
def _zom_arg(lexer): """Return zero or more arguments.""" tok = next(lexer) # ',' EXPR ZOM_X if isinstance(tok, COMMA): return (_expr(lexer), ) + _zom_arg(lexer) # null else: lexer.unpop_token(tok) return tuple()
python
def _zom_arg(lexer): tok = next(lexer) # ',' EXPR ZOM_X if isinstance(tok, COMMA): return (_expr(lexer), ) + _zom_arg(lexer) # null else: lexer.unpop_token(tok) return tuple()
[ "def", "_zom_arg", "(", "lexer", ")", ":", "tok", "=", "next", "(", "lexer", ")", "# ',' EXPR ZOM_X", "if", "isinstance", "(", "tok", ",", "COMMA", ")", ":", "return", "(", "_expr", "(", "lexer", ")", ",", ")", "+", "_zom_arg", "(", "lexer", ")", "...
Return zero or more arguments.
[ "Return", "zero", "or", "more", "arguments", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L593-L602
27,455
cjdrake/pyeda
pyeda/parsing/boolexpr.py
_variable
def _variable(lexer): """Return a variable expression.""" names = _names(lexer) tok = next(lexer) # NAMES '[' ... ']' if isinstance(tok, LBRACK): indices = _indices(lexer) _expect_token(lexer, {RBRACK}) # NAMES else: lexer.unpop_token(tok) indices = tuple() return ('var', names, indices)
python
def _variable(lexer): names = _names(lexer) tok = next(lexer) # NAMES '[' ... ']' if isinstance(tok, LBRACK): indices = _indices(lexer) _expect_token(lexer, {RBRACK}) # NAMES else: lexer.unpop_token(tok) indices = tuple() return ('var', names, indices)
[ "def", "_variable", "(", "lexer", ")", ":", "names", "=", "_names", "(", "lexer", ")", "tok", "=", "next", "(", "lexer", ")", "# NAMES '[' ... ']'", "if", "isinstance", "(", "tok", ",", "LBRACK", ")", ":", "indices", "=", "_indices", "(", "lexer", ")",...
Return a variable expression.
[ "Return", "a", "variable", "expression", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L605-L619
27,456
cjdrake/pyeda
pyeda/parsing/boolexpr.py
_names
def _names(lexer): """Return a tuple of names.""" first = _expect_token(lexer, {NameToken}).value rest = _zom_name(lexer) rnames = (first, ) + rest return rnames[::-1]
python
def _names(lexer): first = _expect_token(lexer, {NameToken}).value rest = _zom_name(lexer) rnames = (first, ) + rest return rnames[::-1]
[ "def", "_names", "(", "lexer", ")", ":", "first", "=", "_expect_token", "(", "lexer", ",", "{", "NameToken", "}", ")", ".", "value", "rest", "=", "_zom_name", "(", "lexer", ")", "rnames", "=", "(", "first", ",", ")", "+", "rest", "return", "rnames", ...
Return a tuple of names.
[ "Return", "a", "tuple", "of", "names", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L622-L627
27,457
cjdrake/pyeda
pyeda/parsing/boolexpr.py
_zom_name
def _zom_name(lexer): """Return zero or more names.""" tok = next(lexer) # '.' NAME ZOM_NAME if isinstance(tok, DOT): first = _expect_token(lexer, {NameToken}).value rest = _zom_name(lexer) return (first, ) + rest # null else: lexer.unpop_token(tok) return tuple()
python
def _zom_name(lexer): tok = next(lexer) # '.' NAME ZOM_NAME if isinstance(tok, DOT): first = _expect_token(lexer, {NameToken}).value rest = _zom_name(lexer) return (first, ) + rest # null else: lexer.unpop_token(tok) return tuple()
[ "def", "_zom_name", "(", "lexer", ")", ":", "tok", "=", "next", "(", "lexer", ")", "# '.' NAME ZOM_NAME", "if", "isinstance", "(", "tok", ",", "DOT", ")", ":", "first", "=", "_expect_token", "(", "lexer", ",", "{", "NameToken", "}", ")", ".", "value", ...
Return zero or more names.
[ "Return", "zero", "or", "more", "names", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L630-L641
27,458
cjdrake/pyeda
pyeda/parsing/boolexpr.py
_indices
def _indices(lexer): """Return a tuple of indices.""" first = _expect_token(lexer, {IntegerToken}).value rest = _zom_index(lexer) return (first, ) + rest
python
def _indices(lexer): first = _expect_token(lexer, {IntegerToken}).value rest = _zom_index(lexer) return (first, ) + rest
[ "def", "_indices", "(", "lexer", ")", ":", "first", "=", "_expect_token", "(", "lexer", ",", "{", "IntegerToken", "}", ")", ".", "value", "rest", "=", "_zom_index", "(", "lexer", ")", "return", "(", "first", ",", ")", "+", "rest" ]
Return a tuple of indices.
[ "Return", "a", "tuple", "of", "indices", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L644-L648
27,459
cjdrake/pyeda
pyeda/parsing/boolexpr.py
_zom_index
def _zom_index(lexer): """Return zero or more indices.""" tok = next(lexer) # ',' INT if isinstance(tok, COMMA): first = _expect_token(lexer, {IntegerToken}).value rest = _zom_index(lexer) return (first, ) + rest # null else: lexer.unpop_token(tok) return tuple()
python
def _zom_index(lexer): tok = next(lexer) # ',' INT if isinstance(tok, COMMA): first = _expect_token(lexer, {IntegerToken}).value rest = _zom_index(lexer) return (first, ) + rest # null else: lexer.unpop_token(tok) return tuple()
[ "def", "_zom_index", "(", "lexer", ")", ":", "tok", "=", "next", "(", "lexer", ")", "# ',' INT", "if", "isinstance", "(", "tok", ",", "COMMA", ")", ":", "first", "=", "_expect_token", "(", "lexer", ",", "{", "IntegerToken", "}", ")", ".", "value", "r...
Return zero or more indices.
[ "Return", "zero", "or", "more", "indices", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L651-L662
27,460
cjdrake/pyeda
pyeda/logic/aes.py
subword
def subword(w): """ Function used in the Key Expansion routine that takes a four-byte input word and applies an S-box to each of the four bytes to produce an output word. """ w = w.reshape(4, 8) return SBOX[w[0]] + SBOX[w[1]] + SBOX[w[2]] + SBOX[w[3]]
python
def subword(w): w = w.reshape(4, 8) return SBOX[w[0]] + SBOX[w[1]] + SBOX[w[2]] + SBOX[w[3]]
[ "def", "subword", "(", "w", ")", ":", "w", "=", "w", ".", "reshape", "(", "4", ",", "8", ")", "return", "SBOX", "[", "w", "[", "0", "]", "]", "+", "SBOX", "[", "w", "[", "1", "]", "]", "+", "SBOX", "[", "w", "[", "2", "]", "]", "+", "...
Function used in the Key Expansion routine that takes a four-byte input word and applies an S-box to each of the four bytes to produce an output word.
[ "Function", "used", "in", "the", "Key", "Expansion", "routine", "that", "takes", "a", "four", "-", "byte", "input", "word", "and", "applies", "an", "S", "-", "box", "to", "each", "of", "the", "four", "bytes", "to", "produce", "an", "output", "word", "....
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/aes.py#L144-L150
27,461
cjdrake/pyeda
pyeda/logic/aes.py
multiply
def multiply(a, col): """Multiply a matrix by one column.""" a = a.reshape(4, 4, 4) col = col.reshape(4, 8) return fcat( rowxcol(a[0], col), rowxcol(a[1], col), rowxcol(a[2], col), rowxcol(a[3], col), )
python
def multiply(a, col): a = a.reshape(4, 4, 4) col = col.reshape(4, 8) return fcat( rowxcol(a[0], col), rowxcol(a[1], col), rowxcol(a[2], col), rowxcol(a[3], col), )
[ "def", "multiply", "(", "a", ",", "col", ")", ":", "a", "=", "a", ".", "reshape", "(", "4", ",", "4", ",", "4", ")", "col", "=", "col", ".", "reshape", "(", "4", ",", "8", ")", "return", "fcat", "(", "rowxcol", "(", "a", "[", "0", "]", ",...
Multiply a matrix by one column.
[ "Multiply", "a", "matrix", "by", "one", "column", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/aes.py#L170-L179
27,462
cjdrake/pyeda
pyeda/logic/aes.py
rowxcol
def rowxcol(row, col): """Multiply one row and one column.""" row = row.reshape(4, 4) col = col.reshape(4, 8) ret = uint2exprs(0, 8) for i in range(4): for j in range(4): if row[i, j]: ret ^= xtime(col[i], j) return ret
python
def rowxcol(row, col): row = row.reshape(4, 4) col = col.reshape(4, 8) ret = uint2exprs(0, 8) for i in range(4): for j in range(4): if row[i, j]: ret ^= xtime(col[i], j) return ret
[ "def", "rowxcol", "(", "row", ",", "col", ")", ":", "row", "=", "row", ".", "reshape", "(", "4", ",", "4", ")", "col", "=", "col", ".", "reshape", "(", "4", ",", "8", ")", "ret", "=", "uint2exprs", "(", "0", ",", "8", ")", "for", "i", "in",...
Multiply one row and one column.
[ "Multiply", "one", "row", "and", "one", "column", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/aes.py#L182-L191
27,463
cjdrake/pyeda
pyeda/logic/aes.py
shift_rows
def shift_rows(state): """ Transformation in the Cipher that processes the State by cyclically shifting the last three rows of the State by different offsets. """ state = state.reshape(4, 4, 8) return fcat( state[0][0], state[1][1], state[2][2], state[3][3], state[1][0], state[2][1], state[3][2], state[0][3], state[2][0], state[3][1], state[0][2], state[1][3], state[3][0], state[0][1], state[1][2], state[2][3] )
python
def shift_rows(state): state = state.reshape(4, 4, 8) return fcat( state[0][0], state[1][1], state[2][2], state[3][3], state[1][0], state[2][1], state[3][2], state[0][3], state[2][0], state[3][1], state[0][2], state[1][3], state[3][0], state[0][1], state[1][2], state[2][3] )
[ "def", "shift_rows", "(", "state", ")", ":", "state", "=", "state", ".", "reshape", "(", "4", ",", "4", ",", "8", ")", "return", "fcat", "(", "state", "[", "0", "]", "[", "0", "]", ",", "state", "[", "1", "]", "[", "1", "]", ",", "state", "...
Transformation in the Cipher that processes the State by cyclically shifting the last three rows of the State by different offsets.
[ "Transformation", "in", "the", "Cipher", "that", "processes", "the", "State", "by", "cyclically", "shifting", "the", "last", "three", "rows", "of", "the", "State", "by", "different", "offsets", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/aes.py#L247-L258
27,464
cjdrake/pyeda
pyeda/logic/aes.py
key_expand
def key_expand(key, Nk=4): """Expand the key into the round key.""" assert Nk in {4, 6, 8} Nr = Nk + 6 key = key.reshape(Nk, 32) rkey = exprzeros(4*(Nr+1), 32) for i in range(Nk): rkey[i] = key[i] for i in range(Nk, 4*(Nr+1)): if i % Nk == 0: rkey[i] = rkey[i-Nk] ^ subword(rotword(rkey[i-1])) ^ RCON[i//Nk].zext(32-8) elif Nk > 6 and i % Nk == 4: rkey[i] = rkey[i-Nk] ^ subword(rkey[i-1]) else: rkey[i] = rkey[i-Nk] ^ rkey[i-1] return rkey
python
def key_expand(key, Nk=4): assert Nk in {4, 6, 8} Nr = Nk + 6 key = key.reshape(Nk, 32) rkey = exprzeros(4*(Nr+1), 32) for i in range(Nk): rkey[i] = key[i] for i in range(Nk, 4*(Nr+1)): if i % Nk == 0: rkey[i] = rkey[i-Nk] ^ subword(rotword(rkey[i-1])) ^ RCON[i//Nk].zext(32-8) elif Nk > 6 and i % Nk == 4: rkey[i] = rkey[i-Nk] ^ subword(rkey[i-1]) else: rkey[i] = rkey[i-Nk] ^ rkey[i-1] return rkey
[ "def", "key_expand", "(", "key", ",", "Nk", "=", "4", ")", ":", "assert", "Nk", "in", "{", "4", ",", "6", ",", "8", "}", "Nr", "=", "Nk", "+", "6", "key", "=", "key", ".", "reshape", "(", "Nk", ",", "32", ")", "rkey", "=", "exprzeros", "(",...
Expand the key into the round key.
[ "Expand", "the", "key", "into", "the", "round", "key", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/aes.py#L301-L320
27,465
cjdrake/pyeda
pyeda/logic/aes.py
cipher
def cipher(rkey, pt, Nk=4): """AES encryption cipher.""" assert Nk in {4, 6, 8} Nr = Nk + 6 rkey = rkey.reshape(4*(Nr+1), 32) pt = pt.reshape(128) # first round state = add_round_key(pt, rkey[0:4]) for i in range(1, Nr): state = sub_bytes(state) state = shift_rows(state) state = mix_columns(state) state = add_round_key(state, rkey[4*i:4*(i+1)]) # final round state = sub_bytes(state) state = shift_rows(state) state = add_round_key(state, rkey[4*Nr:4*(Nr+1)]) return state
python
def cipher(rkey, pt, Nk=4): assert Nk in {4, 6, 8} Nr = Nk + 6 rkey = rkey.reshape(4*(Nr+1), 32) pt = pt.reshape(128) # first round state = add_round_key(pt, rkey[0:4]) for i in range(1, Nr): state = sub_bytes(state) state = shift_rows(state) state = mix_columns(state) state = add_round_key(state, rkey[4*i:4*(i+1)]) # final round state = sub_bytes(state) state = shift_rows(state) state = add_round_key(state, rkey[4*Nr:4*(Nr+1)]) return state
[ "def", "cipher", "(", "rkey", ",", "pt", ",", "Nk", "=", "4", ")", ":", "assert", "Nk", "in", "{", "4", ",", "6", ",", "8", "}", "Nr", "=", "Nk", "+", "6", "rkey", "=", "rkey", ".", "reshape", "(", "4", "*", "(", "Nr", "+", "1", ")", ",...
AES encryption cipher.
[ "AES", "encryption", "cipher", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/aes.py#L323-L345
27,466
cjdrake/pyeda
pyeda/logic/aes.py
inv_cipher
def inv_cipher(rkey, ct, Nk=4): """AES decryption cipher.""" assert Nk in {4, 6, 8} Nr = Nk + 6 rkey = rkey.reshape(4*(Nr+1), 32) ct = ct.reshape(128) # first round state = add_round_key(ct, rkey[4*Nr:4*(Nr+1)]) for i in range(Nr-1, 0, -1): state = inv_shift_rows(state) state = inv_sub_bytes(state) state = add_round_key(state, rkey[4*i:4*(i+1)]) state = inv_mix_columns(state) # final round state = inv_shift_rows(state) state = inv_sub_bytes(state) state = add_round_key(state, rkey[0:4]) return state
python
def inv_cipher(rkey, ct, Nk=4): assert Nk in {4, 6, 8} Nr = Nk + 6 rkey = rkey.reshape(4*(Nr+1), 32) ct = ct.reshape(128) # first round state = add_round_key(ct, rkey[4*Nr:4*(Nr+1)]) for i in range(Nr-1, 0, -1): state = inv_shift_rows(state) state = inv_sub_bytes(state) state = add_round_key(state, rkey[4*i:4*(i+1)]) state = inv_mix_columns(state) # final round state = inv_shift_rows(state) state = inv_sub_bytes(state) state = add_round_key(state, rkey[0:4]) return state
[ "def", "inv_cipher", "(", "rkey", ",", "ct", ",", "Nk", "=", "4", ")", ":", "assert", "Nk", "in", "{", "4", ",", "6", ",", "8", "}", "Nr", "=", "Nk", "+", "6", "rkey", "=", "rkey", ".", "reshape", "(", "4", "*", "(", "Nr", "+", "1", ")", ...
AES decryption cipher.
[ "AES", "decryption", "cipher", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/aes.py#L348-L370
27,467
cjdrake/pyeda
pyeda/logic/aes.py
encrypt
def encrypt(key, pt, Nk=4): """Encrypt a plain text block.""" assert Nk in {4, 6, 8} rkey = key_expand(key, Nk) ct = cipher(rkey, pt, Nk) return ct
python
def encrypt(key, pt, Nk=4): assert Nk in {4, 6, 8} rkey = key_expand(key, Nk) ct = cipher(rkey, pt, Nk) return ct
[ "def", "encrypt", "(", "key", ",", "pt", ",", "Nk", "=", "4", ")", ":", "assert", "Nk", "in", "{", "4", ",", "6", ",", "8", "}", "rkey", "=", "key_expand", "(", "key", ",", "Nk", ")", "ct", "=", "cipher", "(", "rkey", ",", "pt", ",", "Nk", ...
Encrypt a plain text block.
[ "Encrypt", "a", "plain", "text", "block", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/aes.py#L373-L379
27,468
cjdrake/pyeda
pyeda/logic/aes.py
decrypt
def decrypt(key, ct, Nk=4): """Decrypt a plain text block.""" assert Nk in {4, 6, 8} rkey = key_expand(key, Nk) pt = inv_cipher(rkey, ct, Nk) return pt
python
def decrypt(key, ct, Nk=4): assert Nk in {4, 6, 8} rkey = key_expand(key, Nk) pt = inv_cipher(rkey, ct, Nk) return pt
[ "def", "decrypt", "(", "key", ",", "ct", ",", "Nk", "=", "4", ")", ":", "assert", "Nk", "in", "{", "4", ",", "6", ",", "8", "}", "rkey", "=", "key_expand", "(", "key", ",", "Nk", ")", "pt", "=", "inv_cipher", "(", "rkey", ",", "ct", ",", "N...
Decrypt a plain text block.
[ "Decrypt", "a", "plain", "text", "block", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/aes.py#L382-L388
27,469
cjdrake/pyeda
pyeda/logic/graycode.py
gray2bin
def gray2bin(G): """Convert a gray-coded vector into a binary-coded vector.""" return farray([G[i:].uxor() for i, _ in enumerate(G)])
python
def gray2bin(G): return farray([G[i:].uxor() for i, _ in enumerate(G)])
[ "def", "gray2bin", "(", "G", ")", ":", "return", "farray", "(", "[", "G", "[", "i", ":", "]", ".", "uxor", "(", ")", "for", "i", ",", "_", "in", "enumerate", "(", "G", ")", "]", ")" ]
Convert a gray-coded vector into a binary-coded vector.
[ "Convert", "a", "gray", "-", "coded", "vector", "into", "a", "binary", "-", "coded", "vector", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/graycode.py#L22-L24
27,470
cjdrake/pyeda
pyeda/boolalg/expr.py
_assume2point
def _assume2point(): """Convert global assumptions to a point.""" point = dict() for lit in _ASSUMPTIONS: if isinstance(lit, Complement): point[~lit] = 0 elif isinstance(lit, Variable): point[lit] = 1 return point
python
def _assume2point(): point = dict() for lit in _ASSUMPTIONS: if isinstance(lit, Complement): point[~lit] = 0 elif isinstance(lit, Variable): point[lit] = 1 return point
[ "def", "_assume2point", "(", ")", ":", "point", "=", "dict", "(", ")", "for", "lit", "in", "_ASSUMPTIONS", ":", "if", "isinstance", "(", "lit", ",", "Complement", ")", ":", "point", "[", "~", "lit", "]", "=", "0", "elif", "isinstance", "(", "lit", ...
Convert global assumptions to a point.
[ "Convert", "global", "assumptions", "to", "a", "point", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L125-L133
27,471
cjdrake/pyeda
pyeda/boolalg/expr.py
exprvar
def exprvar(name, index=None): r"""Return a unique Expression variable. A Boolean *variable* is an abstract numerical quantity that may assume any value in the set :math:`B = \{0, 1\}`. The ``exprvar`` function returns a unique Boolean variable instance represented by a logic expression. Variable instances may be used to symbolically construct larger expressions. A variable is defined by one or more *names*, and zero or more *indices*. Multiple names establish hierarchical namespaces, and multiple indices group several related variables. If the ``name`` parameter is a single ``str``, it will be converted to ``(name, )``. The ``index`` parameter is optional; when empty, it will be converted to an empty tuple ``()``. If the ``index`` parameter is a single ``int``, it will be converted to ``(index, )``. Given identical names and indices, the ``exprvar`` function will always return the same variable: >>> exprvar('a', 0) is exprvar('a', 0) True To create several single-letter variables: >>> a, b, c, d = map(exprvar, 'abcd') To create variables with multiple names (inner-most first): >>> fifo_push = exprvar(('push', 'fifo')) >>> fifo_pop = exprvar(('pop', 'fifo')) .. seealso:: For creating arrays of variables with incremental indices, use the :func:`pyeda.boolalg.bfarray.exprvars` function. """ bvar = boolfunc.var(name, index) try: var = _LITS[bvar.uniqid] except KeyError: var = _LITS[bvar.uniqid] = Variable(bvar) return var
python
def exprvar(name, index=None): r"""Return a unique Expression variable. A Boolean *variable* is an abstract numerical quantity that may assume any value in the set :math:`B = \{0, 1\}`. The ``exprvar`` function returns a unique Boolean variable instance represented by a logic expression. Variable instances may be used to symbolically construct larger expressions. A variable is defined by one or more *names*, and zero or more *indices*. Multiple names establish hierarchical namespaces, and multiple indices group several related variables. If the ``name`` parameter is a single ``str``, it will be converted to ``(name, )``. The ``index`` parameter is optional; when empty, it will be converted to an empty tuple ``()``. If the ``index`` parameter is a single ``int``, it will be converted to ``(index, )``. Given identical names and indices, the ``exprvar`` function will always return the same variable: >>> exprvar('a', 0) is exprvar('a', 0) True To create several single-letter variables: >>> a, b, c, d = map(exprvar, 'abcd') To create variables with multiple names (inner-most first): >>> fifo_push = exprvar(('push', 'fifo')) >>> fifo_pop = exprvar(('pop', 'fifo')) .. seealso:: For creating arrays of variables with incremental indices, use the :func:`pyeda.boolalg.bfarray.exprvars` function. """ bvar = boolfunc.var(name, index) try: var = _LITS[bvar.uniqid] except KeyError: var = _LITS[bvar.uniqid] = Variable(bvar) return var
[ "def", "exprvar", "(", "name", ",", "index", "=", "None", ")", ":", "bvar", "=", "boolfunc", ".", "var", "(", "name", ",", "index", ")", "try", ":", "var", "=", "_LITS", "[", "bvar", ".", "uniqid", "]", "except", "KeyError", ":", "var", "=", "_LI...
r"""Return a unique Expression variable. A Boolean *variable* is an abstract numerical quantity that may assume any value in the set :math:`B = \{0, 1\}`. The ``exprvar`` function returns a unique Boolean variable instance represented by a logic expression. Variable instances may be used to symbolically construct larger expressions. A variable is defined by one or more *names*, and zero or more *indices*. Multiple names establish hierarchical namespaces, and multiple indices group several related variables. If the ``name`` parameter is a single ``str``, it will be converted to ``(name, )``. The ``index`` parameter is optional; when empty, it will be converted to an empty tuple ``()``. If the ``index`` parameter is a single ``int``, it will be converted to ``(index, )``. Given identical names and indices, the ``exprvar`` function will always return the same variable: >>> exprvar('a', 0) is exprvar('a', 0) True To create several single-letter variables: >>> a, b, c, d = map(exprvar, 'abcd') To create variables with multiple names (inner-most first): >>> fifo_push = exprvar(('push', 'fifo')) >>> fifo_pop = exprvar(('pop', 'fifo')) .. seealso:: For creating arrays of variables with incremental indices, use the :func:`pyeda.boolalg.bfarray.exprvars` function.
[ "r", "Return", "a", "unique", "Expression", "variable", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L136-L180
27,472
cjdrake/pyeda
pyeda/boolalg/expr.py
_exprcomp
def _exprcomp(node): """Return a unique Expression complement.""" try: comp = _LITS[node.data()] except KeyError: comp = _LITS[node.data()] = Complement(node) return comp
python
def _exprcomp(node): try: comp = _LITS[node.data()] except KeyError: comp = _LITS[node.data()] = Complement(node) return comp
[ "def", "_exprcomp", "(", "node", ")", ":", "try", ":", "comp", "=", "_LITS", "[", "node", ".", "data", "(", ")", "]", "except", "KeyError", ":", "comp", "=", "_LITS", "[", "node", ".", "data", "(", ")", "]", "=", "Complement", "(", "node", ")", ...
Return a unique Expression complement.
[ "Return", "a", "unique", "Expression", "complement", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L183-L189
27,473
cjdrake/pyeda
pyeda/boolalg/expr.py
expr
def expr(obj, simplify=True): """Convert an arbitrary object into an Expression.""" if isinstance(obj, Expression): return obj # False, True, 0, 1 elif isinstance(obj, int) and obj in {0, 1}: return _CONSTS[obj] elif isinstance(obj, str): ast = pyeda.parsing.boolexpr.parse(obj) ex = ast2expr(ast) if simplify: ex = ex.simplify() return ex else: return One if bool(obj) else Zero
python
def expr(obj, simplify=True): if isinstance(obj, Expression): return obj # False, True, 0, 1 elif isinstance(obj, int) and obj in {0, 1}: return _CONSTS[obj] elif isinstance(obj, str): ast = pyeda.parsing.boolexpr.parse(obj) ex = ast2expr(ast) if simplify: ex = ex.simplify() return ex else: return One if bool(obj) else Zero
[ "def", "expr", "(", "obj", ",", "simplify", "=", "True", ")", ":", "if", "isinstance", "(", "obj", ",", "Expression", ")", ":", "return", "obj", "# False, True, 0, 1", "elif", "isinstance", "(", "obj", ",", "int", ")", "and", "obj", "in", "{", "0", "...
Convert an arbitrary object into an Expression.
[ "Convert", "an", "arbitrary", "object", "into", "an", "Expression", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L214-L228
27,474
cjdrake/pyeda
pyeda/boolalg/expr.py
ast2expr
def ast2expr(ast): """Convert an abstract syntax tree to an Expression.""" if ast[0] == 'const': return _CONSTS[ast[1]] elif ast[0] == 'var': return exprvar(ast[1], ast[2]) else: xs = [ast2expr(x) for x in ast[1:]] return ASTOPS[ast[0]](*xs, simplify=False)
python
def ast2expr(ast): if ast[0] == 'const': return _CONSTS[ast[1]] elif ast[0] == 'var': return exprvar(ast[1], ast[2]) else: xs = [ast2expr(x) for x in ast[1:]] return ASTOPS[ast[0]](*xs, simplify=False)
[ "def", "ast2expr", "(", "ast", ")", ":", "if", "ast", "[", "0", "]", "==", "'const'", ":", "return", "_CONSTS", "[", "ast", "[", "1", "]", "]", "elif", "ast", "[", "0", "]", "==", "'var'", ":", "return", "exprvar", "(", "ast", "[", "1", "]", ...
Convert an abstract syntax tree to an Expression.
[ "Convert", "an", "abstract", "syntax", "tree", "to", "an", "Expression", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L231-L239
27,475
cjdrake/pyeda
pyeda/boolalg/expr.py
expr2dimacscnf
def expr2dimacscnf(ex): """Convert an expression into an equivalent DIMACS CNF.""" litmap, nvars, clauses = ex.encode_cnf() return litmap, DimacsCNF(nvars, clauses)
python
def expr2dimacscnf(ex): litmap, nvars, clauses = ex.encode_cnf() return litmap, DimacsCNF(nvars, clauses)
[ "def", "expr2dimacscnf", "(", "ex", ")", ":", "litmap", ",", "nvars", ",", "clauses", "=", "ex", ".", "encode_cnf", "(", ")", "return", "litmap", ",", "DimacsCNF", "(", "nvars", ",", "clauses", ")" ]
Convert an expression into an equivalent DIMACS CNF.
[ "Convert", "an", "expression", "into", "an", "equivalent", "DIMACS", "CNF", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L242-L245
27,476
cjdrake/pyeda
pyeda/boolalg/expr.py
expr2dimacssat
def expr2dimacssat(ex): """Convert an expression into an equivalent DIMACS SAT string.""" if not ex.simple: raise ValueError("expected ex to be simplified") litmap, nvars = ex.encode_inputs() formula = _expr2sat(ex, litmap) if 'xor' in formula: if '=' in formula: fmt = 'satex' else: fmt = 'satx' elif '=' in formula: fmt = 'sate' else: fmt = 'sat' return "p {} {}\n{}".format(fmt, nvars, formula)
python
def expr2dimacssat(ex): if not ex.simple: raise ValueError("expected ex to be simplified") litmap, nvars = ex.encode_inputs() formula = _expr2sat(ex, litmap) if 'xor' in formula: if '=' in formula: fmt = 'satex' else: fmt = 'satx' elif '=' in formula: fmt = 'sate' else: fmt = 'sat' return "p {} {}\n{}".format(fmt, nvars, formula)
[ "def", "expr2dimacssat", "(", "ex", ")", ":", "if", "not", "ex", ".", "simple", ":", "raise", "ValueError", "(", "\"expected ex to be simplified\"", ")", "litmap", ",", "nvars", "=", "ex", ".", "encode_inputs", "(", ")", "formula", "=", "_expr2sat", "(", "...
Convert an expression into an equivalent DIMACS SAT string.
[ "Convert", "an", "expression", "into", "an", "equivalent", "DIMACS", "SAT", "string", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L248-L266
27,477
cjdrake/pyeda
pyeda/boolalg/expr.py
_expr2sat
def _expr2sat(ex, litmap): # pragma: no cover """Convert an expression to a DIMACS SAT string.""" if isinstance(ex, Literal): return str(litmap[ex]) elif isinstance(ex, NotOp): return "-(" + _expr2sat(ex.x, litmap) + ")" elif isinstance(ex, OrOp): return "+(" + " ".join(_expr2sat(x, litmap) for x in ex.xs) + ")" elif isinstance(ex, AndOp): return "*(" + " ".join(_expr2sat(x, litmap) for x in ex.xs) + ")" elif isinstance(ex, XorOp): return ("xor(" + " ".join(_expr2sat(x, litmap) for x in ex.xs) + ")") elif isinstance(ex, EqualOp): return "=(" + " ".join(_expr2sat(x, litmap) for x in ex.xs) + ")" else: fstr = ("expected ex to be a Literal or Not/Or/And/Xor/Equal op, " "got {0.__name__}") raise ValueError(fstr.format(type(ex)))
python
def _expr2sat(ex, litmap): # pragma: no cover if isinstance(ex, Literal): return str(litmap[ex]) elif isinstance(ex, NotOp): return "-(" + _expr2sat(ex.x, litmap) + ")" elif isinstance(ex, OrOp): return "+(" + " ".join(_expr2sat(x, litmap) for x in ex.xs) + ")" elif isinstance(ex, AndOp): return "*(" + " ".join(_expr2sat(x, litmap) for x in ex.xs) + ")" elif isinstance(ex, XorOp): return ("xor(" + " ".join(_expr2sat(x, litmap) for x in ex.xs) + ")") elif isinstance(ex, EqualOp): return "=(" + " ".join(_expr2sat(x, litmap) for x in ex.xs) + ")" else: fstr = ("expected ex to be a Literal or Not/Or/And/Xor/Equal op, " "got {0.__name__}") raise ValueError(fstr.format(type(ex)))
[ "def", "_expr2sat", "(", "ex", ",", "litmap", ")", ":", "# pragma: no cover", "if", "isinstance", "(", "ex", ",", "Literal", ")", ":", "return", "str", "(", "litmap", "[", "ex", "]", ")", "elif", "isinstance", "(", "ex", ",", "NotOp", ")", ":", "retu...
Convert an expression to a DIMACS SAT string.
[ "Convert", "an", "expression", "to", "a", "DIMACS", "SAT", "string", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L269-L290
27,478
cjdrake/pyeda
pyeda/boolalg/expr.py
upoint2exprpoint
def upoint2exprpoint(upoint): """Convert an untyped point into an Expression point. .. seealso:: For definitions of points and untyped points, see the :mod:`pyeda.boolalg.boolfunc` module. """ point = dict() for uniqid in upoint[0]: point[_LITS[uniqid]] = 0 for uniqid in upoint[1]: point[_LITS[uniqid]] = 1 return point
python
def upoint2exprpoint(upoint): point = dict() for uniqid in upoint[0]: point[_LITS[uniqid]] = 0 for uniqid in upoint[1]: point[_LITS[uniqid]] = 1 return point
[ "def", "upoint2exprpoint", "(", "upoint", ")", ":", "point", "=", "dict", "(", ")", "for", "uniqid", "in", "upoint", "[", "0", "]", ":", "point", "[", "_LITS", "[", "uniqid", "]", "]", "=", "0", "for", "uniqid", "in", "upoint", "[", "1", "]", ":"...
Convert an untyped point into an Expression point. .. seealso:: For definitions of points and untyped points, see the :mod:`pyeda.boolalg.boolfunc` module.
[ "Convert", "an", "untyped", "point", "into", "an", "Expression", "point", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L293-L305
27,479
cjdrake/pyeda
pyeda/boolalg/expr.py
Not
def Not(x, simplify=True): """Expression negation operator If *simplify* is ``True``, return a simplified expression. """ x = Expression.box(x).node y = exprnode.not_(x) if simplify: y = y.simplify() return _expr(y)
python
def Not(x, simplify=True): x = Expression.box(x).node y = exprnode.not_(x) if simplify: y = y.simplify() return _expr(y)
[ "def", "Not", "(", "x", ",", "simplify", "=", "True", ")", ":", "x", "=", "Expression", ".", "box", "(", "x", ")", ".", "node", "y", "=", "exprnode", ".", "not_", "(", "x", ")", "if", "simplify", ":", "y", "=", "y", ".", "simplify", "(", ")",...
Expression negation operator If *simplify* is ``True``, return a simplified expression.
[ "Expression", "negation", "operator" ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L309-L318
27,480
cjdrake/pyeda
pyeda/boolalg/expr.py
Equal
def Equal(*xs, simplify=True): """Expression equality operator If *simplify* is ``True``, return a simplified expression. """ xs = [Expression.box(x).node for x in xs] y = exprnode.eq(*xs) if simplify: y = y.simplify() return _expr(y)
python
def Equal(*xs, simplify=True): xs = [Expression.box(x).node for x in xs] y = exprnode.eq(*xs) if simplify: y = y.simplify() return _expr(y)
[ "def", "Equal", "(", "*", "xs", ",", "simplify", "=", "True", ")", ":", "xs", "=", "[", "Expression", ".", "box", "(", "x", ")", ".", "node", "for", "x", "in", "xs", "]", "y", "=", "exprnode", ".", "eq", "(", "*", "xs", ")", "if", "simplify",...
Expression equality operator If *simplify* is ``True``, return a simplified expression.
[ "Expression", "equality", "operator" ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L358-L367
27,481
cjdrake/pyeda
pyeda/boolalg/expr.py
Implies
def Implies(p, q, simplify=True): """Expression implication operator If *simplify* is ``True``, return a simplified expression. """ p = Expression.box(p).node q = Expression.box(q).node y = exprnode.impl(p, q) if simplify: y = y.simplify() return _expr(y)
python
def Implies(p, q, simplify=True): p = Expression.box(p).node q = Expression.box(q).node y = exprnode.impl(p, q) if simplify: y = y.simplify() return _expr(y)
[ "def", "Implies", "(", "p", ",", "q", ",", "simplify", "=", "True", ")", ":", "p", "=", "Expression", ".", "box", "(", "p", ")", ".", "node", "q", "=", "Expression", ".", "box", "(", "q", ")", ".", "node", "y", "=", "exprnode", ".", "impl", "...
Expression implication operator If *simplify* is ``True``, return a simplified expression.
[ "Expression", "implication", "operator" ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L370-L380
27,482
cjdrake/pyeda
pyeda/boolalg/expr.py
Unequal
def Unequal(*xs, simplify=True): """Expression inequality operator If *simplify* is ``True``, return a simplified expression. """ xs = [Expression.box(x).node for x in xs] y = exprnode.not_(exprnode.eq(*xs)) if simplify: y = y.simplify() return _expr(y)
python
def Unequal(*xs, simplify=True): xs = [Expression.box(x).node for x in xs] y = exprnode.not_(exprnode.eq(*xs)) if simplify: y = y.simplify() return _expr(y)
[ "def", "Unequal", "(", "*", "xs", ",", "simplify", "=", "True", ")", ":", "xs", "=", "[", "Expression", ".", "box", "(", "x", ")", ".", "node", "for", "x", "in", "xs", "]", "y", "=", "exprnode", ".", "not_", "(", "exprnode", ".", "eq", "(", "...
Expression inequality operator If *simplify* is ``True``, return a simplified expression.
[ "Expression", "inequality", "operator" ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L434-L443
27,483
cjdrake/pyeda
pyeda/boolalg/expr.py
OneHot0
def OneHot0(*xs, simplify=True, conj=True): """ Return an expression that means "at most one input function is true". If *simplify* is ``True``, return a simplified expression. If *conj* is ``True``, return a CNF. Otherwise, return a DNF. """ xs = [Expression.box(x).node for x in xs] terms = list() if conj: for x0, x1 in itertools.combinations(xs, 2): terms.append(exprnode.or_(exprnode.not_(x0), exprnode.not_(x1))) y = exprnode.and_(*terms) else: for _xs in itertools.combinations(xs, len(xs) - 1): terms.append(exprnode.and_(*[exprnode.not_(x) for x in _xs])) y = exprnode.or_(*terms) if simplify: y = y.simplify() return _expr(y)
python
def OneHot0(*xs, simplify=True, conj=True): xs = [Expression.box(x).node for x in xs] terms = list() if conj: for x0, x1 in itertools.combinations(xs, 2): terms.append(exprnode.or_(exprnode.not_(x0), exprnode.not_(x1))) y = exprnode.and_(*terms) else: for _xs in itertools.combinations(xs, len(xs) - 1): terms.append(exprnode.and_(*[exprnode.not_(x) for x in _xs])) y = exprnode.or_(*terms) if simplify: y = y.simplify() return _expr(y)
[ "def", "OneHot0", "(", "*", "xs", ",", "simplify", "=", "True", ",", "conj", "=", "True", ")", ":", "xs", "=", "[", "Expression", ".", "box", "(", "x", ")", ".", "node", "for", "x", "in", "xs", "]", "terms", "=", "list", "(", ")", "if", "conj...
Return an expression that means "at most one input function is true". If *simplify* is ``True``, return a simplified expression. If *conj* is ``True``, return a CNF. Otherwise, return a DNF.
[ "Return", "an", "expression", "that", "means", "at", "most", "one", "input", "function", "is", "true", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L446-L469
27,484
cjdrake/pyeda
pyeda/boolalg/expr.py
OneHot
def OneHot(*xs, simplify=True, conj=True): """ Return an expression that means "exactly one input function is true". If *simplify* is ``True``, return a simplified expression. If *conj* is ``True``, return a CNF. Otherwise, return a DNF. """ xs = [Expression.box(x).node for x in xs] terms = list() if conj: for x0, x1 in itertools.combinations(xs, 2): terms.append(exprnode.or_(exprnode.not_(x0), exprnode.not_(x1))) terms.append(exprnode.or_(*xs)) y = exprnode.and_(*terms) else: for i, xi in enumerate(xs): zeros = [exprnode.not_(x) for x in xs[:i] + xs[i+1:]] terms.append(exprnode.and_(xi, *zeros)) y = exprnode.or_(*terms) if simplify: y = y.simplify() return _expr(y)
python
def OneHot(*xs, simplify=True, conj=True): xs = [Expression.box(x).node for x in xs] terms = list() if conj: for x0, x1 in itertools.combinations(xs, 2): terms.append(exprnode.or_(exprnode.not_(x0), exprnode.not_(x1))) terms.append(exprnode.or_(*xs)) y = exprnode.and_(*terms) else: for i, xi in enumerate(xs): zeros = [exprnode.not_(x) for x in xs[:i] + xs[i+1:]] terms.append(exprnode.and_(xi, *zeros)) y = exprnode.or_(*terms) if simplify: y = y.simplify() return _expr(y)
[ "def", "OneHot", "(", "*", "xs", ",", "simplify", "=", "True", ",", "conj", "=", "True", ")", ":", "xs", "=", "[", "Expression", ".", "box", "(", "x", ")", ".", "node", "for", "x", "in", "xs", "]", "terms", "=", "list", "(", ")", "if", "conj"...
Return an expression that means "exactly one input function is true". If *simplify* is ``True``, return a simplified expression. If *conj* is ``True``, return a CNF. Otherwise, return a DNF.
[ "Return", "an", "expression", "that", "means", "exactly", "one", "input", "function", "is", "true", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L472-L497
27,485
cjdrake/pyeda
pyeda/boolalg/expr.py
NHot
def NHot(n, *xs, simplify=True): """ Return an expression that means "exactly N input functions are true". If *simplify* is ``True``, return a simplified expression. """ if not isinstance(n, int): raise TypeError("expected n to be an int") if not 0 <= n <= len(xs): fstr = "expected 0 <= n <= {}, got {}" raise ValueError(fstr.format(len(xs), n)) xs = [Expression.box(x).node for x in xs] num = len(xs) terms = list() for hot_idxs in itertools.combinations(range(num), n): hot_idxs = set(hot_idxs) _xs = [xs[i] if i in hot_idxs else exprnode.not_(xs[i]) for i in range(num)] terms.append(exprnode.and_(*_xs)) y = exprnode.or_(*terms) if simplify: y = y.simplify() return _expr(y)
python
def NHot(n, *xs, simplify=True): if not isinstance(n, int): raise TypeError("expected n to be an int") if not 0 <= n <= len(xs): fstr = "expected 0 <= n <= {}, got {}" raise ValueError(fstr.format(len(xs), n)) xs = [Expression.box(x).node for x in xs] num = len(xs) terms = list() for hot_idxs in itertools.combinations(range(num), n): hot_idxs = set(hot_idxs) _xs = [xs[i] if i in hot_idxs else exprnode.not_(xs[i]) for i in range(num)] terms.append(exprnode.and_(*_xs)) y = exprnode.or_(*terms) if simplify: y = y.simplify() return _expr(y)
[ "def", "NHot", "(", "n", ",", "*", "xs", ",", "simplify", "=", "True", ")", ":", "if", "not", "isinstance", "(", "n", ",", "int", ")", ":", "raise", "TypeError", "(", "\"expected n to be an int\"", ")", "if", "not", "0", "<=", "n", "<=", "len", "("...
Return an expression that means "exactly N input functions are true". If *simplify* is ``True``, return a simplified expression.
[ "Return", "an", "expression", "that", "means", "exactly", "N", "input", "functions", "are", "true", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L500-L524
27,486
cjdrake/pyeda
pyeda/boolalg/expr.py
Majority
def Majority(*xs, simplify=True, conj=False): """ Return an expression that means "the majority of input functions are true". If *simplify* is ``True``, return a simplified expression. If *conj* is ``True``, return a CNF. Otherwise, return a DNF. """ xs = [Expression.box(x).node for x in xs] if conj: terms = list() for _xs in itertools.combinations(xs, (len(xs) + 1) // 2): terms.append(exprnode.or_(*_xs)) y = exprnode.and_(*terms) else: terms = list() for _xs in itertools.combinations(xs, len(xs) // 2 + 1): terms.append(exprnode.and_(*_xs)) y = exprnode.or_(*terms) if simplify: y = y.simplify() return _expr(y)
python
def Majority(*xs, simplify=True, conj=False): xs = [Expression.box(x).node for x in xs] if conj: terms = list() for _xs in itertools.combinations(xs, (len(xs) + 1) // 2): terms.append(exprnode.or_(*_xs)) y = exprnode.and_(*terms) else: terms = list() for _xs in itertools.combinations(xs, len(xs) // 2 + 1): terms.append(exprnode.and_(*_xs)) y = exprnode.or_(*terms) if simplify: y = y.simplify() return _expr(y)
[ "def", "Majority", "(", "*", "xs", ",", "simplify", "=", "True", ",", "conj", "=", "False", ")", ":", "xs", "=", "[", "Expression", ".", "box", "(", "x", ")", ".", "node", "for", "x", "in", "xs", "]", "if", "conj", ":", "terms", "=", "list", ...
Return an expression that means "the majority of input functions are true". If *simplify* is ``True``, return a simplified expression. If *conj* is ``True``, return a CNF. Otherwise, return a DNF.
[ "Return", "an", "expression", "that", "means", "the", "majority", "of", "input", "functions", "are", "true", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L527-L550
27,487
cjdrake/pyeda
pyeda/boolalg/expr.py
Mux
def Mux(fs, sel, simplify=True): """ Return an expression that multiplexes a sequence of input functions over a sequence of select functions. """ # convert Mux([a, b], x) to Mux([a, b], [x]) if isinstance(sel, Expression): sel = [sel] if len(sel) < clog2(len(fs)): fstr = "expected at least {} select bits, got {}" raise ValueError(fstr.format(clog2(len(fs)), len(sel))) it = boolfunc.iter_terms(sel) y = exprnode.or_(*[exprnode.and_(f.node, *[lit.node for lit in next(it)]) for f in fs]) if simplify: y = y.simplify() return _expr(y)
python
def Mux(fs, sel, simplify=True): # convert Mux([a, b], x) to Mux([a, b], [x]) if isinstance(sel, Expression): sel = [sel] if len(sel) < clog2(len(fs)): fstr = "expected at least {} select bits, got {}" raise ValueError(fstr.format(clog2(len(fs)), len(sel))) it = boolfunc.iter_terms(sel) y = exprnode.or_(*[exprnode.and_(f.node, *[lit.node for lit in next(it)]) for f in fs]) if simplify: y = y.simplify() return _expr(y)
[ "def", "Mux", "(", "fs", ",", "sel", ",", "simplify", "=", "True", ")", ":", "# convert Mux([a, b], x) to Mux([a, b], [x])", "if", "isinstance", "(", "sel", ",", "Expression", ")", ":", "sel", "=", "[", "sel", "]", "if", "len", "(", "sel", ")", "<", "c...
Return an expression that multiplexes a sequence of input functions over a sequence of select functions.
[ "Return", "an", "expression", "that", "multiplexes", "a", "sequence", "of", "input", "functions", "over", "a", "sequence", "of", "select", "functions", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L572-L590
27,488
cjdrake/pyeda
pyeda/boolalg/expr.py
_backtrack
def _backtrack(ex): """ If this function is satisfiable, return a satisfying input upoint. Otherwise, return None. """ if ex is Zero: return None elif ex is One: return dict() else: v = ex.top points = {v: 0}, {v: 1} for point in points: soln = _backtrack(ex.restrict(point)) if soln is not None: soln.update(point) return soln return None
python
def _backtrack(ex): if ex is Zero: return None elif ex is One: return dict() else: v = ex.top points = {v: 0}, {v: 1} for point in points: soln = _backtrack(ex.restrict(point)) if soln is not None: soln.update(point) return soln return None
[ "def", "_backtrack", "(", "ex", ")", ":", "if", "ex", "is", "Zero", ":", "return", "None", "elif", "ex", "is", "One", ":", "return", "dict", "(", ")", "else", ":", "v", "=", "ex", ".", "top", "points", "=", "{", "v", ":", "0", "}", ",", "{", ...
If this function is satisfiable, return a satisfying input upoint. Otherwise, return None.
[ "If", "this", "function", "is", "satisfiable", "return", "a", "satisfying", "input", "upoint", ".", "Otherwise", "return", "None", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L1270-L1287
27,489
cjdrake/pyeda
pyeda/boolalg/expr.py
_iter_backtrack
def _iter_backtrack(ex, rand=False): """Iterate through all satisfying points using backtrack algorithm.""" if ex is One: yield dict() elif ex is not Zero: if rand: v = random.choice(ex.inputs) if rand else ex.top else: v = ex.top points = [{v: 0}, {v: 1}] if rand: random.shuffle(points) for point in points: for soln in _iter_backtrack(ex.restrict(point), rand): soln.update(point) yield soln
python
def _iter_backtrack(ex, rand=False): if ex is One: yield dict() elif ex is not Zero: if rand: v = random.choice(ex.inputs) if rand else ex.top else: v = ex.top points = [{v: 0}, {v: 1}] if rand: random.shuffle(points) for point in points: for soln in _iter_backtrack(ex.restrict(point), rand): soln.update(point) yield soln
[ "def", "_iter_backtrack", "(", "ex", ",", "rand", "=", "False", ")", ":", "if", "ex", "is", "One", ":", "yield", "dict", "(", ")", "elif", "ex", "is", "not", "Zero", ":", "if", "rand", ":", "v", "=", "random", ".", "choice", "(", "ex", ".", "in...
Iterate through all satisfying points using backtrack algorithm.
[ "Iterate", "through", "all", "satisfying", "points", "using", "backtrack", "algorithm", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L1290-L1305
27,490
cjdrake/pyeda
pyeda/boolalg/expr.py
_tseitin
def _tseitin(ex, auxvarname, auxvars=None): """ Convert a factored expression to a literal, and a list of constraints. """ if isinstance(ex, Literal): return ex, list() else: if auxvars is None: auxvars = list() lits = list() constraints = list() for x in ex.xs: lit, subcons = _tseitin(x, auxvarname, auxvars) lits.append(lit) constraints.extend(subcons) auxvarindex = len(auxvars) auxvar = exprvar(auxvarname, auxvarindex) auxvars.append(auxvar) f = ASTOPS[ex.ASTOP](*lits) constraints.append((auxvar, f)) return auxvar, constraints
python
def _tseitin(ex, auxvarname, auxvars=None): if isinstance(ex, Literal): return ex, list() else: if auxvars is None: auxvars = list() lits = list() constraints = list() for x in ex.xs: lit, subcons = _tseitin(x, auxvarname, auxvars) lits.append(lit) constraints.extend(subcons) auxvarindex = len(auxvars) auxvar = exprvar(auxvarname, auxvarindex) auxvars.append(auxvar) f = ASTOPS[ex.ASTOP](*lits) constraints.append((auxvar, f)) return auxvar, constraints
[ "def", "_tseitin", "(", "ex", ",", "auxvarname", ",", "auxvars", "=", "None", ")", ":", "if", "isinstance", "(", "ex", ",", "Literal", ")", ":", "return", "ex", ",", "list", "(", ")", "else", ":", "if", "auxvars", "is", "None", ":", "auxvars", "=",...
Convert a factored expression to a literal, and a list of constraints.
[ "Convert", "a", "factored", "expression", "to", "a", "literal", "and", "a", "list", "of", "constraints", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L1412-L1435
27,491
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.eq
def eq(self, other): """Boolean equal operator.""" other_node = self.box(other).node return _expr(exprnode.eq(self.node, other_node))
python
def eq(self, other): other_node = self.box(other).node return _expr(exprnode.eq(self.node, other_node))
[ "def", "eq", "(", "self", ",", "other", ")", ":", "other_node", "=", "self", ".", "box", "(", "other", ")", ".", "node", "return", "_expr", "(", "exprnode", ".", "eq", "(", "self", ".", "node", ",", "other_node", ")", ")" ]
Boolean equal operator.
[ "Boolean", "equal", "operator", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L685-L688
27,492
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.pushdown_not
def pushdown_not(self): """Return an expression with NOT operators pushed down thru dual ops. Specifically, perform the following transformations: ~(a | b | c ...) <=> ~a & ~b & ~c ... ~(a & b & c ...) <=> ~a | ~b | ~c ... ~(s ? d1 : d0) <=> s ? ~d1 : ~d0 """ node = self.node.pushdown_not() if node is self.node: return self else: return _expr(node)
python
def pushdown_not(self): node = self.node.pushdown_not() if node is self.node: return self else: return _expr(node)
[ "def", "pushdown_not", "(", "self", ")", ":", "node", "=", "self", ".", "node", ".", "pushdown_not", "(", ")", "if", "node", "is", "self", ".", "node", ":", "return", "self", "else", ":", "return", "_expr", "(", "node", ")" ]
Return an expression with NOT operators pushed down thru dual ops. Specifically, perform the following transformations: ~(a | b | c ...) <=> ~a & ~b & ~c ... ~(a & b & c ...) <=> ~a | ~b | ~c ... ~(s ? d1 : d0) <=> s ? ~d1 : ~d0
[ "Return", "an", "expression", "with", "NOT", "operators", "pushed", "down", "thru", "dual", "ops", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L820-L832
27,493
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.simplify
def simplify(self): """Return a simplified expression.""" node = self.node.simplify() if node is self.node: return self else: return _expr(node)
python
def simplify(self): node = self.node.simplify() if node is self.node: return self else: return _expr(node)
[ "def", "simplify", "(", "self", ")", ":", "node", "=", "self", ".", "node", ".", "simplify", "(", ")", "if", "node", "is", "self", ".", "node", ":", "return", "self", "else", ":", "return", "_expr", "(", "node", ")" ]
Return a simplified expression.
[ "Return", "a", "simplified", "expression", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L834-L840
27,494
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.to_binary
def to_binary(self): """Convert N-ary operators to binary operators.""" node = self.node.to_binary() if node is self.node: return self else: return _expr(node)
python
def to_binary(self): node = self.node.to_binary() if node is self.node: return self else: return _expr(node)
[ "def", "to_binary", "(", "self", ")", ":", "node", "=", "self", ".", "node", ".", "to_binary", "(", ")", "if", "node", "is", "self", ".", "node", ":", "return", "self", "else", ":", "return", "_expr", "(", "node", ")" ]
Convert N-ary operators to binary operators.
[ "Convert", "N", "-", "ary", "operators", "to", "binary", "operators", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L847-L853
27,495
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.to_nnf
def to_nnf(self): """Return an equivalent expression is negation normal form.""" node = self.node.to_nnf() if node is self.node: return self else: return _expr(node)
python
def to_nnf(self): node = self.node.to_nnf() if node is self.node: return self else: return _expr(node)
[ "def", "to_nnf", "(", "self", ")", ":", "node", "=", "self", ".", "node", ".", "to_nnf", "(", ")", "if", "node", "is", "self", ".", "node", ":", "return", "self", "else", ":", "return", "_expr", "(", "node", ")" ]
Return an equivalent expression is negation normal form.
[ "Return", "an", "equivalent", "expression", "is", "negation", "normal", "form", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L855-L861
27,496
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.to_dnf
def to_dnf(self): """Return an equivalent expression in disjunctive normal form.""" node = self.node.to_dnf() if node is self.node: return self else: return _expr(node)
python
def to_dnf(self): node = self.node.to_dnf() if node is self.node: return self else: return _expr(node)
[ "def", "to_dnf", "(", "self", ")", ":", "node", "=", "self", ".", "node", ".", "to_dnf", "(", ")", "if", "node", "is", "self", ".", "node", ":", "return", "self", "else", ":", "return", "_expr", "(", "node", ")" ]
Return an equivalent expression in disjunctive normal form.
[ "Return", "an", "equivalent", "expression", "in", "disjunctive", "normal", "form", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L863-L869
27,497
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.to_cnf
def to_cnf(self): """Return an equivalent expression in conjunctive normal form.""" node = self.node.to_cnf() if node is self.node: return self else: return _expr(node)
python
def to_cnf(self): node = self.node.to_cnf() if node is self.node: return self else: return _expr(node)
[ "def", "to_cnf", "(", "self", ")", ":", "node", "=", "self", ".", "node", ".", "to_cnf", "(", ")", "if", "node", "is", "self", ".", "node", ":", "return", "self", "else", ":", "return", "_expr", "(", "node", ")" ]
Return an equivalent expression in conjunctive normal form.
[ "Return", "an", "equivalent", "expression", "in", "conjunctive", "normal", "form", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L871-L877
27,498
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.complete_sum
def complete_sum(self): """ Return an equivalent DNF expression that includes all prime implicants. """ node = self.node.complete_sum() if node is self.node: return self else: return _expr(node)
python
def complete_sum(self): node = self.node.complete_sum() if node is self.node: return self else: return _expr(node)
[ "def", "complete_sum", "(", "self", ")", ":", "node", "=", "self", ".", "node", ".", "complete_sum", "(", ")", "if", "node", "is", "self", ".", "node", ":", "return", "self", "else", ":", "return", "_expr", "(", "node", ")" ]
Return an equivalent DNF expression that includes all prime implicants.
[ "Return", "an", "equivalent", "DNF", "expression", "that", "includes", "all", "prime", "implicants", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L879-L888
27,499
cjdrake/pyeda
pyeda/boolalg/expr.py
Expression.expand
def expand(self, vs=None, conj=False): """Return the Shannon expansion with respect to a list of variables.""" vs = self._expect_vars(vs) if vs: outer, inner = (And, Or) if conj else (Or, And) terms = [inner(self.restrict(p), *boolfunc.point2term(p, conj)) for p in boolfunc.iter_points(vs)] if conj: terms = [term for term in terms if term is not One] else: terms = [term for term in terms if term is not Zero] return outer(*terms, simplify=False) else: return self
python
def expand(self, vs=None, conj=False): vs = self._expect_vars(vs) if vs: outer, inner = (And, Or) if conj else (Or, And) terms = [inner(self.restrict(p), *boolfunc.point2term(p, conj)) for p in boolfunc.iter_points(vs)] if conj: terms = [term for term in terms if term is not One] else: terms = [term for term in terms if term is not Zero] return outer(*terms, simplify=False) else: return self
[ "def", "expand", "(", "self", ",", "vs", "=", "None", ",", "conj", "=", "False", ")", ":", "vs", "=", "self", ".", "_expect_vars", "(", "vs", ")", "if", "vs", ":", "outer", ",", "inner", "=", "(", "And", ",", "Or", ")", "if", "conj", "else", ...
Return the Shannon expansion with respect to a list of variables.
[ "Return", "the", "Shannon", "expansion", "with", "respect", "to", "a", "list", "of", "variables", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L891-L905