id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
17,200
pysathq/pysat
pysat/solvers.py
Solver.add_clause
def add_clause(self, clause, no_return=True): """ This method is used to add a single clause to the solver. An optional argument ``no_return`` controls whether or not to check the formula's satisfiability after adding the new clause. :param clause: an iterable over literals. :param no_return: check solver's internal formula and return the result, if set to ``False``. :type clause: iterable(int) :type no_return: bool :rtype: bool if ``no_return`` is set to ``False``. Note that a clause can be either a ``list`` of integers or another iterable type over integers, e.g. ``tuple`` or ``set`` among others. A usage example is the following: .. code-block:: python >>> s = Solver(bootstrap_with=[[-1, 2], [-1, -2]]) >>> s.add_clause([1], no_return=False) False """ if self.solver: res = self.solver.add_clause(clause, no_return) if not no_return: return res
python
def add_clause(self, clause, no_return=True): """ This method is used to add a single clause to the solver. An optional argument ``no_return`` controls whether or not to check the formula's satisfiability after adding the new clause. :param clause: an iterable over literals. :param no_return: check solver's internal formula and return the result, if set to ``False``. :type clause: iterable(int) :type no_return: bool :rtype: bool if ``no_return`` is set to ``False``. Note that a clause can be either a ``list`` of integers or another iterable type over integers, e.g. ``tuple`` or ``set`` among others. A usage example is the following: .. code-block:: python >>> s = Solver(bootstrap_with=[[-1, 2], [-1, -2]]) >>> s.add_clause([1], no_return=False) False """ if self.solver: res = self.solver.add_clause(clause, no_return) if not no_return: return res
[ "def", "add_clause", "(", "self", ",", "clause", ",", "no_return", "=", "True", ")", ":", "if", "self", ".", "solver", ":", "res", "=", "self", ".", "solver", ".", "add_clause", "(", "clause", ",", "no_return", ")", "if", "not", "no_return", ":", "return", "res" ]
This method is used to add a single clause to the solver. An optional argument ``no_return`` controls whether or not to check the formula's satisfiability after adding the new clause. :param clause: an iterable over literals. :param no_return: check solver's internal formula and return the result, if set to ``False``. :type clause: iterable(int) :type no_return: bool :rtype: bool if ``no_return`` is set to ``False``. Note that a clause can be either a ``list`` of integers or another iterable type over integers, e.g. ``tuple`` or ``set`` among others. A usage example is the following: .. code-block:: python >>> s = Solver(bootstrap_with=[[-1, 2], [-1, -2]]) >>> s.add_clause([1], no_return=False) False
[ "This", "method", "is", "used", "to", "add", "a", "single", "clause", "to", "the", "solver", ".", "An", "optional", "argument", "no_return", "controls", "whether", "or", "not", "to", "check", "the", "formula", "s", "satisfiability", "after", "adding", "the", "new", "clause", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L825-L856
17,201
pysathq/pysat
pysat/solvers.py
Solver.append_formula
def append_formula(self, formula, no_return=True): """ This method can be used to add a given list of clauses into the solver. :param formula: a list of clauses. :param no_return: check solver's internal formula and return the result, if set to ``False``. :type formula: iterable(iterable(int)) :type no_return: bool The ``no_return`` argument is set to ``True`` by default. :rtype: bool if ``no_return`` is set to ``False``. .. code-block:: python >>> cnf = CNF() ... # assume the formula contains clauses >>> s = Solver() >>> s.append_formula(cnf.clauses, no_return=False) True """ if self.solver: res = self.solver.append_formula(formula, no_return) if not no_return: return res
python
def append_formula(self, formula, no_return=True): """ This method can be used to add a given list of clauses into the solver. :param formula: a list of clauses. :param no_return: check solver's internal formula and return the result, if set to ``False``. :type formula: iterable(iterable(int)) :type no_return: bool The ``no_return`` argument is set to ``True`` by default. :rtype: bool if ``no_return`` is set to ``False``. .. code-block:: python >>> cnf = CNF() ... # assume the formula contains clauses >>> s = Solver() >>> s.append_formula(cnf.clauses, no_return=False) True """ if self.solver: res = self.solver.append_formula(formula, no_return) if not no_return: return res
[ "def", "append_formula", "(", "self", ",", "formula", ",", "no_return", "=", "True", ")", ":", "if", "self", ".", "solver", ":", "res", "=", "self", ".", "solver", ".", "append_formula", "(", "formula", ",", "no_return", ")", "if", "not", "no_return", ":", "return", "res" ]
This method can be used to add a given list of clauses into the solver. :param formula: a list of clauses. :param no_return: check solver's internal formula and return the result, if set to ``False``. :type formula: iterable(iterable(int)) :type no_return: bool The ``no_return`` argument is set to ``True`` by default. :rtype: bool if ``no_return`` is set to ``False``. .. code-block:: python >>> cnf = CNF() ... # assume the formula contains clauses >>> s = Solver() >>> s.append_formula(cnf.clauses, no_return=False) True
[ "This", "method", "can", "be", "used", "to", "add", "a", "given", "list", "of", "clauses", "into", "the", "solver", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L896-L924
17,202
pysathq/pysat
pysat/solvers.py
Glucose4.enum_models
def enum_models(self, assumptions=[]): """ Iterate over models of the internal formula. """ if self.glucose: done = False while not done: if self.use_timer: start_time = time.clock() self.status = pysolvers.glucose41_solve(self.glucose, assumptions) if self.use_timer: self.call_time = time.clock() - start_time self.accu_time += self.call_time model = self.get_model() if model: self.add_clause([-l for l in model]) # blocking model yield model else: done = True
python
def enum_models(self, assumptions=[]): """ Iterate over models of the internal formula. """ if self.glucose: done = False while not done: if self.use_timer: start_time = time.clock() self.status = pysolvers.glucose41_solve(self.glucose, assumptions) if self.use_timer: self.call_time = time.clock() - start_time self.accu_time += self.call_time model = self.get_model() if model: self.add_clause([-l for l in model]) # blocking model yield model else: done = True
[ "def", "enum_models", "(", "self", ",", "assumptions", "=", "[", "]", ")", ":", "if", "self", ".", "glucose", ":", "done", "=", "False", "while", "not", "done", ":", "if", "self", ".", "use_timer", ":", "start_time", "=", "time", ".", "clock", "(", ")", "self", ".", "status", "=", "pysolvers", ".", "glucose41_solve", "(", "self", ".", "glucose", ",", "assumptions", ")", "if", "self", ".", "use_timer", ":", "self", ".", "call_time", "=", "time", ".", "clock", "(", ")", "-", "start_time", "self", ".", "accu_time", "+=", "self", ".", "call_time", "model", "=", "self", ".", "get_model", "(", ")", "if", "model", ":", "self", ".", "add_clause", "(", "[", "-", "l", "for", "l", "in", "model", "]", ")", "# blocking model", "yield", "model", "else", ":", "done", "=", "True" ]
Iterate over models of the internal formula.
[ "Iterate", "over", "models", "of", "the", "internal", "formula", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L1453-L1476
17,203
pysathq/pysat
pysat/solvers.py
MapleChrono.propagate
def propagate(self, assumptions=[], phase_saving=0): """ Propagate a given set of assumption literals. """ if self.maplesat: if self.use_timer: start_time = time.clock() # saving default SIGINT handler def_sigint_handler = signal.signal(signal.SIGINT, signal.SIG_DFL) st, props = pysolvers.maplechrono_propagate(self.maplesat, assumptions, phase_saving) # recovering default SIGINT handler def_sigint_handler = signal.signal(signal.SIGINT, def_sigint_handler) if self.use_timer: self.call_time = time.clock() - start_time self.accu_time += self.call_time return bool(st), props if props != None else []
python
def propagate(self, assumptions=[], phase_saving=0): """ Propagate a given set of assumption literals. """ if self.maplesat: if self.use_timer: start_time = time.clock() # saving default SIGINT handler def_sigint_handler = signal.signal(signal.SIGINT, signal.SIG_DFL) st, props = pysolvers.maplechrono_propagate(self.maplesat, assumptions, phase_saving) # recovering default SIGINT handler def_sigint_handler = signal.signal(signal.SIGINT, def_sigint_handler) if self.use_timer: self.call_time = time.clock() - start_time self.accu_time += self.call_time return bool(st), props if props != None else []
[ "def", "propagate", "(", "self", ",", "assumptions", "=", "[", "]", ",", "phase_saving", "=", "0", ")", ":", "if", "self", ".", "maplesat", ":", "if", "self", ".", "use_timer", ":", "start_time", "=", "time", ".", "clock", "(", ")", "# saving default SIGINT handler", "def_sigint_handler", "=", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "signal", ".", "SIG_DFL", ")", "st", ",", "props", "=", "pysolvers", ".", "maplechrono_propagate", "(", "self", ".", "maplesat", ",", "assumptions", ",", "phase_saving", ")", "# recovering default SIGINT handler", "def_sigint_handler", "=", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "def_sigint_handler", ")", "if", "self", ".", "use_timer", ":", "self", ".", "call_time", "=", "time", ".", "clock", "(", ")", "-", "start_time", "self", ".", "accu_time", "+=", "self", ".", "call_time", "return", "bool", "(", "st", ")", ",", "props", "if", "props", "!=", "None", "else", "[", "]" ]
Propagate a given set of assumption literals.
[ "Propagate", "a", "given", "set", "of", "assumption", "literals", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L1892-L1913
17,204
pysathq/pysat
pysat/solvers.py
MapleChrono.get_proof
def get_proof(self): """ Get a proof produced while deciding the formula. """ if self.maplesat and self.prfile: self.prfile.seek(0) return [line.rstrip() for line in self.prfile.readlines()]
python
def get_proof(self): """ Get a proof produced while deciding the formula. """ if self.maplesat and self.prfile: self.prfile.seek(0) return [line.rstrip() for line in self.prfile.readlines()]
[ "def", "get_proof", "(", "self", ")", ":", "if", "self", ".", "maplesat", "and", "self", ".", "prfile", ":", "self", ".", "prfile", ".", "seek", "(", "0", ")", "return", "[", "line", ".", "rstrip", "(", ")", "for", "line", "in", "self", ".", "prfile", ".", "readlines", "(", ")", "]" ]
Get a proof produced while deciding the formula.
[ "Get", "a", "proof", "produced", "while", "deciding", "the", "formula", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L1949-L1956
17,205
pysathq/pysat
pysat/solvers.py
Minicard.add_atmost
def add_atmost(self, lits, k, no_return=True): """ Add a new atmost constraint to solver's internal formula. """ if self.minicard: res = pysolvers.minicard_add_am(self.minicard, lits, k) if res == False: self.status = False if not no_return: return res
python
def add_atmost(self, lits, k, no_return=True): """ Add a new atmost constraint to solver's internal formula. """ if self.minicard: res = pysolvers.minicard_add_am(self.minicard, lits, k) if res == False: self.status = False if not no_return: return res
[ "def", "add_atmost", "(", "self", ",", "lits", ",", "k", ",", "no_return", "=", "True", ")", ":", "if", "self", ".", "minicard", ":", "res", "=", "pysolvers", ".", "minicard_add_am", "(", "self", ".", "minicard", ",", "lits", ",", "k", ")", "if", "res", "==", "False", ":", "self", ".", "status", "=", "False", "if", "not", "no_return", ":", "return", "res" ]
Add a new atmost constraint to solver's internal formula.
[ "Add", "a", "new", "atmost", "constraint", "to", "solver", "s", "internal", "formula", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L2885-L2897
17,206
pysathq/pysat
pysat/formula.py
IDPool.id
def id(self, obj): """ The method is to be used to assign an integer variable ID for a given new object. If the object already has an ID, no new ID is created and the old one is returned instead. An object can be anything. In some cases it is convenient to use string variable names. :param obj: an object to assign an ID to. :rtype: int. Example: .. code-block:: python >>> from pysat.formula import IDPool >>> vpool = IDPool(occupied=[[12, 18], [3, 10]]) >>> >>> # creating 5 unique variables for the following strings >>> for i in range(5): ... print vpool.id('v{0}'.format(i + 1)) 1 2 11 19 20 In some cases, it makes sense to create an external function for accessing IDPool, e.g.: .. code-block:: python >>> # continuing the previous example >>> var = lambda i: vpool.id('var{0}'.format(i)) >>> var(5) 20 >>> var('hello_world!') 21 """ vid = self.obj2id[obj] if vid not in self.id2obj: self.id2obj[vid] = obj return vid
python
def id(self, obj): """ The method is to be used to assign an integer variable ID for a given new object. If the object already has an ID, no new ID is created and the old one is returned instead. An object can be anything. In some cases it is convenient to use string variable names. :param obj: an object to assign an ID to. :rtype: int. Example: .. code-block:: python >>> from pysat.formula import IDPool >>> vpool = IDPool(occupied=[[12, 18], [3, 10]]) >>> >>> # creating 5 unique variables for the following strings >>> for i in range(5): ... print vpool.id('v{0}'.format(i + 1)) 1 2 11 19 20 In some cases, it makes sense to create an external function for accessing IDPool, e.g.: .. code-block:: python >>> # continuing the previous example >>> var = lambda i: vpool.id('var{0}'.format(i)) >>> var(5) 20 >>> var('hello_world!') 21 """ vid = self.obj2id[obj] if vid not in self.id2obj: self.id2obj[vid] = obj return vid
[ "def", "id", "(", "self", ",", "obj", ")", ":", "vid", "=", "self", ".", "obj2id", "[", "obj", "]", "if", "vid", "not", "in", "self", ".", "id2obj", ":", "self", ".", "id2obj", "[", "vid", "]", "=", "obj", "return", "vid" ]
The method is to be used to assign an integer variable ID for a given new object. If the object already has an ID, no new ID is created and the old one is returned instead. An object can be anything. In some cases it is convenient to use string variable names. :param obj: an object to assign an ID to. :rtype: int. Example: .. code-block:: python >>> from pysat.formula import IDPool >>> vpool = IDPool(occupied=[[12, 18], [3, 10]]) >>> >>> # creating 5 unique variables for the following strings >>> for i in range(5): ... print vpool.id('v{0}'.format(i + 1)) 1 2 11 19 20 In some cases, it makes sense to create an external function for accessing IDPool, e.g.: .. code-block:: python >>> # continuing the previous example >>> var = lambda i: vpool.id('var{0}'.format(i)) >>> var(5) 20 >>> var('hello_world!') 21
[ "The", "method", "is", "to", "be", "used", "to", "assign", "an", "integer", "variable", "ID", "for", "a", "given", "new", "object", ".", "If", "the", "object", "already", "has", "an", "ID", "no", "new", "ID", "is", "created", "and", "the", "old", "one", "is", "returned", "instead", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L264-L311
17,207
pysathq/pysat
pysat/formula.py
IDPool._next
def _next(self): """ Get next variable ID. Skip occupied intervals if any. """ self.top += 1 while self._occupied and self.top >= self._occupied[0][0]: if self.top <= self._occupied[0][1]: self.top = self._occupied[0][1] + 1 self._occupied.pop(0) return self.top
python
def _next(self): """ Get next variable ID. Skip occupied intervals if any. """ self.top += 1 while self._occupied and self.top >= self._occupied[0][0]: if self.top <= self._occupied[0][1]: self.top = self._occupied[0][1] + 1 self._occupied.pop(0) return self.top
[ "def", "_next", "(", "self", ")", ":", "self", ".", "top", "+=", "1", "while", "self", ".", "_occupied", "and", "self", ".", "top", ">=", "self", ".", "_occupied", "[", "0", "]", "[", "0", "]", ":", "if", "self", ".", "top", "<=", "self", ".", "_occupied", "[", "0", "]", "[", "1", "]", ":", "self", ".", "top", "=", "self", ".", "_occupied", "[", "0", "]", "[", "1", "]", "+", "1", "self", ".", "_occupied", ".", "pop", "(", "0", ")", "return", "self", ".", "top" ]
Get next variable ID. Skip occupied intervals if any.
[ "Get", "next", "variable", "ID", ".", "Skip", "occupied", "intervals", "if", "any", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L351-L364
17,208
pysathq/pysat
pysat/formula.py
CNF.from_file
def from_file(self, fname, comment_lead=['c'], compressed_with='use_ext'): """ Read a CNF formula from a file in the DIMACS format. A file name is expected as an argument. A default argument is ``comment_lead`` for parsing comment lines. A given file can be compressed by either gzip, bzip2, or lzma. :param fname: name of a file to parse. :param comment_lead: a list of characters leading comment lines :param compressed_with: file compression algorithm :type fname: str :type comment_lead: list(str) :type compressed_with: str Note that the ``compressed_with`` parameter can be ``None`` (i.e. the file is uncompressed), ``'gzip'``, ``'bzip2'``, ``'lzma'``, or ``'use_ext'``. The latter value indicates that compression type should be automatically determined based on the file extension. Using ``'lzma'`` in Python 2 requires the ``backports.lzma`` package to be additionally installed. Usage example: .. code-block:: python >>> from pysat.formula import CNF >>> cnf1 = CNF() >>> cnf1.from_file('some-file.cnf.gz', compressed_with='gzip') >>> >>> cnf2 = CNF(from_file='another-file.cnf') """ with FileObject(fname, mode='r', compression=compressed_with) as fobj: self.from_fp(fobj.fp, comment_lead)
python
def from_file(self, fname, comment_lead=['c'], compressed_with='use_ext'): """ Read a CNF formula from a file in the DIMACS format. A file name is expected as an argument. A default argument is ``comment_lead`` for parsing comment lines. A given file can be compressed by either gzip, bzip2, or lzma. :param fname: name of a file to parse. :param comment_lead: a list of characters leading comment lines :param compressed_with: file compression algorithm :type fname: str :type comment_lead: list(str) :type compressed_with: str Note that the ``compressed_with`` parameter can be ``None`` (i.e. the file is uncompressed), ``'gzip'``, ``'bzip2'``, ``'lzma'``, or ``'use_ext'``. The latter value indicates that compression type should be automatically determined based on the file extension. Using ``'lzma'`` in Python 2 requires the ``backports.lzma`` package to be additionally installed. Usage example: .. code-block:: python >>> from pysat.formula import CNF >>> cnf1 = CNF() >>> cnf1.from_file('some-file.cnf.gz', compressed_with='gzip') >>> >>> cnf2 = CNF(from_file='another-file.cnf') """ with FileObject(fname, mode='r', compression=compressed_with) as fobj: self.from_fp(fobj.fp, comment_lead)
[ "def", "from_file", "(", "self", ",", "fname", ",", "comment_lead", "=", "[", "'c'", "]", ",", "compressed_with", "=", "'use_ext'", ")", ":", "with", "FileObject", "(", "fname", ",", "mode", "=", "'r'", ",", "compression", "=", "compressed_with", ")", "as", "fobj", ":", "self", ".", "from_fp", "(", "fobj", ".", "fp", ",", "comment_lead", ")" ]
Read a CNF formula from a file in the DIMACS format. A file name is expected as an argument. A default argument is ``comment_lead`` for parsing comment lines. A given file can be compressed by either gzip, bzip2, or lzma. :param fname: name of a file to parse. :param comment_lead: a list of characters leading comment lines :param compressed_with: file compression algorithm :type fname: str :type comment_lead: list(str) :type compressed_with: str Note that the ``compressed_with`` parameter can be ``None`` (i.e. the file is uncompressed), ``'gzip'``, ``'bzip2'``, ``'lzma'``, or ``'use_ext'``. The latter value indicates that compression type should be automatically determined based on the file extension. Using ``'lzma'`` in Python 2 requires the ``backports.lzma`` package to be additionally installed. Usage example: .. code-block:: python >>> from pysat.formula import CNF >>> cnf1 = CNF() >>> cnf1.from_file('some-file.cnf.gz', compressed_with='gzip') >>> >>> cnf2 = CNF(from_file='another-file.cnf')
[ "Read", "a", "CNF", "formula", "from", "a", "file", "in", "the", "DIMACS", "format", ".", "A", "file", "name", "is", "expected", "as", "an", "argument", ".", "A", "default", "argument", "is", "comment_lead", "for", "parsing", "comment", "lines", ".", "A", "given", "file", "can", "be", "compressed", "by", "either", "gzip", "bzip2", "or", "lzma", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L409-L443
17,209
pysathq/pysat
pysat/formula.py
CNF.from_fp
def from_fp(self, file_pointer, comment_lead=['c']): """ Read a CNF formula from a file pointer. A file pointer should be specified as an argument. The only default argument is ``comment_lead``, which can be used for parsing specific comment lines. :param file_pointer: a file pointer to read the formula from. :param comment_lead: a list of characters leading comment lines :type file_pointer: file pointer :type comment_lead: list(str) Usage example: .. code-block:: python >>> with open('some-file.cnf', 'r') as fp: ... cnf1 = CNF() ... cnf1.from_fp(fp) >>> >>> with open('another-file.cnf', 'r') as fp: ... cnf2 = CNF(from_fp=fp) """ self.nv = 0 self.clauses = [] self.comments = [] comment_lead = tuple('p') + tuple(comment_lead) for line in file_pointer: line = line.strip() if line: if line[0] not in comment_lead: cl = [int(l) for l in line.split()[:-1]] self.nv = max([abs(l) for l in cl] + [self.nv]) self.clauses.append(cl) elif not line.startswith('p cnf '): self.comments.append(line)
python
def from_fp(self, file_pointer, comment_lead=['c']): """ Read a CNF formula from a file pointer. A file pointer should be specified as an argument. The only default argument is ``comment_lead``, which can be used for parsing specific comment lines. :param file_pointer: a file pointer to read the formula from. :param comment_lead: a list of characters leading comment lines :type file_pointer: file pointer :type comment_lead: list(str) Usage example: .. code-block:: python >>> with open('some-file.cnf', 'r') as fp: ... cnf1 = CNF() ... cnf1.from_fp(fp) >>> >>> with open('another-file.cnf', 'r') as fp: ... cnf2 = CNF(from_fp=fp) """ self.nv = 0 self.clauses = [] self.comments = [] comment_lead = tuple('p') + tuple(comment_lead) for line in file_pointer: line = line.strip() if line: if line[0] not in comment_lead: cl = [int(l) for l in line.split()[:-1]] self.nv = max([abs(l) for l in cl] + [self.nv]) self.clauses.append(cl) elif not line.startswith('p cnf '): self.comments.append(line)
[ "def", "from_fp", "(", "self", ",", "file_pointer", ",", "comment_lead", "=", "[", "'c'", "]", ")", ":", "self", ".", "nv", "=", "0", "self", ".", "clauses", "=", "[", "]", "self", ".", "comments", "=", "[", "]", "comment_lead", "=", "tuple", "(", "'p'", ")", "+", "tuple", "(", "comment_lead", ")", "for", "line", "in", "file_pointer", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", ":", "if", "line", "[", "0", "]", "not", "in", "comment_lead", ":", "cl", "=", "[", "int", "(", "l", ")", "for", "l", "in", "line", ".", "split", "(", ")", "[", ":", "-", "1", "]", "]", "self", ".", "nv", "=", "max", "(", "[", "abs", "(", "l", ")", "for", "l", "in", "cl", "]", "+", "[", "self", ".", "nv", "]", ")", "self", ".", "clauses", ".", "append", "(", "cl", ")", "elif", "not", "line", ".", "startswith", "(", "'p cnf '", ")", ":", "self", ".", "comments", ".", "append", "(", "line", ")" ]
Read a CNF formula from a file pointer. A file pointer should be specified as an argument. The only default argument is ``comment_lead``, which can be used for parsing specific comment lines. :param file_pointer: a file pointer to read the formula from. :param comment_lead: a list of characters leading comment lines :type file_pointer: file pointer :type comment_lead: list(str) Usage example: .. code-block:: python >>> with open('some-file.cnf', 'r') as fp: ... cnf1 = CNF() ... cnf1.from_fp(fp) >>> >>> with open('another-file.cnf', 'r') as fp: ... cnf2 = CNF(from_fp=fp)
[ "Read", "a", "CNF", "formula", "from", "a", "file", "pointer", ".", "A", "file", "pointer", "should", "be", "specified", "as", "an", "argument", ".", "The", "only", "default", "argument", "is", "comment_lead", "which", "can", "be", "used", "for", "parsing", "specific", "comment", "lines", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L445-L484
17,210
pysathq/pysat
pysat/formula.py
CNF.from_clauses
def from_clauses(self, clauses): """ This methods copies a list of clauses into a CNF object. :param clauses: a list of clauses. :type clauses: list(list(int)) Example: .. code-block:: python >>> from pysat.formula import CNF >>> cnf = CNF(from_clauses=[[-1, 2], [1, -2], [5]]) >>> print cnf.clauses [[-1, 2], [1, -2], [5]] >>> print cnf.nv 5 """ self.clauses = copy.deepcopy(clauses) for cl in self.clauses: self.nv = max([abs(l) for l in cl] + [self.nv])
python
def from_clauses(self, clauses): """ This methods copies a list of clauses into a CNF object. :param clauses: a list of clauses. :type clauses: list(list(int)) Example: .. code-block:: python >>> from pysat.formula import CNF >>> cnf = CNF(from_clauses=[[-1, 2], [1, -2], [5]]) >>> print cnf.clauses [[-1, 2], [1, -2], [5]] >>> print cnf.nv 5 """ self.clauses = copy.deepcopy(clauses) for cl in self.clauses: self.nv = max([abs(l) for l in cl] + [self.nv])
[ "def", "from_clauses", "(", "self", ",", "clauses", ")", ":", "self", ".", "clauses", "=", "copy", ".", "deepcopy", "(", "clauses", ")", "for", "cl", "in", "self", ".", "clauses", ":", "self", ".", "nv", "=", "max", "(", "[", "abs", "(", "l", ")", "for", "l", "in", "cl", "]", "+", "[", "self", ".", "nv", "]", ")" ]
This methods copies a list of clauses into a CNF object. :param clauses: a list of clauses. :type clauses: list(list(int)) Example: .. code-block:: python >>> from pysat.formula import CNF >>> cnf = CNF(from_clauses=[[-1, 2], [1, -2], [5]]) >>> print cnf.clauses [[-1, 2], [1, -2], [5]] >>> print cnf.nv 5
[ "This", "methods", "copies", "a", "list", "of", "clauses", "into", "a", "CNF", "object", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L518-L540
17,211
pysathq/pysat
pysat/formula.py
CNF.to_fp
def to_fp(self, file_pointer, comments=None): """ The method can be used to save a CNF formula into a file pointer. The file pointer is expected as an argument. Additionally, supplementary comment lines can be specified in the ``comments`` parameter. :param fname: a file name where to store the formula. :param comments: additional comments to put in the file. :type fname: str :type comments: list(str) Example: .. code-block:: python >>> from pysat.formula import CNF >>> cnf = CNF() ... >>> # the formula is filled with a bunch of clauses >>> with open('some-file.cnf', 'w') as fp: ... cnf.to_fp(fp) # writing to the file pointer """ # saving formula's internal comments for c in self.comments: print(c, file=file_pointer) # saving externally specified comments if comments: for c in comments: print(c, file=file_pointer) print('p cnf', self.nv, len(self.clauses), file=file_pointer) for cl in self.clauses: print(' '.join(str(l) for l in cl), '0', file=file_pointer)
python
def to_fp(self, file_pointer, comments=None): """ The method can be used to save a CNF formula into a file pointer. The file pointer is expected as an argument. Additionally, supplementary comment lines can be specified in the ``comments`` parameter. :param fname: a file name where to store the formula. :param comments: additional comments to put in the file. :type fname: str :type comments: list(str) Example: .. code-block:: python >>> from pysat.formula import CNF >>> cnf = CNF() ... >>> # the formula is filled with a bunch of clauses >>> with open('some-file.cnf', 'w') as fp: ... cnf.to_fp(fp) # writing to the file pointer """ # saving formula's internal comments for c in self.comments: print(c, file=file_pointer) # saving externally specified comments if comments: for c in comments: print(c, file=file_pointer) print('p cnf', self.nv, len(self.clauses), file=file_pointer) for cl in self.clauses: print(' '.join(str(l) for l in cl), '0', file=file_pointer)
[ "def", "to_fp", "(", "self", ",", "file_pointer", ",", "comments", "=", "None", ")", ":", "# saving formula's internal comments", "for", "c", "in", "self", ".", "comments", ":", "print", "(", "c", ",", "file", "=", "file_pointer", ")", "# saving externally specified comments", "if", "comments", ":", "for", "c", "in", "comments", ":", "print", "(", "c", ",", "file", "=", "file_pointer", ")", "print", "(", "'p cnf'", ",", "self", ".", "nv", ",", "len", "(", "self", ".", "clauses", ")", ",", "file", "=", "file_pointer", ")", "for", "cl", "in", "self", ".", "clauses", ":", "print", "(", "' '", ".", "join", "(", "str", "(", "l", ")", "for", "l", "in", "cl", ")", ",", "'0'", ",", "file", "=", "file_pointer", ")" ]
The method can be used to save a CNF formula into a file pointer. The file pointer is expected as an argument. Additionally, supplementary comment lines can be specified in the ``comments`` parameter. :param fname: a file name where to store the formula. :param comments: additional comments to put in the file. :type fname: str :type comments: list(str) Example: .. code-block:: python >>> from pysat.formula import CNF >>> cnf = CNF() ... >>> # the formula is filled with a bunch of clauses >>> with open('some-file.cnf', 'w') as fp: ... cnf.to_fp(fp) # writing to the file pointer
[ "The", "method", "can", "be", "used", "to", "save", "a", "CNF", "formula", "into", "a", "file", "pointer", ".", "The", "file", "pointer", "is", "expected", "as", "an", "argument", ".", "Additionally", "supplementary", "comment", "lines", "can", "be", "specified", "in", "the", "comments", "parameter", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L606-L643
17,212
pysathq/pysat
pysat/formula.py
CNF.append
def append(self, clause): """ Add one more clause to CNF formula. This method additionally updates the number of variables, i.e. variable ``self.nv``, used in the formula. :param clause: a new clause to add. :type clause: list(int) .. code-block:: python >>> from pysat.formula import CNF >>> cnf = CNF(from_clauses=[[-1, 2], [3]]) >>> cnf.append([-3, 4]) >>> print cnf.clauses [[-1, 2], [3], [-3, 4]] """ self.nv = max([abs(l) for l in clause] + [self.nv]) self.clauses.append(clause)
python
def append(self, clause): """ Add one more clause to CNF formula. This method additionally updates the number of variables, i.e. variable ``self.nv``, used in the formula. :param clause: a new clause to add. :type clause: list(int) .. code-block:: python >>> from pysat.formula import CNF >>> cnf = CNF(from_clauses=[[-1, 2], [3]]) >>> cnf.append([-3, 4]) >>> print cnf.clauses [[-1, 2], [3], [-3, 4]] """ self.nv = max([abs(l) for l in clause] + [self.nv]) self.clauses.append(clause)
[ "def", "append", "(", "self", ",", "clause", ")", ":", "self", ".", "nv", "=", "max", "(", "[", "abs", "(", "l", ")", "for", "l", "in", "clause", "]", "+", "[", "self", ".", "nv", "]", ")", "self", ".", "clauses", ".", "append", "(", "clause", ")" ]
Add one more clause to CNF formula. This method additionally updates the number of variables, i.e. variable ``self.nv``, used in the formula. :param clause: a new clause to add. :type clause: list(int) .. code-block:: python >>> from pysat.formula import CNF >>> cnf = CNF(from_clauses=[[-1, 2], [3]]) >>> cnf.append([-3, 4]) >>> print cnf.clauses [[-1, 2], [3], [-3, 4]]
[ "Add", "one", "more", "clause", "to", "CNF", "formula", ".", "This", "method", "additionally", "updates", "the", "number", "of", "variables", "i", ".", "e", ".", "variable", "self", ".", "nv", "used", "in", "the", "formula", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L645-L664
17,213
pysathq/pysat
pysat/formula.py
WCNF.from_fp
def from_fp(self, file_pointer, comment_lead=['c']): """ Read a WCNF formula from a file pointer. A file pointer should be specified as an argument. The only default argument is ``comment_lead``, which can be used for parsing specific comment lines. :param file_pointer: a file pointer to read the formula from. :param comment_lead: a list of characters leading comment lines :type file_pointer: file pointer :type comment_lead: list(str) Usage example: .. code-block:: python >>> with open('some-file.cnf', 'r') as fp: ... cnf1 = WCNF() ... cnf1.from_fp(fp) >>> >>> with open('another-file.cnf', 'r') as fp: ... cnf2 = WCNF(from_fp=fp) """ self.nv = 0 self.hard = [] self.soft = [] self.wght = [] self.topw = 0 self.comments = [] comment_lead = tuple('p') + tuple(comment_lead) for line in file_pointer: line = line.strip() if line: if line[0] not in comment_lead: cl = [int(l) for l in line.split()[:-1]] w = cl.pop(0) self.nv = max([abs(l) for l in cl] + [self.nv]) if w >= self.topw: self.hard.append(cl) else: self.soft.append(cl) self.wght.append(w) elif not line.startswith('p wcnf '): self.comments.append(line) else: # expecting the preamble self.topw = int(line.rsplit(' ', 1)[1])
python
def from_fp(self, file_pointer, comment_lead=['c']): """ Read a WCNF formula from a file pointer. A file pointer should be specified as an argument. The only default argument is ``comment_lead``, which can be used for parsing specific comment lines. :param file_pointer: a file pointer to read the formula from. :param comment_lead: a list of characters leading comment lines :type file_pointer: file pointer :type comment_lead: list(str) Usage example: .. code-block:: python >>> with open('some-file.cnf', 'r') as fp: ... cnf1 = WCNF() ... cnf1.from_fp(fp) >>> >>> with open('another-file.cnf', 'r') as fp: ... cnf2 = WCNF(from_fp=fp) """ self.nv = 0 self.hard = [] self.soft = [] self.wght = [] self.topw = 0 self.comments = [] comment_lead = tuple('p') + tuple(comment_lead) for line in file_pointer: line = line.strip() if line: if line[0] not in comment_lead: cl = [int(l) for l in line.split()[:-1]] w = cl.pop(0) self.nv = max([abs(l) for l in cl] + [self.nv]) if w >= self.topw: self.hard.append(cl) else: self.soft.append(cl) self.wght.append(w) elif not line.startswith('p wcnf '): self.comments.append(line) else: # expecting the preamble self.topw = int(line.rsplit(' ', 1)[1])
[ "def", "from_fp", "(", "self", ",", "file_pointer", ",", "comment_lead", "=", "[", "'c'", "]", ")", ":", "self", ".", "nv", "=", "0", "self", ".", "hard", "=", "[", "]", "self", ".", "soft", "=", "[", "]", "self", ".", "wght", "=", "[", "]", "self", ".", "topw", "=", "0", "self", ".", "comments", "=", "[", "]", "comment_lead", "=", "tuple", "(", "'p'", ")", "+", "tuple", "(", "comment_lead", ")", "for", "line", "in", "file_pointer", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", ":", "if", "line", "[", "0", "]", "not", "in", "comment_lead", ":", "cl", "=", "[", "int", "(", "l", ")", "for", "l", "in", "line", ".", "split", "(", ")", "[", ":", "-", "1", "]", "]", "w", "=", "cl", ".", "pop", "(", "0", ")", "self", ".", "nv", "=", "max", "(", "[", "abs", "(", "l", ")", "for", "l", "in", "cl", "]", "+", "[", "self", ".", "nv", "]", ")", "if", "w", ">=", "self", ".", "topw", ":", "self", ".", "hard", ".", "append", "(", "cl", ")", "else", ":", "self", ".", "soft", ".", "append", "(", "cl", ")", "self", ".", "wght", ".", "append", "(", "w", ")", "elif", "not", "line", ".", "startswith", "(", "'p wcnf '", ")", ":", "self", ".", "comments", ".", "append", "(", "line", ")", "else", ":", "# expecting the preamble", "self", ".", "topw", "=", "int", "(", "line", ".", "rsplit", "(", "' '", ",", "1", ")", "[", "1", "]", ")" ]
Read a WCNF formula from a file pointer. A file pointer should be specified as an argument. The only default argument is ``comment_lead``, which can be used for parsing specific comment lines. :param file_pointer: a file pointer to read the formula from. :param comment_lead: a list of characters leading comment lines :type file_pointer: file pointer :type comment_lead: list(str) Usage example: .. code-block:: python >>> with open('some-file.cnf', 'r') as fp: ... cnf1 = WCNF() ... cnf1.from_fp(fp) >>> >>> with open('another-file.cnf', 'r') as fp: ... cnf2 = WCNF(from_fp=fp)
[ "Read", "a", "WCNF", "formula", "from", "a", "file", "pointer", ".", "A", "file", "pointer", "should", "be", "specified", "as", "an", "argument", ".", "The", "only", "default", "argument", "is", "comment_lead", "which", "can", "be", "used", "for", "parsing", "specific", "comment", "lines", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L863-L912
17,214
pysathq/pysat
pysat/formula.py
WCNF.to_fp
def to_fp(self, file_pointer, comments=None): """ The method can be used to save a WCNF formula into a file pointer. The file pointer is expected as an argument. Additionally, supplementary comment lines can be specified in the ``comments`` parameter. :param fname: a file name where to store the formula. :param comments: additional comments to put in the file. :type fname: str :type comments: list(str) Example: .. code-block:: python >>> from pysat.formula import WCNF >>> wcnf = WCNF() ... >>> # the formula is filled with a bunch of clauses >>> with open('some-file.wcnf', 'w') as fp: ... wcnf.to_fp(fp) # writing to the file pointer """ # saving formula's internal comments for c in self.comments: print(c, file=file_pointer) # saving externally specified comments if comments: for c in comments: print(c, file=file_pointer) print('p wcnf', self.nv, len(self.hard) + len(self.soft), self.topw, file=file_pointer) # soft clauses are dumped first because # some tools (e.g. LBX) cannot count them properly for i, cl in enumerate(self.soft): print(self.wght[i], ' '.join(str(l) for l in cl), '0', file=file_pointer) for cl in self.hard: print(self.topw, ' '.join(str(l) for l in cl), '0', file=file_pointer)
python
def to_fp(self, file_pointer, comments=None): """ The method can be used to save a WCNF formula into a file pointer. The file pointer is expected as an argument. Additionally, supplementary comment lines can be specified in the ``comments`` parameter. :param fname: a file name where to store the formula. :param comments: additional comments to put in the file. :type fname: str :type comments: list(str) Example: .. code-block:: python >>> from pysat.formula import WCNF >>> wcnf = WCNF() ... >>> # the formula is filled with a bunch of clauses >>> with open('some-file.wcnf', 'w') as fp: ... wcnf.to_fp(fp) # writing to the file pointer """ # saving formula's internal comments for c in self.comments: print(c, file=file_pointer) # saving externally specified comments if comments: for c in comments: print(c, file=file_pointer) print('p wcnf', self.nv, len(self.hard) + len(self.soft), self.topw, file=file_pointer) # soft clauses are dumped first because # some tools (e.g. LBX) cannot count them properly for i, cl in enumerate(self.soft): print(self.wght[i], ' '.join(str(l) for l in cl), '0', file=file_pointer) for cl in self.hard: print(self.topw, ' '.join(str(l) for l in cl), '0', file=file_pointer)
[ "def", "to_fp", "(", "self", ",", "file_pointer", ",", "comments", "=", "None", ")", ":", "# saving formula's internal comments", "for", "c", "in", "self", ".", "comments", ":", "print", "(", "c", ",", "file", "=", "file_pointer", ")", "# saving externally specified comments", "if", "comments", ":", "for", "c", "in", "comments", ":", "print", "(", "c", ",", "file", "=", "file_pointer", ")", "print", "(", "'p wcnf'", ",", "self", ".", "nv", ",", "len", "(", "self", ".", "hard", ")", "+", "len", "(", "self", ".", "soft", ")", ",", "self", ".", "topw", ",", "file", "=", "file_pointer", ")", "# soft clauses are dumped first because", "# some tools (e.g. LBX) cannot count them properly", "for", "i", ",", "cl", "in", "enumerate", "(", "self", ".", "soft", ")", ":", "print", "(", "self", ".", "wght", "[", "i", "]", ",", "' '", ".", "join", "(", "str", "(", "l", ")", "for", "l", "in", "cl", ")", ",", "'0'", ",", "file", "=", "file_pointer", ")", "for", "cl", "in", "self", ".", "hard", ":", "print", "(", "self", ".", "topw", ",", "' '", ".", "join", "(", "str", "(", "l", ")", "for", "l", "in", "cl", ")", ",", "'0'", ",", "file", "=", "file_pointer", ")" ]
The method can be used to save a WCNF formula into a file pointer. The file pointer is expected as an argument. Additionally, supplementary comment lines can be specified in the ``comments`` parameter. :param fname: a file name where to store the formula. :param comments: additional comments to put in the file. :type fname: str :type comments: list(str) Example: .. code-block:: python >>> from pysat.formula import WCNF >>> wcnf = WCNF() ... >>> # the formula is filled with a bunch of clauses >>> with open('some-file.wcnf', 'w') as fp: ... wcnf.to_fp(fp) # writing to the file pointer
[ "The", "method", "can", "be", "used", "to", "save", "a", "WCNF", "formula", "into", "a", "file", "pointer", ".", "The", "file", "pointer", "is", "expected", "as", "an", "argument", ".", "Additionally", "supplementary", "comment", "lines", "can", "be", "specified", "in", "the", "comments", "parameter", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L1024-L1066
17,215
pysathq/pysat
pysat/formula.py
WCNF.append
def append(self, clause, weight=None): """ Add one more clause to WCNF formula. This method additionally updates the number of variables, i.e. variable ``self.nv``, used in the formula. The clause can be hard or soft depending on the ``weight`` argument. If no weight is set, the clause is considered to be hard. :param clause: a new clause to add. :param weight: integer weight of the clause. :type clause: list(int) :type weight: integer or None .. code-block:: python >>> from pysat.formula import WCNF >>> cnf = WCNF() >>> cnf.append([-1, 2]) >>> cnf.append([1], weight=10) >>> cnf.append([-2], weight=20) >>> print cnf.hard [[-1, 2]] >>> print cnf.soft [[1], [-2]] >>> print cnf.wght [10, 20] """ self.nv = max([abs(l) for l in clause] + [self.nv]) if weight: self.soft.append(clause) self.wght.append(weight) else: self.hard.append(clause)
python
def append(self, clause, weight=None): """ Add one more clause to WCNF formula. This method additionally updates the number of variables, i.e. variable ``self.nv``, used in the formula. The clause can be hard or soft depending on the ``weight`` argument. If no weight is set, the clause is considered to be hard. :param clause: a new clause to add. :param weight: integer weight of the clause. :type clause: list(int) :type weight: integer or None .. code-block:: python >>> from pysat.formula import WCNF >>> cnf = WCNF() >>> cnf.append([-1, 2]) >>> cnf.append([1], weight=10) >>> cnf.append([-2], weight=20) >>> print cnf.hard [[-1, 2]] >>> print cnf.soft [[1], [-2]] >>> print cnf.wght [10, 20] """ self.nv = max([abs(l) for l in clause] + [self.nv]) if weight: self.soft.append(clause) self.wght.append(weight) else: self.hard.append(clause)
[ "def", "append", "(", "self", ",", "clause", ",", "weight", "=", "None", ")", ":", "self", ".", "nv", "=", "max", "(", "[", "abs", "(", "l", ")", "for", "l", "in", "clause", "]", "+", "[", "self", ".", "nv", "]", ")", "if", "weight", ":", "self", ".", "soft", ".", "append", "(", "clause", ")", "self", ".", "wght", ".", "append", "(", "weight", ")", "else", ":", "self", ".", "hard", ".", "append", "(", "clause", ")" ]
Add one more clause to WCNF formula. This method additionally updates the number of variables, i.e. variable ``self.nv``, used in the formula. The clause can be hard or soft depending on the ``weight`` argument. If no weight is set, the clause is considered to be hard. :param clause: a new clause to add. :param weight: integer weight of the clause. :type clause: list(int) :type weight: integer or None .. code-block:: python >>> from pysat.formula import WCNF >>> cnf = WCNF() >>> cnf.append([-1, 2]) >>> cnf.append([1], weight=10) >>> cnf.append([-2], weight=20) >>> print cnf.hard [[-1, 2]] >>> print cnf.soft [[1], [-2]] >>> print cnf.wght [10, 20]
[ "Add", "one", "more", "clause", "to", "WCNF", "formula", ".", "This", "method", "additionally", "updates", "the", "number", "of", "variables", "i", ".", "e", ".", "variable", "self", ".", "nv", "used", "in", "the", "formula", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L1068-L1104
17,216
pysathq/pysat
pysat/formula.py
CNFPlus.from_fp
def from_fp(self, file_pointer, comment_lead=['c']): """ Read a CNF+ formula from a file pointer. A file pointer should be specified as an argument. The only default argument is ``comment_lead``, which can be used for parsing specific comment lines. :param file_pointer: a file pointer to read the formula from. :param comment_lead: a list of characters leading comment lines :type file_pointer: file pointer :type comment_lead: list(str) Usage example: .. code-block:: python >>> with open('some-file.cnf+', 'r') as fp: ... cnf1 = CNFPlus() ... cnf1.from_fp(fp) >>> >>> with open('another-file.cnf+', 'r') as fp: ... cnf2 = CNFPlus(from_fp=fp) """ self.nv = 0 self.clauses = [] self.atmosts = [] self.comments = [] comment_lead = tuple('p') + tuple(comment_lead) for line in file_pointer: line = line.strip() if line: if line[0] not in comment_lead: if line[-1] == '0': # normal clause cl = [int(l) for l in line.split()[:-1]] self.nv = max([abs(l) for l in cl] + [self.nv]) self.clauses.append(cl) else: # atmost/atleast constraint items = [i for i in line.split()] lits = [int(l) for l in items[:-2]] rhs = int(items[-1]) self.nv = max([abs(l) for l in lits] + [self.nv]) if items[-2][0] == '>': lits = list(map(lambda l: -l, lits)) rhs = len(lits) - rhs self.atmosts.append([lits, rhs]) elif not line.startswith('p cnf+ '): self.comments.append(line)
python
def from_fp(self, file_pointer, comment_lead=['c']): """ Read a CNF+ formula from a file pointer. A file pointer should be specified as an argument. The only default argument is ``comment_lead``, which can be used for parsing specific comment lines. :param file_pointer: a file pointer to read the formula from. :param comment_lead: a list of characters leading comment lines :type file_pointer: file pointer :type comment_lead: list(str) Usage example: .. code-block:: python >>> with open('some-file.cnf+', 'r') as fp: ... cnf1 = CNFPlus() ... cnf1.from_fp(fp) >>> >>> with open('another-file.cnf+', 'r') as fp: ... cnf2 = CNFPlus(from_fp=fp) """ self.nv = 0 self.clauses = [] self.atmosts = [] self.comments = [] comment_lead = tuple('p') + tuple(comment_lead) for line in file_pointer: line = line.strip() if line: if line[0] not in comment_lead: if line[-1] == '0': # normal clause cl = [int(l) for l in line.split()[:-1]] self.nv = max([abs(l) for l in cl] + [self.nv]) self.clauses.append(cl) else: # atmost/atleast constraint items = [i for i in line.split()] lits = [int(l) for l in items[:-2]] rhs = int(items[-1]) self.nv = max([abs(l) for l in lits] + [self.nv]) if items[-2][0] == '>': lits = list(map(lambda l: -l, lits)) rhs = len(lits) - rhs self.atmosts.append([lits, rhs]) elif not line.startswith('p cnf+ '): self.comments.append(line)
[ "def", "from_fp", "(", "self", ",", "file_pointer", ",", "comment_lead", "=", "[", "'c'", "]", ")", ":", "self", ".", "nv", "=", "0", "self", ".", "clauses", "=", "[", "]", "self", ".", "atmosts", "=", "[", "]", "self", ".", "comments", "=", "[", "]", "comment_lead", "=", "tuple", "(", "'p'", ")", "+", "tuple", "(", "comment_lead", ")", "for", "line", "in", "file_pointer", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", ":", "if", "line", "[", "0", "]", "not", "in", "comment_lead", ":", "if", "line", "[", "-", "1", "]", "==", "'0'", ":", "# normal clause", "cl", "=", "[", "int", "(", "l", ")", "for", "l", "in", "line", ".", "split", "(", ")", "[", ":", "-", "1", "]", "]", "self", ".", "nv", "=", "max", "(", "[", "abs", "(", "l", ")", "for", "l", "in", "cl", "]", "+", "[", "self", ".", "nv", "]", ")", "self", ".", "clauses", ".", "append", "(", "cl", ")", "else", ":", "# atmost/atleast constraint", "items", "=", "[", "i", "for", "i", "in", "line", ".", "split", "(", ")", "]", "lits", "=", "[", "int", "(", "l", ")", "for", "l", "in", "items", "[", ":", "-", "2", "]", "]", "rhs", "=", "int", "(", "items", "[", "-", "1", "]", ")", "self", ".", "nv", "=", "max", "(", "[", "abs", "(", "l", ")", "for", "l", "in", "lits", "]", "+", "[", "self", ".", "nv", "]", ")", "if", "items", "[", "-", "2", "]", "[", "0", "]", "==", "'>'", ":", "lits", "=", "list", "(", "map", "(", "lambda", "l", ":", "-", "l", ",", "lits", ")", ")", "rhs", "=", "len", "(", "lits", ")", "-", "rhs", "self", ".", "atmosts", ".", "append", "(", "[", "lits", ",", "rhs", "]", ")", "elif", "not", "line", ".", "startswith", "(", "'p cnf+ '", ")", ":", "self", ".", "comments", ".", "append", "(", "line", ")" ]
Read a CNF+ formula from a file pointer. A file pointer should be specified as an argument. The only default argument is ``comment_lead``, which can be used for parsing specific comment lines. :param file_pointer: a file pointer to read the formula from. :param comment_lead: a list of characters leading comment lines :type file_pointer: file pointer :type comment_lead: list(str) Usage example: .. code-block:: python >>> with open('some-file.cnf+', 'r') as fp: ... cnf1 = CNFPlus() ... cnf1.from_fp(fp) >>> >>> with open('another-file.cnf+', 'r') as fp: ... cnf2 = CNFPlus(from_fp=fp)
[ "Read", "a", "CNF", "+", "formula", "from", "a", "file", "pointer", ".", "A", "file", "pointer", "should", "be", "specified", "as", "an", "argument", ".", "The", "only", "default", "argument", "is", "comment_lead", "which", "can", "be", "used", "for", "parsing", "specific", "comment", "lines", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L1239-L1291
17,217
pysathq/pysat
pysat/formula.py
CNFPlus.to_fp
def to_fp(self, file_pointer, comments=None): """ The method can be used to save a CNF+ formula into a file pointer. The file pointer is expected as an argument. Additionally, supplementary comment lines can be specified in the ``comments`` parameter. :param fname: a file name where to store the formula. :param comments: additional comments to put in the file. :type fname: str :type comments: list(str) Example: .. code-block:: python >>> from pysat.formula import CNFPlus >>> cnf = CNFPlus() ... >>> # the formula is filled with a bunch of clauses >>> with open('some-file.cnf+', 'w') as fp: ... cnf.to_fp(fp) # writing to the file pointer """ # saving formula's internal comments for c in self.comments: print(c, file=file_pointer) # saving externally specified comments if comments: for c in comments: print(c, file=file_pointer) ftype = 'cnf+' if self.atmosts else 'cnf' print('p', ftype, self.nv, len(self.clauses) + len(self.atmosts), file=file_pointer) for cl in self.clauses: print(' '.join(str(l) for l in cl), '0', file=file_pointer) for am in self.atmosts: print(' '.join(str(l) for l in am[0]), '<=', am[1], file=file_pointer)
python
def to_fp(self, file_pointer, comments=None): """ The method can be used to save a CNF+ formula into a file pointer. The file pointer is expected as an argument. Additionally, supplementary comment lines can be specified in the ``comments`` parameter. :param fname: a file name where to store the formula. :param comments: additional comments to put in the file. :type fname: str :type comments: list(str) Example: .. code-block:: python >>> from pysat.formula import CNFPlus >>> cnf = CNFPlus() ... >>> # the formula is filled with a bunch of clauses >>> with open('some-file.cnf+', 'w') as fp: ... cnf.to_fp(fp) # writing to the file pointer """ # saving formula's internal comments for c in self.comments: print(c, file=file_pointer) # saving externally specified comments if comments: for c in comments: print(c, file=file_pointer) ftype = 'cnf+' if self.atmosts else 'cnf' print('p', ftype, self.nv, len(self.clauses) + len(self.atmosts), file=file_pointer) for cl in self.clauses: print(' '.join(str(l) for l in cl), '0', file=file_pointer) for am in self.atmosts: print(' '.join(str(l) for l in am[0]), '<=', am[1], file=file_pointer)
[ "def", "to_fp", "(", "self", ",", "file_pointer", ",", "comments", "=", "None", ")", ":", "# saving formula's internal comments", "for", "c", "in", "self", ".", "comments", ":", "print", "(", "c", ",", "file", "=", "file_pointer", ")", "# saving externally specified comments", "if", "comments", ":", "for", "c", "in", "comments", ":", "print", "(", "c", ",", "file", "=", "file_pointer", ")", "ftype", "=", "'cnf+'", "if", "self", ".", "atmosts", "else", "'cnf'", "print", "(", "'p'", ",", "ftype", ",", "self", ".", "nv", ",", "len", "(", "self", ".", "clauses", ")", "+", "len", "(", "self", ".", "atmosts", ")", ",", "file", "=", "file_pointer", ")", "for", "cl", "in", "self", ".", "clauses", ":", "print", "(", "' '", ".", "join", "(", "str", "(", "l", ")", "for", "l", "in", "cl", ")", ",", "'0'", ",", "file", "=", "file_pointer", ")", "for", "am", "in", "self", ".", "atmosts", ":", "print", "(", "' '", ".", "join", "(", "str", "(", "l", ")", "for", "l", "in", "am", "[", "0", "]", ")", ",", "'<='", ",", "am", "[", "1", "]", ",", "file", "=", "file_pointer", ")" ]
The method can be used to save a CNF+ formula into a file pointer. The file pointer is expected as an argument. Additionally, supplementary comment lines can be specified in the ``comments`` parameter. :param fname: a file name where to store the formula. :param comments: additional comments to put in the file. :type fname: str :type comments: list(str) Example: .. code-block:: python >>> from pysat.formula import CNFPlus >>> cnf = CNFPlus() ... >>> # the formula is filled with a bunch of clauses >>> with open('some-file.cnf+', 'w') as fp: ... cnf.to_fp(fp) # writing to the file pointer
[ "The", "method", "can", "be", "used", "to", "save", "a", "CNF", "+", "formula", "into", "a", "file", "pointer", ".", "The", "file", "pointer", "is", "expected", "as", "an", "argument", ".", "Additionally", "supplementary", "comment", "lines", "can", "be", "specified", "in", "the", "comments", "parameter", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L1293-L1335
17,218
pysathq/pysat
pysat/formula.py
CNFPlus.append
def append(self, clause, is_atmost=False): """ Add a single clause or a single AtMostK constraint to CNF+ formula. This method additionally updates the number of variables, i.e. variable ``self.nv``, used in the formula. If the clause is an AtMostK constraint, this should be set with the use of the additional default argument ``is_atmost``, which is set to ``False`` by default. :param clause: a new clause to add. :param is_atmost: if ``True``, the clause is AtMostK. :type clause: list(int) :type is_atmost: bool .. code-block:: python >>> from pysat.formula import CNFPlus >>> cnf = CNFPlus() >>> cnf.append([-3, 4]) >>> cnf.append([[1, 2, 3], 1], is_atmost=True) >>> print cnf.clauses [[-3, 4]] >>> print cnf.atmosts [[1, 2, 3], 1] """ if not is_atmost: self.nv = max([abs(l) for l in clause] + [self.nv]) self.clauses.append(clause) else: self.nv = max([abs(l) for l in clause[0]] + [self.nv]) self.atmosts.append(clause)
python
def append(self, clause, is_atmost=False): """ Add a single clause or a single AtMostK constraint to CNF+ formula. This method additionally updates the number of variables, i.e. variable ``self.nv``, used in the formula. If the clause is an AtMostK constraint, this should be set with the use of the additional default argument ``is_atmost``, which is set to ``False`` by default. :param clause: a new clause to add. :param is_atmost: if ``True``, the clause is AtMostK. :type clause: list(int) :type is_atmost: bool .. code-block:: python >>> from pysat.formula import CNFPlus >>> cnf = CNFPlus() >>> cnf.append([-3, 4]) >>> cnf.append([[1, 2, 3], 1], is_atmost=True) >>> print cnf.clauses [[-3, 4]] >>> print cnf.atmosts [[1, 2, 3], 1] """ if not is_atmost: self.nv = max([abs(l) for l in clause] + [self.nv]) self.clauses.append(clause) else: self.nv = max([abs(l) for l in clause[0]] + [self.nv]) self.atmosts.append(clause)
[ "def", "append", "(", "self", ",", "clause", ",", "is_atmost", "=", "False", ")", ":", "if", "not", "is_atmost", ":", "self", ".", "nv", "=", "max", "(", "[", "abs", "(", "l", ")", "for", "l", "in", "clause", "]", "+", "[", "self", ".", "nv", "]", ")", "self", ".", "clauses", ".", "append", "(", "clause", ")", "else", ":", "self", ".", "nv", "=", "max", "(", "[", "abs", "(", "l", ")", "for", "l", "in", "clause", "[", "0", "]", "]", "+", "[", "self", ".", "nv", "]", ")", "self", ".", "atmosts", ".", "append", "(", "clause", ")" ]
Add a single clause or a single AtMostK constraint to CNF+ formula. This method additionally updates the number of variables, i.e. variable ``self.nv``, used in the formula. If the clause is an AtMostK constraint, this should be set with the use of the additional default argument ``is_atmost``, which is set to ``False`` by default. :param clause: a new clause to add. :param is_atmost: if ``True``, the clause is AtMostK. :type clause: list(int) :type is_atmost: bool .. code-block:: python >>> from pysat.formula import CNFPlus >>> cnf = CNFPlus() >>> cnf.append([-3, 4]) >>> cnf.append([[1, 2, 3], 1], is_atmost=True) >>> print cnf.clauses [[-3, 4]] >>> print cnf.atmosts [[1, 2, 3], 1]
[ "Add", "a", "single", "clause", "or", "a", "single", "AtMostK", "constraint", "to", "CNF", "+", "formula", ".", "This", "method", "additionally", "updates", "the", "number", "of", "variables", "i", ".", "e", ".", "variable", "self", ".", "nv", "used", "in", "the", "formula", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L1337-L1370
17,219
pysathq/pysat
pysat/formula.py
WCNFPlus.from_fp
def from_fp(self, file_pointer, comment_lead=['c']): """ Read a WCNF+ formula from a file pointer. A file pointer should be specified as an argument. The only default argument is ``comment_lead``, which can be used for parsing specific comment lines. :param file_pointer: a file pointer to read the formula from. :param comment_lead: a list of characters leading comment lines :type file_pointer: file pointer :type comment_lead: list(str) Usage example: .. code-block:: python >>> with open('some-file.wcnf+', 'r') as fp: ... cnf1 = WCNFPlus() ... cnf1.from_fp(fp) >>> >>> with open('another-file.wcnf+', 'r') as fp: ... cnf2 = WCNFPlus(from_fp=fp) """ self.nv = 0 self.hard = [] self.atms = [] self.soft = [] self.wght = [] self.topw = 0 self.comments = [] comment_lead = tuple('p') + tuple(comment_lead) for line in file_pointer: line = line.strip() if line: if line[0] not in comment_lead: if line[-1] == '0': # normal clause cl = [int(l) for l in line.split()[:-1]] w = cl.pop(0) self.nv = max([abs(l) for l in cl] + [self.nv]) if w >= self.topw: self.hard.append(cl) else: self.soft.append(cl) self.wght.append(w) else: # atmost/atleast constraint items = [i for i in line.split()] lits = [int(l) for l in items[1:-2]] rhs = int(items[-1]) self.nv = max([abs(l) for l in lits] + [self.nv]) if items[-2][0] == '>': lits = list(map(lambda l: -l, lits)) rhs = len(lits) - rhs self.atms.append([lits, rhs]) elif not line.startswith('p wcnf+ '): self.comments.append(line) else: # expecting the preamble self.topw = int(line.rsplit(' ', 1)[1])
python
def from_fp(self, file_pointer, comment_lead=['c']): """ Read a WCNF+ formula from a file pointer. A file pointer should be specified as an argument. The only default argument is ``comment_lead``, which can be used for parsing specific comment lines. :param file_pointer: a file pointer to read the formula from. :param comment_lead: a list of characters leading comment lines :type file_pointer: file pointer :type comment_lead: list(str) Usage example: .. code-block:: python >>> with open('some-file.wcnf+', 'r') as fp: ... cnf1 = WCNFPlus() ... cnf1.from_fp(fp) >>> >>> with open('another-file.wcnf+', 'r') as fp: ... cnf2 = WCNFPlus(from_fp=fp) """ self.nv = 0 self.hard = [] self.atms = [] self.soft = [] self.wght = [] self.topw = 0 self.comments = [] comment_lead = tuple('p') + tuple(comment_lead) for line in file_pointer: line = line.strip() if line: if line[0] not in comment_lead: if line[-1] == '0': # normal clause cl = [int(l) for l in line.split()[:-1]] w = cl.pop(0) self.nv = max([abs(l) for l in cl] + [self.nv]) if w >= self.topw: self.hard.append(cl) else: self.soft.append(cl) self.wght.append(w) else: # atmost/atleast constraint items = [i for i in line.split()] lits = [int(l) for l in items[1:-2]] rhs = int(items[-1]) self.nv = max([abs(l) for l in lits] + [self.nv]) if items[-2][0] == '>': lits = list(map(lambda l: -l, lits)) rhs = len(lits) - rhs self.atms.append([lits, rhs]) elif not line.startswith('p wcnf+ '): self.comments.append(line) else: # expecting the preamble self.topw = int(line.rsplit(' ', 1)[1])
[ "def", "from_fp", "(", "self", ",", "file_pointer", ",", "comment_lead", "=", "[", "'c'", "]", ")", ":", "self", ".", "nv", "=", "0", "self", ".", "hard", "=", "[", "]", "self", ".", "atms", "=", "[", "]", "self", ".", "soft", "=", "[", "]", "self", ".", "wght", "=", "[", "]", "self", ".", "topw", "=", "0", "self", ".", "comments", "=", "[", "]", "comment_lead", "=", "tuple", "(", "'p'", ")", "+", "tuple", "(", "comment_lead", ")", "for", "line", "in", "file_pointer", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", ":", "if", "line", "[", "0", "]", "not", "in", "comment_lead", ":", "if", "line", "[", "-", "1", "]", "==", "'0'", ":", "# normal clause", "cl", "=", "[", "int", "(", "l", ")", "for", "l", "in", "line", ".", "split", "(", ")", "[", ":", "-", "1", "]", "]", "w", "=", "cl", ".", "pop", "(", "0", ")", "self", ".", "nv", "=", "max", "(", "[", "abs", "(", "l", ")", "for", "l", "in", "cl", "]", "+", "[", "self", ".", "nv", "]", ")", "if", "w", ">=", "self", ".", "topw", ":", "self", ".", "hard", ".", "append", "(", "cl", ")", "else", ":", "self", ".", "soft", ".", "append", "(", "cl", ")", "self", ".", "wght", ".", "append", "(", "w", ")", "else", ":", "# atmost/atleast constraint", "items", "=", "[", "i", "for", "i", "in", "line", ".", "split", "(", ")", "]", "lits", "=", "[", "int", "(", "l", ")", "for", "l", "in", "items", "[", "1", ":", "-", "2", "]", "]", "rhs", "=", "int", "(", "items", "[", "-", "1", "]", ")", "self", ".", "nv", "=", "max", "(", "[", "abs", "(", "l", ")", "for", "l", "in", "lits", "]", "+", "[", "self", ".", "nv", "]", ")", "if", "items", "[", "-", "2", "]", "[", "0", "]", "==", "'>'", ":", "lits", "=", "list", "(", "map", "(", "lambda", "l", ":", "-", "l", ",", "lits", ")", ")", "rhs", "=", "len", "(", "lits", ")", "-", "rhs", "self", ".", "atms", ".", "append", "(", "[", "lits", ",", "rhs", "]", ")", "elif", "not", "line", ".", "startswith", "(", "'p wcnf+ '", ")", ":", "self", ".", "comments", ".", "append", "(", "line", ")", "else", ":", "# expecting the preamble", "self", ".", "topw", "=", "int", "(", "line", ".", "rsplit", "(", "' '", ",", "1", ")", "[", "1", "]", ")" ]
Read a WCNF+ formula from a file pointer. A file pointer should be specified as an argument. The only default argument is ``comment_lead``, which can be used for parsing specific comment lines. :param file_pointer: a file pointer to read the formula from. :param comment_lead: a list of characters leading comment lines :type file_pointer: file pointer :type comment_lead: list(str) Usage example: .. code-block:: python >>> with open('some-file.wcnf+', 'r') as fp: ... cnf1 = WCNFPlus() ... cnf1.from_fp(fp) >>> >>> with open('another-file.wcnf+', 'r') as fp: ... cnf2 = WCNFPlus(from_fp=fp)
[ "Read", "a", "WCNF", "+", "formula", "from", "a", "file", "pointer", ".", "A", "file", "pointer", "should", "be", "specified", "as", "an", "argument", ".", "The", "only", "default", "argument", "is", "comment_lead", "which", "can", "be", "used", "for", "parsing", "specific", "comment", "lines", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L1438-L1500
17,220
pysathq/pysat
pysat/formula.py
WCNFPlus.append
def append(self, clause, weight=None, is_atmost=False): """ Add a single clause or a single AtMostK constraint to WCNF+ formula. This method additionally updates the number of variables, i.e. variable ``self.nv``, used in the formula. If the clause is an AtMostK constraint, this should be set with the use of the additional default argument ``is_atmost``, which is set to ``False`` by default. If ``is_atmost`` is set to ``False``, the clause can be either hard or soft depending on the ``weight`` argument. If no weight is specified, the clause is considered hard. Otherwise, the clause is soft. :param clause: a new clause to add. :param weight: an integer weight of the clause. :param is_atmost: if ``True``, the clause is AtMostK. :type clause: list(int) :type weight: integer or None :type is_atmost: bool .. code-block:: python >>> from pysat.formula import WCNFPlus >>> cnf = WCNFPlus() >>> cnf.append([-3, 4]) >>> cnf.append([[1, 2, 3], 1], is_atmost=True) >>> cnf.append([-1, -2], weight=35) >>> print cnf.hard [[-3, 4]] >>> print cnf.atms [[1, 2, 3], 1] >>> print cnf.soft [[-1, -2]] >>> print cnf.wght [35] """ if not is_atmost: self.nv = max([abs(l) for l in clause] + [self.nv]) if weight: self.soft.append(clause) self.wght.append(weight) else: self.hard.append(clause) else: self.nv = max([abs(l) for l in clause[0]] + [self.nv]) self.atms.append(clause)
python
def append(self, clause, weight=None, is_atmost=False): """ Add a single clause or a single AtMostK constraint to WCNF+ formula. This method additionally updates the number of variables, i.e. variable ``self.nv``, used in the formula. If the clause is an AtMostK constraint, this should be set with the use of the additional default argument ``is_atmost``, which is set to ``False`` by default. If ``is_atmost`` is set to ``False``, the clause can be either hard or soft depending on the ``weight`` argument. If no weight is specified, the clause is considered hard. Otherwise, the clause is soft. :param clause: a new clause to add. :param weight: an integer weight of the clause. :param is_atmost: if ``True``, the clause is AtMostK. :type clause: list(int) :type weight: integer or None :type is_atmost: bool .. code-block:: python >>> from pysat.formula import WCNFPlus >>> cnf = WCNFPlus() >>> cnf.append([-3, 4]) >>> cnf.append([[1, 2, 3], 1], is_atmost=True) >>> cnf.append([-1, -2], weight=35) >>> print cnf.hard [[-3, 4]] >>> print cnf.atms [[1, 2, 3], 1] >>> print cnf.soft [[-1, -2]] >>> print cnf.wght [35] """ if not is_atmost: self.nv = max([abs(l) for l in clause] + [self.nv]) if weight: self.soft.append(clause) self.wght.append(weight) else: self.hard.append(clause) else: self.nv = max([abs(l) for l in clause[0]] + [self.nv]) self.atms.append(clause)
[ "def", "append", "(", "self", ",", "clause", ",", "weight", "=", "None", ",", "is_atmost", "=", "False", ")", ":", "if", "not", "is_atmost", ":", "self", ".", "nv", "=", "max", "(", "[", "abs", "(", "l", ")", "for", "l", "in", "clause", "]", "+", "[", "self", ".", "nv", "]", ")", "if", "weight", ":", "self", ".", "soft", ".", "append", "(", "clause", ")", "self", ".", "wght", ".", "append", "(", "weight", ")", "else", ":", "self", ".", "hard", ".", "append", "(", "clause", ")", "else", ":", "self", ".", "nv", "=", "max", "(", "[", "abs", "(", "l", ")", "for", "l", "in", "clause", "[", "0", "]", "]", "+", "[", "self", ".", "nv", "]", ")", "self", ".", "atms", ".", "append", "(", "clause", ")" ]
Add a single clause or a single AtMostK constraint to WCNF+ formula. This method additionally updates the number of variables, i.e. variable ``self.nv``, used in the formula. If the clause is an AtMostK constraint, this should be set with the use of the additional default argument ``is_atmost``, which is set to ``False`` by default. If ``is_atmost`` is set to ``False``, the clause can be either hard or soft depending on the ``weight`` argument. If no weight is specified, the clause is considered hard. Otherwise, the clause is soft. :param clause: a new clause to add. :param weight: an integer weight of the clause. :param is_atmost: if ``True``, the clause is AtMostK. :type clause: list(int) :type weight: integer or None :type is_atmost: bool .. code-block:: python >>> from pysat.formula import WCNFPlus >>> cnf = WCNFPlus() >>> cnf.append([-3, 4]) >>> cnf.append([[1, 2, 3], 1], is_atmost=True) >>> cnf.append([-1, -2], weight=35) >>> print cnf.hard [[-3, 4]] >>> print cnf.atms [[1, 2, 3], 1] >>> print cnf.soft [[-1, -2]] >>> print cnf.wght [35]
[ "Add", "a", "single", "clause", "or", "a", "single", "AtMostK", "constraint", "to", "WCNF", "+", "formula", ".", "This", "method", "additionally", "updates", "the", "number", "of", "variables", "i", ".", "e", ".", "variable", "self", ".", "nv", "used", "in", "the", "formula", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L1552-L1602
17,221
pysathq/pysat
examples/fm.py
FM.delete
def delete(self): """ Explicit destructor of the internal SAT oracle. """ if self.oracle: self.time += self.oracle.time_accum() # keep SAT solving time self.oracle.delete() self.oracle = None
python
def delete(self): """ Explicit destructor of the internal SAT oracle. """ if self.oracle: self.time += self.oracle.time_accum() # keep SAT solving time self.oracle.delete() self.oracle = None
[ "def", "delete", "(", "self", ")", ":", "if", "self", ".", "oracle", ":", "self", ".", "time", "+=", "self", ".", "oracle", ".", "time_accum", "(", ")", "# keep SAT solving time", "self", ".", "oracle", ".", "delete", "(", ")", "self", ".", "oracle", "=", "None" ]
Explicit destructor of the internal SAT oracle.
[ "Explicit", "destructor", "of", "the", "internal", "SAT", "oracle", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/fm.py#L216-L225
17,222
pysathq/pysat
examples/fm.py
FM.split_core
def split_core(self, minw): """ Split clauses in the core whenever necessary. Given a list of soft clauses in an unsatisfiable core, the method is used for splitting clauses whose weights are greater than the minimum weight of the core, i.e. the ``minw`` value computed in :func:`treat_core`. Each clause :math:`(c\\vee\\neg{s},w)`, s.t. :math:`w>minw` and :math:`s` is its selector literal, is split into clauses (1) clause :math:`(c\\vee\\neg{s}, minw)` and (2) a residual clause :math:`(c\\vee\\neg{s}',w-minw)`. Note that the residual clause has a fresh selector literal :math:`s'` different from :math:`s`. :param minw: minimum weight of the core :type minw: int """ for clid in self.core: sel = self.sels[clid] if self.wght[clid] > minw: self.topv += 1 cl_new = [] for l in self.soft[clid]: if l != -sel: cl_new.append(l) else: cl_new.append(-self.topv) self.sels.append(self.topv) self.vmap[self.topv] = len(self.soft) self.soft.append(cl_new) self.wght.append(self.wght[clid] - minw) self.wght[clid] = minw self.scpy.append(True)
python
def split_core(self, minw): """ Split clauses in the core whenever necessary. Given a list of soft clauses in an unsatisfiable core, the method is used for splitting clauses whose weights are greater than the minimum weight of the core, i.e. the ``minw`` value computed in :func:`treat_core`. Each clause :math:`(c\\vee\\neg{s},w)`, s.t. :math:`w>minw` and :math:`s` is its selector literal, is split into clauses (1) clause :math:`(c\\vee\\neg{s}, minw)` and (2) a residual clause :math:`(c\\vee\\neg{s}',w-minw)`. Note that the residual clause has a fresh selector literal :math:`s'` different from :math:`s`. :param minw: minimum weight of the core :type minw: int """ for clid in self.core: sel = self.sels[clid] if self.wght[clid] > minw: self.topv += 1 cl_new = [] for l in self.soft[clid]: if l != -sel: cl_new.append(l) else: cl_new.append(-self.topv) self.sels.append(self.topv) self.vmap[self.topv] = len(self.soft) self.soft.append(cl_new) self.wght.append(self.wght[clid] - minw) self.wght[clid] = minw self.scpy.append(True)
[ "def", "split_core", "(", "self", ",", "minw", ")", ":", "for", "clid", "in", "self", ".", "core", ":", "sel", "=", "self", ".", "sels", "[", "clid", "]", "if", "self", ".", "wght", "[", "clid", "]", ">", "minw", ":", "self", ".", "topv", "+=", "1", "cl_new", "=", "[", "]", "for", "l", "in", "self", ".", "soft", "[", "clid", "]", ":", "if", "l", "!=", "-", "sel", ":", "cl_new", ".", "append", "(", "l", ")", "else", ":", "cl_new", ".", "append", "(", "-", "self", ".", "topv", ")", "self", ".", "sels", ".", "append", "(", "self", ".", "topv", ")", "self", ".", "vmap", "[", "self", ".", "topv", "]", "=", "len", "(", "self", ".", "soft", ")", "self", ".", "soft", ".", "append", "(", "cl_new", ")", "self", ".", "wght", ".", "append", "(", "self", ".", "wght", "[", "clid", "]", "-", "minw", ")", "self", ".", "wght", "[", "clid", "]", "=", "minw", "self", ".", "scpy", ".", "append", "(", "True", ")" ]
Split clauses in the core whenever necessary. Given a list of soft clauses in an unsatisfiable core, the method is used for splitting clauses whose weights are greater than the minimum weight of the core, i.e. the ``minw`` value computed in :func:`treat_core`. Each clause :math:`(c\\vee\\neg{s},w)`, s.t. :math:`w>minw` and :math:`s` is its selector literal, is split into clauses (1) clause :math:`(c\\vee\\neg{s}, minw)` and (2) a residual clause :math:`(c\\vee\\neg{s}',w-minw)`. Note that the residual clause has a fresh selector literal :math:`s'` different from :math:`s`. :param minw: minimum weight of the core :type minw: int
[ "Split", "clauses", "in", "the", "core", "whenever", "necessary", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/fm.py#L325-L363
17,223
pysathq/pysat
examples/fm.py
FM.relax_core
def relax_core(self): """ Relax and bound the core. After unsatisfiable core splitting, this method is called. If the core contains only one clause, i.e. this clause cannot be satisfied together with the hard clauses of the formula, the formula gets augmented with the negation of the clause (see :func:`remove_unit_core`). Otherwise (if the core contains more than one clause), every clause :math:`c` of the core is *relaxed*. This means a new *relaxation literal* is added to the clause, i.e. :math:`c\gets c\\vee r`, where :math:`r` is a fresh (unused) relaxation variable. After the clauses get relaxed, a new cardinality encoding is added to the formula enforcing the sum of the new relaxation variables to be not greater than 1, :math:`\sum_{c\in\phi}{r\leq 1}`, where :math:`\phi` denotes the unsatisfiable core. """ if len(self.core) > 1: # relaxing rels = [] for clid in self.core: self.topv += 1 rels.append(self.topv) self.soft[clid].append(self.topv) # creating a new cardinality constraint am1 = CardEnc.atmost(lits=rels, top_id=self.topv, encoding=self.cenc) for cl in am1.clauses: self.hard.append(cl) # only if minicard # (for other solvers am1.atmosts should be empty) for am in am1.atmosts: self.atm1.append(am) self.topv = am1.nv elif len(self.core) == 1: # unit core => simply negate the clause self.remove_unit_core()
python
def relax_core(self): """ Relax and bound the core. After unsatisfiable core splitting, this method is called. If the core contains only one clause, i.e. this clause cannot be satisfied together with the hard clauses of the formula, the formula gets augmented with the negation of the clause (see :func:`remove_unit_core`). Otherwise (if the core contains more than one clause), every clause :math:`c` of the core is *relaxed*. This means a new *relaxation literal* is added to the clause, i.e. :math:`c\gets c\\vee r`, where :math:`r` is a fresh (unused) relaxation variable. After the clauses get relaxed, a new cardinality encoding is added to the formula enforcing the sum of the new relaxation variables to be not greater than 1, :math:`\sum_{c\in\phi}{r\leq 1}`, where :math:`\phi` denotes the unsatisfiable core. """ if len(self.core) > 1: # relaxing rels = [] for clid in self.core: self.topv += 1 rels.append(self.topv) self.soft[clid].append(self.topv) # creating a new cardinality constraint am1 = CardEnc.atmost(lits=rels, top_id=self.topv, encoding=self.cenc) for cl in am1.clauses: self.hard.append(cl) # only if minicard # (for other solvers am1.atmosts should be empty) for am in am1.atmosts: self.atm1.append(am) self.topv = am1.nv elif len(self.core) == 1: # unit core => simply negate the clause self.remove_unit_core()
[ "def", "relax_core", "(", "self", ")", ":", "if", "len", "(", "self", ".", "core", ")", ">", "1", ":", "# relaxing", "rels", "=", "[", "]", "for", "clid", "in", "self", ".", "core", ":", "self", ".", "topv", "+=", "1", "rels", ".", "append", "(", "self", ".", "topv", ")", "self", ".", "soft", "[", "clid", "]", ".", "append", "(", "self", ".", "topv", ")", "# creating a new cardinality constraint", "am1", "=", "CardEnc", ".", "atmost", "(", "lits", "=", "rels", ",", "top_id", "=", "self", ".", "topv", ",", "encoding", "=", "self", ".", "cenc", ")", "for", "cl", "in", "am1", ".", "clauses", ":", "self", ".", "hard", ".", "append", "(", "cl", ")", "# only if minicard", "# (for other solvers am1.atmosts should be empty)", "for", "am", "in", "am1", ".", "atmosts", ":", "self", ".", "atm1", ".", "append", "(", "am", ")", "self", ".", "topv", "=", "am1", ".", "nv", "elif", "len", "(", "self", ".", "core", ")", "==", "1", ":", "# unit core => simply negate the clause", "self", ".", "remove_unit_core", "(", ")" ]
Relax and bound the core. After unsatisfiable core splitting, this method is called. If the core contains only one clause, i.e. this clause cannot be satisfied together with the hard clauses of the formula, the formula gets augmented with the negation of the clause (see :func:`remove_unit_core`). Otherwise (if the core contains more than one clause), every clause :math:`c` of the core is *relaxed*. This means a new *relaxation literal* is added to the clause, i.e. :math:`c\gets c\\vee r`, where :math:`r` is a fresh (unused) relaxation variable. After the clauses get relaxed, a new cardinality encoding is added to the formula enforcing the sum of the new relaxation variables to be not greater than 1, :math:`\sum_{c\in\phi}{r\leq 1}`, where :math:`\phi` denotes the unsatisfiable core.
[ "Relax", "and", "bound", "the", "core", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/fm.py#L365-L408
17,224
pysathq/pysat
examples/lsu.py
parse_options
def parse_options(): """ Parses command-line options. """ try: opts, args = getopt.getopt(sys.argv[1:], 'hms:v', ['help', 'model', 'solver=', 'verbose']) except getopt.GetoptError as err: sys.stderr.write(str(err).capitalize()) print_usage() sys.exit(1) solver = 'g4' verbose = 1 print_model = False for opt, arg in opts: if opt in ('-h', '--help'): print_usage() sys.exit(0) elif opt in ('-m', '--model'): print_model = True elif opt in ('-s', '--solver'): solver = str(arg) elif opt in ('-v', '--verbose'): verbose += 1 else: assert False, 'Unhandled option: {0} {1}'.format(opt, arg) return print_model, solver, verbose, args
python
def parse_options(): """ Parses command-line options. """ try: opts, args = getopt.getopt(sys.argv[1:], 'hms:v', ['help', 'model', 'solver=', 'verbose']) except getopt.GetoptError as err: sys.stderr.write(str(err).capitalize()) print_usage() sys.exit(1) solver = 'g4' verbose = 1 print_model = False for opt, arg in opts: if opt in ('-h', '--help'): print_usage() sys.exit(0) elif opt in ('-m', '--model'): print_model = True elif opt in ('-s', '--solver'): solver = str(arg) elif opt in ('-v', '--verbose'): verbose += 1 else: assert False, 'Unhandled option: {0} {1}'.format(opt, arg) return print_model, solver, verbose, args
[ "def", "parse_options", "(", ")", ":", "try", ":", "opts", ",", "args", "=", "getopt", ".", "getopt", "(", "sys", ".", "argv", "[", "1", ":", "]", ",", "'hms:v'", ",", "[", "'help'", ",", "'model'", ",", "'solver='", ",", "'verbose'", "]", ")", "except", "getopt", ".", "GetoptError", "as", "err", ":", "sys", ".", "stderr", ".", "write", "(", "str", "(", "err", ")", ".", "capitalize", "(", ")", ")", "print_usage", "(", ")", "sys", ".", "exit", "(", "1", ")", "solver", "=", "'g4'", "verbose", "=", "1", "print_model", "=", "False", "for", "opt", ",", "arg", "in", "opts", ":", "if", "opt", "in", "(", "'-h'", ",", "'--help'", ")", ":", "print_usage", "(", ")", "sys", ".", "exit", "(", "0", ")", "elif", "opt", "in", "(", "'-m'", ",", "'--model'", ")", ":", "print_model", "=", "True", "elif", "opt", "in", "(", "'-s'", ",", "'--solver'", ")", ":", "solver", "=", "str", "(", "arg", ")", "elif", "opt", "in", "(", "'-v'", ",", "'--verbose'", ")", ":", "verbose", "+=", "1", "else", ":", "assert", "False", ",", "'Unhandled option: {0} {1}'", ".", "format", "(", "opt", ",", "arg", ")", "return", "print_model", ",", "solver", ",", "verbose", ",", "args" ]
Parses command-line options.
[ "Parses", "command", "-", "line", "options", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/lsu.py#L308-L337
17,225
pysathq/pysat
examples/lsu.py
parse_formula
def parse_formula(fml_file): """ Parse and return MaxSAT formula. """ if re.search('\.wcnf(\.(gz|bz2|lzma|xz))?$', fml_file): fml = WCNF(from_file=fml_file) else: # expecting '*.cnf' fml = CNF(from_file=fml_file).weighted() return fml
python
def parse_formula(fml_file): """ Parse and return MaxSAT formula. """ if re.search('\.wcnf(\.(gz|bz2|lzma|xz))?$', fml_file): fml = WCNF(from_file=fml_file) else: # expecting '*.cnf' fml = CNF(from_file=fml_file).weighted() return fml
[ "def", "parse_formula", "(", "fml_file", ")", ":", "if", "re", ".", "search", "(", "'\\.wcnf(\\.(gz|bz2|lzma|xz))?$'", ",", "fml_file", ")", ":", "fml", "=", "WCNF", "(", "from_file", "=", "fml_file", ")", "else", ":", "# expecting '*.cnf'", "fml", "=", "CNF", "(", "from_file", "=", "fml_file", ")", ".", "weighted", "(", ")", "return", "fml" ]
Parse and return MaxSAT formula.
[ "Parse", "and", "return", "MaxSAT", "formula", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/lsu.py#L358-L368
17,226
pysathq/pysat
examples/lsu.py
LSU._init
def _init(self, formula): """ SAT oracle initialization. The method creates a new SAT oracle and feeds it with the formula's hard clauses. Afterwards, all soft clauses of the formula are augmented with selector literals and also added to the solver. The list of all introduced selectors is stored in variable ``self.sels``. :param formula: input MaxSAT formula :type formula: :class:`WCNF` """ self.oracle = Solver(name=self.solver, bootstrap_with=formula.hard, incr=True, use_timer=True) for i, cl in enumerate(formula.soft): # TODO: if clause is unit, use its literal as selector # (ITotalizer must be extended to support PB constraints first) self.topv += 1 selv = self.topv cl.append(self.topv) self.oracle.add_clause(cl) self.sels.append(selv) if self.verbose > 1: print('c formula: {0} vars, {1} hard, {2} soft'.format(formula.nv, len(formula.hard), len(formula.soft)))
python
def _init(self, formula): """ SAT oracle initialization. The method creates a new SAT oracle and feeds it with the formula's hard clauses. Afterwards, all soft clauses of the formula are augmented with selector literals and also added to the solver. The list of all introduced selectors is stored in variable ``self.sels``. :param formula: input MaxSAT formula :type formula: :class:`WCNF` """ self.oracle = Solver(name=self.solver, bootstrap_with=formula.hard, incr=True, use_timer=True) for i, cl in enumerate(formula.soft): # TODO: if clause is unit, use its literal as selector # (ITotalizer must be extended to support PB constraints first) self.topv += 1 selv = self.topv cl.append(self.topv) self.oracle.add_clause(cl) self.sels.append(selv) if self.verbose > 1: print('c formula: {0} vars, {1} hard, {2} soft'.format(formula.nv, len(formula.hard), len(formula.soft)))
[ "def", "_init", "(", "self", ",", "formula", ")", ":", "self", ".", "oracle", "=", "Solver", "(", "name", "=", "self", ".", "solver", ",", "bootstrap_with", "=", "formula", ".", "hard", ",", "incr", "=", "True", ",", "use_timer", "=", "True", ")", "for", "i", ",", "cl", "in", "enumerate", "(", "formula", ".", "soft", ")", ":", "# TODO: if clause is unit, use its literal as selector", "# (ITotalizer must be extended to support PB constraints first)", "self", ".", "topv", "+=", "1", "selv", "=", "self", ".", "topv", "cl", ".", "append", "(", "self", ".", "topv", ")", "self", ".", "oracle", ".", "add_clause", "(", "cl", ")", "self", ".", "sels", ".", "append", "(", "selv", ")", "if", "self", ".", "verbose", ">", "1", ":", "print", "(", "'c formula: {0} vars, {1} hard, {2} soft'", ".", "format", "(", "formula", ".", "nv", ",", "len", "(", "formula", ".", "hard", ")", ",", "len", "(", "formula", ".", "soft", ")", ")", ")" ]
SAT oracle initialization. The method creates a new SAT oracle and feeds it with the formula's hard clauses. Afterwards, all soft clauses of the formula are augmented with selector literals and also added to the solver. The list of all introduced selectors is stored in variable ``self.sels``. :param formula: input MaxSAT formula :type formula: :class:`WCNF`
[ "SAT", "oracle", "initialization", ".", "The", "method", "creates", "a", "new", "SAT", "oracle", "and", "feeds", "it", "with", "the", "formula", "s", "hard", "clauses", ".", "Afterwards", "all", "soft", "clauses", "of", "the", "formula", "are", "augmented", "with", "selector", "literals", "and", "also", "added", "to", "the", "solver", ".", "The", "list", "of", "all", "introduced", "selectors", "is", "stored", "in", "variable", "self", ".", "sels", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/lsu.py#L139-L164
17,227
pysathq/pysat
examples/lsu.py
LSU._get_model_cost
def _get_model_cost(self, formula, model): """ Given a WCNF formula and a model, the method computes the MaxSAT cost of the model, i.e. the sum of weights of soft clauses that are unsatisfied by the model. :param formula: an input MaxSAT formula :param model: a satisfying assignment :type formula: :class:`.WCNF` :type model: list(int) :rtype: int """ model_set = set(model) cost = 0 for i, cl in enumerate(formula.soft): cost += formula.wght[i] if all(l not in model_set for l in filter(lambda l: abs(l) <= self.formula.nv, cl)) else 0 return cost
python
def _get_model_cost(self, formula, model): """ Given a WCNF formula and a model, the method computes the MaxSAT cost of the model, i.e. the sum of weights of soft clauses that are unsatisfied by the model. :param formula: an input MaxSAT formula :param model: a satisfying assignment :type formula: :class:`.WCNF` :type model: list(int) :rtype: int """ model_set = set(model) cost = 0 for i, cl in enumerate(formula.soft): cost += formula.wght[i] if all(l not in model_set for l in filter(lambda l: abs(l) <= self.formula.nv, cl)) else 0 return cost
[ "def", "_get_model_cost", "(", "self", ",", "formula", ",", "model", ")", ":", "model_set", "=", "set", "(", "model", ")", "cost", "=", "0", "for", "i", ",", "cl", "in", "enumerate", "(", "formula", ".", "soft", ")", ":", "cost", "+=", "formula", ".", "wght", "[", "i", "]", "if", "all", "(", "l", "not", "in", "model_set", "for", "l", "in", "filter", "(", "lambda", "l", ":", "abs", "(", "l", ")", "<=", "self", ".", "formula", ".", "nv", ",", "cl", ")", ")", "else", "0", "return", "cost" ]
Given a WCNF formula and a model, the method computes the MaxSAT cost of the model, i.e. the sum of weights of soft clauses that are unsatisfied by the model. :param formula: an input MaxSAT formula :param model: a satisfying assignment :type formula: :class:`.WCNF` :type model: list(int) :rtype: int
[ "Given", "a", "WCNF", "formula", "and", "a", "model", "the", "method", "computes", "the", "MaxSAT", "cost", "of", "the", "model", "i", ".", "e", ".", "the", "sum", "of", "weights", "of", "soft", "clauses", "that", "are", "unsatisfied", "by", "the", "model", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/lsu.py#L249-L270
17,228
pysathq/pysat
examples/rc2.py
parse_options
def parse_options(): """ Parses command-line option """ try: opts, args = getopt.getopt(sys.argv[1:], 'ac:e:hilms:t:vx', ['adapt', 'comp=', 'enum=', 'exhaust', 'help', 'incr', 'blo', 'minimize', 'solver=', 'trim=', 'verbose']) except getopt.GetoptError as err: sys.stderr.write(str(err).capitalize()) usage() sys.exit(1) adapt = False exhaust = False cmode = None to_enum = 1 incr = False blo = False minz = False solver = 'g3' trim = 0 verbose = 1 for opt, arg in opts: if opt in ('-a', '--adapt'): adapt = True elif opt in ('-c', '--comp'): cmode = str(arg) elif opt in ('-e', '--enum'): to_enum = str(arg) if to_enum != 'all': to_enum = int(to_enum) else: to_enum = 0 elif opt in ('-h', '--help'): usage() sys.exit(0) elif opt in ('-i', '--incr'): incr = True elif opt in ('-l', '--blo'): blo = True elif opt in ('-m', '--minimize'): minz = True elif opt in ('-s', '--solver'): solver = str(arg) elif opt in ('-t', '--trim'): trim = int(arg) elif opt in ('-v', '--verbose'): verbose += 1 elif opt in ('-x', '--exhaust'): exhaust = True else: assert False, 'Unhandled option: {0} {1}'.format(opt, arg) return adapt, blo, cmode, to_enum, exhaust, incr, minz, solver, trim, \ verbose, args
python
def parse_options(): """ Parses command-line option """ try: opts, args = getopt.getopt(sys.argv[1:], 'ac:e:hilms:t:vx', ['adapt', 'comp=', 'enum=', 'exhaust', 'help', 'incr', 'blo', 'minimize', 'solver=', 'trim=', 'verbose']) except getopt.GetoptError as err: sys.stderr.write(str(err).capitalize()) usage() sys.exit(1) adapt = False exhaust = False cmode = None to_enum = 1 incr = False blo = False minz = False solver = 'g3' trim = 0 verbose = 1 for opt, arg in opts: if opt in ('-a', '--adapt'): adapt = True elif opt in ('-c', '--comp'): cmode = str(arg) elif opt in ('-e', '--enum'): to_enum = str(arg) if to_enum != 'all': to_enum = int(to_enum) else: to_enum = 0 elif opt in ('-h', '--help'): usage() sys.exit(0) elif opt in ('-i', '--incr'): incr = True elif opt in ('-l', '--blo'): blo = True elif opt in ('-m', '--minimize'): minz = True elif opt in ('-s', '--solver'): solver = str(arg) elif opt in ('-t', '--trim'): trim = int(arg) elif opt in ('-v', '--verbose'): verbose += 1 elif opt in ('-x', '--exhaust'): exhaust = True else: assert False, 'Unhandled option: {0} {1}'.format(opt, arg) return adapt, blo, cmode, to_enum, exhaust, incr, minz, solver, trim, \ verbose, args
[ "def", "parse_options", "(", ")", ":", "try", ":", "opts", ",", "args", "=", "getopt", ".", "getopt", "(", "sys", ".", "argv", "[", "1", ":", "]", ",", "'ac:e:hilms:t:vx'", ",", "[", "'adapt'", ",", "'comp='", ",", "'enum='", ",", "'exhaust'", ",", "'help'", ",", "'incr'", ",", "'blo'", ",", "'minimize'", ",", "'solver='", ",", "'trim='", ",", "'verbose'", "]", ")", "except", "getopt", ".", "GetoptError", "as", "err", ":", "sys", ".", "stderr", ".", "write", "(", "str", "(", "err", ")", ".", "capitalize", "(", ")", ")", "usage", "(", ")", "sys", ".", "exit", "(", "1", ")", "adapt", "=", "False", "exhaust", "=", "False", "cmode", "=", "None", "to_enum", "=", "1", "incr", "=", "False", "blo", "=", "False", "minz", "=", "False", "solver", "=", "'g3'", "trim", "=", "0", "verbose", "=", "1", "for", "opt", ",", "arg", "in", "opts", ":", "if", "opt", "in", "(", "'-a'", ",", "'--adapt'", ")", ":", "adapt", "=", "True", "elif", "opt", "in", "(", "'-c'", ",", "'--comp'", ")", ":", "cmode", "=", "str", "(", "arg", ")", "elif", "opt", "in", "(", "'-e'", ",", "'--enum'", ")", ":", "to_enum", "=", "str", "(", "arg", ")", "if", "to_enum", "!=", "'all'", ":", "to_enum", "=", "int", "(", "to_enum", ")", "else", ":", "to_enum", "=", "0", "elif", "opt", "in", "(", "'-h'", ",", "'--help'", ")", ":", "usage", "(", ")", "sys", ".", "exit", "(", "0", ")", "elif", "opt", "in", "(", "'-i'", ",", "'--incr'", ")", ":", "incr", "=", "True", "elif", "opt", "in", "(", "'-l'", ",", "'--blo'", ")", ":", "blo", "=", "True", "elif", "opt", "in", "(", "'-m'", ",", "'--minimize'", ")", ":", "minz", "=", "True", "elif", "opt", "in", "(", "'-s'", ",", "'--solver'", ")", ":", "solver", "=", "str", "(", "arg", ")", "elif", "opt", "in", "(", "'-t'", ",", "'--trim'", ")", ":", "trim", "=", "int", "(", "arg", ")", "elif", "opt", "in", "(", "'-v'", ",", "'--verbose'", ")", ":", "verbose", "+=", "1", "elif", "opt", "in", "(", "'-x'", ",", "'--exhaust'", ")", ":", "exhaust", "=", "True", "else", ":", "assert", "False", ",", "'Unhandled option: {0} {1}'", ".", "format", "(", "opt", ",", "arg", ")", "return", "adapt", ",", "blo", ",", "cmode", ",", "to_enum", ",", "exhaust", ",", "incr", ",", "minz", ",", "solver", ",", "trim", ",", "verbose", ",", "args" ]
Parses command-line option
[ "Parses", "command", "-", "line", "option" ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/rc2.py#L1463-L1520
17,229
pysathq/pysat
examples/rc2.py
RC2.delete
def delete(self): """ Explicit destructor of the internal SAT oracle and all the totalizer objects creating during the solving process. """ if self.oracle: self.oracle.delete() self.oracle = None if self.solver != 'mc': # for minicard, there is nothing to free for t in six.itervalues(self.tobj): t.delete()
python
def delete(self): """ Explicit destructor of the internal SAT oracle and all the totalizer objects creating during the solving process. """ if self.oracle: self.oracle.delete() self.oracle = None if self.solver != 'mc': # for minicard, there is nothing to free for t in six.itervalues(self.tobj): t.delete()
[ "def", "delete", "(", "self", ")", ":", "if", "self", ".", "oracle", ":", "self", ".", "oracle", ".", "delete", "(", ")", "self", ".", "oracle", "=", "None", "if", "self", ".", "solver", "!=", "'mc'", ":", "# for minicard, there is nothing to free", "for", "t", "in", "six", ".", "itervalues", "(", "self", ".", "tobj", ")", ":", "t", ".", "delete", "(", ")" ]
Explicit destructor of the internal SAT oracle and all the totalizer objects creating during the solving process.
[ "Explicit", "destructor", "of", "the", "internal", "SAT", "oracle", "and", "all", "the", "totalizer", "objects", "creating", "during", "the", "solving", "process", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/rc2.py#L382-L394
17,230
pysathq/pysat
examples/rc2.py
RC2.trim_core
def trim_core(self): """ This method trims a previously extracted unsatisfiable core at most a given number of times. If a fixed point is reached before that, the method returns. """ for i in range(self.trim): # call solver with core assumption only # it must return 'unsatisfiable' self.oracle.solve(assumptions=self.core) # extract a new core new_core = self.oracle.get_core() if len(new_core) == len(self.core): # stop if new core is not better than the previous one break # otherwise, update core self.core = new_core
python
def trim_core(self): """ This method trims a previously extracted unsatisfiable core at most a given number of times. If a fixed point is reached before that, the method returns. """ for i in range(self.trim): # call solver with core assumption only # it must return 'unsatisfiable' self.oracle.solve(assumptions=self.core) # extract a new core new_core = self.oracle.get_core() if len(new_core) == len(self.core): # stop if new core is not better than the previous one break # otherwise, update core self.core = new_core
[ "def", "trim_core", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "trim", ")", ":", "# call solver with core assumption only", "# it must return 'unsatisfiable'", "self", ".", "oracle", ".", "solve", "(", "assumptions", "=", "self", ".", "core", ")", "# extract a new core", "new_core", "=", "self", ".", "oracle", ".", "get_core", "(", ")", "if", "len", "(", "new_core", ")", "==", "len", "(", "self", ".", "core", ")", ":", "# stop if new core is not better than the previous one", "break", "# otherwise, update core", "self", ".", "core", "=", "new_core" ]
This method trims a previously extracted unsatisfiable core at most a given number of times. If a fixed point is reached before that, the method returns.
[ "This", "method", "trims", "a", "previously", "extracted", "unsatisfiable", "core", "at", "most", "a", "given", "number", "of", "times", ".", "If", "a", "fixed", "point", "is", "reached", "before", "that", "the", "method", "returns", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/rc2.py#L757-L777
17,231
pysathq/pysat
examples/rc2.py
RC2.minimize_core
def minimize_core(self): """ Reduce a previously extracted core and compute an over-approximation of an MUS. This is done using the simple deletion-based MUS extraction algorithm. The idea is to try to deactivate soft clauses of the unsatisfiable core one by one while checking if the remaining soft clauses together with the hard part of the formula are unsatisfiable. Clauses that are necessary for preserving unsatisfiability comprise an MUS of the input formula (it is contained in the given unsatisfiable core) and are reported as a result of the procedure. During this core minimization procedure, all SAT calls are dropped after obtaining 1000 conflicts. """ if self.minz and len(self.core) > 1: self.core = sorted(self.core, key=lambda l: self.wght[l]) self.oracle.conf_budget(1000) i = 0 while i < len(self.core): to_test = self.core[:i] + self.core[(i + 1):] if self.oracle.solve_limited(assumptions=to_test) == False: self.core = to_test else: i += 1
python
def minimize_core(self): """ Reduce a previously extracted core and compute an over-approximation of an MUS. This is done using the simple deletion-based MUS extraction algorithm. The idea is to try to deactivate soft clauses of the unsatisfiable core one by one while checking if the remaining soft clauses together with the hard part of the formula are unsatisfiable. Clauses that are necessary for preserving unsatisfiability comprise an MUS of the input formula (it is contained in the given unsatisfiable core) and are reported as a result of the procedure. During this core minimization procedure, all SAT calls are dropped after obtaining 1000 conflicts. """ if self.minz and len(self.core) > 1: self.core = sorted(self.core, key=lambda l: self.wght[l]) self.oracle.conf_budget(1000) i = 0 while i < len(self.core): to_test = self.core[:i] + self.core[(i + 1):] if self.oracle.solve_limited(assumptions=to_test) == False: self.core = to_test else: i += 1
[ "def", "minimize_core", "(", "self", ")", ":", "if", "self", ".", "minz", "and", "len", "(", "self", ".", "core", ")", ">", "1", ":", "self", ".", "core", "=", "sorted", "(", "self", ".", "core", ",", "key", "=", "lambda", "l", ":", "self", ".", "wght", "[", "l", "]", ")", "self", ".", "oracle", ".", "conf_budget", "(", "1000", ")", "i", "=", "0", "while", "i", "<", "len", "(", "self", ".", "core", ")", ":", "to_test", "=", "self", ".", "core", "[", ":", "i", "]", "+", "self", ".", "core", "[", "(", "i", "+", "1", ")", ":", "]", "if", "self", ".", "oracle", ".", "solve_limited", "(", "assumptions", "=", "to_test", ")", "==", "False", ":", "self", ".", "core", "=", "to_test", "else", ":", "i", "+=", "1" ]
Reduce a previously extracted core and compute an over-approximation of an MUS. This is done using the simple deletion-based MUS extraction algorithm. The idea is to try to deactivate soft clauses of the unsatisfiable core one by one while checking if the remaining soft clauses together with the hard part of the formula are unsatisfiable. Clauses that are necessary for preserving unsatisfiability comprise an MUS of the input formula (it is contained in the given unsatisfiable core) and are reported as a result of the procedure. During this core minimization procedure, all SAT calls are dropped after obtaining 1000 conflicts.
[ "Reduce", "a", "previously", "extracted", "core", "and", "compute", "an", "over", "-", "approximation", "of", "an", "MUS", ".", "This", "is", "done", "using", "the", "simple", "deletion", "-", "based", "MUS", "extraction", "algorithm", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/rc2.py#L779-L808
17,232
pysathq/pysat
examples/rc2.py
RC2.update_sum
def update_sum(self, assump): """ The method is used to increase the bound for a given totalizer sum. The totalizer object is identified by the input parameter ``assump``, which is an assumption literal associated with the totalizer object. The method increases the bound for the totalizer sum, which involves adding the corresponding new clauses to the internal SAT oracle. The method returns the totalizer object followed by the new bound obtained. :param assump: assumption literal associated with the sum :type assump: int :rtype: :class:`.ITotalizer`, int Note that if Minicard is used as a SAT oracle, native cardinality constraints are used instead of :class:`.ITotalizer`. """ # getting a totalizer object corresponding to assumption t = self.tobj[assump] # increment the current bound b = self.bnds[assump] + 1 if self.solver != 'mc': # the case of standard totalizer encoding # increasing its bound t.increase(ubound=b, top_id=self.topv) # updating top variable id self.topv = t.top_id # adding its clauses to oracle if t.nof_new: for cl in t.cnf.clauses[-t.nof_new:]: self.oracle.add_clause(cl) else: # the case of cardinality constraints represented natively # right-hand side is always equal to the number of input literals rhs = len(t.lits) if b < rhs: # creating an additional bound if not t.rhs[b]: self.topv += 1 t.rhs[b] = self.topv # a new at-most-b constraint amb = [[-t.rhs[b]] * (rhs - b) + t.lits, rhs] self.oracle.add_atmost(*amb) return t, b
python
def update_sum(self, assump): """ The method is used to increase the bound for a given totalizer sum. The totalizer object is identified by the input parameter ``assump``, which is an assumption literal associated with the totalizer object. The method increases the bound for the totalizer sum, which involves adding the corresponding new clauses to the internal SAT oracle. The method returns the totalizer object followed by the new bound obtained. :param assump: assumption literal associated with the sum :type assump: int :rtype: :class:`.ITotalizer`, int Note that if Minicard is used as a SAT oracle, native cardinality constraints are used instead of :class:`.ITotalizer`. """ # getting a totalizer object corresponding to assumption t = self.tobj[assump] # increment the current bound b = self.bnds[assump] + 1 if self.solver != 'mc': # the case of standard totalizer encoding # increasing its bound t.increase(ubound=b, top_id=self.topv) # updating top variable id self.topv = t.top_id # adding its clauses to oracle if t.nof_new: for cl in t.cnf.clauses[-t.nof_new:]: self.oracle.add_clause(cl) else: # the case of cardinality constraints represented natively # right-hand side is always equal to the number of input literals rhs = len(t.lits) if b < rhs: # creating an additional bound if not t.rhs[b]: self.topv += 1 t.rhs[b] = self.topv # a new at-most-b constraint amb = [[-t.rhs[b]] * (rhs - b) + t.lits, rhs] self.oracle.add_atmost(*amb) return t, b
[ "def", "update_sum", "(", "self", ",", "assump", ")", ":", "# getting a totalizer object corresponding to assumption", "t", "=", "self", ".", "tobj", "[", "assump", "]", "# increment the current bound", "b", "=", "self", ".", "bnds", "[", "assump", "]", "+", "1", "if", "self", ".", "solver", "!=", "'mc'", ":", "# the case of standard totalizer encoding", "# increasing its bound", "t", ".", "increase", "(", "ubound", "=", "b", ",", "top_id", "=", "self", ".", "topv", ")", "# updating top variable id", "self", ".", "topv", "=", "t", ".", "top_id", "# adding its clauses to oracle", "if", "t", ".", "nof_new", ":", "for", "cl", "in", "t", ".", "cnf", ".", "clauses", "[", "-", "t", ".", "nof_new", ":", "]", ":", "self", ".", "oracle", ".", "add_clause", "(", "cl", ")", "else", ":", "# the case of cardinality constraints represented natively", "# right-hand side is always equal to the number of input literals", "rhs", "=", "len", "(", "t", ".", "lits", ")", "if", "b", "<", "rhs", ":", "# creating an additional bound", "if", "not", "t", ".", "rhs", "[", "b", "]", ":", "self", ".", "topv", "+=", "1", "t", ".", "rhs", "[", "b", "]", "=", "self", ".", "topv", "# a new at-most-b constraint", "amb", "=", "[", "[", "-", "t", ".", "rhs", "[", "b", "]", "]", "*", "(", "rhs", "-", "b", ")", "+", "t", ".", "lits", ",", "rhs", "]", "self", ".", "oracle", ".", "add_atmost", "(", "*", "amb", ")", "return", "t", ",", "b" ]
The method is used to increase the bound for a given totalizer sum. The totalizer object is identified by the input parameter ``assump``, which is an assumption literal associated with the totalizer object. The method increases the bound for the totalizer sum, which involves adding the corresponding new clauses to the internal SAT oracle. The method returns the totalizer object followed by the new bound obtained. :param assump: assumption literal associated with the sum :type assump: int :rtype: :class:`.ITotalizer`, int Note that if Minicard is used as a SAT oracle, native cardinality constraints are used instead of :class:`.ITotalizer`.
[ "The", "method", "is", "used", "to", "increase", "the", "bound", "for", "a", "given", "totalizer", "sum", ".", "The", "totalizer", "object", "is", "identified", "by", "the", "input", "parameter", "assump", "which", "is", "an", "assumption", "literal", "associated", "with", "the", "totalizer", "object", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/rc2.py#L990-L1045
17,233
pysathq/pysat
examples/rc2.py
RC2.set_bound
def set_bound(self, tobj, rhs): """ Given a totalizer sum and its right-hand side to be enforced, the method creates a new sum assumption literal, which will be used in the following SAT oracle calls. :param tobj: totalizer sum :param rhs: right-hand side :type tobj: :class:`.ITotalizer` :type rhs: int """ # saving the sum and its weight in a mapping self.tobj[-tobj.rhs[rhs]] = tobj self.bnds[-tobj.rhs[rhs]] = rhs self.wght[-tobj.rhs[rhs]] = self.minw # adding a new assumption to force the sum to be at most rhs self.sums.append(-tobj.rhs[rhs])
python
def set_bound(self, tobj, rhs): """ Given a totalizer sum and its right-hand side to be enforced, the method creates a new sum assumption literal, which will be used in the following SAT oracle calls. :param tobj: totalizer sum :param rhs: right-hand side :type tobj: :class:`.ITotalizer` :type rhs: int """ # saving the sum and its weight in a mapping self.tobj[-tobj.rhs[rhs]] = tobj self.bnds[-tobj.rhs[rhs]] = rhs self.wght[-tobj.rhs[rhs]] = self.minw # adding a new assumption to force the sum to be at most rhs self.sums.append(-tobj.rhs[rhs])
[ "def", "set_bound", "(", "self", ",", "tobj", ",", "rhs", ")", ":", "# saving the sum and its weight in a mapping", "self", ".", "tobj", "[", "-", "tobj", ".", "rhs", "[", "rhs", "]", "]", "=", "tobj", "self", ".", "bnds", "[", "-", "tobj", ".", "rhs", "[", "rhs", "]", "]", "=", "rhs", "self", ".", "wght", "[", "-", "tobj", ".", "rhs", "[", "rhs", "]", "]", "=", "self", ".", "minw", "# adding a new assumption to force the sum to be at most rhs", "self", ".", "sums", ".", "append", "(", "-", "tobj", ".", "rhs", "[", "rhs", "]", ")" ]
Given a totalizer sum and its right-hand side to be enforced, the method creates a new sum assumption literal, which will be used in the following SAT oracle calls. :param tobj: totalizer sum :param rhs: right-hand side :type tobj: :class:`.ITotalizer` :type rhs: int
[ "Given", "a", "totalizer", "sum", "and", "its", "right", "-", "hand", "side", "to", "be", "enforced", "the", "method", "creates", "a", "new", "sum", "assumption", "literal", "which", "will", "be", "used", "in", "the", "following", "SAT", "oracle", "calls", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/rc2.py#L1047-L1066
17,234
pysathq/pysat
examples/rc2.py
RC2.filter_assumps
def filter_assumps(self): """ Filter out unnecessary selectors and sums from the list of assumption literals. The corresponding values are also removed from the dictionaries of bounds and weights. Note that assumptions marked as garbage are collected in the core processing methods, i.e. in :func:`process_core`, :func:`process_sels`, and :func:`process_sums`. """ self.sels = list(filter(lambda x: x not in self.garbage, self.sels)) self.sums = list(filter(lambda x: x not in self.garbage, self.sums)) self.bnds = {l: b for l, b in six.iteritems(self.bnds) if l not in self.garbage} self.wght = {l: w for l, w in six.iteritems(self.wght) if l not in self.garbage} self.garbage.clear()
python
def filter_assumps(self): """ Filter out unnecessary selectors and sums from the list of assumption literals. The corresponding values are also removed from the dictionaries of bounds and weights. Note that assumptions marked as garbage are collected in the core processing methods, i.e. in :func:`process_core`, :func:`process_sels`, and :func:`process_sums`. """ self.sels = list(filter(lambda x: x not in self.garbage, self.sels)) self.sums = list(filter(lambda x: x not in self.garbage, self.sums)) self.bnds = {l: b for l, b in six.iteritems(self.bnds) if l not in self.garbage} self.wght = {l: w for l, w in six.iteritems(self.wght) if l not in self.garbage} self.garbage.clear()
[ "def", "filter_assumps", "(", "self", ")", ":", "self", ".", "sels", "=", "list", "(", "filter", "(", "lambda", "x", ":", "x", "not", "in", "self", ".", "garbage", ",", "self", ".", "sels", ")", ")", "self", ".", "sums", "=", "list", "(", "filter", "(", "lambda", "x", ":", "x", "not", "in", "self", ".", "garbage", ",", "self", ".", "sums", ")", ")", "self", ".", "bnds", "=", "{", "l", ":", "b", "for", "l", ",", "b", "in", "six", ".", "iteritems", "(", "self", ".", "bnds", ")", "if", "l", "not", "in", "self", ".", "garbage", "}", "self", ".", "wght", "=", "{", "l", ":", "w", "for", "l", ",", "w", "in", "six", ".", "iteritems", "(", "self", ".", "wght", ")", "if", "l", "not", "in", "self", ".", "garbage", "}", "self", ".", "garbage", ".", "clear", "(", ")" ]
Filter out unnecessary selectors and sums from the list of assumption literals. The corresponding values are also removed from the dictionaries of bounds and weights. Note that assumptions marked as garbage are collected in the core processing methods, i.e. in :func:`process_core`, :func:`process_sels`, and :func:`process_sums`.
[ "Filter", "out", "unnecessary", "selectors", "and", "sums", "from", "the", "list", "of", "assumption", "literals", ".", "The", "corresponding", "values", "are", "also", "removed", "from", "the", "dictionaries", "of", "bounds", "and", "weights", "." ]
522742e8f2d4c6ac50ecd9087f7a346206774c67
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/rc2.py#L1068-L1085
17,235
Kensuke-Mitsuzawa/JapaneseTokenizers
JapaneseTokenizer/mecab_wrapper/mecab_wrapper.py
MecabWrapper.__get_path_to_mecab_config
def __get_path_to_mecab_config(self): """You get path into mecab-config """ if six.PY2: path_mecab_config_dir = subprocess.check_output(['which', 'mecab-config']) path_mecab_config_dir = path_mecab_config_dir.strip().replace('/mecab-config', '') else: path_mecab_config_dir = subprocess.check_output(['which', 'mecab-config']).decode(self.string_encoding) path_mecab_config_dir = path_mecab_config_dir.strip().replace('/mecab-config', '') logger.info(msg='mecab-config is detected at {}'.format(path_mecab_config_dir)) return path_mecab_config_dir
python
def __get_path_to_mecab_config(self): """You get path into mecab-config """ if six.PY2: path_mecab_config_dir = subprocess.check_output(['which', 'mecab-config']) path_mecab_config_dir = path_mecab_config_dir.strip().replace('/mecab-config', '') else: path_mecab_config_dir = subprocess.check_output(['which', 'mecab-config']).decode(self.string_encoding) path_mecab_config_dir = path_mecab_config_dir.strip().replace('/mecab-config', '') logger.info(msg='mecab-config is detected at {}'.format(path_mecab_config_dir)) return path_mecab_config_dir
[ "def", "__get_path_to_mecab_config", "(", "self", ")", ":", "if", "six", ".", "PY2", ":", "path_mecab_config_dir", "=", "subprocess", ".", "check_output", "(", "[", "'which'", ",", "'mecab-config'", "]", ")", "path_mecab_config_dir", "=", "path_mecab_config_dir", ".", "strip", "(", ")", ".", "replace", "(", "'/mecab-config'", ",", "''", ")", "else", ":", "path_mecab_config_dir", "=", "subprocess", ".", "check_output", "(", "[", "'which'", ",", "'mecab-config'", "]", ")", ".", "decode", "(", "self", ".", "string_encoding", ")", "path_mecab_config_dir", "=", "path_mecab_config_dir", ".", "strip", "(", ")", ".", "replace", "(", "'/mecab-config'", ",", "''", ")", "logger", ".", "info", "(", "msg", "=", "'mecab-config is detected at {}'", ".", "format", "(", "path_mecab_config_dir", ")", ")", "return", "path_mecab_config_dir" ]
You get path into mecab-config
[ "You", "get", "path", "into", "mecab", "-", "config" ]
3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c
https://github.com/Kensuke-Mitsuzawa/JapaneseTokenizers/blob/3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c/JapaneseTokenizer/mecab_wrapper/mecab_wrapper.py#L79-L90
17,236
Kensuke-Mitsuzawa/JapaneseTokenizers
JapaneseTokenizer/mecab_wrapper/mecab_wrapper.py
MecabWrapper.__result_parser
def __result_parser(self, analyzed_line, is_feature, is_surface): # type: (text_type,bool,bool)->TokenizedResult """Extract surface word and feature from analyzed line. Extracted elements are returned with TokenizedResult class """ assert isinstance(analyzed_line, str) assert isinstance(is_feature, bool) assert isinstance(is_surface, bool) surface, features = analyzed_line.split('\t', 1) tuple_pos, word_stem = self.__feature_parser(features, surface) tokenized_obj = TokenizedResult( node_obj=None, analyzed_line=analyzed_line, tuple_pos=tuple_pos, word_stem=word_stem, word_surface=surface, is_feature=is_feature, is_surface=is_surface ) return tokenized_obj
python
def __result_parser(self, analyzed_line, is_feature, is_surface): # type: (text_type,bool,bool)->TokenizedResult """Extract surface word and feature from analyzed line. Extracted elements are returned with TokenizedResult class """ assert isinstance(analyzed_line, str) assert isinstance(is_feature, bool) assert isinstance(is_surface, bool) surface, features = analyzed_line.split('\t', 1) tuple_pos, word_stem = self.__feature_parser(features, surface) tokenized_obj = TokenizedResult( node_obj=None, analyzed_line=analyzed_line, tuple_pos=tuple_pos, word_stem=word_stem, word_surface=surface, is_feature=is_feature, is_surface=is_surface ) return tokenized_obj
[ "def", "__result_parser", "(", "self", ",", "analyzed_line", ",", "is_feature", ",", "is_surface", ")", ":", "# type: (text_type,bool,bool)->TokenizedResult", "assert", "isinstance", "(", "analyzed_line", ",", "str", ")", "assert", "isinstance", "(", "is_feature", ",", "bool", ")", "assert", "isinstance", "(", "is_surface", ",", "bool", ")", "surface", ",", "features", "=", "analyzed_line", ".", "split", "(", "'\\t'", ",", "1", ")", "tuple_pos", ",", "word_stem", "=", "self", ".", "__feature_parser", "(", "features", ",", "surface", ")", "tokenized_obj", "=", "TokenizedResult", "(", "node_obj", "=", "None", ",", "analyzed_line", "=", "analyzed_line", ",", "tuple_pos", "=", "tuple_pos", ",", "word_stem", "=", "word_stem", ",", "word_surface", "=", "surface", ",", "is_feature", "=", "is_feature", ",", "is_surface", "=", "is_surface", ")", "return", "tokenized_obj" ]
Extract surface word and feature from analyzed line. Extracted elements are returned with TokenizedResult class
[ "Extract", "surface", "word", "and", "feature", "from", "analyzed", "line", ".", "Extracted", "elements", "are", "returned", "with", "TokenizedResult", "class" ]
3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c
https://github.com/Kensuke-Mitsuzawa/JapaneseTokenizers/blob/3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c/JapaneseTokenizer/mecab_wrapper/mecab_wrapper.py#L239-L259
17,237
Kensuke-Mitsuzawa/JapaneseTokenizers
JapaneseTokenizer/datamodels.py
__is_valid_pos
def __is_valid_pos(pos_tuple, valid_pos): # type: (Tuple[text_type,...],List[Tuple[text_type,...]])->bool """This function checks token's pos is with in POS set that user specified. If token meets all conditions, Return True; else return False """ def is_valid_pos(valid_pos_tuple): # type: (Tuple[text_type,...])->bool length_valid_pos_tuple = len(valid_pos_tuple) if valid_pos_tuple == pos_tuple[:length_valid_pos_tuple]: return True else: return False seq_bool_flags = [is_valid_pos(valid_pos_tuple) for valid_pos_tuple in valid_pos] if True in set(seq_bool_flags): return True else: return False
python
def __is_valid_pos(pos_tuple, valid_pos): # type: (Tuple[text_type,...],List[Tuple[text_type,...]])->bool """This function checks token's pos is with in POS set that user specified. If token meets all conditions, Return True; else return False """ def is_valid_pos(valid_pos_tuple): # type: (Tuple[text_type,...])->bool length_valid_pos_tuple = len(valid_pos_tuple) if valid_pos_tuple == pos_tuple[:length_valid_pos_tuple]: return True else: return False seq_bool_flags = [is_valid_pos(valid_pos_tuple) for valid_pos_tuple in valid_pos] if True in set(seq_bool_flags): return True else: return False
[ "def", "__is_valid_pos", "(", "pos_tuple", ",", "valid_pos", ")", ":", "# type: (Tuple[text_type,...],List[Tuple[text_type,...]])->bool", "def", "is_valid_pos", "(", "valid_pos_tuple", ")", ":", "# type: (Tuple[text_type,...])->bool", "length_valid_pos_tuple", "=", "len", "(", "valid_pos_tuple", ")", "if", "valid_pos_tuple", "==", "pos_tuple", "[", ":", "length_valid_pos_tuple", "]", ":", "return", "True", "else", ":", "return", "False", "seq_bool_flags", "=", "[", "is_valid_pos", "(", "valid_pos_tuple", ")", "for", "valid_pos_tuple", "in", "valid_pos", "]", "if", "True", "in", "set", "(", "seq_bool_flags", ")", ":", "return", "True", "else", ":", "return", "False" ]
This function checks token's pos is with in POS set that user specified. If token meets all conditions, Return True; else return False
[ "This", "function", "checks", "token", "s", "pos", "is", "with", "in", "POS", "set", "that", "user", "specified", ".", "If", "token", "meets", "all", "conditions", "Return", "True", ";", "else", "return", "False" ]
3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c
https://github.com/Kensuke-Mitsuzawa/JapaneseTokenizers/blob/3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c/JapaneseTokenizer/datamodels.py#L25-L43
17,238
Kensuke-Mitsuzawa/JapaneseTokenizers
JapaneseTokenizer/datamodels.py
filter_words
def filter_words(tokenized_obj, valid_pos, stopwords, check_field_name='stem'): # type: (TokenizedSenetence, List[Tuple[text_type,...]], List[text_type],text_type) -> FilteredObject """This function filter token that user don't want to take. Condition is stopword and pos. * Input - valid_pos - List of Tuple which has POS element to keep. - Keep in your mind, each tokenizer has different POS structure. >>> [('名詞', '固有名詞'), ('動詞', )] - stopwords - List of str, which you'd like to remove >>> ['残念', '今日'] """ assert isinstance(tokenized_obj, TokenizedSenetence) assert isinstance(valid_pos, list) assert isinstance(stopwords, list) filtered_tokens = [] for token_obj in tokenized_obj.tokenized_objects: assert isinstance(token_obj, TokenizedResult) if check_field_name=='stem': res_stopwords = __is_sotpwords(token_obj.word_stem, stopwords) else: res_stopwords = __is_sotpwords(token_obj.word_surface, stopwords) res_pos_condition = __is_valid_pos(token_obj.tuple_pos, valid_pos) # case1: only pos filtering is ON if valid_pos != [] and stopwords == []: if res_pos_condition: filtered_tokens.append(token_obj) # case2: only stopwords filtering is ON if valid_pos == [] and stopwords != []: if res_stopwords is False: filtered_tokens.append(token_obj) # case3: both condition is ON if valid_pos != [] and stopwords != []: if res_stopwords is False and res_pos_condition: filtered_tokens.append(token_obj) filtered_object = FilteredObject( sentence=tokenized_obj.sentence, tokenized_objects=filtered_tokens, pos_condition=valid_pos, stopwords=stopwords ) return filtered_object
python
def filter_words(tokenized_obj, valid_pos, stopwords, check_field_name='stem'): # type: (TokenizedSenetence, List[Tuple[text_type,...]], List[text_type],text_type) -> FilteredObject """This function filter token that user don't want to take. Condition is stopword and pos. * Input - valid_pos - List of Tuple which has POS element to keep. - Keep in your mind, each tokenizer has different POS structure. >>> [('名詞', '固有名詞'), ('動詞', )] - stopwords - List of str, which you'd like to remove >>> ['残念', '今日'] """ assert isinstance(tokenized_obj, TokenizedSenetence) assert isinstance(valid_pos, list) assert isinstance(stopwords, list) filtered_tokens = [] for token_obj in tokenized_obj.tokenized_objects: assert isinstance(token_obj, TokenizedResult) if check_field_name=='stem': res_stopwords = __is_sotpwords(token_obj.word_stem, stopwords) else: res_stopwords = __is_sotpwords(token_obj.word_surface, stopwords) res_pos_condition = __is_valid_pos(token_obj.tuple_pos, valid_pos) # case1: only pos filtering is ON if valid_pos != [] and stopwords == []: if res_pos_condition: filtered_tokens.append(token_obj) # case2: only stopwords filtering is ON if valid_pos == [] and stopwords != []: if res_stopwords is False: filtered_tokens.append(token_obj) # case3: both condition is ON if valid_pos != [] and stopwords != []: if res_stopwords is False and res_pos_condition: filtered_tokens.append(token_obj) filtered_object = FilteredObject( sentence=tokenized_obj.sentence, tokenized_objects=filtered_tokens, pos_condition=valid_pos, stopwords=stopwords ) return filtered_object
[ "def", "filter_words", "(", "tokenized_obj", ",", "valid_pos", ",", "stopwords", ",", "check_field_name", "=", "'stem'", ")", ":", "# type: (TokenizedSenetence, List[Tuple[text_type,...]], List[text_type],text_type) -> FilteredObject", "assert", "isinstance", "(", "tokenized_obj", ",", "TokenizedSenetence", ")", "assert", "isinstance", "(", "valid_pos", ",", "list", ")", "assert", "isinstance", "(", "stopwords", ",", "list", ")", "filtered_tokens", "=", "[", "]", "for", "token_obj", "in", "tokenized_obj", ".", "tokenized_objects", ":", "assert", "isinstance", "(", "token_obj", ",", "TokenizedResult", ")", "if", "check_field_name", "==", "'stem'", ":", "res_stopwords", "=", "__is_sotpwords", "(", "token_obj", ".", "word_stem", ",", "stopwords", ")", "else", ":", "res_stopwords", "=", "__is_sotpwords", "(", "token_obj", ".", "word_surface", ",", "stopwords", ")", "res_pos_condition", "=", "__is_valid_pos", "(", "token_obj", ".", "tuple_pos", ",", "valid_pos", ")", "# case1: only pos filtering is ON", "if", "valid_pos", "!=", "[", "]", "and", "stopwords", "==", "[", "]", ":", "if", "res_pos_condition", ":", "filtered_tokens", ".", "append", "(", "token_obj", ")", "# case2: only stopwords filtering is ON", "if", "valid_pos", "==", "[", "]", "and", "stopwords", "!=", "[", "]", ":", "if", "res_stopwords", "is", "False", ":", "filtered_tokens", ".", "append", "(", "token_obj", ")", "# case3: both condition is ON", "if", "valid_pos", "!=", "[", "]", "and", "stopwords", "!=", "[", "]", ":", "if", "res_stopwords", "is", "False", "and", "res_pos_condition", ":", "filtered_tokens", ".", "append", "(", "token_obj", ")", "filtered_object", "=", "FilteredObject", "(", "sentence", "=", "tokenized_obj", ".", "sentence", ",", "tokenized_objects", "=", "filtered_tokens", ",", "pos_condition", "=", "valid_pos", ",", "stopwords", "=", "stopwords", ")", "return", "filtered_object" ]
This function filter token that user don't want to take. Condition is stopword and pos. * Input - valid_pos - List of Tuple which has POS element to keep. - Keep in your mind, each tokenizer has different POS structure. >>> [('名詞', '固有名詞'), ('動詞', )] - stopwords - List of str, which you'd like to remove >>> ['残念', '今日']
[ "This", "function", "filter", "token", "that", "user", "don", "t", "want", "to", "take", ".", "Condition", "is", "stopword", "and", "pos", "." ]
3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c
https://github.com/Kensuke-Mitsuzawa/JapaneseTokenizers/blob/3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c/JapaneseTokenizer/datamodels.py#L46-L91
17,239
Kensuke-Mitsuzawa/JapaneseTokenizers
JapaneseTokenizer/datamodels.py
TokenizedSenetence.__extend_token_object
def __extend_token_object(self, token_object, is_denormalize=True, func_denormalizer=denormalize_text): # type: (TokenizedResult,bool,Callable[[str],str])->Tuple """This method creates dict object from token object. """ assert isinstance(token_object, TokenizedResult) if is_denormalize: if token_object.is_feature == True: if token_object.is_surface == True: token = (func_denormalizer(token_object.word_surface), token_object.tuple_pos) else: token = (func_denormalizer(token_object.word_stem), token_object.tuple_pos) else: if token_object.is_surface == True: token = func_denormalizer(token_object.word_surface) else: token = func_denormalizer(token_object.word_stem) else: if token_object.is_feature == True: if token_object.is_surface == True: token = (token_object.word_surface, token_object.tuple_pos) else: token = (token_object.word_stem, token_object.tuple_pos) else: if token_object.is_surface == True: token = token_object.word_surface else: token = token_object.word_stem return token
python
def __extend_token_object(self, token_object, is_denormalize=True, func_denormalizer=denormalize_text): # type: (TokenizedResult,bool,Callable[[str],str])->Tuple """This method creates dict object from token object. """ assert isinstance(token_object, TokenizedResult) if is_denormalize: if token_object.is_feature == True: if token_object.is_surface == True: token = (func_denormalizer(token_object.word_surface), token_object.tuple_pos) else: token = (func_denormalizer(token_object.word_stem), token_object.tuple_pos) else: if token_object.is_surface == True: token = func_denormalizer(token_object.word_surface) else: token = func_denormalizer(token_object.word_stem) else: if token_object.is_feature == True: if token_object.is_surface == True: token = (token_object.word_surface, token_object.tuple_pos) else: token = (token_object.word_stem, token_object.tuple_pos) else: if token_object.is_surface == True: token = token_object.word_surface else: token = token_object.word_stem return token
[ "def", "__extend_token_object", "(", "self", ",", "token_object", ",", "is_denormalize", "=", "True", ",", "func_denormalizer", "=", "denormalize_text", ")", ":", "# type: (TokenizedResult,bool,Callable[[str],str])->Tuple", "assert", "isinstance", "(", "token_object", ",", "TokenizedResult", ")", "if", "is_denormalize", ":", "if", "token_object", ".", "is_feature", "==", "True", ":", "if", "token_object", ".", "is_surface", "==", "True", ":", "token", "=", "(", "func_denormalizer", "(", "token_object", ".", "word_surface", ")", ",", "token_object", ".", "tuple_pos", ")", "else", ":", "token", "=", "(", "func_denormalizer", "(", "token_object", ".", "word_stem", ")", ",", "token_object", ".", "tuple_pos", ")", "else", ":", "if", "token_object", ".", "is_surface", "==", "True", ":", "token", "=", "func_denormalizer", "(", "token_object", ".", "word_surface", ")", "else", ":", "token", "=", "func_denormalizer", "(", "token_object", ".", "word_stem", ")", "else", ":", "if", "token_object", ".", "is_feature", "==", "True", ":", "if", "token_object", ".", "is_surface", "==", "True", ":", "token", "=", "(", "token_object", ".", "word_surface", ",", "token_object", ".", "tuple_pos", ")", "else", ":", "token", "=", "(", "token_object", ".", "word_stem", ",", "token_object", ".", "tuple_pos", ")", "else", ":", "if", "token_object", ".", "is_surface", "==", "True", ":", "token", "=", "token_object", ".", "word_surface", "else", ":", "token", "=", "token_object", ".", "word_stem", "return", "token" ]
This method creates dict object from token object.
[ "This", "method", "creates", "dict", "object", "from", "token", "object", "." ]
3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c
https://github.com/Kensuke-Mitsuzawa/JapaneseTokenizers/blob/3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c/JapaneseTokenizer/datamodels.py#L143-L174
17,240
mosquito/cysystemd
cysystemd/daemon.py
notify
def notify(notification, value=None, unset_environment=False): """ Send notification to systemd daemon :type notification: Notification :type value: int :type unset_environment: bool :param value: str or int value for non constant notifications :returns None """ if not isinstance(notification, Notification): raise TypeError("state must be an instance of Notification") state = notification.value if state.constant is not None and value: raise ValueError( "State %s should contain only constant value %r" % (state.name, state.constant), state.name, state.constant ) line = "%s=%s" % ( state.name, state.constant if state.constant is not None else state.type(value) ) log.debug("Send %r into systemd", line) try: return sd_notify(line, unset_environment) except Exception as e: log.error("%s", e)
python
def notify(notification, value=None, unset_environment=False): """ Send notification to systemd daemon :type notification: Notification :type value: int :type unset_environment: bool :param value: str or int value for non constant notifications :returns None """ if not isinstance(notification, Notification): raise TypeError("state must be an instance of Notification") state = notification.value if state.constant is not None and value: raise ValueError( "State %s should contain only constant value %r" % (state.name, state.constant), state.name, state.constant ) line = "%s=%s" % ( state.name, state.constant if state.constant is not None else state.type(value) ) log.debug("Send %r into systemd", line) try: return sd_notify(line, unset_environment) except Exception as e: log.error("%s", e)
[ "def", "notify", "(", "notification", ",", "value", "=", "None", ",", "unset_environment", "=", "False", ")", ":", "if", "not", "isinstance", "(", "notification", ",", "Notification", ")", ":", "raise", "TypeError", "(", "\"state must be an instance of Notification\"", ")", "state", "=", "notification", ".", "value", "if", "state", ".", "constant", "is", "not", "None", "and", "value", ":", "raise", "ValueError", "(", "\"State %s should contain only constant value %r\"", "%", "(", "state", ".", "name", ",", "state", ".", "constant", ")", ",", "state", ".", "name", ",", "state", ".", "constant", ")", "line", "=", "\"%s=%s\"", "%", "(", "state", ".", "name", ",", "state", ".", "constant", "if", "state", ".", "constant", "is", "not", "None", "else", "state", ".", "type", "(", "value", ")", ")", "log", ".", "debug", "(", "\"Send %r into systemd\"", ",", "line", ")", "try", ":", "return", "sd_notify", "(", "line", ",", "unset_environment", ")", "except", "Exception", "as", "e", ":", "log", ".", "error", "(", "\"%s\"", ",", "e", ")" ]
Send notification to systemd daemon :type notification: Notification :type value: int :type unset_environment: bool :param value: str or int value for non constant notifications :returns None
[ "Send", "notification", "to", "systemd", "daemon" ]
e0acede93387d51e4d6b20fdc278b2675052958d
https://github.com/mosquito/cysystemd/blob/e0acede93387d51e4d6b20fdc278b2675052958d/cysystemd/daemon.py#L28-L59
17,241
Pylons/hupper
src/hupper/worker.py
expand_source_paths
def expand_source_paths(paths): """ Convert pyc files into their source equivalents.""" for src_path in paths: # only track the source path if we can find it to avoid double-reloads # when the source and the compiled path change because on some # platforms they are not changed at the same time if src_path.endswith(('.pyc', '.pyo')): py_path = get_py_path(src_path) if os.path.exists(py_path): src_path = py_path yield src_path
python
def expand_source_paths(paths): """ Convert pyc files into their source equivalents.""" for src_path in paths: # only track the source path if we can find it to avoid double-reloads # when the source and the compiled path change because on some # platforms they are not changed at the same time if src_path.endswith(('.pyc', '.pyo')): py_path = get_py_path(src_path) if os.path.exists(py_path): src_path = py_path yield src_path
[ "def", "expand_source_paths", "(", "paths", ")", ":", "for", "src_path", "in", "paths", ":", "# only track the source path if we can find it to avoid double-reloads", "# when the source and the compiled path change because on some", "# platforms they are not changed at the same time", "if", "src_path", ".", "endswith", "(", "(", "'.pyc'", ",", "'.pyo'", ")", ")", ":", "py_path", "=", "get_py_path", "(", "src_path", ")", "if", "os", ".", "path", ".", "exists", "(", "py_path", ")", ":", "src_path", "=", "py_path", "yield", "src_path" ]
Convert pyc files into their source equivalents.
[ "Convert", "pyc", "files", "into", "their", "source", "equivalents", "." ]
197173c09e775b66c148468b6299c571e736c381
https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/worker.py#L84-L94
17,242
Pylons/hupper
src/hupper/worker.py
iter_module_paths
def iter_module_paths(modules=None): """ Yield paths of all imported modules.""" modules = modules or list(sys.modules.values()) for module in modules: try: filename = module.__file__ except (AttributeError, ImportError): # pragma: no cover continue if filename is not None: abs_filename = os.path.abspath(filename) if os.path.isfile(abs_filename): yield abs_filename
python
def iter_module_paths(modules=None): """ Yield paths of all imported modules.""" modules = modules or list(sys.modules.values()) for module in modules: try: filename = module.__file__ except (AttributeError, ImportError): # pragma: no cover continue if filename is not None: abs_filename = os.path.abspath(filename) if os.path.isfile(abs_filename): yield abs_filename
[ "def", "iter_module_paths", "(", "modules", "=", "None", ")", ":", "modules", "=", "modules", "or", "list", "(", "sys", ".", "modules", ".", "values", "(", ")", ")", "for", "module", "in", "modules", ":", "try", ":", "filename", "=", "module", ".", "__file__", "except", "(", "AttributeError", ",", "ImportError", ")", ":", "# pragma: no cover", "continue", "if", "filename", "is", "not", "None", ":", "abs_filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "if", "os", ".", "path", ".", "isfile", "(", "abs_filename", ")", ":", "yield", "abs_filename" ]
Yield paths of all imported modules.
[ "Yield", "paths", "of", "all", "imported", "modules", "." ]
197173c09e775b66c148468b6299c571e736c381
https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/worker.py#L97-L108
17,243
Pylons/hupper
src/hupper/worker.py
WatchSysModules.update_paths
def update_paths(self): """ Check sys.modules for paths to add to our path set.""" new_paths = [] with self.lock: for path in expand_source_paths(iter_module_paths()): if path not in self.paths: self.paths.add(path) new_paths.append(path) if new_paths: self.watch_paths(new_paths)
python
def update_paths(self): """ Check sys.modules for paths to add to our path set.""" new_paths = [] with self.lock: for path in expand_source_paths(iter_module_paths()): if path not in self.paths: self.paths.add(path) new_paths.append(path) if new_paths: self.watch_paths(new_paths)
[ "def", "update_paths", "(", "self", ")", ":", "new_paths", "=", "[", "]", "with", "self", ".", "lock", ":", "for", "path", "in", "expand_source_paths", "(", "iter_module_paths", "(", ")", ")", ":", "if", "path", "not", "in", "self", ".", "paths", ":", "self", ".", "paths", ".", "add", "(", "path", ")", "new_paths", ".", "append", "(", "path", ")", "if", "new_paths", ":", "self", ".", "watch_paths", "(", "new_paths", ")" ]
Check sys.modules for paths to add to our path set.
[ "Check", "sys", ".", "modules", "for", "paths", "to", "add", "to", "our", "path", "set", "." ]
197173c09e775b66c148468b6299c571e736c381
https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/worker.py#L39-L48
17,244
Pylons/hupper
src/hupper/worker.py
WatchSysModules.search_traceback
def search_traceback(self, tb): """ Inspect a traceback for new paths to add to our path set.""" new_paths = [] with self.lock: for filename, line, funcname, txt in traceback.extract_tb(tb): path = os.path.abspath(filename) if path not in self.paths: self.paths.add(path) new_paths.append(path) if new_paths: self.watch_paths(new_paths)
python
def search_traceback(self, tb): """ Inspect a traceback for new paths to add to our path set.""" new_paths = [] with self.lock: for filename, line, funcname, txt in traceback.extract_tb(tb): path = os.path.abspath(filename) if path not in self.paths: self.paths.add(path) new_paths.append(path) if new_paths: self.watch_paths(new_paths)
[ "def", "search_traceback", "(", "self", ",", "tb", ")", ":", "new_paths", "=", "[", "]", "with", "self", ".", "lock", ":", "for", "filename", ",", "line", ",", "funcname", ",", "txt", "in", "traceback", ".", "extract_tb", "(", "tb", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "if", "path", "not", "in", "self", ".", "paths", ":", "self", ".", "paths", ".", "add", "(", "path", ")", "new_paths", ".", "append", "(", "path", ")", "if", "new_paths", ":", "self", ".", "watch_paths", "(", "new_paths", ")" ]
Inspect a traceback for new paths to add to our path set.
[ "Inspect", "a", "traceback", "for", "new", "paths", "to", "add", "to", "our", "path", "set", "." ]
197173c09e775b66c148468b6299c571e736c381
https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/worker.py#L50-L60
17,245
Pylons/hupper
src/hupper/ipc.py
args_from_interpreter_flags
def args_from_interpreter_flags(): """ Return a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions. """ flag_opt_map = { 'debug': 'd', 'dont_write_bytecode': 'B', 'no_user_site': 's', 'no_site': 'S', 'ignore_environment': 'E', 'verbose': 'v', 'bytes_warning': 'b', 'quiet': 'q', 'optimize': 'O', } args = [] for flag, opt in flag_opt_map.items(): v = getattr(sys.flags, flag, 0) if v > 0: args.append('-' + opt * v) for opt in sys.warnoptions: args.append('-W' + opt) return args
python
def args_from_interpreter_flags(): """ Return a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions. """ flag_opt_map = { 'debug': 'd', 'dont_write_bytecode': 'B', 'no_user_site': 's', 'no_site': 'S', 'ignore_environment': 'E', 'verbose': 'v', 'bytes_warning': 'b', 'quiet': 'q', 'optimize': 'O', } args = [] for flag, opt in flag_opt_map.items(): v = getattr(sys.flags, flag, 0) if v > 0: args.append('-' + opt * v) for opt in sys.warnoptions: args.append('-W' + opt) return args
[ "def", "args_from_interpreter_flags", "(", ")", ":", "flag_opt_map", "=", "{", "'debug'", ":", "'d'", ",", "'dont_write_bytecode'", ":", "'B'", ",", "'no_user_site'", ":", "'s'", ",", "'no_site'", ":", "'S'", ",", "'ignore_environment'", ":", "'E'", ",", "'verbose'", ":", "'v'", ",", "'bytes_warning'", ":", "'b'", ",", "'quiet'", ":", "'q'", ",", "'optimize'", ":", "'O'", ",", "}", "args", "=", "[", "]", "for", "flag", ",", "opt", "in", "flag_opt_map", ".", "items", "(", ")", ":", "v", "=", "getattr", "(", "sys", ".", "flags", ",", "flag", ",", "0", ")", "if", "v", ">", "0", ":", "args", ".", "append", "(", "'-'", "+", "opt", "*", "v", ")", "for", "opt", "in", "sys", ".", "warnoptions", ":", "args", ".", "append", "(", "'-W'", "+", "opt", ")", "return", "args" ]
Return a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions.
[ "Return", "a", "list", "of", "command", "-", "line", "arguments", "reproducing", "the", "current", "settings", "in", "sys", ".", "flags", "and", "sys", ".", "warnoptions", "." ]
197173c09e775b66c148468b6299c571e736c381
https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/ipc.py#L221-L245
17,246
Pylons/hupper
src/hupper/ipc.py
spawn
def spawn(spec, kwargs, pass_fds=()): """ Invoke a python function in a subprocess. """ r, w = os.pipe() for fd in [r] + list(pass_fds): set_inheritable(fd, True) preparation_data = get_preparation_data() r_handle = get_handle(r) args, env = get_command_line(pipe_handle=r_handle) process = subprocess.Popen(args, env=env, close_fds=False) to_child = os.fdopen(w, 'wb') to_child.write(pickle.dumps([preparation_data, spec, kwargs])) to_child.close() return process
python
def spawn(spec, kwargs, pass_fds=()): """ Invoke a python function in a subprocess. """ r, w = os.pipe() for fd in [r] + list(pass_fds): set_inheritable(fd, True) preparation_data = get_preparation_data() r_handle = get_handle(r) args, env = get_command_line(pipe_handle=r_handle) process = subprocess.Popen(args, env=env, close_fds=False) to_child = os.fdopen(w, 'wb') to_child.write(pickle.dumps([preparation_data, spec, kwargs])) to_child.close() return process
[ "def", "spawn", "(", "spec", ",", "kwargs", ",", "pass_fds", "=", "(", ")", ")", ":", "r", ",", "w", "=", "os", ".", "pipe", "(", ")", "for", "fd", "in", "[", "r", "]", "+", "list", "(", "pass_fds", ")", ":", "set_inheritable", "(", "fd", ",", "True", ")", "preparation_data", "=", "get_preparation_data", "(", ")", "r_handle", "=", "get_handle", "(", "r", ")", "args", ",", "env", "=", "get_command_line", "(", "pipe_handle", "=", "r_handle", ")", "process", "=", "subprocess", ".", "Popen", "(", "args", ",", "env", "=", "env", ",", "close_fds", "=", "False", ")", "to_child", "=", "os", ".", "fdopen", "(", "w", ",", "'wb'", ")", "to_child", ".", "write", "(", "pickle", ".", "dumps", "(", "[", "preparation_data", ",", "spec", ",", "kwargs", "]", ")", ")", "to_child", ".", "close", "(", ")", "return", "process" ]
Invoke a python function in a subprocess.
[ "Invoke", "a", "python", "function", "in", "a", "subprocess", "." ]
197173c09e775b66c148468b6299c571e736c381
https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/ipc.py#L287-L306
17,247
Pylons/hupper
src/hupper/utils.py
get_watchman_sockpath
def get_watchman_sockpath(binpath='watchman'): """ Find the watchman socket or raise.""" path = os.getenv('WATCHMAN_SOCK') if path: return path cmd = [binpath, '--output-encoding=json', 'get-sockname'] result = subprocess.check_output(cmd) result = json.loads(result) return result['sockname']
python
def get_watchman_sockpath(binpath='watchman'): """ Find the watchman socket or raise.""" path = os.getenv('WATCHMAN_SOCK') if path: return path cmd = [binpath, '--output-encoding=json', 'get-sockname'] result = subprocess.check_output(cmd) result = json.loads(result) return result['sockname']
[ "def", "get_watchman_sockpath", "(", "binpath", "=", "'watchman'", ")", ":", "path", "=", "os", ".", "getenv", "(", "'WATCHMAN_SOCK'", ")", "if", "path", ":", "return", "path", "cmd", "=", "[", "binpath", ",", "'--output-encoding=json'", ",", "'get-sockname'", "]", "result", "=", "subprocess", ".", "check_output", "(", "cmd", ")", "result", "=", "json", ".", "loads", "(", "result", ")", "return", "result", "[", "'sockname'", "]" ]
Find the watchman socket or raise.
[ "Find", "the", "watchman", "socket", "or", "raise", "." ]
197173c09e775b66c148468b6299c571e736c381
https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/utils.py#L49-L58
17,248
Pylons/hupper
src/hupper/reloader.py
start_reloader
def start_reloader( worker_path, reload_interval=1, shutdown_interval=default, verbose=1, logger=None, monitor_factory=None, worker_args=None, worker_kwargs=None, ignore_files=None, ): """ Start a monitor and then fork a worker process which starts by executing the importable function at ``worker_path``. If this function is called from a worker process that is already being monitored then it will return a reference to the current :class:`hupper.interfaces.IReloaderProxy` which can be used to communicate with the monitor. ``worker_path`` must be a dotted string pointing to a globally importable function that will be executed to start the worker. An example could be ``myapp.cli.main``. In most cases it will point at the same function that is invoking ``start_reloader`` in the first place. ``reload_interval`` is a value in seconds and will be used to throttle restarts. Default is ``1``. ``shutdown_interval`` is a value in seconds and will be used to trigger a graceful shutdown of the server. Set to ``None`` to disable the graceful shutdown. Default is the same as ``reload_interval``. ``verbose`` controls the output. Set to ``0`` to turn off any logging of activity and turn up to ``2`` for extra output. Default is ``1``. ``logger``, if supplied, supersedes ``verbose`` and should be an object implementing :class:`hupper.interfaces.ILogger`. ``monitor_factory`` is an instance of :class:`hupper.interfaces.IFileMonitorFactory`. If left unspecified, this will try to create a :class:`hupper.watchdog.WatchdogFileMonitor` if `watchdog <https://pypi.org/project/watchdog/>`_ is installed and will fallback to the less efficient :class:`hupper.polling.PollingFileMonitor` otherwise. If ``monitor_factory`` is ``None`` it can be overridden by the ``HUPPER_DEFAULT_MONITOR`` environment variable. It should be a dotted python path pointing at an object implementing :class:`hupper.interfaces.IFileMonitorFactory`. ``ignore_files`` if provided must be an iterable of shell-style patterns to ignore. """ if is_active(): return get_reloader() if logger is None: logger = DefaultLogger(verbose) if monitor_factory is None: monitor_factory = find_default_monitor_factory(logger) if shutdown_interval is default: shutdown_interval = reload_interval reloader = Reloader( worker_path=worker_path, worker_args=worker_args, worker_kwargs=worker_kwargs, reload_interval=reload_interval, shutdown_interval=shutdown_interval, monitor_factory=monitor_factory, logger=logger, ignore_files=ignore_files, ) return reloader.run()
python
def start_reloader( worker_path, reload_interval=1, shutdown_interval=default, verbose=1, logger=None, monitor_factory=None, worker_args=None, worker_kwargs=None, ignore_files=None, ): """ Start a monitor and then fork a worker process which starts by executing the importable function at ``worker_path``. If this function is called from a worker process that is already being monitored then it will return a reference to the current :class:`hupper.interfaces.IReloaderProxy` which can be used to communicate with the monitor. ``worker_path`` must be a dotted string pointing to a globally importable function that will be executed to start the worker. An example could be ``myapp.cli.main``. In most cases it will point at the same function that is invoking ``start_reloader`` in the first place. ``reload_interval`` is a value in seconds and will be used to throttle restarts. Default is ``1``. ``shutdown_interval`` is a value in seconds and will be used to trigger a graceful shutdown of the server. Set to ``None`` to disable the graceful shutdown. Default is the same as ``reload_interval``. ``verbose`` controls the output. Set to ``0`` to turn off any logging of activity and turn up to ``2`` for extra output. Default is ``1``. ``logger``, if supplied, supersedes ``verbose`` and should be an object implementing :class:`hupper.interfaces.ILogger`. ``monitor_factory`` is an instance of :class:`hupper.interfaces.IFileMonitorFactory`. If left unspecified, this will try to create a :class:`hupper.watchdog.WatchdogFileMonitor` if `watchdog <https://pypi.org/project/watchdog/>`_ is installed and will fallback to the less efficient :class:`hupper.polling.PollingFileMonitor` otherwise. If ``monitor_factory`` is ``None`` it can be overridden by the ``HUPPER_DEFAULT_MONITOR`` environment variable. It should be a dotted python path pointing at an object implementing :class:`hupper.interfaces.IFileMonitorFactory`. ``ignore_files`` if provided must be an iterable of shell-style patterns to ignore. """ if is_active(): return get_reloader() if logger is None: logger = DefaultLogger(verbose) if monitor_factory is None: monitor_factory = find_default_monitor_factory(logger) if shutdown_interval is default: shutdown_interval = reload_interval reloader = Reloader( worker_path=worker_path, worker_args=worker_args, worker_kwargs=worker_kwargs, reload_interval=reload_interval, shutdown_interval=shutdown_interval, monitor_factory=monitor_factory, logger=logger, ignore_files=ignore_files, ) return reloader.run()
[ "def", "start_reloader", "(", "worker_path", ",", "reload_interval", "=", "1", ",", "shutdown_interval", "=", "default", ",", "verbose", "=", "1", ",", "logger", "=", "None", ",", "monitor_factory", "=", "None", ",", "worker_args", "=", "None", ",", "worker_kwargs", "=", "None", ",", "ignore_files", "=", "None", ",", ")", ":", "if", "is_active", "(", ")", ":", "return", "get_reloader", "(", ")", "if", "logger", "is", "None", ":", "logger", "=", "DefaultLogger", "(", "verbose", ")", "if", "monitor_factory", "is", "None", ":", "monitor_factory", "=", "find_default_monitor_factory", "(", "logger", ")", "if", "shutdown_interval", "is", "default", ":", "shutdown_interval", "=", "reload_interval", "reloader", "=", "Reloader", "(", "worker_path", "=", "worker_path", ",", "worker_args", "=", "worker_args", ",", "worker_kwargs", "=", "worker_kwargs", ",", "reload_interval", "=", "reload_interval", ",", "shutdown_interval", "=", "shutdown_interval", ",", "monitor_factory", "=", "monitor_factory", ",", "logger", "=", "logger", ",", "ignore_files", "=", "ignore_files", ",", ")", "return", "reloader", ".", "run", "(", ")" ]
Start a monitor and then fork a worker process which starts by executing the importable function at ``worker_path``. If this function is called from a worker process that is already being monitored then it will return a reference to the current :class:`hupper.interfaces.IReloaderProxy` which can be used to communicate with the monitor. ``worker_path`` must be a dotted string pointing to a globally importable function that will be executed to start the worker. An example could be ``myapp.cli.main``. In most cases it will point at the same function that is invoking ``start_reloader`` in the first place. ``reload_interval`` is a value in seconds and will be used to throttle restarts. Default is ``1``. ``shutdown_interval`` is a value in seconds and will be used to trigger a graceful shutdown of the server. Set to ``None`` to disable the graceful shutdown. Default is the same as ``reload_interval``. ``verbose`` controls the output. Set to ``0`` to turn off any logging of activity and turn up to ``2`` for extra output. Default is ``1``. ``logger``, if supplied, supersedes ``verbose`` and should be an object implementing :class:`hupper.interfaces.ILogger`. ``monitor_factory`` is an instance of :class:`hupper.interfaces.IFileMonitorFactory`. If left unspecified, this will try to create a :class:`hupper.watchdog.WatchdogFileMonitor` if `watchdog <https://pypi.org/project/watchdog/>`_ is installed and will fallback to the less efficient :class:`hupper.polling.PollingFileMonitor` otherwise. If ``monitor_factory`` is ``None`` it can be overridden by the ``HUPPER_DEFAULT_MONITOR`` environment variable. It should be a dotted python path pointing at an object implementing :class:`hupper.interfaces.IFileMonitorFactory`. ``ignore_files`` if provided must be an iterable of shell-style patterns to ignore.
[ "Start", "a", "monitor", "and", "then", "fork", "a", "worker", "process", "which", "starts", "by", "executing", "the", "importable", "function", "at", "worker_path", "." ]
197173c09e775b66c148468b6299c571e736c381
https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/reloader.py#L289-L364
17,249
Pylons/hupper
src/hupper/reloader.py
Reloader.run
def run(self): """ Execute the reloader forever, blocking the current thread. This will invoke ``sys.exit(1)`` if interrupted. """ self._capture_signals() self._start_monitor() try: while True: if not self._run_worker(): self._wait_for_changes() time.sleep(self.reload_interval) except KeyboardInterrupt: pass finally: self._stop_monitor() self._restore_signals() sys.exit(1)
python
def run(self): """ Execute the reloader forever, blocking the current thread. This will invoke ``sys.exit(1)`` if interrupted. """ self._capture_signals() self._start_monitor() try: while True: if not self._run_worker(): self._wait_for_changes() time.sleep(self.reload_interval) except KeyboardInterrupt: pass finally: self._stop_monitor() self._restore_signals() sys.exit(1)
[ "def", "run", "(", "self", ")", ":", "self", ".", "_capture_signals", "(", ")", "self", ".", "_start_monitor", "(", ")", "try", ":", "while", "True", ":", "if", "not", "self", ".", "_run_worker", "(", ")", ":", "self", ".", "_wait_for_changes", "(", ")", "time", ".", "sleep", "(", "self", ".", "reload_interval", ")", "except", "KeyboardInterrupt", ":", "pass", "finally", ":", "self", ".", "_stop_monitor", "(", ")", "self", ".", "_restore_signals", "(", ")", "sys", ".", "exit", "(", "1", ")" ]
Execute the reloader forever, blocking the current thread. This will invoke ``sys.exit(1)`` if interrupted.
[ "Execute", "the", "reloader", "forever", "blocking", "the", "current", "thread", "." ]
197173c09e775b66c148468b6299c571e736c381
https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/reloader.py#L102-L121
17,250
Pylons/hupper
src/hupper/reloader.py
Reloader.run_once
def run_once(self): """ Execute the worker once. This method will return after a file change is detected. """ self._capture_signals() self._start_monitor() try: self._run_worker() except KeyboardInterrupt: return finally: self._stop_monitor() self._restore_signals()
python
def run_once(self): """ Execute the worker once. This method will return after a file change is detected. """ self._capture_signals() self._start_monitor() try: self._run_worker() except KeyboardInterrupt: return finally: self._stop_monitor() self._restore_signals()
[ "def", "run_once", "(", "self", ")", ":", "self", ".", "_capture_signals", "(", ")", "self", ".", "_start_monitor", "(", ")", "try", ":", "self", ".", "_run_worker", "(", ")", "except", "KeyboardInterrupt", ":", "return", "finally", ":", "self", ".", "_stop_monitor", "(", ")", "self", ".", "_restore_signals", "(", ")" ]
Execute the worker once. This method will return after a file change is detected.
[ "Execute", "the", "worker", "once", "." ]
197173c09e775b66c148468b6299c571e736c381
https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/reloader.py#L123-L138
17,251
BYU-PCCL/holodeck
holodeck/holodeckclient.py
HolodeckClient.malloc
def malloc(self, key, shape, dtype): """Allocates a block of shared memory, and returns a numpy array whose data corresponds with that block. Args: key (str): The key to identify the block. shape (list of int): The shape of the numpy array to allocate. dtype (type): The numpy data type (e.g. np.float32). Returns: np.ndarray: The numpy array that is positioned on the shared memory. """ if key not in self._memory or self._memory[key].shape != shape or self._memory[key].dtype != dtype: self._memory[key] = Shmem(key, shape, dtype, self._uuid) return self._memory[key].np_array
python
def malloc(self, key, shape, dtype): """Allocates a block of shared memory, and returns a numpy array whose data corresponds with that block. Args: key (str): The key to identify the block. shape (list of int): The shape of the numpy array to allocate. dtype (type): The numpy data type (e.g. np.float32). Returns: np.ndarray: The numpy array that is positioned on the shared memory. """ if key not in self._memory or self._memory[key].shape != shape or self._memory[key].dtype != dtype: self._memory[key] = Shmem(key, shape, dtype, self._uuid) return self._memory[key].np_array
[ "def", "malloc", "(", "self", ",", "key", ",", "shape", ",", "dtype", ")", ":", "if", "key", "not", "in", "self", ".", "_memory", "or", "self", ".", "_memory", "[", "key", "]", ".", "shape", "!=", "shape", "or", "self", ".", "_memory", "[", "key", "]", ".", "dtype", "!=", "dtype", ":", "self", ".", "_memory", "[", "key", "]", "=", "Shmem", "(", "key", ",", "shape", ",", "dtype", ",", "self", ".", "_uuid", ")", "return", "self", ".", "_memory", "[", "key", "]", ".", "np_array" ]
Allocates a block of shared memory, and returns a numpy array whose data corresponds with that block. Args: key (str): The key to identify the block. shape (list of int): The shape of the numpy array to allocate. dtype (type): The numpy data type (e.g. np.float32). Returns: np.ndarray: The numpy array that is positioned on the shared memory.
[ "Allocates", "a", "block", "of", "shared", "memory", "and", "returns", "a", "numpy", "array", "whose", "data", "corresponds", "with", "that", "block", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/holodeckclient.py#L88-L102
17,252
BYU-PCCL/holodeck
holodeck/packagemanager.py
package_info
def package_info(pkg_name): """Prints the information of a package. Args: pkg_name (str): The name of the desired package to get information """ indent = " " for config, _ in _iter_packages(): if pkg_name == config["name"]: print("Package:", pkg_name) print(indent, "Platform:", config["platform"]) print(indent, "Version:", config["version"]) print(indent, "Path:", config["path"]) print(indent, "Worlds:") for world in config["maps"]: world_info(world["name"], world_config=world, initial_indent=" ")
python
def package_info(pkg_name): """Prints the information of a package. Args: pkg_name (str): The name of the desired package to get information """ indent = " " for config, _ in _iter_packages(): if pkg_name == config["name"]: print("Package:", pkg_name) print(indent, "Platform:", config["platform"]) print(indent, "Version:", config["version"]) print(indent, "Path:", config["path"]) print(indent, "Worlds:") for world in config["maps"]: world_info(world["name"], world_config=world, initial_indent=" ")
[ "def", "package_info", "(", "pkg_name", ")", ":", "indent", "=", "\" \"", "for", "config", ",", "_", "in", "_iter_packages", "(", ")", ":", "if", "pkg_name", "==", "config", "[", "\"name\"", "]", ":", "print", "(", "\"Package:\"", ",", "pkg_name", ")", "print", "(", "indent", ",", "\"Platform:\"", ",", "config", "[", "\"platform\"", "]", ")", "print", "(", "indent", ",", "\"Version:\"", ",", "config", "[", "\"version\"", "]", ")", "print", "(", "indent", ",", "\"Path:\"", ",", "config", "[", "\"path\"", "]", ")", "print", "(", "indent", ",", "\"Worlds:\"", ")", "for", "world", "in", "config", "[", "\"maps\"", "]", ":", "world_info", "(", "world", "[", "\"name\"", "]", ",", "world_config", "=", "world", ",", "initial_indent", "=", "\" \"", ")" ]
Prints the information of a package. Args: pkg_name (str): The name of the desired package to get information
[ "Prints", "the", "information", "of", "a", "package", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/packagemanager.py#L38-L53
17,253
BYU-PCCL/holodeck
holodeck/packagemanager.py
world_info
def world_info(world_name, world_config=None, initial_indent="", next_indent=" "): """Gets and prints the information of a world. Args: world_name (str): the name of the world to retrieve information for world_config (dict optional): A dictionary containing the world's configuration. Will find the config if None. Defaults to None. initial_indent (str optional): This indent will apply to each output line. Defaults to "". next_indent (str optional): This indent will be applied within each nested line. Defaults to " ". """ if world_config is None: for config, _ in _iter_packages(): for world in config["maps"]: if world["name"] == world_name: world_config = world if world_config is None: raise HolodeckException("Couldn't find world " + world_name) second_indent = initial_indent + next_indent agent_indent = second_indent + next_indent sensor_indent = agent_indent + next_indent print(initial_indent, world_config["name"]) print(second_indent, "Resolution:", world_config["window_width"], "x", world_config["window_height"]) print(second_indent, "Agents:") for agent in world_config["agents"]: print(agent_indent, "Name:", agent["agent_name"]) print(agent_indent, "Type:", agent["agent_type"]) print(agent_indent, "Sensors:") for sensor in agent["sensors"]: print(sensor_indent, sensor)
python
def world_info(world_name, world_config=None, initial_indent="", next_indent=" "): """Gets and prints the information of a world. Args: world_name (str): the name of the world to retrieve information for world_config (dict optional): A dictionary containing the world's configuration. Will find the config if None. Defaults to None. initial_indent (str optional): This indent will apply to each output line. Defaults to "". next_indent (str optional): This indent will be applied within each nested line. Defaults to " ". """ if world_config is None: for config, _ in _iter_packages(): for world in config["maps"]: if world["name"] == world_name: world_config = world if world_config is None: raise HolodeckException("Couldn't find world " + world_name) second_indent = initial_indent + next_indent agent_indent = second_indent + next_indent sensor_indent = agent_indent + next_indent print(initial_indent, world_config["name"]) print(second_indent, "Resolution:", world_config["window_width"], "x", world_config["window_height"]) print(second_indent, "Agents:") for agent in world_config["agents"]: print(agent_indent, "Name:", agent["agent_name"]) print(agent_indent, "Type:", agent["agent_type"]) print(agent_indent, "Sensors:") for sensor in agent["sensors"]: print(sensor_indent, sensor)
[ "def", "world_info", "(", "world_name", ",", "world_config", "=", "None", ",", "initial_indent", "=", "\"\"", ",", "next_indent", "=", "\" \"", ")", ":", "if", "world_config", "is", "None", ":", "for", "config", ",", "_", "in", "_iter_packages", "(", ")", ":", "for", "world", "in", "config", "[", "\"maps\"", "]", ":", "if", "world", "[", "\"name\"", "]", "==", "world_name", ":", "world_config", "=", "world", "if", "world_config", "is", "None", ":", "raise", "HolodeckException", "(", "\"Couldn't find world \"", "+", "world_name", ")", "second_indent", "=", "initial_indent", "+", "next_indent", "agent_indent", "=", "second_indent", "+", "next_indent", "sensor_indent", "=", "agent_indent", "+", "next_indent", "print", "(", "initial_indent", ",", "world_config", "[", "\"name\"", "]", ")", "print", "(", "second_indent", ",", "\"Resolution:\"", ",", "world_config", "[", "\"window_width\"", "]", ",", "\"x\"", ",", "world_config", "[", "\"window_height\"", "]", ")", "print", "(", "second_indent", ",", "\"Agents:\"", ")", "for", "agent", "in", "world_config", "[", "\"agents\"", "]", ":", "print", "(", "agent_indent", ",", "\"Name:\"", ",", "agent", "[", "\"agent_name\"", "]", ")", "print", "(", "agent_indent", ",", "\"Type:\"", ",", "agent", "[", "\"agent_type\"", "]", ")", "print", "(", "agent_indent", ",", "\"Sensors:\"", ")", "for", "sensor", "in", "agent", "[", "\"sensors\"", "]", ":", "print", "(", "sensor_indent", ",", "sensor", ")" ]
Gets and prints the information of a world. Args: world_name (str): the name of the world to retrieve information for world_config (dict optional): A dictionary containing the world's configuration. Will find the config if None. Defaults to None. initial_indent (str optional): This indent will apply to each output line. Defaults to "". next_indent (str optional): This indent will be applied within each nested line. Defaults to " ".
[ "Gets", "and", "prints", "the", "information", "of", "a", "world", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/packagemanager.py#L56-L86
17,254
BYU-PCCL/holodeck
holodeck/packagemanager.py
install
def install(package_name): """Installs a holodeck package. Args: package_name (str): The name of the package to install """ holodeck_path = util.get_holodeck_path() binary_website = "https://s3.amazonaws.com/holodeckworlds/" if package_name not in packages: raise HolodeckException("Unknown package name " + package_name) package_url = packages[package_name] print("Installing " + package_name + " at " + holodeck_path) install_path = os.path.join(holodeck_path, "worlds") binary_url = binary_website + util.get_os_key() + "_" + package_url _download_binary(binary_url, install_path) if os.name == "posix": _make_binary_excecutable(package_name, install_path)
python
def install(package_name): """Installs a holodeck package. Args: package_name (str): The name of the package to install """ holodeck_path = util.get_holodeck_path() binary_website = "https://s3.amazonaws.com/holodeckworlds/" if package_name not in packages: raise HolodeckException("Unknown package name " + package_name) package_url = packages[package_name] print("Installing " + package_name + " at " + holodeck_path) install_path = os.path.join(holodeck_path, "worlds") binary_url = binary_website + util.get_os_key() + "_" + package_url _download_binary(binary_url, install_path) if os.name == "posix": _make_binary_excecutable(package_name, install_path)
[ "def", "install", "(", "package_name", ")", ":", "holodeck_path", "=", "util", ".", "get_holodeck_path", "(", ")", "binary_website", "=", "\"https://s3.amazonaws.com/holodeckworlds/\"", "if", "package_name", "not", "in", "packages", ":", "raise", "HolodeckException", "(", "\"Unknown package name \"", "+", "package_name", ")", "package_url", "=", "packages", "[", "package_name", "]", "print", "(", "\"Installing \"", "+", "package_name", "+", "\" at \"", "+", "holodeck_path", ")", "install_path", "=", "os", ".", "path", ".", "join", "(", "holodeck_path", ",", "\"worlds\"", ")", "binary_url", "=", "binary_website", "+", "util", ".", "get_os_key", "(", ")", "+", "\"_\"", "+", "package_url", "_download_binary", "(", "binary_url", ",", "install_path", ")", "if", "os", ".", "name", "==", "\"posix\"", ":", "_make_binary_excecutable", "(", "package_name", ",", "install_path", ")" ]
Installs a holodeck package. Args: package_name (str): The name of the package to install
[ "Installs", "a", "holodeck", "package", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/packagemanager.py#L89-L107
17,255
BYU-PCCL/holodeck
holodeck/packagemanager.py
remove
def remove(package_name): """Removes a holodeck package. Args: package_name (str): the name of the package to remove """ if package_name not in packages: raise HolodeckException("Unknown package name " + package_name) for config, path in _iter_packages(): if config["name"] == package_name: shutil.rmtree(path)
python
def remove(package_name): """Removes a holodeck package. Args: package_name (str): the name of the package to remove """ if package_name not in packages: raise HolodeckException("Unknown package name " + package_name) for config, path in _iter_packages(): if config["name"] == package_name: shutil.rmtree(path)
[ "def", "remove", "(", "package_name", ")", ":", "if", "package_name", "not", "in", "packages", ":", "raise", "HolodeckException", "(", "\"Unknown package name \"", "+", "package_name", ")", "for", "config", ",", "path", "in", "_iter_packages", "(", ")", ":", "if", "config", "[", "\"name\"", "]", "==", "package_name", ":", "shutil", ".", "rmtree", "(", "path", ")" ]
Removes a holodeck package. Args: package_name (str): the name of the package to remove
[ "Removes", "a", "holodeck", "package", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/packagemanager.py#L110-L120
17,256
BYU-PCCL/holodeck
holodeck/holodeck.py
make
def make(world_name, gl_version=GL_VERSION.OPENGL4, window_res=None, cam_res=None, verbose=False): """Creates a holodeck environment using the supplied world name. Args: world_name (str): The name of the world to load as an environment. Must match the name of a world in an installed package. gl_version (int, optional): The OpenGL version to use (Linux only). Defaults to GL_VERSION.OPENGL4. window_res ((int, int), optional): The resolution to load the game window at. Defaults to (512, 512). cam_res ((int, int), optional): The resolution to load the pixel camera sensors at. Defaults to (256, 256). verbose (bool): Whether to run in verbose mode. Defaults to False. Returns: HolodeckEnvironment: A holodeck environment instantiated with all the settings necessary for the specified world, and other supplied arguments. """ holodeck_worlds = _get_worlds_map() if world_name not in holodeck_worlds: raise HolodeckException("Invalid World Name") param_dict = copy(holodeck_worlds[world_name]) param_dict["start_world"] = True param_dict["uuid"] = str(uuid.uuid4()) param_dict["gl_version"] = gl_version param_dict["verbose"] = verbose if window_res is not None: param_dict["window_width"] = window_res[0] param_dict["window_height"] = window_res[1] if cam_res is not None: param_dict["camera_width"] = cam_res[0] param_dict["camera_height"] = cam_res[1] return HolodeckEnvironment(**param_dict)
python
def make(world_name, gl_version=GL_VERSION.OPENGL4, window_res=None, cam_res=None, verbose=False): """Creates a holodeck environment using the supplied world name. Args: world_name (str): The name of the world to load as an environment. Must match the name of a world in an installed package. gl_version (int, optional): The OpenGL version to use (Linux only). Defaults to GL_VERSION.OPENGL4. window_res ((int, int), optional): The resolution to load the game window at. Defaults to (512, 512). cam_res ((int, int), optional): The resolution to load the pixel camera sensors at. Defaults to (256, 256). verbose (bool): Whether to run in verbose mode. Defaults to False. Returns: HolodeckEnvironment: A holodeck environment instantiated with all the settings necessary for the specified world, and other supplied arguments. """ holodeck_worlds = _get_worlds_map() if world_name not in holodeck_worlds: raise HolodeckException("Invalid World Name") param_dict = copy(holodeck_worlds[world_name]) param_dict["start_world"] = True param_dict["uuid"] = str(uuid.uuid4()) param_dict["gl_version"] = gl_version param_dict["verbose"] = verbose if window_res is not None: param_dict["window_width"] = window_res[0] param_dict["window_height"] = window_res[1] if cam_res is not None: param_dict["camera_width"] = cam_res[0] param_dict["camera_height"] = cam_res[1] return HolodeckEnvironment(**param_dict)
[ "def", "make", "(", "world_name", ",", "gl_version", "=", "GL_VERSION", ".", "OPENGL4", ",", "window_res", "=", "None", ",", "cam_res", "=", "None", ",", "verbose", "=", "False", ")", ":", "holodeck_worlds", "=", "_get_worlds_map", "(", ")", "if", "world_name", "not", "in", "holodeck_worlds", ":", "raise", "HolodeckException", "(", "\"Invalid World Name\"", ")", "param_dict", "=", "copy", "(", "holodeck_worlds", "[", "world_name", "]", ")", "param_dict", "[", "\"start_world\"", "]", "=", "True", "param_dict", "[", "\"uuid\"", "]", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "param_dict", "[", "\"gl_version\"", "]", "=", "gl_version", "param_dict", "[", "\"verbose\"", "]", "=", "verbose", "if", "window_res", "is", "not", "None", ":", "param_dict", "[", "\"window_width\"", "]", "=", "window_res", "[", "0", "]", "param_dict", "[", "\"window_height\"", "]", "=", "window_res", "[", "1", "]", "if", "cam_res", "is", "not", "None", ":", "param_dict", "[", "\"camera_width\"", "]", "=", "cam_res", "[", "0", "]", "param_dict", "[", "\"camera_height\"", "]", "=", "cam_res", "[", "1", "]", "return", "HolodeckEnvironment", "(", "*", "*", "param_dict", ")" ]
Creates a holodeck environment using the supplied world name. Args: world_name (str): The name of the world to load as an environment. Must match the name of a world in an installed package. gl_version (int, optional): The OpenGL version to use (Linux only). Defaults to GL_VERSION.OPENGL4. window_res ((int, int), optional): The resolution to load the game window at. Defaults to (512, 512). cam_res ((int, int), optional): The resolution to load the pixel camera sensors at. Defaults to (256, 256). verbose (bool): Whether to run in verbose mode. Defaults to False. Returns: HolodeckEnvironment: A holodeck environment instantiated with all the settings necessary for the specified world, and other supplied arguments.
[ "Creates", "a", "holodeck", "environment", "using", "the", "supplied", "world", "name", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/holodeck.py#L22-L54
17,257
BYU-PCCL/holodeck
holodeck/shmem.py
Shmem.unlink
def unlink(self): """unlinks the shared memory""" if os.name == "posix": self.__linux_unlink__() elif os.name == "nt": self.__windows_unlink__() else: raise HolodeckException("Currently unsupported os: " + os.name)
python
def unlink(self): """unlinks the shared memory""" if os.name == "posix": self.__linux_unlink__() elif os.name == "nt": self.__windows_unlink__() else: raise HolodeckException("Currently unsupported os: " + os.name)
[ "def", "unlink", "(", "self", ")", ":", "if", "os", ".", "name", "==", "\"posix\"", ":", "self", ".", "__linux_unlink__", "(", ")", "elif", "os", ".", "name", "==", "\"nt\"", ":", "self", ".", "__windows_unlink__", "(", ")", "else", ":", "raise", "HolodeckException", "(", "\"Currently unsupported os: \"", "+", "os", ".", "name", ")" ]
unlinks the shared memory
[ "unlinks", "the", "shared", "memory" ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/shmem.py#L51-L58
17,258
BYU-PCCL/holodeck
holodeck/command.py
Command.add_number_parameters
def add_number_parameters(self, number): """Add given number parameters to the internal list. Args: number (list of int or list of float): A number or list of numbers to add to the parameters. """ if isinstance(number, list): for x in number: self.add_number_parameters(x) return self._parameters.append("{ \"value\": " + str(number) + " }")
python
def add_number_parameters(self, number): """Add given number parameters to the internal list. Args: number (list of int or list of float): A number or list of numbers to add to the parameters. """ if isinstance(number, list): for x in number: self.add_number_parameters(x) return self._parameters.append("{ \"value\": " + str(number) + " }")
[ "def", "add_number_parameters", "(", "self", ",", "number", ")", ":", "if", "isinstance", "(", "number", ",", "list", ")", ":", "for", "x", "in", "number", ":", "self", ".", "add_number_parameters", "(", "x", ")", "return", "self", ".", "_parameters", ".", "append", "(", "\"{ \\\"value\\\": \"", "+", "str", "(", "number", ")", "+", "\" }\"", ")" ]
Add given number parameters to the internal list. Args: number (list of int or list of float): A number or list of numbers to add to the parameters.
[ "Add", "given", "number", "parameters", "to", "the", "internal", "list", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/command.py#L49-L59
17,259
BYU-PCCL/holodeck
holodeck/command.py
Command.add_string_parameters
def add_string_parameters(self, string): """Add given string parameters to the internal list. Args: string (list of str or str): A string or list of strings to add to the parameters. """ if isinstance(string, list): for x in string: self.add_string_parameters(x) return self._parameters.append("{ \"value\": \"" + string + "\" }")
python
def add_string_parameters(self, string): """Add given string parameters to the internal list. Args: string (list of str or str): A string or list of strings to add to the parameters. """ if isinstance(string, list): for x in string: self.add_string_parameters(x) return self._parameters.append("{ \"value\": \"" + string + "\" }")
[ "def", "add_string_parameters", "(", "self", ",", "string", ")", ":", "if", "isinstance", "(", "string", ",", "list", ")", ":", "for", "x", "in", "string", ":", "self", ".", "add_string_parameters", "(", "x", ")", "return", "self", ".", "_parameters", ".", "append", "(", "\"{ \\\"value\\\": \\\"\"", "+", "string", "+", "\"\\\" }\"", ")" ]
Add given string parameters to the internal list. Args: string (list of str or str): A string or list of strings to add to the parameters.
[ "Add", "given", "string", "parameters", "to", "the", "internal", "list", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/command.py#L61-L71
17,260
BYU-PCCL/holodeck
holodeck/command.py
SetWeatherCommand.set_type
def set_type(self, weather_type): """Set the weather type. Args: weather_type (str): The weather type. """ weather_type.lower() exists = self.has_type(weather_type) if exists: self.add_string_parameters(weather_type)
python
def set_type(self, weather_type): """Set the weather type. Args: weather_type (str): The weather type. """ weather_type.lower() exists = self.has_type(weather_type) if exists: self.add_string_parameters(weather_type)
[ "def", "set_type", "(", "self", ",", "weather_type", ")", ":", "weather_type", ".", "lower", "(", ")", "exists", "=", "self", ".", "has_type", "(", "weather_type", ")", "if", "exists", ":", "self", ".", "add_string_parameters", "(", "weather_type", ")" ]
Set the weather type. Args: weather_type (str): The weather type.
[ "Set", "the", "weather", "type", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/command.py#L227-L236
17,261
BYU-PCCL/holodeck
example.py
uav_example
def uav_example(): """A basic example of how to use the UAV agent.""" env = holodeck.make("UrbanCity") # This changes the control scheme for the uav env.set_control_scheme("uav0", ControlSchemes.UAV_ROLL_PITCH_YAW_RATE_ALT) for i in range(10): env.reset() # This command tells the UAV to not roll or pitch, but to constantly yaw left at 10m altitude. command = np.array([0, 0, 2, 10]) for _ in range(1000): state, reward, terminal, _ = env.step(command) # To access specific sensor data: pixels = state[Sensors.PIXEL_CAMERA] velocity = state[Sensors.VELOCITY_SENSOR]
python
def uav_example(): """A basic example of how to use the UAV agent.""" env = holodeck.make("UrbanCity") # This changes the control scheme for the uav env.set_control_scheme("uav0", ControlSchemes.UAV_ROLL_PITCH_YAW_RATE_ALT) for i in range(10): env.reset() # This command tells the UAV to not roll or pitch, but to constantly yaw left at 10m altitude. command = np.array([0, 0, 2, 10]) for _ in range(1000): state, reward, terminal, _ = env.step(command) # To access specific sensor data: pixels = state[Sensors.PIXEL_CAMERA] velocity = state[Sensors.VELOCITY_SENSOR]
[ "def", "uav_example", "(", ")", ":", "env", "=", "holodeck", ".", "make", "(", "\"UrbanCity\"", ")", "# This changes the control scheme for the uav", "env", ".", "set_control_scheme", "(", "\"uav0\"", ",", "ControlSchemes", ".", "UAV_ROLL_PITCH_YAW_RATE_ALT", ")", "for", "i", "in", "range", "(", "10", ")", ":", "env", ".", "reset", "(", ")", "# This command tells the UAV to not roll or pitch, but to constantly yaw left at 10m altitude.", "command", "=", "np", ".", "array", "(", "[", "0", ",", "0", ",", "2", ",", "10", "]", ")", "for", "_", "in", "range", "(", "1000", ")", ":", "state", ",", "reward", ",", "terminal", ",", "_", "=", "env", ".", "step", "(", "command", ")", "# To access specific sensor data:", "pixels", "=", "state", "[", "Sensors", ".", "PIXEL_CAMERA", "]", "velocity", "=", "state", "[", "Sensors", ".", "VELOCITY_SENSOR", "]" ]
A basic example of how to use the UAV agent.
[ "A", "basic", "example", "of", "how", "to", "use", "the", "UAV", "agent", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/example.py#L10-L27
17,262
BYU-PCCL/holodeck
example.py
sphere_example
def sphere_example(): """A basic example of how to use the sphere agent.""" env = holodeck.make("MazeWorld") # This command is to constantly rotate to the right command = 2 for i in range(10): env.reset() for _ in range(1000): state, reward, terminal, _ = env.step(command) # To access specific sensor data: pixels = state[Sensors.PIXEL_CAMERA] orientation = state[Sensors.ORIENTATION_SENSOR]
python
def sphere_example(): """A basic example of how to use the sphere agent.""" env = holodeck.make("MazeWorld") # This command is to constantly rotate to the right command = 2 for i in range(10): env.reset() for _ in range(1000): state, reward, terminal, _ = env.step(command) # To access specific sensor data: pixels = state[Sensors.PIXEL_CAMERA] orientation = state[Sensors.ORIENTATION_SENSOR]
[ "def", "sphere_example", "(", ")", ":", "env", "=", "holodeck", ".", "make", "(", "\"MazeWorld\"", ")", "# This command is to constantly rotate to the right", "command", "=", "2", "for", "i", "in", "range", "(", "10", ")", ":", "env", ".", "reset", "(", ")", "for", "_", "in", "range", "(", "1000", ")", ":", "state", ",", "reward", ",", "terminal", ",", "_", "=", "env", ".", "step", "(", "command", ")", "# To access specific sensor data:", "pixels", "=", "state", "[", "Sensors", ".", "PIXEL_CAMERA", "]", "orientation", "=", "state", "[", "Sensors", ".", "ORIENTATION_SENSOR", "]" ]
A basic example of how to use the sphere agent.
[ "A", "basic", "example", "of", "how", "to", "use", "the", "sphere", "agent", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/example.py#L36-L49
17,263
BYU-PCCL/holodeck
example.py
android_example
def android_example(): """A basic example of how to use the android agent.""" env = holodeck.make("AndroidPlayground") # The Android's command is a 94 length vector representing torques to be applied at each of his joints command = np.ones(94) * 10 for i in range(10): env.reset() for j in range(1000): if j % 50 == 0: command *= -1 state, reward, terminal, _ = env.step(command) # To access specific sensor data: pixels = state[Sensors.PIXEL_CAMERA] orientation = state[Sensors.ORIENTATION_SENSOR]
python
def android_example(): """A basic example of how to use the android agent.""" env = holodeck.make("AndroidPlayground") # The Android's command is a 94 length vector representing torques to be applied at each of his joints command = np.ones(94) * 10 for i in range(10): env.reset() for j in range(1000): if j % 50 == 0: command *= -1 state, reward, terminal, _ = env.step(command) # To access specific sensor data: pixels = state[Sensors.PIXEL_CAMERA] orientation = state[Sensors.ORIENTATION_SENSOR]
[ "def", "android_example", "(", ")", ":", "env", "=", "holodeck", ".", "make", "(", "\"AndroidPlayground\"", ")", "# The Android's command is a 94 length vector representing torques to be applied at each of his joints", "command", "=", "np", ".", "ones", "(", "94", ")", "*", "10", "for", "i", "in", "range", "(", "10", ")", ":", "env", ".", "reset", "(", ")", "for", "j", "in", "range", "(", "1000", ")", ":", "if", "j", "%", "50", "==", "0", ":", "command", "*=", "-", "1", "state", ",", "reward", ",", "terminal", ",", "_", "=", "env", ".", "step", "(", "command", ")", "# To access specific sensor data:", "pixels", "=", "state", "[", "Sensors", ".", "PIXEL_CAMERA", "]", "orientation", "=", "state", "[", "Sensors", ".", "ORIENTATION_SENSOR", "]" ]
A basic example of how to use the android agent.
[ "A", "basic", "example", "of", "how", "to", "use", "the", "android", "agent", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/example.py#L53-L69
17,264
BYU-PCCL/holodeck
example.py
multi_agent_example
def multi_agent_example(): """A basic example of using multiple agents""" env = holodeck.make("UrbanCity") cmd0 = np.array([0, 0, -2, 10]) cmd1 = np.array([0, 0, 5, 10]) for i in range(10): env.reset() # This will queue up a new agent to spawn into the environment, given that the coordinates are not blocked. sensors = [Sensors.PIXEL_CAMERA, Sensors.LOCATION_SENSOR, Sensors.VELOCITY_SENSOR] agent = AgentDefinition("uav1", agents.UavAgent, sensors) env.spawn_agent(agent, [1, 1, 5]) env.set_control_scheme("uav0", ControlSchemes.UAV_ROLL_PITCH_YAW_RATE_ALT) env.set_control_scheme("uav1", ControlSchemes.UAV_ROLL_PITCH_YAW_RATE_ALT) env.tick() # Tick the environment once so the second agent spawns before we try to interact with it. env.act("uav0", cmd0) env.act("uav1", cmd1) for _ in range(1000): states = env.tick() uav0_terminal = states["uav0"][Sensors.TERMINAL] uav1_reward = states["uav1"][Sensors.REWARD]
python
def multi_agent_example(): """A basic example of using multiple agents""" env = holodeck.make("UrbanCity") cmd0 = np.array([0, 0, -2, 10]) cmd1 = np.array([0, 0, 5, 10]) for i in range(10): env.reset() # This will queue up a new agent to spawn into the environment, given that the coordinates are not blocked. sensors = [Sensors.PIXEL_CAMERA, Sensors.LOCATION_SENSOR, Sensors.VELOCITY_SENSOR] agent = AgentDefinition("uav1", agents.UavAgent, sensors) env.spawn_agent(agent, [1, 1, 5]) env.set_control_scheme("uav0", ControlSchemes.UAV_ROLL_PITCH_YAW_RATE_ALT) env.set_control_scheme("uav1", ControlSchemes.UAV_ROLL_PITCH_YAW_RATE_ALT) env.tick() # Tick the environment once so the second agent spawns before we try to interact with it. env.act("uav0", cmd0) env.act("uav1", cmd1) for _ in range(1000): states = env.tick() uav0_terminal = states["uav0"][Sensors.TERMINAL] uav1_reward = states["uav1"][Sensors.REWARD]
[ "def", "multi_agent_example", "(", ")", ":", "env", "=", "holodeck", ".", "make", "(", "\"UrbanCity\"", ")", "cmd0", "=", "np", ".", "array", "(", "[", "0", ",", "0", ",", "-", "2", ",", "10", "]", ")", "cmd1", "=", "np", ".", "array", "(", "[", "0", ",", "0", ",", "5", ",", "10", "]", ")", "for", "i", "in", "range", "(", "10", ")", ":", "env", ".", "reset", "(", ")", "# This will queue up a new agent to spawn into the environment, given that the coordinates are not blocked.", "sensors", "=", "[", "Sensors", ".", "PIXEL_CAMERA", ",", "Sensors", ".", "LOCATION_SENSOR", ",", "Sensors", ".", "VELOCITY_SENSOR", "]", "agent", "=", "AgentDefinition", "(", "\"uav1\"", ",", "agents", ".", "UavAgent", ",", "sensors", ")", "env", ".", "spawn_agent", "(", "agent", ",", "[", "1", ",", "1", ",", "5", "]", ")", "env", ".", "set_control_scheme", "(", "\"uav0\"", ",", "ControlSchemes", ".", "UAV_ROLL_PITCH_YAW_RATE_ALT", ")", "env", ".", "set_control_scheme", "(", "\"uav1\"", ",", "ControlSchemes", ".", "UAV_ROLL_PITCH_YAW_RATE_ALT", ")", "env", ".", "tick", "(", ")", "# Tick the environment once so the second agent spawns before we try to interact with it.", "env", ".", "act", "(", "\"uav0\"", ",", "cmd0", ")", "env", ".", "act", "(", "\"uav1\"", ",", "cmd1", ")", "for", "_", "in", "range", "(", "1000", ")", ":", "states", "=", "env", ".", "tick", "(", ")", "uav0_terminal", "=", "states", "[", "\"uav0\"", "]", "[", "Sensors", ".", "TERMINAL", "]", "uav1_reward", "=", "states", "[", "\"uav1\"", "]", "[", "Sensors", ".", "REWARD", "]" ]
A basic example of using multiple agents
[ "A", "basic", "example", "of", "using", "multiple", "agents" ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/example.py#L73-L96
17,265
BYU-PCCL/holodeck
example.py
world_command_examples
def world_command_examples(): """A few examples to showcase commands for manipulating the worlds.""" env = holodeck.make("MazeWorld") # This is the unaltered MazeWorld for _ in range(300): _ = env.tick() env.reset() # The set_day_time_command sets the hour between 0 and 23 (military time). This example sets it to 6 AM. env.set_day_time(6) for _ in range(300): _ = env.tick() env.reset() # reset() undoes all alterations to the world # The start_day_cycle command starts rotating the sun to emulate day cycles. # The parameter sets the day length in minutes. env.start_day_cycle(5) for _ in range(1500): _ = env.tick() env.reset() # The set_fog_density changes the density of the fog in the world. 1 is the maximum density. env.set_fog_density(.25) for _ in range(300): _ = env.tick() env.reset() # The set_weather_command changes the weather in the world. The two available options are "rain" and "cloudy". # The rainfall particle system is attached to the agent, so the rain particles will only be found around each agent. # Every world is clear by default. env.set_weather("rain") for _ in range(500): _ = env.tick() env.reset() env.set_weather("cloudy") for _ in range(500): _ = env.tick() env.reset() env.teleport_camera([1000, 1000, 1000], [0, 0, 0]) for _ in range(500): _ = env.tick() env.reset()
python
def world_command_examples(): """A few examples to showcase commands for manipulating the worlds.""" env = holodeck.make("MazeWorld") # This is the unaltered MazeWorld for _ in range(300): _ = env.tick() env.reset() # The set_day_time_command sets the hour between 0 and 23 (military time). This example sets it to 6 AM. env.set_day_time(6) for _ in range(300): _ = env.tick() env.reset() # reset() undoes all alterations to the world # The start_day_cycle command starts rotating the sun to emulate day cycles. # The parameter sets the day length in minutes. env.start_day_cycle(5) for _ in range(1500): _ = env.tick() env.reset() # The set_fog_density changes the density of the fog in the world. 1 is the maximum density. env.set_fog_density(.25) for _ in range(300): _ = env.tick() env.reset() # The set_weather_command changes the weather in the world. The two available options are "rain" and "cloudy". # The rainfall particle system is attached to the agent, so the rain particles will only be found around each agent. # Every world is clear by default. env.set_weather("rain") for _ in range(500): _ = env.tick() env.reset() env.set_weather("cloudy") for _ in range(500): _ = env.tick() env.reset() env.teleport_camera([1000, 1000, 1000], [0, 0, 0]) for _ in range(500): _ = env.tick() env.reset()
[ "def", "world_command_examples", "(", ")", ":", "env", "=", "holodeck", ".", "make", "(", "\"MazeWorld\"", ")", "# This is the unaltered MazeWorld", "for", "_", "in", "range", "(", "300", ")", ":", "_", "=", "env", ".", "tick", "(", ")", "env", ".", "reset", "(", ")", "# The set_day_time_command sets the hour between 0 and 23 (military time). This example sets it to 6 AM.", "env", ".", "set_day_time", "(", "6", ")", "for", "_", "in", "range", "(", "300", ")", ":", "_", "=", "env", ".", "tick", "(", ")", "env", ".", "reset", "(", ")", "# reset() undoes all alterations to the world", "# The start_day_cycle command starts rotating the sun to emulate day cycles.", "# The parameter sets the day length in minutes.", "env", ".", "start_day_cycle", "(", "5", ")", "for", "_", "in", "range", "(", "1500", ")", ":", "_", "=", "env", ".", "tick", "(", ")", "env", ".", "reset", "(", ")", "# The set_fog_density changes the density of the fog in the world. 1 is the maximum density.", "env", ".", "set_fog_density", "(", ".25", ")", "for", "_", "in", "range", "(", "300", ")", ":", "_", "=", "env", ".", "tick", "(", ")", "env", ".", "reset", "(", ")", "# The set_weather_command changes the weather in the world. The two available options are \"rain\" and \"cloudy\".", "# The rainfall particle system is attached to the agent, so the rain particles will only be found around each agent.", "# Every world is clear by default.", "env", ".", "set_weather", "(", "\"rain\"", ")", "for", "_", "in", "range", "(", "500", ")", ":", "_", "=", "env", ".", "tick", "(", ")", "env", ".", "reset", "(", ")", "env", ".", "set_weather", "(", "\"cloudy\"", ")", "for", "_", "in", "range", "(", "500", ")", ":", "_", "=", "env", ".", "tick", "(", ")", "env", ".", "reset", "(", ")", "env", ".", "teleport_camera", "(", "[", "1000", ",", "1000", ",", "1000", "]", ",", "[", "0", ",", "0", ",", "0", "]", ")", "for", "_", "in", "range", "(", "500", ")", ":", "_", "=", "env", ".", "tick", "(", ")", "env", ".", "reset", "(", ")" ]
A few examples to showcase commands for manipulating the worlds.
[ "A", "few", "examples", "to", "showcase", "commands", "for", "manipulating", "the", "worlds", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/example.py#L99-L143
17,266
BYU-PCCL/holodeck
example.py
editor_example
def editor_example(): """This editor example shows how to interact with holodeck worlds while they are being built in the Unreal Engine. Most people that use holodeck will not need this. """ sensors = [Sensors.PIXEL_CAMERA, Sensors.LOCATION_SENSOR, Sensors.VELOCITY_SENSOR] agent = AgentDefinition("uav0", agents.UavAgent, sensors) env = HolodeckEnvironment(agent, start_world=False) env.agents["uav0"].set_control_scheme(1) command = [0, 0, 10, 50] for i in range(10): env.reset() for _ in range(1000): state, reward, terminal, _ = env.step(command)
python
def editor_example(): """This editor example shows how to interact with holodeck worlds while they are being built in the Unreal Engine. Most people that use holodeck will not need this. """ sensors = [Sensors.PIXEL_CAMERA, Sensors.LOCATION_SENSOR, Sensors.VELOCITY_SENSOR] agent = AgentDefinition("uav0", agents.UavAgent, sensors) env = HolodeckEnvironment(agent, start_world=False) env.agents["uav0"].set_control_scheme(1) command = [0, 0, 10, 50] for i in range(10): env.reset() for _ in range(1000): state, reward, terminal, _ = env.step(command)
[ "def", "editor_example", "(", ")", ":", "sensors", "=", "[", "Sensors", ".", "PIXEL_CAMERA", ",", "Sensors", ".", "LOCATION_SENSOR", ",", "Sensors", ".", "VELOCITY_SENSOR", "]", "agent", "=", "AgentDefinition", "(", "\"uav0\"", ",", "agents", ".", "UavAgent", ",", "sensors", ")", "env", "=", "HolodeckEnvironment", "(", "agent", ",", "start_world", "=", "False", ")", "env", ".", "agents", "[", "\"uav0\"", "]", ".", "set_control_scheme", "(", "1", ")", "command", "=", "[", "0", ",", "0", ",", "10", ",", "50", "]", "for", "i", "in", "range", "(", "10", ")", ":", "env", ".", "reset", "(", ")", "for", "_", "in", "range", "(", "1000", ")", ":", "state", ",", "reward", ",", "terminal", ",", "_", "=", "env", ".", "step", "(", "command", ")" ]
This editor example shows how to interact with holodeck worlds while they are being built in the Unreal Engine. Most people that use holodeck will not need this.
[ "This", "editor", "example", "shows", "how", "to", "interact", "with", "holodeck", "worlds", "while", "they", "are", "being", "built", "in", "the", "Unreal", "Engine", ".", "Most", "people", "that", "use", "holodeck", "will", "not", "need", "this", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/example.py#L146-L159
17,267
BYU-PCCL/holodeck
example.py
editor_multi_agent_example
def editor_multi_agent_example(): """This editor example shows how to interact with holodeck worlds that have multiple agents. This is specifically for when working with UE4 directly and not a prebuilt binary. """ agent_definitions = [ AgentDefinition("uav0", agents.UavAgent, [Sensors.PIXEL_CAMERA, Sensors.LOCATION_SENSOR]), AgentDefinition("uav1", agents.UavAgent, [Sensors.LOCATION_SENSOR, Sensors.VELOCITY_SENSOR]) ] env = HolodeckEnvironment(agent_definitions, start_world=False) cmd0 = np.array([0, 0, -2, 10]) cmd1 = np.array([0, 0, 5, 10]) for i in range(10): env.reset() env.act("uav0", cmd0) env.act("uav1", cmd1) for _ in range(1000): states = env.tick() uav0_terminal = states["uav0"][Sensors.TERMINAL] uav1_reward = states["uav1"][Sensors.REWARD]
python
def editor_multi_agent_example(): """This editor example shows how to interact with holodeck worlds that have multiple agents. This is specifically for when working with UE4 directly and not a prebuilt binary. """ agent_definitions = [ AgentDefinition("uav0", agents.UavAgent, [Sensors.PIXEL_CAMERA, Sensors.LOCATION_SENSOR]), AgentDefinition("uav1", agents.UavAgent, [Sensors.LOCATION_SENSOR, Sensors.VELOCITY_SENSOR]) ] env = HolodeckEnvironment(agent_definitions, start_world=False) cmd0 = np.array([0, 0, -2, 10]) cmd1 = np.array([0, 0, 5, 10]) for i in range(10): env.reset() env.act("uav0", cmd0) env.act("uav1", cmd1) for _ in range(1000): states = env.tick() uav0_terminal = states["uav0"][Sensors.TERMINAL] uav1_reward = states["uav1"][Sensors.REWARD]
[ "def", "editor_multi_agent_example", "(", ")", ":", "agent_definitions", "=", "[", "AgentDefinition", "(", "\"uav0\"", ",", "agents", ".", "UavAgent", ",", "[", "Sensors", ".", "PIXEL_CAMERA", ",", "Sensors", ".", "LOCATION_SENSOR", "]", ")", ",", "AgentDefinition", "(", "\"uav1\"", ",", "agents", ".", "UavAgent", ",", "[", "Sensors", ".", "LOCATION_SENSOR", ",", "Sensors", ".", "VELOCITY_SENSOR", "]", ")", "]", "env", "=", "HolodeckEnvironment", "(", "agent_definitions", ",", "start_world", "=", "False", ")", "cmd0", "=", "np", ".", "array", "(", "[", "0", ",", "0", ",", "-", "2", ",", "10", "]", ")", "cmd1", "=", "np", ".", "array", "(", "[", "0", ",", "0", ",", "5", ",", "10", "]", ")", "for", "i", "in", "range", "(", "10", ")", ":", "env", ".", "reset", "(", ")", "env", ".", "act", "(", "\"uav0\"", ",", "cmd0", ")", "env", ".", "act", "(", "\"uav1\"", ",", "cmd1", ")", "for", "_", "in", "range", "(", "1000", ")", ":", "states", "=", "env", ".", "tick", "(", ")", "uav0_terminal", "=", "states", "[", "\"uav0\"", "]", "[", "Sensors", ".", "TERMINAL", "]", "uav1_reward", "=", "states", "[", "\"uav1\"", "]", "[", "Sensors", ".", "REWARD", "]" ]
This editor example shows how to interact with holodeck worlds that have multiple agents. This is specifically for when working with UE4 directly and not a prebuilt binary.
[ "This", "editor", "example", "shows", "how", "to", "interact", "with", "holodeck", "worlds", "that", "have", "multiple", "agents", ".", "This", "is", "specifically", "for", "when", "working", "with", "UE4", "directly", "and", "not", "a", "prebuilt", "binary", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/example.py#L162-L183
17,268
BYU-PCCL/holodeck
holodeck/util.py
get_holodeck_path
def get_holodeck_path(): """Gets the path of the holodeck environment Returns: (str): path to the current holodeck environment """ if "HOLODECKPATH" in os.environ and os.environ["HOLODECKPATH"] != "": return os.environ["HOLODECKPATH"] if os.name == "posix": return os.path.expanduser("~/.local/share/holodeck") elif os.name == "nt": return os.path.expanduser("~\\AppData\\Local\\holodeck") else: raise NotImplementedError("holodeck is only supported for Linux and Windows")
python
def get_holodeck_path(): """Gets the path of the holodeck environment Returns: (str): path to the current holodeck environment """ if "HOLODECKPATH" in os.environ and os.environ["HOLODECKPATH"] != "": return os.environ["HOLODECKPATH"] if os.name == "posix": return os.path.expanduser("~/.local/share/holodeck") elif os.name == "nt": return os.path.expanduser("~\\AppData\\Local\\holodeck") else: raise NotImplementedError("holodeck is only supported for Linux and Windows")
[ "def", "get_holodeck_path", "(", ")", ":", "if", "\"HOLODECKPATH\"", "in", "os", ".", "environ", "and", "os", ".", "environ", "[", "\"HOLODECKPATH\"", "]", "!=", "\"\"", ":", "return", "os", ".", "environ", "[", "\"HOLODECKPATH\"", "]", "if", "os", ".", "name", "==", "\"posix\"", ":", "return", "os", ".", "path", ".", "expanduser", "(", "\"~/.local/share/holodeck\"", ")", "elif", "os", ".", "name", "==", "\"nt\"", ":", "return", "os", ".", "path", ".", "expanduser", "(", "\"~\\\\AppData\\\\Local\\\\holodeck\"", ")", "else", ":", "raise", "NotImplementedError", "(", "\"holodeck is only supported for Linux and Windows\"", ")" ]
Gets the path of the holodeck environment Returns: (str): path to the current holodeck environment
[ "Gets", "the", "path", "of", "the", "holodeck", "environment" ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/util.py#L11-L24
17,269
BYU-PCCL/holodeck
holodeck/util.py
convert_unicode
def convert_unicode(value): """Resolves python 2 issue with json loading in unicode instead of string Args: value (str): Unicode value to be converted Returns: (str): converted string """ if isinstance(value, dict): return {convert_unicode(key): convert_unicode(value) for key, value in value.iteritems()} elif isinstance(value, list): return [convert_unicode(item) for item in value] elif isinstance(value, unicode): return value.encode('utf-8') else: return value
python
def convert_unicode(value): """Resolves python 2 issue with json loading in unicode instead of string Args: value (str): Unicode value to be converted Returns: (str): converted string """ if isinstance(value, dict): return {convert_unicode(key): convert_unicode(value) for key, value in value.iteritems()} elif isinstance(value, list): return [convert_unicode(item) for item in value] elif isinstance(value, unicode): return value.encode('utf-8') else: return value
[ "def", "convert_unicode", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "return", "{", "convert_unicode", "(", "key", ")", ":", "convert_unicode", "(", "value", ")", "for", "key", ",", "value", "in", "value", ".", "iteritems", "(", ")", "}", "elif", "isinstance", "(", "value", ",", "list", ")", ":", "return", "[", "convert_unicode", "(", "item", ")", "for", "item", "in", "value", "]", "elif", "isinstance", "(", "value", ",", "unicode", ")", ":", "return", "value", ".", "encode", "(", "'utf-8'", ")", "else", ":", "return", "value" ]
Resolves python 2 issue with json loading in unicode instead of string Args: value (str): Unicode value to be converted Returns: (str): converted string
[ "Resolves", "python", "2", "issue", "with", "json", "loading", "in", "unicode", "instead", "of", "string" ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/util.py#L27-L45
17,270
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.info
def info(self): """Returns a string with specific information about the environment. This information includes which agents are in the environment and which sensors they have. Returns: str: The information in a string format. """ result = list() result.append("Agents:\n") for agent in self._all_agents: result.append("\tName: ") result.append(agent.name) result.append("\n\tType: ") result.append(type(agent).__name__) result.append("\n\t") result.append("Sensors:\n") for sensor in self._sensor_map[agent.name].keys(): result.append("\t\t") result.append(Sensors.name(sensor)) result.append("\n") return "".join(result)
python
def info(self): """Returns a string with specific information about the environment. This information includes which agents are in the environment and which sensors they have. Returns: str: The information in a string format. """ result = list() result.append("Agents:\n") for agent in self._all_agents: result.append("\tName: ") result.append(agent.name) result.append("\n\tType: ") result.append(type(agent).__name__) result.append("\n\t") result.append("Sensors:\n") for sensor in self._sensor_map[agent.name].keys(): result.append("\t\t") result.append(Sensors.name(sensor)) result.append("\n") return "".join(result)
[ "def", "info", "(", "self", ")", ":", "result", "=", "list", "(", ")", "result", ".", "append", "(", "\"Agents:\\n\"", ")", "for", "agent", "in", "self", ".", "_all_agents", ":", "result", ".", "append", "(", "\"\\tName: \"", ")", "result", ".", "append", "(", "agent", ".", "name", ")", "result", ".", "append", "(", "\"\\n\\tType: \"", ")", "result", ".", "append", "(", "type", "(", "agent", ")", ".", "__name__", ")", "result", ".", "append", "(", "\"\\n\\t\"", ")", "result", ".", "append", "(", "\"Sensors:\\n\"", ")", "for", "sensor", "in", "self", ".", "_sensor_map", "[", "agent", ".", "name", "]", ".", "keys", "(", ")", ":", "result", ".", "append", "(", "\"\\t\\t\"", ")", "result", ".", "append", "(", "Sensors", ".", "name", "(", "sensor", ")", ")", "result", ".", "append", "(", "\"\\n\"", ")", "return", "\"\"", ".", "join", "(", "result", ")" ]
Returns a string with specific information about the environment. This information includes which agents are in the environment and which sensors they have. Returns: str: The information in a string format.
[ "Returns", "a", "string", "with", "specific", "information", "about", "the", "environment", ".", "This", "information", "includes", "which", "agents", "are", "in", "the", "environment", "and", "which", "sensors", "they", "have", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L142-L162
17,271
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.reset
def reset(self): """Resets the environment, and returns the state. If it is a single agent environment, it returns that state for that agent. Otherwise, it returns a dict from agent name to state. Returns: tuple or dict: For single agent environment, returns the same as `step`. For multi-agent environment, returns the same as `tick`. """ self._reset_ptr[0] = True self._commands.clear() for _ in range(self._pre_start_steps + 1): self.tick() return self._default_state_fn()
python
def reset(self): """Resets the environment, and returns the state. If it is a single agent environment, it returns that state for that agent. Otherwise, it returns a dict from agent name to state. Returns: tuple or dict: For single agent environment, returns the same as `step`. For multi-agent environment, returns the same as `tick`. """ self._reset_ptr[0] = True self._commands.clear() for _ in range(self._pre_start_steps + 1): self.tick() return self._default_state_fn()
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_reset_ptr", "[", "0", "]", "=", "True", "self", ".", "_commands", ".", "clear", "(", ")", "for", "_", "in", "range", "(", "self", ".", "_pre_start_steps", "+", "1", ")", ":", "self", ".", "tick", "(", ")", "return", "self", ".", "_default_state_fn", "(", ")" ]
Resets the environment, and returns the state. If it is a single agent environment, it returns that state for that agent. Otherwise, it returns a dict from agent name to state. Returns: tuple or dict: For single agent environment, returns the same as `step`. For multi-agent environment, returns the same as `tick`.
[ "Resets", "the", "environment", "and", "returns", "the", "state", ".", "If", "it", "is", "a", "single", "agent", "environment", "it", "returns", "that", "state", "for", "that", "agent", ".", "Otherwise", "it", "returns", "a", "dict", "from", "agent", "name", "to", "state", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L164-L179
17,272
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.step
def step(self, action): """Supplies an action to the main agent and tells the environment to tick once. Primary mode of interaction for single agent environments. Args: action (np.ndarray): An action for the main agent to carry out on the next tick. Returns: tuple: The (state, reward, terminal, info) tuple for the agent. State is a dictionary from sensor enum (see :obj:`holodeck.sensors.Sensors`) to np.ndarray. Reward is the float reward returned by the environment. Terminal is the bool terminal signal returned by the environment. Info is any additional info, depending on the world. Defaults to None. """ self._agent.act(action) self._handle_command_buffer() self._client.release() self._client.acquire() return self._get_single_state()
python
def step(self, action): """Supplies an action to the main agent and tells the environment to tick once. Primary mode of interaction for single agent environments. Args: action (np.ndarray): An action for the main agent to carry out on the next tick. Returns: tuple: The (state, reward, terminal, info) tuple for the agent. State is a dictionary from sensor enum (see :obj:`holodeck.sensors.Sensors`) to np.ndarray. Reward is the float reward returned by the environment. Terminal is the bool terminal signal returned by the environment. Info is any additional info, depending on the world. Defaults to None. """ self._agent.act(action) self._handle_command_buffer() self._client.release() self._client.acquire() return self._get_single_state()
[ "def", "step", "(", "self", ",", "action", ")", ":", "self", ".", "_agent", ".", "act", "(", "action", ")", "self", ".", "_handle_command_buffer", "(", ")", "self", ".", "_client", ".", "release", "(", ")", "self", ".", "_client", ".", "acquire", "(", ")", "return", "self", ".", "_get_single_state", "(", ")" ]
Supplies an action to the main agent and tells the environment to tick once. Primary mode of interaction for single agent environments. Args: action (np.ndarray): An action for the main agent to carry out on the next tick. Returns: tuple: The (state, reward, terminal, info) tuple for the agent. State is a dictionary from sensor enum (see :obj:`holodeck.sensors.Sensors`) to np.ndarray. Reward is the float reward returned by the environment. Terminal is the bool terminal signal returned by the environment. Info is any additional info, depending on the world. Defaults to None.
[ "Supplies", "an", "action", "to", "the", "main", "agent", "and", "tells", "the", "environment", "to", "tick", "once", ".", "Primary", "mode", "of", "interaction", "for", "single", "agent", "environments", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L181-L202
17,273
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.teleport
def teleport(self, agent_name, location=None, rotation=None): """Teleports the target agent to any given location, and applies a specific rotation. Args: agent_name (str): The name of the agent to teleport. location (np.ndarray or list): XYZ coordinates (in meters) for the agent to be teleported to. If no location is given, it isn't teleported, but may still be rotated. Defaults to None. rotation (np.ndarray or list): A new rotation target for the agent. If no rotation is given, it isn't rotated, but may still be teleported. Defaults to None. """ self.agents[agent_name].teleport(location * 100, rotation) # * 100 to convert m to cm self.tick()
python
def teleport(self, agent_name, location=None, rotation=None): """Teleports the target agent to any given location, and applies a specific rotation. Args: agent_name (str): The name of the agent to teleport. location (np.ndarray or list): XYZ coordinates (in meters) for the agent to be teleported to. If no location is given, it isn't teleported, but may still be rotated. Defaults to None. rotation (np.ndarray or list): A new rotation target for the agent. If no rotation is given, it isn't rotated, but may still be teleported. Defaults to None. """ self.agents[agent_name].teleport(location * 100, rotation) # * 100 to convert m to cm self.tick()
[ "def", "teleport", "(", "self", ",", "agent_name", ",", "location", "=", "None", ",", "rotation", "=", "None", ")", ":", "self", ".", "agents", "[", "agent_name", "]", ".", "teleport", "(", "location", "*", "100", ",", "rotation", ")", "# * 100 to convert m to cm", "self", ".", "tick", "(", ")" ]
Teleports the target agent to any given location, and applies a specific rotation. Args: agent_name (str): The name of the agent to teleport. location (np.ndarray or list): XYZ coordinates (in meters) for the agent to be teleported to. If no location is given, it isn't teleported, but may still be rotated. Defaults to None. rotation (np.ndarray or list): A new rotation target for the agent. If no rotation is given, it isn't rotated, but may still be teleported. Defaults to None.
[ "Teleports", "the", "target", "agent", "to", "any", "given", "location", "and", "applies", "a", "specific", "rotation", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L204-L215
17,274
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.tick
def tick(self): """Ticks the environment once. Normally used for multi-agent environments. Returns: dict: A dictionary from agent name to its full state. The full state is another dictionary from :obj:`holodeck.sensors.Sensors` enum to np.ndarray, containing the sensors information for each sensor. The sensors always include the reward and terminal sensors. """ self._handle_command_buffer() self._client.release() self._client.acquire() return self._get_full_state()
python
def tick(self): """Ticks the environment once. Normally used for multi-agent environments. Returns: dict: A dictionary from agent name to its full state. The full state is another dictionary from :obj:`holodeck.sensors.Sensors` enum to np.ndarray, containing the sensors information for each sensor. The sensors always include the reward and terminal sensors. """ self._handle_command_buffer() self._client.release() self._client.acquire() return self._get_full_state()
[ "def", "tick", "(", "self", ")", ":", "self", ".", "_handle_command_buffer", "(", ")", "self", ".", "_client", ".", "release", "(", ")", "self", ".", "_client", ".", "acquire", "(", ")", "return", "self", ".", "_get_full_state", "(", ")" ]
Ticks the environment once. Normally used for multi-agent environments. Returns: dict: A dictionary from agent name to its full state. The full state is another dictionary from :obj:`holodeck.sensors.Sensors` enum to np.ndarray, containing the sensors information for each sensor. The sensors always include the reward and terminal sensors.
[ "Ticks", "the", "environment", "once", ".", "Normally", "used", "for", "multi", "-", "agent", "environments", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L229-L240
17,275
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.add_state_sensors
def add_state_sensors(self, agent_name, sensors): """Adds a sensor to a particular agent. This only works if the world you are running also includes that particular sensor on the agent. Args: agent_name (str): The name of the agent to add the sensor to. sensors (:obj:`HolodeckSensor` or list of :obj:`HolodeckSensor`): Sensors to add to the agent. Should be objects that inherit from :obj:`HolodeckSensor`. """ if isinstance(sensors, list): for sensor in sensors: self.add_state_sensors(agent_name, sensor) else: if agent_name not in self._sensor_map: self._sensor_map[agent_name] = dict() self._sensor_map[agent_name][sensors] = self._client.malloc(agent_name + "_" + Sensors.name(sensors), Sensors.shape(sensors), Sensors.dtype(sensors))
python
def add_state_sensors(self, agent_name, sensors): """Adds a sensor to a particular agent. This only works if the world you are running also includes that particular sensor on the agent. Args: agent_name (str): The name of the agent to add the sensor to. sensors (:obj:`HolodeckSensor` or list of :obj:`HolodeckSensor`): Sensors to add to the agent. Should be objects that inherit from :obj:`HolodeckSensor`. """ if isinstance(sensors, list): for sensor in sensors: self.add_state_sensors(agent_name, sensor) else: if agent_name not in self._sensor_map: self._sensor_map[agent_name] = dict() self._sensor_map[agent_name][sensors] = self._client.malloc(agent_name + "_" + Sensors.name(sensors), Sensors.shape(sensors), Sensors.dtype(sensors))
[ "def", "add_state_sensors", "(", "self", ",", "agent_name", ",", "sensors", ")", ":", "if", "isinstance", "(", "sensors", ",", "list", ")", ":", "for", "sensor", "in", "sensors", ":", "self", ".", "add_state_sensors", "(", "agent_name", ",", "sensor", ")", "else", ":", "if", "agent_name", "not", "in", "self", ".", "_sensor_map", ":", "self", ".", "_sensor_map", "[", "agent_name", "]", "=", "dict", "(", ")", "self", ".", "_sensor_map", "[", "agent_name", "]", "[", "sensors", "]", "=", "self", ".", "_client", ".", "malloc", "(", "agent_name", "+", "\"_\"", "+", "Sensors", ".", "name", "(", "sensors", ")", ",", "Sensors", ".", "shape", "(", "sensors", ")", ",", "Sensors", ".", "dtype", "(", "sensors", ")", ")" ]
Adds a sensor to a particular agent. This only works if the world you are running also includes that particular sensor on the agent. Args: agent_name (str): The name of the agent to add the sensor to. sensors (:obj:`HolodeckSensor` or list of :obj:`HolodeckSensor`): Sensors to add to the agent. Should be objects that inherit from :obj:`HolodeckSensor`.
[ "Adds", "a", "sensor", "to", "a", "particular", "agent", ".", "This", "only", "works", "if", "the", "world", "you", "are", "running", "also", "includes", "that", "particular", "sensor", "on", "the", "agent", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L242-L260
17,276
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.spawn_agent
def spawn_agent(self, agent_definition, location): """Queues a spawn agent command. It will be applied when `tick` or `step` is called next. The agent won't be able to be used until the next frame. Args: agent_definition (:obj:`AgentDefinition`): The definition of the agent to spawn. location (np.ndarray or list): The position to spawn the agent in the world, in XYZ coordinates (in meters). """ self._should_write_to_command_buffer = True self._add_agents(agent_definition) command_to_send = SpawnAgentCommand(location, agent_definition.name, agent_definition.type) self._commands.add_command(command_to_send)
python
def spawn_agent(self, agent_definition, location): """Queues a spawn agent command. It will be applied when `tick` or `step` is called next. The agent won't be able to be used until the next frame. Args: agent_definition (:obj:`AgentDefinition`): The definition of the agent to spawn. location (np.ndarray or list): The position to spawn the agent in the world, in XYZ coordinates (in meters). """ self._should_write_to_command_buffer = True self._add_agents(agent_definition) command_to_send = SpawnAgentCommand(location, agent_definition.name, agent_definition.type) self._commands.add_command(command_to_send)
[ "def", "spawn_agent", "(", "self", ",", "agent_definition", ",", "location", ")", ":", "self", ".", "_should_write_to_command_buffer", "=", "True", "self", ".", "_add_agents", "(", "agent_definition", ")", "command_to_send", "=", "SpawnAgentCommand", "(", "location", ",", "agent_definition", ".", "name", ",", "agent_definition", ".", "type", ")", "self", ".", "_commands", ".", "add_command", "(", "command_to_send", ")" ]
Queues a spawn agent command. It will be applied when `tick` or `step` is called next. The agent won't be able to be used until the next frame. Args: agent_definition (:obj:`AgentDefinition`): The definition of the agent to spawn. location (np.ndarray or list): The position to spawn the agent in the world, in XYZ coordinates (in meters).
[ "Queues", "a", "spawn", "agent", "command", ".", "It", "will", "be", "applied", "when", "tick", "or", "step", "is", "called", "next", ".", "The", "agent", "won", "t", "be", "able", "to", "be", "used", "until", "the", "next", "frame", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L262-L273
17,277
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.set_fog_density
def set_fog_density(self, density): """Queue up a change fog density command. It will be applied when `tick` or `step` is called next. By the next tick, the exponential height fog in the world will have the new density. If there is no fog in the world, it will be automatically created with the given density. Args: density (float): The new density value, between 0 and 1. The command will not be sent if the given density is invalid. """ if density < 0 or density > 1: raise HolodeckException("Fog density should be between 0 and 1") self._should_write_to_command_buffer = True command_to_send = ChangeFogDensityCommand(density) self._commands.add_command(command_to_send)
python
def set_fog_density(self, density): """Queue up a change fog density command. It will be applied when `tick` or `step` is called next. By the next tick, the exponential height fog in the world will have the new density. If there is no fog in the world, it will be automatically created with the given density. Args: density (float): The new density value, between 0 and 1. The command will not be sent if the given density is invalid. """ if density < 0 or density > 1: raise HolodeckException("Fog density should be between 0 and 1") self._should_write_to_command_buffer = True command_to_send = ChangeFogDensityCommand(density) self._commands.add_command(command_to_send)
[ "def", "set_fog_density", "(", "self", ",", "density", ")", ":", "if", "density", "<", "0", "or", "density", ">", "1", ":", "raise", "HolodeckException", "(", "\"Fog density should be between 0 and 1\"", ")", "self", ".", "_should_write_to_command_buffer", "=", "True", "command_to_send", "=", "ChangeFogDensityCommand", "(", "density", ")", "self", ".", "_commands", ".", "add_command", "(", "command_to_send", ")" ]
Queue up a change fog density command. It will be applied when `tick` or `step` is called next. By the next tick, the exponential height fog in the world will have the new density. If there is no fog in the world, it will be automatically created with the given density. Args: density (float): The new density value, between 0 and 1. The command will not be sent if the given density is invalid.
[ "Queue", "up", "a", "change", "fog", "density", "command", ".", "It", "will", "be", "applied", "when", "tick", "or", "step", "is", "called", "next", ".", "By", "the", "next", "tick", "the", "exponential", "height", "fog", "in", "the", "world", "will", "have", "the", "new", "density", ".", "If", "there", "is", "no", "fog", "in", "the", "world", "it", "will", "be", "automatically", "created", "with", "the", "given", "density", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L275-L289
17,278
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.set_day_time
def set_day_time(self, hour): """Queue up a change day time command. It will be applied when `tick` or `step` is called next. By the next tick, the lighting and the skysphere will be updated with the new hour. If there is no skysphere or directional light in the world, the command will not function properly but will not cause a crash. Args: hour (int): The hour in military time, between 0 and 23 inclusive. """ self._should_write_to_command_buffer = True command_to_send = DayTimeCommand(hour % 24) self._commands.add_command(command_to_send)
python
def set_day_time(self, hour): """Queue up a change day time command. It will be applied when `tick` or `step` is called next. By the next tick, the lighting and the skysphere will be updated with the new hour. If there is no skysphere or directional light in the world, the command will not function properly but will not cause a crash. Args: hour (int): The hour in military time, between 0 and 23 inclusive. """ self._should_write_to_command_buffer = True command_to_send = DayTimeCommand(hour % 24) self._commands.add_command(command_to_send)
[ "def", "set_day_time", "(", "self", ",", "hour", ")", ":", "self", ".", "_should_write_to_command_buffer", "=", "True", "command_to_send", "=", "DayTimeCommand", "(", "hour", "%", "24", ")", "self", ".", "_commands", ".", "add_command", "(", "command_to_send", ")" ]
Queue up a change day time command. It will be applied when `tick` or `step` is called next. By the next tick, the lighting and the skysphere will be updated with the new hour. If there is no skysphere or directional light in the world, the command will not function properly but will not cause a crash. Args: hour (int): The hour in military time, between 0 and 23 inclusive.
[ "Queue", "up", "a", "change", "day", "time", "command", ".", "It", "will", "be", "applied", "when", "tick", "or", "step", "is", "called", "next", ".", "By", "the", "next", "tick", "the", "lighting", "and", "the", "skysphere", "will", "be", "updated", "with", "the", "new", "hour", ".", "If", "there", "is", "no", "skysphere", "or", "directional", "light", "in", "the", "world", "the", "command", "will", "not", "function", "properly", "but", "will", "not", "cause", "a", "crash", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L291-L301
17,279
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.start_day_cycle
def start_day_cycle(self, day_length): """Queue up a day cycle command to start the day cycle. It will be applied when `tick` or `step` is called next. The sky sphere will now update each tick with an updated sun angle as it moves about the sky. The length of a day will be roughly equivalent to the number of minutes given. Args: day_length (int): The number of minutes each day will be. """ if day_length <= 0: raise HolodeckException("The given day length should be between above 0!") self._should_write_to_command_buffer = True command_to_send = DayCycleCommand(True) command_to_send.set_day_length(day_length) self._commands.add_command(command_to_send)
python
def start_day_cycle(self, day_length): """Queue up a day cycle command to start the day cycle. It will be applied when `tick` or `step` is called next. The sky sphere will now update each tick with an updated sun angle as it moves about the sky. The length of a day will be roughly equivalent to the number of minutes given. Args: day_length (int): The number of minutes each day will be. """ if day_length <= 0: raise HolodeckException("The given day length should be between above 0!") self._should_write_to_command_buffer = True command_to_send = DayCycleCommand(True) command_to_send.set_day_length(day_length) self._commands.add_command(command_to_send)
[ "def", "start_day_cycle", "(", "self", ",", "day_length", ")", ":", "if", "day_length", "<=", "0", ":", "raise", "HolodeckException", "(", "\"The given day length should be between above 0!\"", ")", "self", ".", "_should_write_to_command_buffer", "=", "True", "command_to_send", "=", "DayCycleCommand", "(", "True", ")", "command_to_send", ".", "set_day_length", "(", "day_length", ")", "self", ".", "_commands", ".", "add_command", "(", "command_to_send", ")" ]
Queue up a day cycle command to start the day cycle. It will be applied when `tick` or `step` is called next. The sky sphere will now update each tick with an updated sun angle as it moves about the sky. The length of a day will be roughly equivalent to the number of minutes given. Args: day_length (int): The number of minutes each day will be.
[ "Queue", "up", "a", "day", "cycle", "command", "to", "start", "the", "day", "cycle", ".", "It", "will", "be", "applied", "when", "tick", "or", "step", "is", "called", "next", ".", "The", "sky", "sphere", "will", "now", "update", "each", "tick", "with", "an", "updated", "sun", "angle", "as", "it", "moves", "about", "the", "sky", ".", "The", "length", "of", "a", "day", "will", "be", "roughly", "equivalent", "to", "the", "number", "of", "minutes", "given", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L303-L317
17,280
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.stop_day_cycle
def stop_day_cycle(self): """Queue up a day cycle command to stop the day cycle. It will be applied when `tick` or `step` is called next. By the next tick, day cycle will stop where it is. """ self._should_write_to_command_buffer = True command_to_send = DayCycleCommand(False) self._commands.add_command(command_to_send)
python
def stop_day_cycle(self): """Queue up a day cycle command to stop the day cycle. It will be applied when `tick` or `step` is called next. By the next tick, day cycle will stop where it is. """ self._should_write_to_command_buffer = True command_to_send = DayCycleCommand(False) self._commands.add_command(command_to_send)
[ "def", "stop_day_cycle", "(", "self", ")", ":", "self", ".", "_should_write_to_command_buffer", "=", "True", "command_to_send", "=", "DayCycleCommand", "(", "False", ")", "self", ".", "_commands", ".", "add_command", "(", "command_to_send", ")" ]
Queue up a day cycle command to stop the day cycle. It will be applied when `tick` or `step` is called next. By the next tick, day cycle will stop where it is.
[ "Queue", "up", "a", "day", "cycle", "command", "to", "stop", "the", "day", "cycle", ".", "It", "will", "be", "applied", "when", "tick", "or", "step", "is", "called", "next", ".", "By", "the", "next", "tick", "day", "cycle", "will", "stop", "where", "it", "is", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L319-L325
17,281
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.teleport_camera
def teleport_camera(self, location, rotation): """Queue up a teleport camera command to stop the day cycle. By the next tick, the camera's location and rotation will be updated """ self._should_write_to_command_buffer = True command_to_send = TeleportCameraCommand(location, rotation) self._commands.add_command(command_to_send)
python
def teleport_camera(self, location, rotation): """Queue up a teleport camera command to stop the day cycle. By the next tick, the camera's location and rotation will be updated """ self._should_write_to_command_buffer = True command_to_send = TeleportCameraCommand(location, rotation) self._commands.add_command(command_to_send)
[ "def", "teleport_camera", "(", "self", ",", "location", ",", "rotation", ")", ":", "self", ".", "_should_write_to_command_buffer", "=", "True", "command_to_send", "=", "TeleportCameraCommand", "(", "location", ",", "rotation", ")", "self", ".", "_commands", ".", "add_command", "(", "command_to_send", ")" ]
Queue up a teleport camera command to stop the day cycle. By the next tick, the camera's location and rotation will be updated
[ "Queue", "up", "a", "teleport", "camera", "command", "to", "stop", "the", "day", "cycle", ".", "By", "the", "next", "tick", "the", "camera", "s", "location", "and", "rotation", "will", "be", "updated" ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L327-L333
17,282
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.set_control_scheme
def set_control_scheme(self, agent_name, control_scheme): """Set the control scheme for a specific agent. Args: agent_name (str): The name of the agent to set the control scheme for. control_scheme (int): A control scheme value (see :obj:`holodeck.agents.ControlSchemes`) """ if agent_name not in self.agents: print("No such agent %s" % agent_name) else: self.agents[agent_name].set_control_scheme(control_scheme)
python
def set_control_scheme(self, agent_name, control_scheme): """Set the control scheme for a specific agent. Args: agent_name (str): The name of the agent to set the control scheme for. control_scheme (int): A control scheme value (see :obj:`holodeck.agents.ControlSchemes`) """ if agent_name not in self.agents: print("No such agent %s" % agent_name) else: self.agents[agent_name].set_control_scheme(control_scheme)
[ "def", "set_control_scheme", "(", "self", ",", "agent_name", ",", "control_scheme", ")", ":", "if", "agent_name", "not", "in", "self", ".", "agents", ":", "print", "(", "\"No such agent %s\"", "%", "agent_name", ")", "else", ":", "self", ".", "agents", "[", "agent_name", "]", ".", "set_control_scheme", "(", "control_scheme", ")" ]
Set the control scheme for a specific agent. Args: agent_name (str): The name of the agent to set the control scheme for. control_scheme (int): A control scheme value (see :obj:`holodeck.agents.ControlSchemes`)
[ "Set", "the", "control", "scheme", "for", "a", "specific", "agent", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L357-L367
17,283
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment._handle_command_buffer
def _handle_command_buffer(self): """Checks if we should write to the command buffer, writes all of the queued commands to the buffer, and then clears the contents of the self._commands list""" if self._should_write_to_command_buffer: self._write_to_command_buffer(self._commands.to_json()) self._should_write_to_command_buffer = False self._commands.clear()
python
def _handle_command_buffer(self): """Checks if we should write to the command buffer, writes all of the queued commands to the buffer, and then clears the contents of the self._commands list""" if self._should_write_to_command_buffer: self._write_to_command_buffer(self._commands.to_json()) self._should_write_to_command_buffer = False self._commands.clear()
[ "def", "_handle_command_buffer", "(", "self", ")", ":", "if", "self", ".", "_should_write_to_command_buffer", ":", "self", ".", "_write_to_command_buffer", "(", "self", ".", "_commands", ".", "to_json", "(", ")", ")", "self", ".", "_should_write_to_command_buffer", "=", "False", "self", ".", "_commands", ".", "clear", "(", ")" ]
Checks if we should write to the command buffer, writes all of the queued commands to the buffer, and then clears the contents of the self._commands list
[ "Checks", "if", "we", "should", "write", "to", "the", "command", "buffer", "writes", "all", "of", "the", "queued", "commands", "to", "the", "buffer", "and", "then", "clears", "the", "contents", "of", "the", "self", ".", "_commands", "list" ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L423-L429
17,284
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment._write_to_command_buffer
def _write_to_command_buffer(self, to_write): """Write input to the command buffer. Reformat input string to the correct format. Args: to_write (str): The string to write to the command buffer. """ # TODO(mitch): Handle the edge case of writing too much data to the buffer. np.copyto(self._command_bool_ptr, True) to_write += '0' # The gason JSON parser in holodeck expects a 0 at the end of the file. input_bytes = str.encode(to_write) for index, val in enumerate(input_bytes): self._command_buffer_ptr[index] = val
python
def _write_to_command_buffer(self, to_write): """Write input to the command buffer. Reformat input string to the correct format. Args: to_write (str): The string to write to the command buffer. """ # TODO(mitch): Handle the edge case of writing too much data to the buffer. np.copyto(self._command_bool_ptr, True) to_write += '0' # The gason JSON parser in holodeck expects a 0 at the end of the file. input_bytes = str.encode(to_write) for index, val in enumerate(input_bytes): self._command_buffer_ptr[index] = val
[ "def", "_write_to_command_buffer", "(", "self", ",", "to_write", ")", ":", "# TODO(mitch): Handle the edge case of writing too much data to the buffer.", "np", ".", "copyto", "(", "self", ".", "_command_bool_ptr", ",", "True", ")", "to_write", "+=", "'0'", "# The gason JSON parser in holodeck expects a 0 at the end of the file.", "input_bytes", "=", "str", ".", "encode", "(", "to_write", ")", "for", "index", ",", "val", "in", "enumerate", "(", "input_bytes", ")", ":", "self", ".", "_command_buffer_ptr", "[", "index", "]", "=", "val" ]
Write input to the command buffer. Reformat input string to the correct format. Args: to_write (str): The string to write to the command buffer.
[ "Write", "input", "to", "the", "command", "buffer", ".", "Reformat", "input", "string", "to", "the", "correct", "format", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L453-L464
17,285
BYU-PCCL/holodeck
holodeck/agents.py
HolodeckAgent.teleport
def teleport(self, location=None, rotation=None): """Teleports the agent to a specific location, with a specific rotation. Args: location (np.ndarray, optional): An array with three elements specifying the target world coordinate in meters. If None, keeps the current location. Defaults to None. rotation (np.ndarray, optional): An array with three elements specifying the target rotation of the agent. If None, keeps the current rotation. Defaults to None. Returns: None """ val = 0 if location is not None: val += 1 np.copyto(self._teleport_buffer, location) if rotation is not None: np.copyto(self._rotation_buffer, rotation) val += 2 self._teleport_bool_buffer[0] = val
python
def teleport(self, location=None, rotation=None): """Teleports the agent to a specific location, with a specific rotation. Args: location (np.ndarray, optional): An array with three elements specifying the target world coordinate in meters. If None, keeps the current location. Defaults to None. rotation (np.ndarray, optional): An array with three elements specifying the target rotation of the agent. If None, keeps the current rotation. Defaults to None. Returns: None """ val = 0 if location is not None: val += 1 np.copyto(self._teleport_buffer, location) if rotation is not None: np.copyto(self._rotation_buffer, rotation) val += 2 self._teleport_bool_buffer[0] = val
[ "def", "teleport", "(", "self", ",", "location", "=", "None", ",", "rotation", "=", "None", ")", ":", "val", "=", "0", "if", "location", "is", "not", "None", ":", "val", "+=", "1", "np", ".", "copyto", "(", "self", ".", "_teleport_buffer", ",", "location", ")", "if", "rotation", "is", "not", "None", ":", "np", ".", "copyto", "(", "self", ".", "_rotation_buffer", ",", "rotation", ")", "val", "+=", "2", "self", ".", "_teleport_bool_buffer", "[", "0", "]", "=", "val" ]
Teleports the agent to a specific location, with a specific rotation. Args: location (np.ndarray, optional): An array with three elements specifying the target world coordinate in meters. If None, keeps the current location. Defaults to None. rotation (np.ndarray, optional): An array with three elements specifying the target rotation of the agent. If None, keeps the current rotation. Defaults to None. Returns: None
[ "Teleports", "the", "agent", "to", "a", "specific", "location", "with", "a", "specific", "rotation", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/agents.py#L79-L98
17,286
browniebroke/deezer-python
deezer/client.py
Client.url
def url(self, request=""): """Build the url with the appended request if provided.""" if request.startswith("/"): request = request[1:] return "{}://{}/{}".format(self.scheme, self.host, request)
python
def url(self, request=""): """Build the url with the appended request if provided.""" if request.startswith("/"): request = request[1:] return "{}://{}/{}".format(self.scheme, self.host, request)
[ "def", "url", "(", "self", ",", "request", "=", "\"\"", ")", ":", "if", "request", ".", "startswith", "(", "\"/\"", ")", ":", "request", "=", "request", "[", "1", ":", "]", "return", "\"{}://{}/{}\"", ".", "format", "(", "self", ".", "scheme", ",", "self", ".", "host", ",", "request", ")" ]
Build the url with the appended request if provided.
[ "Build", "the", "url", "with", "the", "appended", "request", "if", "provided", "." ]
fb869c3617045b22e7124e4b783ec1a68d283ac3
https://github.com/browniebroke/deezer-python/blob/fb869c3617045b22e7124e4b783ec1a68d283ac3/deezer/client.py#L95-L99
17,287
browniebroke/deezer-python
deezer/client.py
Client.object_url
def object_url(self, object_t, object_id=None, relation=None, **kwargs): """ Helper method to build the url to query to access the object passed as parameter :raises TypeError: if the object type is invalid """ if object_t not in self.objects_types: raise TypeError("{} is not a valid type".format(object_t)) request_items = ( str(item) for item in [object_t, object_id, relation] if item is not None ) request = "/".join(request_items) base_url = self.url(request) if self.access_token is not None: kwargs["access_token"] = str(self.access_token) if kwargs: for key, value in kwargs.items(): if not isinstance(value, str): kwargs[key] = str(value) # kwargs are sorted (for consistent tests between Python < 3.7 and >= 3.7) sorted_kwargs = SortedDict.from_dict(kwargs) result = "{}?{}".format(base_url, urlencode(sorted_kwargs)) else: result = base_url return result
python
def object_url(self, object_t, object_id=None, relation=None, **kwargs): """ Helper method to build the url to query to access the object passed as parameter :raises TypeError: if the object type is invalid """ if object_t not in self.objects_types: raise TypeError("{} is not a valid type".format(object_t)) request_items = ( str(item) for item in [object_t, object_id, relation] if item is not None ) request = "/".join(request_items) base_url = self.url(request) if self.access_token is not None: kwargs["access_token"] = str(self.access_token) if kwargs: for key, value in kwargs.items(): if not isinstance(value, str): kwargs[key] = str(value) # kwargs are sorted (for consistent tests between Python < 3.7 and >= 3.7) sorted_kwargs = SortedDict.from_dict(kwargs) result = "{}?{}".format(base_url, urlencode(sorted_kwargs)) else: result = base_url return result
[ "def", "object_url", "(", "self", ",", "object_t", ",", "object_id", "=", "None", ",", "relation", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "object_t", "not", "in", "self", ".", "objects_types", ":", "raise", "TypeError", "(", "\"{} is not a valid type\"", ".", "format", "(", "object_t", ")", ")", "request_items", "=", "(", "str", "(", "item", ")", "for", "item", "in", "[", "object_t", ",", "object_id", ",", "relation", "]", "if", "item", "is", "not", "None", ")", "request", "=", "\"/\"", ".", "join", "(", "request_items", ")", "base_url", "=", "self", ".", "url", "(", "request", ")", "if", "self", ".", "access_token", "is", "not", "None", ":", "kwargs", "[", "\"access_token\"", "]", "=", "str", "(", "self", ".", "access_token", ")", "if", "kwargs", ":", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "not", "isinstance", "(", "value", ",", "str", ")", ":", "kwargs", "[", "key", "]", "=", "str", "(", "value", ")", "# kwargs are sorted (for consistent tests between Python < 3.7 and >= 3.7)", "sorted_kwargs", "=", "SortedDict", ".", "from_dict", "(", "kwargs", ")", "result", "=", "\"{}?{}\"", ".", "format", "(", "base_url", ",", "urlencode", "(", "sorted_kwargs", ")", ")", "else", ":", "result", "=", "base_url", "return", "result" ]
Helper method to build the url to query to access the object passed as parameter :raises TypeError: if the object type is invalid
[ "Helper", "method", "to", "build", "the", "url", "to", "query", "to", "access", "the", "object", "passed", "as", "parameter" ]
fb869c3617045b22e7124e4b783ec1a68d283ac3
https://github.com/browniebroke/deezer-python/blob/fb869c3617045b22e7124e4b783ec1a68d283ac3/deezer/client.py#L101-L126
17,288
browniebroke/deezer-python
deezer/client.py
Client.get_album
def get_album(self, object_id, relation=None, **kwargs): """ Get the album with the provided id :returns: an :class:`~deezer.resources.Album` object """ return self.get_object("album", object_id, relation=relation, **kwargs)
python
def get_album(self, object_id, relation=None, **kwargs): """ Get the album with the provided id :returns: an :class:`~deezer.resources.Album` object """ return self.get_object("album", object_id, relation=relation, **kwargs)
[ "def", "get_album", "(", "self", ",", "object_id", ",", "relation", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "get_object", "(", "\"album\"", ",", "object_id", ",", "relation", "=", "relation", ",", "*", "*", "kwargs", ")" ]
Get the album with the provided id :returns: an :class:`~deezer.resources.Album` object
[ "Get", "the", "album", "with", "the", "provided", "id" ]
fb869c3617045b22e7124e4b783ec1a68d283ac3
https://github.com/browniebroke/deezer-python/blob/fb869c3617045b22e7124e4b783ec1a68d283ac3/deezer/client.py#L150-L156
17,289
browniebroke/deezer-python
deezer/client.py
Client.get_artist
def get_artist(self, object_id, relation=None, **kwargs): """ Get the artist with the provided id :returns: an :class:`~deezer.resources.Artist` object """ return self.get_object("artist", object_id, relation=relation, **kwargs)
python
def get_artist(self, object_id, relation=None, **kwargs): """ Get the artist with the provided id :returns: an :class:`~deezer.resources.Artist` object """ return self.get_object("artist", object_id, relation=relation, **kwargs)
[ "def", "get_artist", "(", "self", ",", "object_id", ",", "relation", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "get_object", "(", "\"artist\"", ",", "object_id", ",", "relation", "=", "relation", ",", "*", "*", "kwargs", ")" ]
Get the artist with the provided id :returns: an :class:`~deezer.resources.Artist` object
[ "Get", "the", "artist", "with", "the", "provided", "id" ]
fb869c3617045b22e7124e4b783ec1a68d283ac3
https://github.com/browniebroke/deezer-python/blob/fb869c3617045b22e7124e4b783ec1a68d283ac3/deezer/client.py#L158-L164
17,290
browniebroke/deezer-python
deezer/client.py
Client.search
def search(self, query, relation=None, index=0, limit=25, **kwargs): """ Search track, album, artist or user :returns: a list of :class:`~deezer.resources.Resource` objects. """ return self.get_object( "search", relation=relation, q=query, index=index, limit=limit, **kwargs )
python
def search(self, query, relation=None, index=0, limit=25, **kwargs): """ Search track, album, artist or user :returns: a list of :class:`~deezer.resources.Resource` objects. """ return self.get_object( "search", relation=relation, q=query, index=index, limit=limit, **kwargs )
[ "def", "search", "(", "self", ",", "query", ",", "relation", "=", "None", ",", "index", "=", "0", ",", "limit", "=", "25", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "get_object", "(", "\"search\"", ",", "relation", "=", "relation", ",", "q", "=", "query", ",", "index", "=", "index", ",", "limit", "=", "limit", ",", "*", "*", "kwargs", ")" ]
Search track, album, artist or user :returns: a list of :class:`~deezer.resources.Resource` objects.
[ "Search", "track", "album", "artist", "or", "user" ]
fb869c3617045b22e7124e4b783ec1a68d283ac3
https://github.com/browniebroke/deezer-python/blob/fb869c3617045b22e7124e4b783ec1a68d283ac3/deezer/client.py#L236-L244
17,291
browniebroke/deezer-python
deezer/client.py
Client.advanced_search
def advanced_search(self, terms, relation=None, index=0, limit=25, **kwargs): """ Advanced search of track, album or artist. See `Search section of Deezer API <https://developers.deezer.com/api/search>`_ for search terms. :returns: a list of :class:`~deezer.resources.Resource` objects. >>> client.advanced_search({"artist": "Daft Punk", "album": "Homework"}) >>> client.advanced_search({"artist": "Daft Punk", "album": "Homework"}, ... relation="track") """ assert isinstance(terms, dict), "terms must be a dict" # terms are sorted (for consistent tests between Python < 3.7 and >= 3.7) query = " ".join(sorted(['{}:"{}"'.format(k, v) for (k, v) in terms.items()])) return self.get_object( "search", relation=relation, q=query, index=index, limit=limit, **kwargs )
python
def advanced_search(self, terms, relation=None, index=0, limit=25, **kwargs): """ Advanced search of track, album or artist. See `Search section of Deezer API <https://developers.deezer.com/api/search>`_ for search terms. :returns: a list of :class:`~deezer.resources.Resource` objects. >>> client.advanced_search({"artist": "Daft Punk", "album": "Homework"}) >>> client.advanced_search({"artist": "Daft Punk", "album": "Homework"}, ... relation="track") """ assert isinstance(terms, dict), "terms must be a dict" # terms are sorted (for consistent tests between Python < 3.7 and >= 3.7) query = " ".join(sorted(['{}:"{}"'.format(k, v) for (k, v) in terms.items()])) return self.get_object( "search", relation=relation, q=query, index=index, limit=limit, **kwargs )
[ "def", "advanced_search", "(", "self", ",", "terms", ",", "relation", "=", "None", ",", "index", "=", "0", ",", "limit", "=", "25", ",", "*", "*", "kwargs", ")", ":", "assert", "isinstance", "(", "terms", ",", "dict", ")", ",", "\"terms must be a dict\"", "# terms are sorted (for consistent tests between Python < 3.7 and >= 3.7)", "query", "=", "\" \"", ".", "join", "(", "sorted", "(", "[", "'{}:\"{}\"'", ".", "format", "(", "k", ",", "v", ")", "for", "(", "k", ",", "v", ")", "in", "terms", ".", "items", "(", ")", "]", ")", ")", "return", "self", ".", "get_object", "(", "\"search\"", ",", "relation", "=", "relation", ",", "q", "=", "query", ",", "index", "=", "index", ",", "limit", "=", "limit", ",", "*", "*", "kwargs", ")" ]
Advanced search of track, album or artist. See `Search section of Deezer API <https://developers.deezer.com/api/search>`_ for search terms. :returns: a list of :class:`~deezer.resources.Resource` objects. >>> client.advanced_search({"artist": "Daft Punk", "album": "Homework"}) >>> client.advanced_search({"artist": "Daft Punk", "album": "Homework"}, ... relation="track")
[ "Advanced", "search", "of", "track", "album", "or", "artist", "." ]
fb869c3617045b22e7124e4b783ec1a68d283ac3
https://github.com/browniebroke/deezer-python/blob/fb869c3617045b22e7124e4b783ec1a68d283ac3/deezer/client.py#L246-L264
17,292
browniebroke/deezer-python
deezer/resources.py
Resource.asdict
def asdict(self): """ Convert resource to dictionary """ result = {} for key in self._fields: value = getattr(self, key) if isinstance(value, list): value = [i.asdict() if isinstance(i, Resource) else i for i in value] if isinstance(value, Resource): value = value.asdict() result[key] = value return result
python
def asdict(self): """ Convert resource to dictionary """ result = {} for key in self._fields: value = getattr(self, key) if isinstance(value, list): value = [i.asdict() if isinstance(i, Resource) else i for i in value] if isinstance(value, Resource): value = value.asdict() result[key] = value return result
[ "def", "asdict", "(", "self", ")", ":", "result", "=", "{", "}", "for", "key", "in", "self", ".", "_fields", ":", "value", "=", "getattr", "(", "self", ",", "key", ")", "if", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", "[", "i", ".", "asdict", "(", ")", "if", "isinstance", "(", "i", ",", "Resource", ")", "else", "i", "for", "i", "in", "value", "]", "if", "isinstance", "(", "value", ",", "Resource", ")", ":", "value", "=", "value", ".", "asdict", "(", ")", "result", "[", "key", "]", "=", "value", "return", "result" ]
Convert resource to dictionary
[ "Convert", "resource", "to", "dictionary" ]
fb869c3617045b22e7124e4b783ec1a68d283ac3
https://github.com/browniebroke/deezer-python/blob/fb869c3617045b22e7124e4b783ec1a68d283ac3/deezer/resources.py#L28-L40
17,293
browniebroke/deezer-python
deezer/resources.py
Resource.get_relation
def get_relation(self, relation, **kwargs): """ Generic method to load the relation from any resource. Query the client with the object's known parameters and try to retrieve the provided relation type. This is not meant to be used directly by a client, it's more a helper method for the child objects. """ # pylint: disable=E1101 return self.client.get_object(self.type, self.id, relation, self, **kwargs)
python
def get_relation(self, relation, **kwargs): """ Generic method to load the relation from any resource. Query the client with the object's known parameters and try to retrieve the provided relation type. This is not meant to be used directly by a client, it's more a helper method for the child objects. """ # pylint: disable=E1101 return self.client.get_object(self.type, self.id, relation, self, **kwargs)
[ "def", "get_relation", "(", "self", ",", "relation", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=E1101", "return", "self", ".", "client", ".", "get_object", "(", "self", ".", "type", ",", "self", ".", "id", ",", "relation", ",", "self", ",", "*", "*", "kwargs", ")" ]
Generic method to load the relation from any resource. Query the client with the object's known parameters and try to retrieve the provided relation type. This is not meant to be used directly by a client, it's more a helper method for the child objects.
[ "Generic", "method", "to", "load", "the", "relation", "from", "any", "resource", "." ]
fb869c3617045b22e7124e4b783ec1a68d283ac3
https://github.com/browniebroke/deezer-python/blob/fb869c3617045b22e7124e4b783ec1a68d283ac3/deezer/resources.py#L42-L52
17,294
browniebroke/deezer-python
deezer/resources.py
Resource.iter_relation
def iter_relation(self, relation, **kwargs): """ Generic method to iterate relation from any resource. Query the client with the object's known parameters and try to retrieve the provided relation type. This is not meant to be used directly by a client, it's more a helper method for the child objects. """ # pylint: disable=E1101 index = 0 while 1: items = self.get_relation(relation, index=index, **kwargs) for item in items: yield (item) if len(items) == 0: break index += len(items)
python
def iter_relation(self, relation, **kwargs): """ Generic method to iterate relation from any resource. Query the client with the object's known parameters and try to retrieve the provided relation type. This is not meant to be used directly by a client, it's more a helper method for the child objects. """ # pylint: disable=E1101 index = 0 while 1: items = self.get_relation(relation, index=index, **kwargs) for item in items: yield (item) if len(items) == 0: break index += len(items)
[ "def", "iter_relation", "(", "self", ",", "relation", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=E1101", "index", "=", "0", "while", "1", ":", "items", "=", "self", ".", "get_relation", "(", "relation", ",", "index", "=", "index", ",", "*", "*", "kwargs", ")", "for", "item", "in", "items", ":", "yield", "(", "item", ")", "if", "len", "(", "items", ")", "==", "0", ":", "break", "index", "+=", "len", "(", "items", ")" ]
Generic method to iterate relation from any resource. Query the client with the object's known parameters and try to retrieve the provided relation type. This is not meant to be used directly by a client, it's more a helper method for the child objects.
[ "Generic", "method", "to", "iterate", "relation", "from", "any", "resource", "." ]
fb869c3617045b22e7124e4b783ec1a68d283ac3
https://github.com/browniebroke/deezer-python/blob/fb869c3617045b22e7124e4b783ec1a68d283ac3/deezer/resources.py#L54-L72
17,295
lambdamusic/Ontospy
ontospy/ontodocs/viz/viz_sigmajs.py
run
def run(graph, save_on_github=False, main_entity=None): """ 2016-11-30 """ try: ontology = graph.all_ontologies[0] uri = ontology.uri except: ontology = None uri = ";".join([s for s in graph.sources]) # ontotemplate = open("template.html", "r") ontotemplate = open(ONTODOCS_VIZ_TEMPLATES + "sigmajs.html", "r") t = Template(ontotemplate.read()) dict_graph = build_class_json(graph.classes) JSON_DATA_CLASSES = json.dumps(dict_graph) if False: c_mylist = build_D3treeStandard(0, 99, 1, graph.toplayer_classes) p_mylist = build_D3treeStandard(0, 99, 1, graph.toplayer_properties) s_mylist = build_D3treeStandard(0, 99, 1, graph.toplayer_skos) c_total = len(graph.classes) p_total = len(graph.all_properties) s_total = len(graph.all_skos_concepts) # hack to make sure that we have a default top level object JSON_DATA_CLASSES = json.dumps({'children' : c_mylist, 'name' : 'owl:Thing', 'id' : "None" }) JSON_DATA_PROPERTIES = json.dumps({'children' : p_mylist, 'name' : 'Properties', 'id' : "None" }) JSON_DATA_CONCEPTS = json.dumps({'children' : s_mylist, 'name' : 'Concepts', 'id' : "None" }) c = Context({ "ontology": ontology, "main_uri" : uri, "STATIC_PATH": ONTODOCS_VIZ_STATIC, "classes": graph.classes, "classes_TOPLAYER": len(graph.toplayer_classes), "properties": graph.all_properties, "properties_TOPLAYER": len(graph.toplayer_properties), "skosConcepts": graph.all_skos_concepts, "skosConcepts_TOPLAYER": len(graph.toplayer_skos), # "TOTAL_CLASSES": c_total, # "TOTAL_PROPERTIES": p_total, # "TOTAL_CONCEPTS": s_total, 'JSON_DATA_CLASSES' : JSON_DATA_CLASSES, # 'JSON_DATA_PROPERTIES' : JSON_DATA_PROPERTIES, # 'JSON_DATA_CONCEPTS' : JSON_DATA_CONCEPTS, }) rnd = t.render(c) return safe_str(rnd)
python
def run(graph, save_on_github=False, main_entity=None): """ 2016-11-30 """ try: ontology = graph.all_ontologies[0] uri = ontology.uri except: ontology = None uri = ";".join([s for s in graph.sources]) # ontotemplate = open("template.html", "r") ontotemplate = open(ONTODOCS_VIZ_TEMPLATES + "sigmajs.html", "r") t = Template(ontotemplate.read()) dict_graph = build_class_json(graph.classes) JSON_DATA_CLASSES = json.dumps(dict_graph) if False: c_mylist = build_D3treeStandard(0, 99, 1, graph.toplayer_classes) p_mylist = build_D3treeStandard(0, 99, 1, graph.toplayer_properties) s_mylist = build_D3treeStandard(0, 99, 1, graph.toplayer_skos) c_total = len(graph.classes) p_total = len(graph.all_properties) s_total = len(graph.all_skos_concepts) # hack to make sure that we have a default top level object JSON_DATA_CLASSES = json.dumps({'children' : c_mylist, 'name' : 'owl:Thing', 'id' : "None" }) JSON_DATA_PROPERTIES = json.dumps({'children' : p_mylist, 'name' : 'Properties', 'id' : "None" }) JSON_DATA_CONCEPTS = json.dumps({'children' : s_mylist, 'name' : 'Concepts', 'id' : "None" }) c = Context({ "ontology": ontology, "main_uri" : uri, "STATIC_PATH": ONTODOCS_VIZ_STATIC, "classes": graph.classes, "classes_TOPLAYER": len(graph.toplayer_classes), "properties": graph.all_properties, "properties_TOPLAYER": len(graph.toplayer_properties), "skosConcepts": graph.all_skos_concepts, "skosConcepts_TOPLAYER": len(graph.toplayer_skos), # "TOTAL_CLASSES": c_total, # "TOTAL_PROPERTIES": p_total, # "TOTAL_CONCEPTS": s_total, 'JSON_DATA_CLASSES' : JSON_DATA_CLASSES, # 'JSON_DATA_PROPERTIES' : JSON_DATA_PROPERTIES, # 'JSON_DATA_CONCEPTS' : JSON_DATA_CONCEPTS, }) rnd = t.render(c) return safe_str(rnd)
[ "def", "run", "(", "graph", ",", "save_on_github", "=", "False", ",", "main_entity", "=", "None", ")", ":", "try", ":", "ontology", "=", "graph", ".", "all_ontologies", "[", "0", "]", "uri", "=", "ontology", ".", "uri", "except", ":", "ontology", "=", "None", "uri", "=", "\";\"", ".", "join", "(", "[", "s", "for", "s", "in", "graph", ".", "sources", "]", ")", "# ontotemplate = open(\"template.html\", \"r\")", "ontotemplate", "=", "open", "(", "ONTODOCS_VIZ_TEMPLATES", "+", "\"sigmajs.html\"", ",", "\"r\"", ")", "t", "=", "Template", "(", "ontotemplate", ".", "read", "(", ")", ")", "dict_graph", "=", "build_class_json", "(", "graph", ".", "classes", ")", "JSON_DATA_CLASSES", "=", "json", ".", "dumps", "(", "dict_graph", ")", "if", "False", ":", "c_mylist", "=", "build_D3treeStandard", "(", "0", ",", "99", ",", "1", ",", "graph", ".", "toplayer_classes", ")", "p_mylist", "=", "build_D3treeStandard", "(", "0", ",", "99", ",", "1", ",", "graph", ".", "toplayer_properties", ")", "s_mylist", "=", "build_D3treeStandard", "(", "0", ",", "99", ",", "1", ",", "graph", ".", "toplayer_skos", ")", "c_total", "=", "len", "(", "graph", ".", "classes", ")", "p_total", "=", "len", "(", "graph", ".", "all_properties", ")", "s_total", "=", "len", "(", "graph", ".", "all_skos_concepts", ")", "# hack to make sure that we have a default top level object", "JSON_DATA_CLASSES", "=", "json", ".", "dumps", "(", "{", "'children'", ":", "c_mylist", ",", "'name'", ":", "'owl:Thing'", ",", "'id'", ":", "\"None\"", "}", ")", "JSON_DATA_PROPERTIES", "=", "json", ".", "dumps", "(", "{", "'children'", ":", "p_mylist", ",", "'name'", ":", "'Properties'", ",", "'id'", ":", "\"None\"", "}", ")", "JSON_DATA_CONCEPTS", "=", "json", ".", "dumps", "(", "{", "'children'", ":", "s_mylist", ",", "'name'", ":", "'Concepts'", ",", "'id'", ":", "\"None\"", "}", ")", "c", "=", "Context", "(", "{", "\"ontology\"", ":", "ontology", ",", "\"main_uri\"", ":", "uri", ",", "\"STATIC_PATH\"", ":", "ONTODOCS_VIZ_STATIC", ",", "\"classes\"", ":", "graph", ".", "classes", ",", "\"classes_TOPLAYER\"", ":", "len", "(", "graph", ".", "toplayer_classes", ")", ",", "\"properties\"", ":", "graph", ".", "all_properties", ",", "\"properties_TOPLAYER\"", ":", "len", "(", "graph", ".", "toplayer_properties", ")", ",", "\"skosConcepts\"", ":", "graph", ".", "all_skos_concepts", ",", "\"skosConcepts_TOPLAYER\"", ":", "len", "(", "graph", ".", "toplayer_skos", ")", ",", "# \"TOTAL_CLASSES\": c_total,", "# \"TOTAL_PROPERTIES\": p_total,", "# \"TOTAL_CONCEPTS\": s_total,", "'JSON_DATA_CLASSES'", ":", "JSON_DATA_CLASSES", ",", "# 'JSON_DATA_PROPERTIES' : JSON_DATA_PROPERTIES,", "# 'JSON_DATA_CONCEPTS' : JSON_DATA_CONCEPTS,", "}", ")", "rnd", "=", "t", ".", "render", "(", "c", ")", "return", "safe_str", "(", "rnd", ")" ]
2016-11-30
[ "2016", "-", "11", "-", "30" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/ontodocs/viz/viz_sigmajs.py#L149-L204
17,296
lambdamusic/Ontospy
ontospy/core/rdf_loader.py
RDFLoader._debugGraph
def _debugGraph(self): """internal util to print out contents of graph""" print("Len of graph: ", len(self.rdflib_graph)) for x, y, z in self.rdflib_graph: print(x, y, z)
python
def _debugGraph(self): """internal util to print out contents of graph""" print("Len of graph: ", len(self.rdflib_graph)) for x, y, z in self.rdflib_graph: print(x, y, z)
[ "def", "_debugGraph", "(", "self", ")", ":", "print", "(", "\"Len of graph: \"", ",", "len", "(", "self", ".", "rdflib_graph", ")", ")", "for", "x", ",", "y", ",", "z", "in", "self", ".", "rdflib_graph", ":", "print", "(", "x", ",", "y", ",", "z", ")" ]
internal util to print out contents of graph
[ "internal", "util", "to", "print", "out", "contents", "of", "graph" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/rdf_loader.py#L61-L65
17,297
lambdamusic/Ontospy
ontospy/core/rdf_loader.py
RDFLoader.load_uri
def load_uri(self, uri): """ Load a single resource into the graph for this object. Approach: try loading into a temporary graph first, if that succeeds merge it into the main graph. This allows to deal with the JSONLD loading issues which can solved only by using a ConjunctiveGraph (https://github.com/RDFLib/rdflib/issues/436). Also it deals with the RDFA error message which seems to stick into a graph even if the parse operation fails. NOTE the final merge operation can be improved as graph-set operations involving blank nodes could case collisions (https://rdflib.readthedocs.io/en/stable/merging.html) :param uri: single RDF source location :return: None (sets self.rdflib_graph and self.sources_valid) """ # if self.verbose: printDebug("----------") if self.verbose: printDebug("Reading: <%s>" % uri, fg="green") success = False sorted_fmt_opts = try_sort_fmt_opts(self.rdf_format_opts, uri) for f in sorted_fmt_opts: if self.verbose: printDebug(".. trying rdf serialization: <%s>" % f) try: if f == 'json-ld': if self.verbose: printDebug( "Detected JSONLD - loading data into rdflib.ConjunctiveGraph()", fg='green') temp_graph = rdflib.ConjunctiveGraph() else: temp_graph = rdflib.Graph() temp_graph.parse(uri, format=f) if self.verbose: printDebug("..... success!", bold=True) success = True self.sources_valid += [uri] # ok, so merge self.rdflib_graph = self.rdflib_graph + temp_graph break except: temp = None if self.verbose: printDebug("..... failed") # self._debugGraph() if not success == True: self.loading_failed(sorted_fmt_opts, uri=uri) self.sources_invalid += [uri]
python
def load_uri(self, uri): """ Load a single resource into the graph for this object. Approach: try loading into a temporary graph first, if that succeeds merge it into the main graph. This allows to deal with the JSONLD loading issues which can solved only by using a ConjunctiveGraph (https://github.com/RDFLib/rdflib/issues/436). Also it deals with the RDFA error message which seems to stick into a graph even if the parse operation fails. NOTE the final merge operation can be improved as graph-set operations involving blank nodes could case collisions (https://rdflib.readthedocs.io/en/stable/merging.html) :param uri: single RDF source location :return: None (sets self.rdflib_graph and self.sources_valid) """ # if self.verbose: printDebug("----------") if self.verbose: printDebug("Reading: <%s>" % uri, fg="green") success = False sorted_fmt_opts = try_sort_fmt_opts(self.rdf_format_opts, uri) for f in sorted_fmt_opts: if self.verbose: printDebug(".. trying rdf serialization: <%s>" % f) try: if f == 'json-ld': if self.verbose: printDebug( "Detected JSONLD - loading data into rdflib.ConjunctiveGraph()", fg='green') temp_graph = rdflib.ConjunctiveGraph() else: temp_graph = rdflib.Graph() temp_graph.parse(uri, format=f) if self.verbose: printDebug("..... success!", bold=True) success = True self.sources_valid += [uri] # ok, so merge self.rdflib_graph = self.rdflib_graph + temp_graph break except: temp = None if self.verbose: printDebug("..... failed") # self._debugGraph() if not success == True: self.loading_failed(sorted_fmt_opts, uri=uri) self.sources_invalid += [uri]
[ "def", "load_uri", "(", "self", ",", "uri", ")", ":", "# if self.verbose: printDebug(\"----------\")", "if", "self", ".", "verbose", ":", "printDebug", "(", "\"Reading: <%s>\"", "%", "uri", ",", "fg", "=", "\"green\"", ")", "success", "=", "False", "sorted_fmt_opts", "=", "try_sort_fmt_opts", "(", "self", ".", "rdf_format_opts", ",", "uri", ")", "for", "f", "in", "sorted_fmt_opts", ":", "if", "self", ".", "verbose", ":", "printDebug", "(", "\".. trying rdf serialization: <%s>\"", "%", "f", ")", "try", ":", "if", "f", "==", "'json-ld'", ":", "if", "self", ".", "verbose", ":", "printDebug", "(", "\"Detected JSONLD - loading data into rdflib.ConjunctiveGraph()\"", ",", "fg", "=", "'green'", ")", "temp_graph", "=", "rdflib", ".", "ConjunctiveGraph", "(", ")", "else", ":", "temp_graph", "=", "rdflib", ".", "Graph", "(", ")", "temp_graph", ".", "parse", "(", "uri", ",", "format", "=", "f", ")", "if", "self", ".", "verbose", ":", "printDebug", "(", "\"..... success!\"", ",", "bold", "=", "True", ")", "success", "=", "True", "self", ".", "sources_valid", "+=", "[", "uri", "]", "# ok, so merge", "self", ".", "rdflib_graph", "=", "self", ".", "rdflib_graph", "+", "temp_graph", "break", "except", ":", "temp", "=", "None", "if", "self", ".", "verbose", ":", "printDebug", "(", "\"..... failed\"", ")", "# self._debugGraph()", "if", "not", "success", "==", "True", ":", "self", ".", "loading_failed", "(", "sorted_fmt_opts", ",", "uri", "=", "uri", ")", "self", ".", "sources_invalid", "+=", "[", "uri", "]" ]
Load a single resource into the graph for this object. Approach: try loading into a temporary graph first, if that succeeds merge it into the main graph. This allows to deal with the JSONLD loading issues which can solved only by using a ConjunctiveGraph (https://github.com/RDFLib/rdflib/issues/436). Also it deals with the RDFA error message which seems to stick into a graph even if the parse operation fails. NOTE the final merge operation can be improved as graph-set operations involving blank nodes could case collisions (https://rdflib.readthedocs.io/en/stable/merging.html) :param uri: single RDF source location :return: None (sets self.rdflib_graph and self.sources_valid)
[ "Load", "a", "single", "resource", "into", "the", "graph", "for", "this", "object", "." ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/rdf_loader.py#L114-L158
17,298
lambdamusic/Ontospy
ontospy/core/rdf_loader.py
RDFLoader.print_summary
def print_summary(self): """ print out stats about loading operation """ if self.sources_valid: printDebug( "----------\nLoaded %d triples.\n----------" % len( self.rdflib_graph), fg='white') printDebug( "RDF sources loaded successfully: %d of %d." % (len(self.sources_valid), len(self.sources_valid) + len(self.sources_invalid)), fg='green') for s in self.sources_valid: printDebug("..... '" + s + "'", fg='white') printDebug("----------", fg='white') else: printDebug("Sorry - no valid RDF was found", fg='red') if self.sources_invalid: printDebug( "----------\nRDF sources failed to load: %d.\n----------" % (len(self.sources_invalid)), fg='red') for s in self.sources_invalid: printDebug("-> " + s, fg="red")
python
def print_summary(self): """ print out stats about loading operation """ if self.sources_valid: printDebug( "----------\nLoaded %d triples.\n----------" % len( self.rdflib_graph), fg='white') printDebug( "RDF sources loaded successfully: %d of %d." % (len(self.sources_valid), len(self.sources_valid) + len(self.sources_invalid)), fg='green') for s in self.sources_valid: printDebug("..... '" + s + "'", fg='white') printDebug("----------", fg='white') else: printDebug("Sorry - no valid RDF was found", fg='red') if self.sources_invalid: printDebug( "----------\nRDF sources failed to load: %d.\n----------" % (len(self.sources_invalid)), fg='red') for s in self.sources_invalid: printDebug("-> " + s, fg="red")
[ "def", "print_summary", "(", "self", ")", ":", "if", "self", ".", "sources_valid", ":", "printDebug", "(", "\"----------\\nLoaded %d triples.\\n----------\"", "%", "len", "(", "self", ".", "rdflib_graph", ")", ",", "fg", "=", "'white'", ")", "printDebug", "(", "\"RDF sources loaded successfully: %d of %d.\"", "%", "(", "len", "(", "self", ".", "sources_valid", ")", ",", "len", "(", "self", ".", "sources_valid", ")", "+", "len", "(", "self", ".", "sources_invalid", ")", ")", ",", "fg", "=", "'green'", ")", "for", "s", "in", "self", ".", "sources_valid", ":", "printDebug", "(", "\"..... '\"", "+", "s", "+", "\"'\"", ",", "fg", "=", "'white'", ")", "printDebug", "(", "\"----------\"", ",", "fg", "=", "'white'", ")", "else", ":", "printDebug", "(", "\"Sorry - no valid RDF was found\"", ",", "fg", "=", "'red'", ")", "if", "self", ".", "sources_invalid", ":", "printDebug", "(", "\"----------\\nRDF sources failed to load: %d.\\n----------\"", "%", "(", "len", "(", "self", ".", "sources_invalid", ")", ")", ",", "fg", "=", "'red'", ")", "for", "s", "in", "self", ".", "sources_invalid", ":", "printDebug", "(", "\"-> \"", "+", "s", ",", "fg", "=", "\"red\"", ")" ]
print out stats about loading operation
[ "print", "out", "stats", "about", "loading", "operation" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/rdf_loader.py#L225-L251
17,299
lambdamusic/Ontospy
ontospy/core/rdf_loader.py
RDFLoader.loading_failed
def loading_failed(self, rdf_format_opts, uri=""): """default message if we need to abort loading""" if uri: uri = " <%s>" % str(uri) printDebug( "----------\nFatal error parsing graph%s\n(using RDF serializations: %s)" % (uri, str(rdf_format_opts)), "red") printDebug( "----------\nTIP: You can try one of the following RDF validation services\n<http://mowl-power.cs.man.ac.uk:8080/validator/validate>\n<http://www.ivan-herman.net/Misc/2008/owlrl/>" ) return
python
def loading_failed(self, rdf_format_opts, uri=""): """default message if we need to abort loading""" if uri: uri = " <%s>" % str(uri) printDebug( "----------\nFatal error parsing graph%s\n(using RDF serializations: %s)" % (uri, str(rdf_format_opts)), "red") printDebug( "----------\nTIP: You can try one of the following RDF validation services\n<http://mowl-power.cs.man.ac.uk:8080/validator/validate>\n<http://www.ivan-herman.net/Misc/2008/owlrl/>" ) return
[ "def", "loading_failed", "(", "self", ",", "rdf_format_opts", ",", "uri", "=", "\"\"", ")", ":", "if", "uri", ":", "uri", "=", "\" <%s>\"", "%", "str", "(", "uri", ")", "printDebug", "(", "\"----------\\nFatal error parsing graph%s\\n(using RDF serializations: %s)\"", "%", "(", "uri", ",", "str", "(", "rdf_format_opts", ")", ")", ",", "\"red\"", ")", "printDebug", "(", "\"----------\\nTIP: You can try one of the following RDF validation services\\n<http://mowl-power.cs.man.ac.uk:8080/validator/validate>\\n<http://www.ivan-herman.net/Misc/2008/owlrl/>\"", ")", "return" ]
default message if we need to abort loading
[ "default", "message", "if", "we", "need", "to", "abort", "loading" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/rdf_loader.py#L253-L264