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
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
bootphon/h5features
h5features/features.py
contains_empty
def contains_empty(features): """Check features data are not empty :param features: The features data to check. :type features: list of numpy arrays. :return: True if one of the array is empty, False else. """ if not features: return True for feature in features: if feature.shape[0] == 0: return True return False
python
def contains_empty(features): """Check features data are not empty :param features: The features data to check. :type features: list of numpy arrays. :return: True if one of the array is empty, False else. """ if not features: return True for feature in features: if feature.shape[0] == 0: return True return False
[ "def", "contains_empty", "(", "features", ")", ":", "if", "not", "features", ":", "return", "True", "for", "feature", "in", "features", ":", "if", "feature", ".", "shape", "[", "0", "]", "==", "0", ":", "return", "True", "return", "False" ]
Check features data are not empty :param features: The features data to check. :type features: list of numpy arrays. :return: True if one of the array is empty, False else.
[ "Check", "features", "data", "are", "not", "empty" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L27-L41
train
25,900
bootphon/h5features
h5features/features.py
parse_dformat
def parse_dformat(dformat, check=True): """Return `dformat` or raise if it is not 'dense' or 'sparse'""" if check and dformat not in ['dense', 'sparse']: raise IOError( "{} is a bad features format, please choose 'dense' or 'sparse'" .format(dformat)) return dformat
python
def parse_dformat(dformat, check=True): """Return `dformat` or raise if it is not 'dense' or 'sparse'""" if check and dformat not in ['dense', 'sparse']: raise IOError( "{} is a bad features format, please choose 'dense' or 'sparse'" .format(dformat)) return dformat
[ "def", "parse_dformat", "(", "dformat", ",", "check", "=", "True", ")", ":", "if", "check", "and", "dformat", "not", "in", "[", "'dense'", ",", "'sparse'", "]", ":", "raise", "IOError", "(", "\"{} is a bad features format, please choose 'dense' or 'sparse'\"", "."...
Return `dformat` or raise if it is not 'dense' or 'sparse
[ "Return", "dformat", "or", "raise", "if", "it", "is", "not", "dense", "or", "sparse" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L44-L50
train
25,901
bootphon/h5features
h5features/features.py
parse_dtype
def parse_dtype(features, check=True): """Return the features scalar type, raise if error Raise IOError if all features have not the same data type. Return dtype, the features scalar type. """ dtype = features[0].dtype if check: types = [x.dtype for x in features] if not all([t == dtype for t in types]): raise IOError('features must be homogeneous') return dtype
python
def parse_dtype(features, check=True): """Return the features scalar type, raise if error Raise IOError if all features have not the same data type. Return dtype, the features scalar type. """ dtype = features[0].dtype if check: types = [x.dtype for x in features] if not all([t == dtype for t in types]): raise IOError('features must be homogeneous') return dtype
[ "def", "parse_dtype", "(", "features", ",", "check", "=", "True", ")", ":", "dtype", "=", "features", "[", "0", "]", ".", "dtype", "if", "check", ":", "types", "=", "[", "x", ".", "dtype", "for", "x", "in", "features", "]", "if", "not", "all", "(...
Return the features scalar type, raise if error Raise IOError if all features have not the same data type. Return dtype, the features scalar type.
[ "Return", "the", "features", "scalar", "type", "raise", "if", "error" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L53-L65
train
25,902
bootphon/h5features
h5features/features.py
parse_dim
def parse_dim(features, check=True): """Return the features dimension, raise if error Raise IOError if features have not all the same positive dimension. Return dim (int), the features dimension. """ # try: dim = features[0].shape[1] # except IndexError: # dim = 1 if check and not dim > 0: raise IOError('features dimension must be strictly positive') if check and not all([d == dim for d in [x.shape[1] for x in features]]): raise IOError('all files must have the same feature dimension') return dim
python
def parse_dim(features, check=True): """Return the features dimension, raise if error Raise IOError if features have not all the same positive dimension. Return dim (int), the features dimension. """ # try: dim = features[0].shape[1] # except IndexError: # dim = 1 if check and not dim > 0: raise IOError('features dimension must be strictly positive') if check and not all([d == dim for d in [x.shape[1] for x in features]]): raise IOError('all files must have the same feature dimension') return dim
[ "def", "parse_dim", "(", "features", ",", "check", "=", "True", ")", ":", "# try:", "dim", "=", "features", "[", "0", "]", ".", "shape", "[", "1", "]", "# except IndexError:", "# dim = 1", "if", "check", "and", "not", "dim", ">", "0", ":", "raise",...
Return the features dimension, raise if error Raise IOError if features have not all the same positive dimension. Return dim (int), the features dimension.
[ "Return", "the", "features", "dimension", "raise", "if", "error" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L68-L84
train
25,903
bootphon/h5features
h5features/features.py
Features.is_appendable_to
def is_appendable_to(self, group): """Return True if features are appendable to a HDF5 group""" return (group.attrs['format'] == self.dformat and group[self.name].dtype == self.dtype and # We use a method because dim differs in dense and sparse. self._group_dim(group) == self.dim)
python
def is_appendable_to(self, group): """Return True if features are appendable to a HDF5 group""" return (group.attrs['format'] == self.dformat and group[self.name].dtype == self.dtype and # We use a method because dim differs in dense and sparse. self._group_dim(group) == self.dim)
[ "def", "is_appendable_to", "(", "self", ",", "group", ")", ":", "return", "(", "group", ".", "attrs", "[", "'format'", "]", "==", "self", ".", "dformat", "and", "group", "[", "self", ".", "name", "]", ".", "dtype", "==", "self", ".", "dtype", "and", ...
Return True if features are appendable to a HDF5 group
[ "Return", "True", "if", "features", "are", "appendable", "to", "a", "HDF5", "group" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L139-L144
train
25,904
bootphon/h5features
h5features/features.py
Features.create_dataset
def create_dataset( self, group, chunk_size, compression=None, compression_opts=None): """Initialize the features subgoup""" group.attrs['format'] = self.dformat super(Features, self)._create_dataset( group, chunk_size, compression, compression_opts) # TODO attribute declared outside __init__ is not safe. Used # because Labels.create_dataset need it. if chunk_size != 'auto': self.nb_per_chunk = nb_per_chunk( self.dtype.itemsize, self.dim, chunk_size) else: self.nb_per_chunk = 'auto'
python
def create_dataset( self, group, chunk_size, compression=None, compression_opts=None): """Initialize the features subgoup""" group.attrs['format'] = self.dformat super(Features, self)._create_dataset( group, chunk_size, compression, compression_opts) # TODO attribute declared outside __init__ is not safe. Used # because Labels.create_dataset need it. if chunk_size != 'auto': self.nb_per_chunk = nb_per_chunk( self.dtype.itemsize, self.dim, chunk_size) else: self.nb_per_chunk = 'auto'
[ "def", "create_dataset", "(", "self", ",", "group", ",", "chunk_size", ",", "compression", "=", "None", ",", "compression_opts", "=", "None", ")", ":", "group", ".", "attrs", "[", "'format'", "]", "=", "self", ".", "dformat", "super", "(", "Features", ",...
Initialize the features subgoup
[ "Initialize", "the", "features", "subgoup" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L153-L166
train
25,905
bootphon/h5features
h5features/features.py
Features.write_to
def write_to(self, group, append=False): """Write stored features to a given group""" if self.sparsetodense: self.data = [x.todense() if sp.issparse(x) else x for x in self.data] nframes = sum([d.shape[0] for d in self.data]) dim = self._group_dim(group) feats = np.concatenate(self.data, axis=0) if append: nframes_group = group[self.name].shape[0] group[self.name].resize(nframes_group + nframes, axis=0) if dim == 1: group[self.name][nframes_group:] = feats else: group[self.name][nframes_group:, :] = feats else: group[self.name].resize(nframes, axis=0) group[self.name][...] = feats if dim == 1 else feats
python
def write_to(self, group, append=False): """Write stored features to a given group""" if self.sparsetodense: self.data = [x.todense() if sp.issparse(x) else x for x in self.data] nframes = sum([d.shape[0] for d in self.data]) dim = self._group_dim(group) feats = np.concatenate(self.data, axis=0) if append: nframes_group = group[self.name].shape[0] group[self.name].resize(nframes_group + nframes, axis=0) if dim == 1: group[self.name][nframes_group:] = feats else: group[self.name][nframes_group:, :] = feats else: group[self.name].resize(nframes, axis=0) group[self.name][...] = feats if dim == 1 else feats
[ "def", "write_to", "(", "self", ",", "group", ",", "append", "=", "False", ")", ":", "if", "self", ".", "sparsetodense", ":", "self", ".", "data", "=", "[", "x", ".", "todense", "(", ")", "if", "sp", ".", "issparse", "(", "x", ")", "else", "x", ...
Write stored features to a given group
[ "Write", "stored", "features", "to", "a", "given", "group" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L168-L187
train
25,906
bootphon/h5features
h5features/features.py
SparseFeatures.create_dataset
def create_dataset(self, group, chunk_size): """Initializes sparse specific datasets""" group.attrs['format'] = self.dformat group.attrs['dim'] = self.dim if chunk_size == 'auto': group.create_dataset( 'coordinates', (0, 2), dtype=np.float64, chunks=True, maxshape=(None, 2)) group.create_dataset( self.name, (0,), dtype=self.dtype, chunks=True, maxshape=(None,)) else: # for storing sparse data we don't use the self.nb_per_chunk, # which is only used by the Writer to determine times chunking. per_chunk = nb_per_chunk(self.dtype.itemsize, 1, chunk_size) group.create_dataset( 'coordinates', (0, 2), dtype=np.float64, chunks=(per_chunk, 2), maxshape=(None, 2)) group.create_dataset( self.name, (0,), dtype=self.dtype, chunks=(per_chunk,), maxshape=(None,)) dtype = np.int64 if chunk_size == 'auto': chunks = True self.nb_per_chunk = 'auto' else: chunks = (nb_per_chunk(np.dtype(dtype).itemsize, 1, chunk_size),) # Needed by Times.create_dataset self.nb_per_chunk = nb_per_chunk( self.dtype.itemsize, int(round(self.sparsity*self.dim)), chunk_size) group.create_dataset( 'frames', (0,), dtype=dtype, chunks=chunks, maxshape=(None,))
python
def create_dataset(self, group, chunk_size): """Initializes sparse specific datasets""" group.attrs['format'] = self.dformat group.attrs['dim'] = self.dim if chunk_size == 'auto': group.create_dataset( 'coordinates', (0, 2), dtype=np.float64, chunks=True, maxshape=(None, 2)) group.create_dataset( self.name, (0,), dtype=self.dtype, chunks=True, maxshape=(None,)) else: # for storing sparse data we don't use the self.nb_per_chunk, # which is only used by the Writer to determine times chunking. per_chunk = nb_per_chunk(self.dtype.itemsize, 1, chunk_size) group.create_dataset( 'coordinates', (0, 2), dtype=np.float64, chunks=(per_chunk, 2), maxshape=(None, 2)) group.create_dataset( self.name, (0,), dtype=self.dtype, chunks=(per_chunk,), maxshape=(None,)) dtype = np.int64 if chunk_size == 'auto': chunks = True self.nb_per_chunk = 'auto' else: chunks = (nb_per_chunk(np.dtype(dtype).itemsize, 1, chunk_size),) # Needed by Times.create_dataset self.nb_per_chunk = nb_per_chunk( self.dtype.itemsize, int(round(self.sparsity*self.dim)), chunk_size) group.create_dataset( 'frames', (0,), dtype=dtype, chunks=chunks, maxshape=(None,))
[ "def", "create_dataset", "(", "self", ",", "group", ",", "chunk_size", ")", ":", "group", ".", "attrs", "[", "'format'", "]", "=", "self", ".", "dformat", "group", ".", "attrs", "[", "'dim'", "]", "=", "self", ".", "dim", "if", "chunk_size", "==", "'...
Initializes sparse specific datasets
[ "Initializes", "sparse", "specific", "datasets" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L215-L256
train
25,907
bootphon/h5features
h5features/properties.py
read_properties
def read_properties(group): """Returns properties loaded from a group""" if 'properties' not in group: raise IOError('no properties in group') data = group['properties'][...][0].replace(b'__NULL__', b'\x00') return pickle.loads(data)
python
def read_properties(group): """Returns properties loaded from a group""" if 'properties' not in group: raise IOError('no properties in group') data = group['properties'][...][0].replace(b'__NULL__', b'\x00') return pickle.loads(data)
[ "def", "read_properties", "(", "group", ")", ":", "if", "'properties'", "not", "in", "group", ":", "raise", "IOError", "(", "'no properties in group'", ")", "data", "=", "group", "[", "'properties'", "]", "[", "...", "]", "[", "0", "]", ".", "replace", "...
Returns properties loaded from a group
[ "Returns", "properties", "loaded", "from", "a", "group" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/properties.py#L24-L30
train
25,908
bootphon/h5features
h5features/properties.py
Properties._eq_dicts
def _eq_dicts(d1, d2): """Returns True if d1 == d2, False otherwise""" if not d1.keys() == d2.keys(): return False for k, v1 in d1.items(): v2 = d2[k] if not type(v1) == type(v2): return False if isinstance(v1, np.ndarray): if not np.array_equal(v1, v2): return False else: if not v1 == v2: return False return True
python
def _eq_dicts(d1, d2): """Returns True if d1 == d2, False otherwise""" if not d1.keys() == d2.keys(): return False for k, v1 in d1.items(): v2 = d2[k] if not type(v1) == type(v2): return False if isinstance(v1, np.ndarray): if not np.array_equal(v1, v2): return False else: if not v1 == v2: return False return True
[ "def", "_eq_dicts", "(", "d1", ",", "d2", ")", ":", "if", "not", "d1", ".", "keys", "(", ")", "==", "d2", ".", "keys", "(", ")", ":", "return", "False", "for", "k", ",", "v1", "in", "d1", ".", "items", "(", ")", ":", "v2", "=", "d2", "[", ...
Returns True if d1 == d2, False otherwise
[ "Returns", "True", "if", "d1", "==", "d2", "False", "otherwise" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/properties.py#L57-L72
train
25,909
bootphon/h5features
h5features/properties.py
Properties.write_to
def write_to(self, group, append=False): """Writes the properties to a `group`, or append it""" data = self.data if append is True: try: # concatenate original and new properties in a single list original = read_properties(group) data = original + data except EOFError: pass # no former data to append on # h5py does not support embedded NULLs in strings ('\x00') data = pickle.dumps(data).replace(b'\x00', b'__NULL__') group['properties'][...] = np.void(data)
python
def write_to(self, group, append=False): """Writes the properties to a `group`, or append it""" data = self.data if append is True: try: # concatenate original and new properties in a single list original = read_properties(group) data = original + data except EOFError: pass # no former data to append on # h5py does not support embedded NULLs in strings ('\x00') data = pickle.dumps(data).replace(b'\x00', b'__NULL__') group['properties'][...] = np.void(data)
[ "def", "write_to", "(", "self", ",", "group", ",", "append", "=", "False", ")", ":", "data", "=", "self", ".", "data", "if", "append", "is", "True", ":", "try", ":", "# concatenate original and new properties in a single list", "original", "=", "read_properties"...
Writes the properties to a `group`, or append it
[ "Writes", "the", "properties", "to", "a", "group", "or", "append", "it" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/properties.py#L83-L96
train
25,910
bootphon/h5features
docs/exemple.py
generate_data
def generate_data(nitem, nfeat=2, dim=10, labeldim=1, base='item'): """Returns a randomly generated h5f.Data instance. - nitem is the number of items to generate. - nfeat is the number of features to generate for each item. - dim is the dimension of the features vectors. - base is the items basename - labeldim is the dimension of the labels vectors. """ import numpy as np # A list of item names items = [base + '_' + str(i) for i in range(nitem)] # A list of features arrays features = [np.random.randn(nfeat, dim) for _ in range(nitem)] # A list on 1D or 2D times arrays if labeldim == 1: labels = [np.linspace(0, 1, nfeat)] * nitem else: t = np.linspace(0, 1, nfeat) labels = [np.array([t+i for i in range(labeldim)])] * nitem # Format data as required by the writer return h5f.Data(items, labels, features, check=True)
python
def generate_data(nitem, nfeat=2, dim=10, labeldim=1, base='item'): """Returns a randomly generated h5f.Data instance. - nitem is the number of items to generate. - nfeat is the number of features to generate for each item. - dim is the dimension of the features vectors. - base is the items basename - labeldim is the dimension of the labels vectors. """ import numpy as np # A list of item names items = [base + '_' + str(i) for i in range(nitem)] # A list of features arrays features = [np.random.randn(nfeat, dim) for _ in range(nitem)] # A list on 1D or 2D times arrays if labeldim == 1: labels = [np.linspace(0, 1, nfeat)] * nitem else: t = np.linspace(0, 1, nfeat) labels = [np.array([t+i for i in range(labeldim)])] * nitem # Format data as required by the writer return h5f.Data(items, labels, features, check=True)
[ "def", "generate_data", "(", "nitem", ",", "nfeat", "=", "2", ",", "dim", "=", "10", ",", "labeldim", "=", "1", ",", "base", "=", "'item'", ")", ":", "import", "numpy", "as", "np", "# A list of item names", "items", "=", "[", "base", "+", "'_'", "+",...
Returns a randomly generated h5f.Data instance. - nitem is the number of items to generate. - nfeat is the number of features to generate for each item. - dim is the dimension of the features vectors. - base is the items basename - labeldim is the dimension of the labels vectors.
[ "Returns", "a", "randomly", "generated", "h5f", ".", "Data", "instance", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/docs/exemple.py#L7-L32
train
25,911
bootphon/h5features
h5features/index.py
create_index
def create_index(group, chunk_size, compression=None, compression_opts=None): """Create an empty index dataset in the given group.""" dtype = np.int64 if chunk_size == 'auto': chunks = True else: chunks = (nb_per_chunk(np.dtype(dtype).itemsize, 1, chunk_size),) group.create_dataset( 'index', (0,), dtype=dtype, chunks=chunks, maxshape=(None,), compression=compression, compression_opts=compression_opts)
python
def create_index(group, chunk_size, compression=None, compression_opts=None): """Create an empty index dataset in the given group.""" dtype = np.int64 if chunk_size == 'auto': chunks = True else: chunks = (nb_per_chunk(np.dtype(dtype).itemsize, 1, chunk_size),) group.create_dataset( 'index', (0,), dtype=dtype, chunks=chunks, maxshape=(None,), compression=compression, compression_opts=compression_opts)
[ "def", "create_index", "(", "group", ",", "chunk_size", ",", "compression", "=", "None", ",", "compression_opts", "=", "None", ")", ":", "dtype", "=", "np", ".", "int64", "if", "chunk_size", "==", "'auto'", ":", "chunks", "=", "True", "else", ":", "chunk...
Create an empty index dataset in the given group.
[ "Create", "an", "empty", "index", "dataset", "in", "the", "given", "group", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/index.py#L37-L48
train
25,912
bootphon/h5features
h5features/index.py
write_index
def write_index(data, group, append): """Write the data index to the given group. :param h5features.Data data: The that is being indexed. :param h5py.Group group: The group where to write the index. :param bool append: If True, append the created index to the existing one in the `group`. Delete any existing data in index if False. """ # build the index from data nitems = group['items'].shape[0] if 'items' in group else 0 last_index = group['index'][-1] if nitems > 0 else -1 index = last_index + cumindex(data._entries['features']) if append: nidx = group['index'].shape[0] # # in case we append to the end of an existing item # if data._entries['items']._continue_last_item(group): # nidx -= 1 group['index'].resize((nidx + index.shape[0],)) group['index'][nidx:] = index else: group['index'].resize((index.shape[0],)) group['index'][...] = index
python
def write_index(data, group, append): """Write the data index to the given group. :param h5features.Data data: The that is being indexed. :param h5py.Group group: The group where to write the index. :param bool append: If True, append the created index to the existing one in the `group`. Delete any existing data in index if False. """ # build the index from data nitems = group['items'].shape[0] if 'items' in group else 0 last_index = group['index'][-1] if nitems > 0 else -1 index = last_index + cumindex(data._entries['features']) if append: nidx = group['index'].shape[0] # # in case we append to the end of an existing item # if data._entries['items']._continue_last_item(group): # nidx -= 1 group['index'].resize((nidx + index.shape[0],)) group['index'][nidx:] = index else: group['index'].resize((index.shape[0],)) group['index'][...] = index
[ "def", "write_index", "(", "data", ",", "group", ",", "append", ")", ":", "# build the index from data", "nitems", "=", "group", "[", "'items'", "]", ".", "shape", "[", "0", "]", "if", "'items'", "in", "group", "else", "0", "last_index", "=", "group", "[...
Write the data index to the given group. :param h5features.Data data: The that is being indexed. :param h5py.Group group: The group where to write the index. :param bool append: If True, append the created index to the existing one in the `group`. Delete any existing data in index if False.
[ "Write", "the", "data", "index", "to", "the", "given", "group", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/index.py#L51-L76
train
25,913
bootphon/h5features
h5features/index.py
read_index
def read_index(group, version='1.1'): """Return the index stored in a h5features group. :param h5py.Group group: The group to read the index from. :param str version: The h5features version of the `group`. :return: a 1D numpy array of features indices. """ if version == '0.1': return np.int64(group['index'][...]) elif version == '1.0': return group['file_index'][...] else: return group['index'][...]
python
def read_index(group, version='1.1'): """Return the index stored in a h5features group. :param h5py.Group group: The group to read the index from. :param str version: The h5features version of the `group`. :return: a 1D numpy array of features indices. """ if version == '0.1': return np.int64(group['index'][...]) elif version == '1.0': return group['file_index'][...] else: return group['index'][...]
[ "def", "read_index", "(", "group", ",", "version", "=", "'1.1'", ")", ":", "if", "version", "==", "'0.1'", ":", "return", "np", ".", "int64", "(", "group", "[", "'index'", "]", "[", "...", "]", ")", "elif", "version", "==", "'1.0'", ":", "return", ...
Return the index stored in a h5features group. :param h5py.Group group: The group to read the index from. :param str version: The h5features version of the `group`. :return: a 1D numpy array of features indices.
[ "Return", "the", "index", "stored", "in", "a", "h5features", "group", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/index.py#L79-L91
train
25,914
bootphon/h5features
h5features/entry.py
nb_per_chunk
def nb_per_chunk(item_size, item_dim, chunk_size): """Return the number of items that can be stored in one chunk. :param int item_size: Size of an item's scalar componant in Bytes (e.g. for np.float64 this is 8) :param int item_dim: Items dimension (length of the second axis) :param float chunk_size: The size of a chunk given in MBytes. """ # from Mbytes to bytes size = chunk_size * 10.**6 ratio = int(round(size / (item_size*item_dim))) return max(10, ratio)
python
def nb_per_chunk(item_size, item_dim, chunk_size): """Return the number of items that can be stored in one chunk. :param int item_size: Size of an item's scalar componant in Bytes (e.g. for np.float64 this is 8) :param int item_dim: Items dimension (length of the second axis) :param float chunk_size: The size of a chunk given in MBytes. """ # from Mbytes to bytes size = chunk_size * 10.**6 ratio = int(round(size / (item_size*item_dim))) return max(10, ratio)
[ "def", "nb_per_chunk", "(", "item_size", ",", "item_dim", ",", "chunk_size", ")", ":", "# from Mbytes to bytes", "size", "=", "chunk_size", "*", "10.", "**", "6", "ratio", "=", "int", "(", "round", "(", "size", "/", "(", "item_size", "*", "item_dim", ")", ...
Return the number of items that can be stored in one chunk. :param int item_size: Size of an item's scalar componant in Bytes (e.g. for np.float64 this is 8) :param int item_dim: Items dimension (length of the second axis) :param float chunk_size: The size of a chunk given in MBytes.
[ "Return", "the", "number", "of", "items", "that", "can", "be", "stored", "in", "one", "chunk", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/entry.py#L22-L36
train
25,915
bootphon/h5features
h5features/entry.py
Entry.is_appendable
def is_appendable(self, entry): """Return True if entry can be appended to self""" try: if ( self.name == entry.name and self.dtype == entry.dtype and self.dim == entry.dim ): return True except AttributeError: return False return False
python
def is_appendable(self, entry): """Return True if entry can be appended to self""" try: if ( self.name == entry.name and self.dtype == entry.dtype and self.dim == entry.dim ): return True except AttributeError: return False return False
[ "def", "is_appendable", "(", "self", ",", "entry", ")", ":", "try", ":", "if", "(", "self", ".", "name", "==", "entry", ".", "name", "and", "self", ".", "dtype", "==", "entry", ".", "dtype", "and", "self", ".", "dim", "==", "entry", ".", "dim", "...
Return True if entry can be appended to self
[ "Return", "True", "if", "entry", "can", "be", "appended", "to", "self" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/entry.py#L74-L85
train
25,916
bootphon/h5features
h5features/entry.py
Entry.append
def append(self, entry): """Append an entry to self""" if not self.is_appendable(entry): raise ValueError('entry not appendable') self.data += entry.data
python
def append(self, entry): """Append an entry to self""" if not self.is_appendable(entry): raise ValueError('entry not appendable') self.data += entry.data
[ "def", "append", "(", "self", ",", "entry", ")", ":", "if", "not", "self", ".", "is_appendable", "(", "entry", ")", ":", "raise", "ValueError", "(", "'entry not appendable'", ")", "self", ".", "data", "+=", "entry", ".", "data" ]
Append an entry to self
[ "Append", "an", "entry", "to", "self" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/entry.py#L87-L91
train
25,917
bootphon/h5features
h5features/writer.py
Writer.write
def write(self, data, groupname='h5features', append=False): """Write h5features data in a specified group of the file. :param dict data: A `h5features.Data` instance to be writed on disk. :param str groupname: Optional. The name of the group in which to write the data. :param bool append: Optional. This parameter has no effect if the `groupname` is not an existing group in the file. If set to True, try to append new data in the group. If False (default) erase all data in the group before writing. :raise IOError: if append requested but not possible. """ if append and groupname in self.h5file: # append data to the group, raise if we cannot group = self.h5file[groupname] if not is_same_version(self.version, group): raise IOError( 'data is not appendable to the group {}: ' 'versions are different'.format(group.name)) if not data.is_appendable_to(group): raise IOError( 'data is not appendable to the group {}' .format(group.name)) else: # overwrite any existing data in group group = self._prepare(data, groupname) data.write_to(group, append)
python
def write(self, data, groupname='h5features', append=False): """Write h5features data in a specified group of the file. :param dict data: A `h5features.Data` instance to be writed on disk. :param str groupname: Optional. The name of the group in which to write the data. :param bool append: Optional. This parameter has no effect if the `groupname` is not an existing group in the file. If set to True, try to append new data in the group. If False (default) erase all data in the group before writing. :raise IOError: if append requested but not possible. """ if append and groupname in self.h5file: # append data to the group, raise if we cannot group = self.h5file[groupname] if not is_same_version(self.version, group): raise IOError( 'data is not appendable to the group {}: ' 'versions are different'.format(group.name)) if not data.is_appendable_to(group): raise IOError( 'data is not appendable to the group {}' .format(group.name)) else: # overwrite any existing data in group group = self._prepare(data, groupname) data.write_to(group, append)
[ "def", "write", "(", "self", ",", "data", ",", "groupname", "=", "'h5features'", ",", "append", "=", "False", ")", ":", "if", "append", "and", "groupname", "in", "self", ".", "h5file", ":", "# append data to the group, raise if we cannot", "group", "=", "self"...
Write h5features data in a specified group of the file. :param dict data: A `h5features.Data` instance to be writed on disk. :param str groupname: Optional. The name of the group in which to write the data. :param bool append: Optional. This parameter has no effect if the `groupname` is not an existing group in the file. If set to True, try to append new data in the group. If False (default) erase all data in the group before writing. :raise IOError: if append requested but not possible.
[ "Write", "h5features", "data", "in", "a", "specified", "group", "of", "the", "file", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/writer.py#L123-L154
train
25,918
bootphon/h5features
h5features/writer.py
Writer._prepare
def _prepare(self, data, groupname): """Clear the group if existing and initialize empty datasets.""" if groupname in self.h5file: del self.h5file[groupname] group = self.h5file.create_group(groupname) group.attrs['version'] = self.version data.init_group( group, self.chunk_size, self.compression, self.compression_opts) return group
python
def _prepare(self, data, groupname): """Clear the group if existing and initialize empty datasets.""" if groupname in self.h5file: del self.h5file[groupname] group = self.h5file.create_group(groupname) group.attrs['version'] = self.version data.init_group( group, self.chunk_size, self.compression, self.compression_opts) return group
[ "def", "_prepare", "(", "self", ",", "data", ",", "groupname", ")", ":", "if", "groupname", "in", "self", ".", "h5file", ":", "del", "self", ".", "h5file", "[", "groupname", "]", "group", "=", "self", ".", "h5file", ".", "create_group", "(", "groupname...
Clear the group if existing and initialize empty datasets.
[ "Clear", "the", "group", "if", "existing", "and", "initialize", "empty", "datasets", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/writer.py#L156-L164
train
25,919
bootphon/h5features
h5features/items.py
read_items
def read_items(group, version='1.1', check=False): """Return an Items instance initialized from a h5features group.""" if version == '0.1': # parse unicode to strings return ''.join( [unichr(int(c)) for c in group['files'][...]] ).replace('/-', '/').split('/\\') elif version == '1.0': return Items(list(group['files'][...]), check) else: return Items(list(group['items'][...]), check)
python
def read_items(group, version='1.1', check=False): """Return an Items instance initialized from a h5features group.""" if version == '0.1': # parse unicode to strings return ''.join( [unichr(int(c)) for c in group['files'][...]] ).replace('/-', '/').split('/\\') elif version == '1.0': return Items(list(group['files'][...]), check) else: return Items(list(group['items'][...]), check)
[ "def", "read_items", "(", "group", ",", "version", "=", "'1.1'", ",", "check", "=", "False", ")", ":", "if", "version", "==", "'0.1'", ":", "# parse unicode to strings", "return", "''", ".", "join", "(", "[", "unichr", "(", "int", "(", "c", ")", ")", ...
Return an Items instance initialized from a h5features group.
[ "Return", "an", "Items", "instance", "initialized", "from", "a", "h5features", "group", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/items.py#L26-L36
train
25,920
bootphon/h5features
h5features/items.py
Items.write_to
def write_to(self, group): """Write stored items to the given HDF5 group. We assume that self.create() has been called. """ # The HDF5 group where to write data items_group = group[self.name] nitems = items_group.shape[0] items_group.resize((nitems + len(self.data),)) items_group[nitems:] = self.data
python
def write_to(self, group): """Write stored items to the given HDF5 group. We assume that self.create() has been called. """ # The HDF5 group where to write data items_group = group[self.name] nitems = items_group.shape[0] items_group.resize((nitems + len(self.data),)) items_group[nitems:] = self.data
[ "def", "write_to", "(", "self", ",", "group", ")", ":", "# The HDF5 group where to write data", "items_group", "=", "group", "[", "self", ".", "name", "]", "nitems", "=", "items_group", ".", "shape", "[", "0", "]", "items_group", ".", "resize", "(", "(", "...
Write stored items to the given HDF5 group. We assume that self.create() has been called.
[ "Write", "stored", "items", "to", "the", "given", "HDF5", "group", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/items.py#L68-L79
train
25,921
bootphon/h5features
h5features/items.py
Items._create_dataset
def _create_dataset( self, group, chunk_size, compression, compression_opts): """Create an empty dataset in a group.""" if chunk_size == 'auto': chunks = True else: # if dtype is a variable str, guess representative size is 20 bytes per_chunk = ( nb_per_chunk(20, 1, chunk_size) if self.dtype == np.dtype('O') else nb_per_chunk( np.dtype(self.dtype).itemsize, 1, chunk_size)) chunks = (per_chunk,) shape = (0,) maxshape = (None,) # raise if per_chunk >= 4 Gb, this is requested by h5py group.create_dataset( self.name, shape, dtype=self.dtype, chunks=chunks, maxshape=maxshape, compression=compression, compression_opts=compression_opts)
python
def _create_dataset( self, group, chunk_size, compression, compression_opts): """Create an empty dataset in a group.""" if chunk_size == 'auto': chunks = True else: # if dtype is a variable str, guess representative size is 20 bytes per_chunk = ( nb_per_chunk(20, 1, chunk_size) if self.dtype == np.dtype('O') else nb_per_chunk( np.dtype(self.dtype).itemsize, 1, chunk_size)) chunks = (per_chunk,) shape = (0,) maxshape = (None,) # raise if per_chunk >= 4 Gb, this is requested by h5py group.create_dataset( self.name, shape, dtype=self.dtype, chunks=chunks, maxshape=maxshape, compression=compression, compression_opts=compression_opts)
[ "def", "_create_dataset", "(", "self", ",", "group", ",", "chunk_size", ",", "compression", ",", "compression_opts", ")", ":", "if", "chunk_size", "==", "'auto'", ":", "chunks", "=", "True", "else", ":", "# if dtype is a variable str, guess representative size is 20 b...
Create an empty dataset in a group.
[ "Create", "an", "empty", "dataset", "in", "a", "group", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/items.py#L91-L111
train
25,922
bootphon/h5features
h5features/version.py
read_version
def read_version(group): """Return the h5features version of a given HDF5 `group`. Look for a 'version' attribute in the `group` and return its value. Return '0.1' if the version is not found. Raises an IOError if it is not supported. """ version = ('0.1' if 'version' not in group.attrs else group.attrs['version']) # decode from bytes to str if needed if isinstance(version, bytes): version = version.decode() if not is_supported_version(version): raise IOError('version {} is not supported'.format(version)) return version
python
def read_version(group): """Return the h5features version of a given HDF5 `group`. Look for a 'version' attribute in the `group` and return its value. Return '0.1' if the version is not found. Raises an IOError if it is not supported. """ version = ('0.1' if 'version' not in group.attrs else group.attrs['version']) # decode from bytes to str if needed if isinstance(version, bytes): version = version.decode() if not is_supported_version(version): raise IOError('version {} is not supported'.format(version)) return version
[ "def", "read_version", "(", "group", ")", ":", "version", "=", "(", "'0.1'", "if", "'version'", "not", "in", "group", ".", "attrs", "else", "group", ".", "attrs", "[", "'version'", "]", ")", "# decode from bytes to str if needed", "if", "isinstance", "(", "v...
Return the h5features version of a given HDF5 `group`. Look for a 'version' attribute in the `group` and return its value. Return '0.1' if the version is not found. Raises an IOError if it is not supported.
[ "Return", "the", "h5features", "version", "of", "a", "given", "HDF5", "group", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/version.py#L46-L64
train
25,923
bootphon/h5features
h5features/reader.py
Reader.read
def read(self, from_item=None, to_item=None, from_time=None, to_time=None): """Retrieve requested data coordinates from the h5features index. :param str from_item: Optional. Read the data starting from this item. (defaults to the first stored item) :param str to_item: Optional. Read the data until reaching the item. (defaults to from_item if it was specified and to the last stored item otherwise). :param float from_time: Optional. (defaults to the beginning time in from_item) The specified times are included in the output. :param float to_time: Optional. (defaults to the ending time in to_item) the specified times are included in the output. :return: An instance of h5features.Data read from the file. """ # handling default arguments if to_item is None: to_item = self.items.data[-1] if from_item is None else from_item if from_item is None: from_item = self.items.data[0] # index coordinates of from/to_item. TODO optimize because we # have 4 accesses to list.index() where 2 are enougth. if not self.items.is_valid_interval(from_item, to_item): raise IOError('cannot read items: not a valid interval') from_idx = self.items.data.index(from_item) to_idx = self.items.data.index(to_item) from_pos = self._get_item_position(from_idx) to_pos = self._get_item_position(to_idx) lower = self._get_from_time(from_time, from_pos) # upper included with +1 upper = self._get_to_time(to_time, to_pos) + 1 # Step 2: access actual data if self.dformat == 'sparse': raise NotImplementedError( 'Reading sparse features not implemented') else: features = (self.group['features'][:, lower:upper].T if self.version == '0.1' else self.group['features'][lower:upper, ...]) labels = self._labels_group[lower:upper] # If we read a single item if to_idx == from_idx: features = [features] labels = [labels] # Several items case: split them from the index else: item_ends = self._index[from_idx:to_idx] - from_pos[0] + 1 features = np.split(features, item_ends, axis=0) labels = np.split(labels, item_ends, axis=0) items = self.items.data[from_idx:to_idx + 1] if self.properties is None: properties = None else: properties = self.properties[from_idx:to_idx + 1] return Data( items, labels, features, properties=properties, check=False)
python
def read(self, from_item=None, to_item=None, from_time=None, to_time=None): """Retrieve requested data coordinates from the h5features index. :param str from_item: Optional. Read the data starting from this item. (defaults to the first stored item) :param str to_item: Optional. Read the data until reaching the item. (defaults to from_item if it was specified and to the last stored item otherwise). :param float from_time: Optional. (defaults to the beginning time in from_item) The specified times are included in the output. :param float to_time: Optional. (defaults to the ending time in to_item) the specified times are included in the output. :return: An instance of h5features.Data read from the file. """ # handling default arguments if to_item is None: to_item = self.items.data[-1] if from_item is None else from_item if from_item is None: from_item = self.items.data[0] # index coordinates of from/to_item. TODO optimize because we # have 4 accesses to list.index() where 2 are enougth. if not self.items.is_valid_interval(from_item, to_item): raise IOError('cannot read items: not a valid interval') from_idx = self.items.data.index(from_item) to_idx = self.items.data.index(to_item) from_pos = self._get_item_position(from_idx) to_pos = self._get_item_position(to_idx) lower = self._get_from_time(from_time, from_pos) # upper included with +1 upper = self._get_to_time(to_time, to_pos) + 1 # Step 2: access actual data if self.dformat == 'sparse': raise NotImplementedError( 'Reading sparse features not implemented') else: features = (self.group['features'][:, lower:upper].T if self.version == '0.1' else self.group['features'][lower:upper, ...]) labels = self._labels_group[lower:upper] # If we read a single item if to_idx == from_idx: features = [features] labels = [labels] # Several items case: split them from the index else: item_ends = self._index[from_idx:to_idx] - from_pos[0] + 1 features = np.split(features, item_ends, axis=0) labels = np.split(labels, item_ends, axis=0) items = self.items.data[from_idx:to_idx + 1] if self.properties is None: properties = None else: properties = self.properties[from_idx:to_idx + 1] return Data( items, labels, features, properties=properties, check=False)
[ "def", "read", "(", "self", ",", "from_item", "=", "None", ",", "to_item", "=", "None", ",", "from_time", "=", "None", ",", "to_time", "=", "None", ")", ":", "# handling default arguments", "if", "to_item", "is", "None", ":", "to_item", "=", "self", ".",...
Retrieve requested data coordinates from the h5features index. :param str from_item: Optional. Read the data starting from this item. (defaults to the first stored item) :param str to_item: Optional. Read the data until reaching the item. (defaults to from_item if it was specified and to the last stored item otherwise). :param float from_time: Optional. (defaults to the beginning time in from_item) The specified times are included in the output. :param float to_time: Optional. (defaults to the ending time in to_item) the specified times are included in the output. :return: An instance of h5features.Data read from the file.
[ "Retrieve", "requested", "data", "coordinates", "from", "the", "h5features", "index", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/reader.py#L102-L171
train
25,924
openai/pachi-py
pachi_py/pachi/tools/twogtp.py
GTP_game.writesgf
def writesgf(self, sgffilename): "Write the game to an SGF file after a game" size = self.size outfile = open(sgffilename, "w") if not outfile: print "Couldn't create " + sgffilename return black_name = self.blackplayer.get_program_name() white_name = self.whiteplayer.get_program_name() black_seed = self.blackplayer.get_random_seed() white_seed = self.whiteplayer.get_random_seed() handicap = self.handicap komi = self.komi result = self.resultw outfile.write("(;GM[1]FF[4]RU[Japanese]SZ[%s]HA[%s]KM[%s]RE[%s]\n" % (size, handicap, komi, result)) outfile.write("PW[%s (random seed %s)]PB[%s (random seed %s)]\n" % (white_name, white_seed, black_name, black_seed)) outfile.write(self.sgffilestart) if handicap > 1: outfile.write("AB"); for stone in self.handicap_stones: outfile.write("[%s]" %(coords_to_sgf(size, stone))) outfile.write("PL[W]\n") to_play = self.first_to_play for move in self.moves: sgfmove = coords_to_sgf(size, move) outfile.write(";%s[%s]\n" % (to_play, sgfmove)) if to_play == "B": to_play = "W" else: to_play = "B" outfile.write(")\n") outfile.close
python
def writesgf(self, sgffilename): "Write the game to an SGF file after a game" size = self.size outfile = open(sgffilename, "w") if not outfile: print "Couldn't create " + sgffilename return black_name = self.blackplayer.get_program_name() white_name = self.whiteplayer.get_program_name() black_seed = self.blackplayer.get_random_seed() white_seed = self.whiteplayer.get_random_seed() handicap = self.handicap komi = self.komi result = self.resultw outfile.write("(;GM[1]FF[4]RU[Japanese]SZ[%s]HA[%s]KM[%s]RE[%s]\n" % (size, handicap, komi, result)) outfile.write("PW[%s (random seed %s)]PB[%s (random seed %s)]\n" % (white_name, white_seed, black_name, black_seed)) outfile.write(self.sgffilestart) if handicap > 1: outfile.write("AB"); for stone in self.handicap_stones: outfile.write("[%s]" %(coords_to_sgf(size, stone))) outfile.write("PL[W]\n") to_play = self.first_to_play for move in self.moves: sgfmove = coords_to_sgf(size, move) outfile.write(";%s[%s]\n" % (to_play, sgfmove)) if to_play == "B": to_play = "W" else: to_play = "B" outfile.write(")\n") outfile.close
[ "def", "writesgf", "(", "self", ",", "sgffilename", ")", ":", "size", "=", "self", ".", "size", "outfile", "=", "open", "(", "sgffilename", ",", "\"w\"", ")", "if", "not", "outfile", ":", "print", "\"Couldn't create \"", "+", "sgffilename", "return", "blac...
Write the game to an SGF file after a game
[ "Write", "the", "game", "to", "an", "SGF", "file", "after", "a", "game" ]
65f29fdd28747d34f2c3001f4016913e4aaeb8fc
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/twogtp.py#L272-L310
train
25,925
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
_escapeText
def _escapeText(text): """ Adds backslash-escapes to property value characters that need them.""" output = "" index = 0 match = reCharsToEscape.search(text, index) while match: output = output + text[index:match.start()] + '\\' + text[match.start()] index = match.end() match = reCharsToEscape.search(text, index) output = output + text[index:] return output
python
def _escapeText(text): """ Adds backslash-escapes to property value characters that need them.""" output = "" index = 0 match = reCharsToEscape.search(text, index) while match: output = output + text[index:match.start()] + '\\' + text[match.start()] index = match.end() match = reCharsToEscape.search(text, index) output = output + text[index:] return output
[ "def", "_escapeText", "(", "text", ")", ":", "output", "=", "\"\"", "index", "=", "0", "match", "=", "reCharsToEscape", ".", "search", "(", "text", ",", "index", ")", "while", "match", ":", "output", "=", "output", "+", "text", "[", "index", ":", "ma...
Adds backslash-escapes to property value characters that need them.
[ "Adds", "backslash", "-", "escapes", "to", "property", "value", "characters", "that", "need", "them", "." ]
65f29fdd28747d34f2c3001f4016913e4aaeb8fc
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L579-L589
train
25,926
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
SGFParser.parse
def parse(self): """ Parses the SGF data stored in 'self.data', and returns a 'Collection'.""" c = Collection() while self.index < self.datalen: g = self.parseOneGame() if g: c.append(g) else: break return c
python
def parse(self): """ Parses the SGF data stored in 'self.data', and returns a 'Collection'.""" c = Collection() while self.index < self.datalen: g = self.parseOneGame() if g: c.append(g) else: break return c
[ "def", "parse", "(", "self", ")", ":", "c", "=", "Collection", "(", ")", "while", "self", ".", "index", "<", "self", ".", "datalen", ":", "g", "=", "self", ".", "parseOneGame", "(", ")", "if", "g", ":", "c", ".", "append", "(", "g", ")", "else"...
Parses the SGF data stored in 'self.data', and returns a 'Collection'.
[ "Parses", "the", "SGF", "data", "stored", "in", "self", ".", "data", "and", "returns", "a", "Collection", "." ]
65f29fdd28747d34f2c3001f4016913e4aaeb8fc
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L153-L162
train
25,927
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
SGFParser.parseOneGame
def parseOneGame(self): """ Parses one game from 'self.data'. Returns a 'GameTree' containing one game, or 'None' if the end of 'self.data' has been reached.""" if self.index < self.datalen: match = self.reGameTreeStart.match(self.data, self.index) if match: self.index = match.end() return self.parseGameTree() return None
python
def parseOneGame(self): """ Parses one game from 'self.data'. Returns a 'GameTree' containing one game, or 'None' if the end of 'self.data' has been reached.""" if self.index < self.datalen: match = self.reGameTreeStart.match(self.data, self.index) if match: self.index = match.end() return self.parseGameTree() return None
[ "def", "parseOneGame", "(", "self", ")", ":", "if", "self", ".", "index", "<", "self", ".", "datalen", ":", "match", "=", "self", ".", "reGameTreeStart", ".", "match", "(", "self", ".", "data", ",", "self", ".", "index", ")", "if", "match", ":", "s...
Parses one game from 'self.data'. Returns a 'GameTree' containing one game, or 'None' if the end of 'self.data' has been reached.
[ "Parses", "one", "game", "from", "self", ".", "data", ".", "Returns", "a", "GameTree", "containing", "one", "game", "or", "None", "if", "the", "end", "of", "self", ".", "data", "has", "been", "reached", "." ]
65f29fdd28747d34f2c3001f4016913e4aaeb8fc
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L164-L172
train
25,928
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
Cursor.reset
def reset(self): """ Set 'Cursor' to point to the start of the root 'GameTree', 'self.game'.""" self.gametree = self.game self.nodenum = 0 self.index = 0 self.stack = [] self.node = self.gametree[self.index] self._setChildren() self._setFlags()
python
def reset(self): """ Set 'Cursor' to point to the start of the root 'GameTree', 'self.game'.""" self.gametree = self.game self.nodenum = 0 self.index = 0 self.stack = [] self.node = self.gametree[self.index] self._setChildren() self._setFlags()
[ "def", "reset", "(", "self", ")", ":", "self", ".", "gametree", "=", "self", ".", "game", "self", ".", "nodenum", "=", "0", "self", ".", "index", "=", "0", "self", ".", "stack", "=", "[", "]", "self", ".", "node", "=", "self", ".", "gametree", ...
Set 'Cursor' to point to the start of the root 'GameTree', 'self.game'.
[ "Set", "Cursor", "to", "point", "to", "the", "start", "of", "the", "root", "GameTree", "self", ".", "game", "." ]
65f29fdd28747d34f2c3001f4016913e4aaeb8fc
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L511-L519
train
25,929
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
Cursor.previous
def previous(self): """ Moves the 'Cursor' to & returns the previous 'Node'. Raises 'GameTreeEndError' if the start of a branch is exceeded.""" if self.index - 1 >= 0: # more main line? self.index = self.index - 1 elif self.stack: # were we in a variation? self.gametree = self.stack.pop() self.index = len(self.gametree) - 1 else: raise GameTreeEndError self.node = self.gametree[self.index] self.nodenum = self.nodenum - 1 self._setChildren() self._setFlags() return self.node
python
def previous(self): """ Moves the 'Cursor' to & returns the previous 'Node'. Raises 'GameTreeEndError' if the start of a branch is exceeded.""" if self.index - 1 >= 0: # more main line? self.index = self.index - 1 elif self.stack: # were we in a variation? self.gametree = self.stack.pop() self.index = len(self.gametree) - 1 else: raise GameTreeEndError self.node = self.gametree[self.index] self.nodenum = self.nodenum - 1 self._setChildren() self._setFlags() return self.node
[ "def", "previous", "(", "self", ")", ":", "if", "self", ".", "index", "-", "1", ">=", "0", ":", "# more main line?", "self", ".", "index", "=", "self", ".", "index", "-", "1", "elif", "self", ".", "stack", ":", "# were we in a variation?", "self", ".",...
Moves the 'Cursor' to & returns the previous 'Node'. Raises 'GameTreeEndError' if the start of a branch is exceeded.
[ "Moves", "the", "Cursor", "to", "&", "returns", "the", "previous", "Node", ".", "Raises", "GameTreeEndError", "if", "the", "start", "of", "a", "branch", "is", "exceeded", "." ]
65f29fdd28747d34f2c3001f4016913e4aaeb8fc
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L548-L562
train
25,930
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
Cursor._setChildren
def _setChildren(self): """ Sets up 'self.children'.""" if self.index + 1 < len(self.gametree): self.children = [self.gametree[self.index+1]] else: self.children = map(lambda list: list[0], self.gametree.variations)
python
def _setChildren(self): """ Sets up 'self.children'.""" if self.index + 1 < len(self.gametree): self.children = [self.gametree[self.index+1]] else: self.children = map(lambda list: list[0], self.gametree.variations)
[ "def", "_setChildren", "(", "self", ")", ":", "if", "self", ".", "index", "+", "1", "<", "len", "(", "self", ".", "gametree", ")", ":", "self", ".", "children", "=", "[", "self", ".", "gametree", "[", "self", ".", "index", "+", "1", "]", "]", "...
Sets up 'self.children'.
[ "Sets", "up", "self", ".", "children", "." ]
65f29fdd28747d34f2c3001f4016913e4aaeb8fc
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L564-L569
train
25,931
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
Cursor._setFlags
def _setFlags(self): """ Sets up the flags 'self.atEnd' and 'self.atStart'.""" self.atEnd = not self.gametree.variations and (self.index + 1 == len(self.gametree)) self.atStart = not self.stack and (self.index == 0)
python
def _setFlags(self): """ Sets up the flags 'self.atEnd' and 'self.atStart'.""" self.atEnd = not self.gametree.variations and (self.index + 1 == len(self.gametree)) self.atStart = not self.stack and (self.index == 0)
[ "def", "_setFlags", "(", "self", ")", ":", "self", ".", "atEnd", "=", "not", "self", ".", "gametree", ".", "variations", "and", "(", "self", ".", "index", "+", "1", "==", "len", "(", "self", ".", "gametree", ")", ")", "self", ".", "atStart", "=", ...
Sets up the flags 'self.atEnd' and 'self.atStart'.
[ "Sets", "up", "the", "flags", "self", ".", "atEnd", "and", "self", ".", "atStart", "." ]
65f29fdd28747d34f2c3001f4016913e4aaeb8fc
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L571-L574
train
25,932
cjdrake/pyeda
pyeda/logic/addition.py
ripple_carry_add
def ripple_carry_add(A, B, cin=0): """Return symbolic logic for an N-bit ripple carry adder.""" if len(A) != len(B): raise ValueError("expected A and B to be equal length") ss, cs = list(), list() for i, a in enumerate(A): c = (cin if i == 0 else cs[i-1]) ss.append(a ^ B[i] ^ c) cs.append(a & B[i] | a & c | B[i] & c) return farray(ss), farray(cs)
python
def ripple_carry_add(A, B, cin=0): """Return symbolic logic for an N-bit ripple carry adder.""" if len(A) != len(B): raise ValueError("expected A and B to be equal length") ss, cs = list(), list() for i, a in enumerate(A): c = (cin if i == 0 else cs[i-1]) ss.append(a ^ B[i] ^ c) cs.append(a & B[i] | a & c | B[i] & c) return farray(ss), farray(cs)
[ "def", "ripple_carry_add", "(", "A", ",", "B", ",", "cin", "=", "0", ")", ":", "if", "len", "(", "A", ")", "!=", "len", "(", "B", ")", ":", "raise", "ValueError", "(", "\"expected A and B to be equal length\"", ")", "ss", ",", "cs", "=", "list", "(",...
Return symbolic logic for an N-bit ripple carry adder.
[ "Return", "symbolic", "logic", "for", "an", "N", "-", "bit", "ripple", "carry", "adder", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/addition.py#L21-L30
train
25,933
cjdrake/pyeda
pyeda/logic/addition.py
kogge_stone_add
def kogge_stone_add(A, B, cin=0): """Return symbolic logic for an N-bit Kogge-Stone adder.""" if len(A) != len(B): raise ValueError("expected A and B to be equal length") N = len(A) # generate/propagate logic gs = [A[i] & B[i] for i in range(N)] ps = [A[i] ^ B[i] for i in range(N)] for i in range(clog2(N)): start = 1 << i for j in range(start, N): gs[j] = gs[j] | ps[j] & gs[j-start] ps[j] = ps[j] & ps[j-start] # sum logic ss = [A[0] ^ B[0] ^ cin] ss += [A[i] ^ B[i] ^ gs[i-1] for i in range(1, N)] return farray(ss), farray(gs)
python
def kogge_stone_add(A, B, cin=0): """Return symbolic logic for an N-bit Kogge-Stone adder.""" if len(A) != len(B): raise ValueError("expected A and B to be equal length") N = len(A) # generate/propagate logic gs = [A[i] & B[i] for i in range(N)] ps = [A[i] ^ B[i] for i in range(N)] for i in range(clog2(N)): start = 1 << i for j in range(start, N): gs[j] = gs[j] | ps[j] & gs[j-start] ps[j] = ps[j] & ps[j-start] # sum logic ss = [A[0] ^ B[0] ^ cin] ss += [A[i] ^ B[i] ^ gs[i-1] for i in range(1, N)] return farray(ss), farray(gs)
[ "def", "kogge_stone_add", "(", "A", ",", "B", ",", "cin", "=", "0", ")", ":", "if", "len", "(", "A", ")", "!=", "len", "(", "B", ")", ":", "raise", "ValueError", "(", "\"expected A and B to be equal length\"", ")", "N", "=", "len", "(", "A", ")", "...
Return symbolic logic for an N-bit Kogge-Stone adder.
[ "Return", "symbolic", "logic", "for", "an", "N", "-", "bit", "Kogge", "-", "Stone", "adder", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/addition.py#L33-L49
train
25,934
cjdrake/pyeda
pyeda/logic/addition.py
brent_kung_add
def brent_kung_add(A, B, cin=0): """Return symbolic logic for an N-bit Brent-Kung adder.""" if len(A) != len(B): raise ValueError("expected A and B to be equal length") N = len(A) # generate/propagate logic gs = [A[i] & B[i] for i in range(N)] ps = [A[i] ^ B[i] for i in range(N)] # carry tree for i in range(floor(log(N, 2))): step = 2**i for start in range(2**(i+1)-1, N, 2**(i+1)): gs[start] = gs[start] | ps[start] & gs[start-step] ps[start] = ps[start] & ps[start-step] # inverse carry tree for i in range(floor(log(N, 2))-2, -1, -1): start = 2**(i+1)-1 step = 2**i while start + step < N: gs[start+step] = gs[start+step] | ps[start+step] & gs[start] ps[start+step] = ps[start+step] & ps[start] start += step # sum logic ss = [A[0] ^ B[0] ^ cin] ss += [A[i] ^ B[i] ^ gs[i-1] for i in range(1, N)] return farray(ss), farray(gs)
python
def brent_kung_add(A, B, cin=0): """Return symbolic logic for an N-bit Brent-Kung adder.""" if len(A) != len(B): raise ValueError("expected A and B to be equal length") N = len(A) # generate/propagate logic gs = [A[i] & B[i] for i in range(N)] ps = [A[i] ^ B[i] for i in range(N)] # carry tree for i in range(floor(log(N, 2))): step = 2**i for start in range(2**(i+1)-1, N, 2**(i+1)): gs[start] = gs[start] | ps[start] & gs[start-step] ps[start] = ps[start] & ps[start-step] # inverse carry tree for i in range(floor(log(N, 2))-2, -1, -1): start = 2**(i+1)-1 step = 2**i while start + step < N: gs[start+step] = gs[start+step] | ps[start+step] & gs[start] ps[start+step] = ps[start+step] & ps[start] start += step # sum logic ss = [A[0] ^ B[0] ^ cin] ss += [A[i] ^ B[i] ^ gs[i-1] for i in range(1, N)] return farray(ss), farray(gs)
[ "def", "brent_kung_add", "(", "A", ",", "B", ",", "cin", "=", "0", ")", ":", "if", "len", "(", "A", ")", "!=", "len", "(", "B", ")", ":", "raise", "ValueError", "(", "\"expected A and B to be equal length\"", ")", "N", "=", "len", "(", "A", ")", "#...
Return symbolic logic for an N-bit Brent-Kung adder.
[ "Return", "symbolic", "logic", "for", "an", "N", "-", "bit", "Brent", "-", "Kung", "adder", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/addition.py#L52-L77
train
25,935
cjdrake/pyeda
pyeda/parsing/dimacs.py
_expect_token
def _expect_token(lexer, types): """Return the next token, or raise an exception.""" tok = next(lexer) if any(isinstance(tok, t) for t in types): return tok else: raise Error("unexpected token: " + str(tok))
python
def _expect_token(lexer, types): """Return the next token, or raise an exception.""" tok = next(lexer) if any(isinstance(tok, t) for t in types): return tok else: raise Error("unexpected token: " + str(tok))
[ "def", "_expect_token", "(", "lexer", ",", "types", ")", ":", "tok", "=", "next", "(", "lexer", ")", "if", "any", "(", "isinstance", "(", "tok", ",", "t", ")", "for", "t", "in", "types", ")", ":", "return", "tok", "else", ":", "raise", "Error", "...
Return the next token, or raise an exception.
[ "Return", "the", "next", "token", "or", "raise", "an", "exception", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L134-L140
train
25,936
cjdrake/pyeda
pyeda/parsing/dimacs.py
parse_cnf
def parse_cnf(s, varname='x'): """ Parse an input string in DIMACS CNF format, and return an expression abstract syntax tree. Parameters ---------- s : str String containing a DIMACS CNF. varname : str, optional The variable name used for creating literals. Defaults to 'x'. Returns ------- An ast tuple, defined recursively: ast := ('var', names, indices) | ('not', ast) | ('or', ast, ...) | ('and', ast, ...) names := (name, ...) indices := (index, ...) """ lexer = iter(CNFLexer(s)) try: ast = _cnf(lexer, varname) 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 ast
python
def parse_cnf(s, varname='x'): """ Parse an input string in DIMACS CNF format, and return an expression abstract syntax tree. Parameters ---------- s : str String containing a DIMACS CNF. varname : str, optional The variable name used for creating literals. Defaults to 'x'. Returns ------- An ast tuple, defined recursively: ast := ('var', names, indices) | ('not', ast) | ('or', ast, ...) | ('and', ast, ...) names := (name, ...) indices := (index, ...) """ lexer = iter(CNFLexer(s)) try: ast = _cnf(lexer, varname) 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 ast
[ "def", "parse_cnf", "(", "s", ",", "varname", "=", "'x'", ")", ":", "lexer", "=", "iter", "(", "CNFLexer", "(", "s", ")", ")", "try", ":", "ast", "=", "_cnf", "(", "lexer", ",", "varname", ")", "except", "lex", ".", "RunError", "as", "exc", ":", ...
Parse an input string in DIMACS CNF format, and return an expression abstract syntax tree. Parameters ---------- s : str String containing a DIMACS CNF. varname : str, optional The variable name used for creating literals. Defaults to 'x'. Returns ------- An ast tuple, defined recursively: ast := ('var', names, indices) | ('not', ast) | ('or', ast, ...) | ('and', ast, ...) names := (name, ...) indices := (index, ...)
[ "Parse", "an", "input", "string", "in", "DIMACS", "CNF", "format", "and", "return", "an", "expression", "abstract", "syntax", "tree", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L143-L181
train
25,937
cjdrake/pyeda
pyeda/parsing/dimacs.py
_cnf
def _cnf(lexer, varname): """Return a DIMACS CNF.""" _expect_token(lexer, {KW_p}) _expect_token(lexer, {KW_cnf}) nvars = _expect_token(lexer, {IntegerToken}).value nclauses = _expect_token(lexer, {IntegerToken}).value return _cnf_formula(lexer, varname, nvars, nclauses)
python
def _cnf(lexer, varname): """Return a DIMACS CNF.""" _expect_token(lexer, {KW_p}) _expect_token(lexer, {KW_cnf}) nvars = _expect_token(lexer, {IntegerToken}).value nclauses = _expect_token(lexer, {IntegerToken}).value return _cnf_formula(lexer, varname, nvars, nclauses)
[ "def", "_cnf", "(", "lexer", ",", "varname", ")", ":", "_expect_token", "(", "lexer", ",", "{", "KW_p", "}", ")", "_expect_token", "(", "lexer", ",", "{", "KW_cnf", "}", ")", "nvars", "=", "_expect_token", "(", "lexer", ",", "{", "IntegerToken", "}", ...
Return a DIMACS CNF.
[ "Return", "a", "DIMACS", "CNF", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L184-L190
train
25,938
cjdrake/pyeda
pyeda/parsing/dimacs.py
_cnf_formula
def _cnf_formula(lexer, varname, nvars, nclauses): """Return a DIMACS CNF formula.""" clauses = _clauses(lexer, varname, nvars) if len(clauses) < nclauses: fstr = "formula has fewer than {} clauses" raise Error(fstr.format(nclauses)) if len(clauses) > nclauses: fstr = "formula has more than {} clauses" raise Error(fstr.format(nclauses)) return ('and', ) + clauses
python
def _cnf_formula(lexer, varname, nvars, nclauses): """Return a DIMACS CNF formula.""" clauses = _clauses(lexer, varname, nvars) if len(clauses) < nclauses: fstr = "formula has fewer than {} clauses" raise Error(fstr.format(nclauses)) if len(clauses) > nclauses: fstr = "formula has more than {} clauses" raise Error(fstr.format(nclauses)) return ('and', ) + clauses
[ "def", "_cnf_formula", "(", "lexer", ",", "varname", ",", "nvars", ",", "nclauses", ")", ":", "clauses", "=", "_clauses", "(", "lexer", ",", "varname", ",", "nvars", ")", "if", "len", "(", "clauses", ")", "<", "nclauses", ":", "fstr", "=", "\"formula h...
Return a DIMACS CNF formula.
[ "Return", "a", "DIMACS", "CNF", "formula", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L193-L204
train
25,939
cjdrake/pyeda
pyeda/parsing/dimacs.py
_clauses
def _clauses(lexer, varname, nvars): """Return a tuple of DIMACS CNF clauses.""" tok = next(lexer) toktype = type(tok) if toktype is OP_not or toktype is IntegerToken: lexer.unpop_token(tok) first = _clause(lexer, varname, nvars) rest = _clauses(lexer, varname, nvars) return (first, ) + rest # null else: lexer.unpop_token(tok) return tuple()
python
def _clauses(lexer, varname, nvars): """Return a tuple of DIMACS CNF clauses.""" tok = next(lexer) toktype = type(tok) if toktype is OP_not or toktype is IntegerToken: lexer.unpop_token(tok) first = _clause(lexer, varname, nvars) rest = _clauses(lexer, varname, nvars) return (first, ) + rest # null else: lexer.unpop_token(tok) return tuple()
[ "def", "_clauses", "(", "lexer", ",", "varname", ",", "nvars", ")", ":", "tok", "=", "next", "(", "lexer", ")", "toktype", "=", "type", "(", "tok", ")", "if", "toktype", "is", "OP_not", "or", "toktype", "is", "IntegerToken", ":", "lexer", ".", "unpop...
Return a tuple of DIMACS CNF clauses.
[ "Return", "a", "tuple", "of", "DIMACS", "CNF", "clauses", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L207-L219
train
25,940
cjdrake/pyeda
pyeda/parsing/dimacs.py
_lits
def _lits(lexer, varname, nvars): """Return a tuple of DIMACS CNF clause literals.""" tok = _expect_token(lexer, {OP_not, IntegerToken}) if isinstance(tok, IntegerToken) and tok.value == 0: return tuple() else: if isinstance(tok, OP_not): neg = True tok = _expect_token(lexer, {IntegerToken}) else: neg = False index = tok.value if index > nvars: fstr = "formula literal {} is greater than {}" raise Error(fstr.format(index, nvars)) lit = ('var', (varname, ), (index, )) if neg: lit = ('not', lit) return (lit, ) + _lits(lexer, varname, nvars)
python
def _lits(lexer, varname, nvars): """Return a tuple of DIMACS CNF clause literals.""" tok = _expect_token(lexer, {OP_not, IntegerToken}) if isinstance(tok, IntegerToken) and tok.value == 0: return tuple() else: if isinstance(tok, OP_not): neg = True tok = _expect_token(lexer, {IntegerToken}) else: neg = False index = tok.value if index > nvars: fstr = "formula literal {} is greater than {}" raise Error(fstr.format(index, nvars)) lit = ('var', (varname, ), (index, )) if neg: lit = ('not', lit) return (lit, ) + _lits(lexer, varname, nvars)
[ "def", "_lits", "(", "lexer", ",", "varname", ",", "nvars", ")", ":", "tok", "=", "_expect_token", "(", "lexer", ",", "{", "OP_not", ",", "IntegerToken", "}", ")", "if", "isinstance", "(", "tok", ",", "IntegerToken", ")", "and", "tok", ".", "value", ...
Return a tuple of DIMACS CNF clause literals.
[ "Return", "a", "tuple", "of", "DIMACS", "CNF", "clause", "literals", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L227-L248
train
25,941
cjdrake/pyeda
pyeda/parsing/dimacs.py
parse_sat
def parse_sat(s, varname='x'): """ Parse an input string in DIMACS SAT format, and return an expression. """ lexer = iter(SATLexer(s)) try: ast = _sat(lexer, varname) 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 ast
python
def parse_sat(s, varname='x'): """ Parse an input string in DIMACS SAT format, and return an expression. """ lexer = iter(SATLexer(s)) try: ast = _sat(lexer, varname) 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 ast
[ "def", "parse_sat", "(", "s", ",", "varname", "=", "'x'", ")", ":", "lexer", "=", "iter", "(", "SATLexer", "(", "s", ")", ")", "try", ":", "ast", "=", "_sat", "(", "lexer", ",", "varname", ")", "except", "lex", ".", "RunError", "as", "exc", ":", ...
Parse an input string in DIMACS SAT format, and return an expression.
[ "Parse", "an", "input", "string", "in", "DIMACS", "SAT", "format", "and", "return", "an", "expression", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L357-L374
train
25,942
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): """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)
[ "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
train
25,943
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): """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
[ "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
train
25,944
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): """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()
[ "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
train
25,945
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): """Push a keyword onto the token queue.""" 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
train
25,946
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): """Push an operator onto the token queue.""" 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
train
25,947
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): """Push punctuation onto the token queue.""" 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
train
25,948
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): """ 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
[ "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
train
25,949
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): """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
[ "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
train
25,950
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): """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)
[ "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
train
25,951
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): """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)
[ "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
train
25,952
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: """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
[ "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
train
25,953
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): """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)
[ "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
train
25,954
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): """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
[ "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
train
25,955
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
train
25,956
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
train
25,957
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
train
25,958
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
train
25,959
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): """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
[ "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
train
25,960
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): """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)
[ "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
train
25,961
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): """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]
[ "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
train
25,962
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): """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)
[ "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
train
25,963
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): """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"
[ "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
train
25,964
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): """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
[ "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
train
25,965
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): """Convert an expression into a truth table.""" 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
train
25,966
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): """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])
[ "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
train
25,967
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): """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)
[ "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
train
25,968
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): """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
[ "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
train
25,969
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): """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
[ "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
train
25,970
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): """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
[ "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
train
25,971
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): """ 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
[ "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
train
25,972
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
train
25,973
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): """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))
[ "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
train
25,974
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
train
25,975
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): """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)
[ "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
train
25,976
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): """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])
[ "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
train
25,977
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): """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
[ "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
train
25,978
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): """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
[ "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
train
25,979
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): """Return a unique BDD.""" 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
train
25,980
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): """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])}
[ "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
train
25,981
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()): """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
[ "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
train
25,982
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()): """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)
[ "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
train
25,983
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): """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)
[ "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
train
25,984
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): """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
[ "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
train
25,985
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): """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
[ "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
train
25,986
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): """ 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
[ "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
train
25,987
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): """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
[ "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
train
25,988
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): """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
[ "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
train
25,989
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): """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)
[ "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
train
25,990
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): """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
[ "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
train
25,991
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): """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)
[ "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
train
25,992
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): """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
[ "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
train
25,993
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): """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)
[ "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
train
25,994
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): """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
[ "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
train
25,995
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): """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)
[ "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
train
25,996
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): """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()
[ "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
train
25,997
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): """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)
[ "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
train
25,998
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): """Return a tuple of names.""" 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
train
25,999