def _output_from_command_list(self, command_list, polys, verbose = False): """ A pexpect interface to phcpack, given a command list for interactive dialogs. The input file is supplied from the polynomial list, output file is also supplied. This is only used as a building block for the interface. INPUT: - command_list -- a list of commands to phc - polys -- a polynomial system as a list of polynomials OUTPUT: - an output string from phc EXAMPLES:: sage: from sage.interfaces.phc import * sage: R2.<x,y> = PolynomialRing(QQ,2) sage: start_sys = [(x-1)^2+(y-1)-1, x^2+y^2-1] # optional -- phc sage: a = phc._output_from_command_list(['phc -m','4','n','n','n'], start_sys) # optional -- phc """ # Get temporary file names (these will be in SAGE_HOME/.sage/tmp/pid) input_filename = tmp_filename() output_filename = tmp_filename() # Get the input polynomial text input = self._input_file(polys) if verbose: print("Writing the input file to %s" % input_filename) open(input_filename, 'w').write(input) if verbose: print("The following file will be the input polynomial file to phc.") print(input) # Create a phc process child_phc = pexpect.spawn(command_list[0]) # feed it the commands child_phc.sendline('y') child_phc.sendline(input_filename) child_phc.sendline(output_filename) for command_string in command_list[1:]: if verbose: print(command_string) child_phc.sendline(command_string) child_phc.expect('results') read_stuff = child_phc.read() if verbose: print(read_stuff) child_phc.close() if not os.path.exists(output_filename): raise RuntimeError("The output file does not exist; something went wrong running phc.") # Delete the input file os.unlink(input_filename) # Return the output filename return output_filename
def _path_track_file(self, start_filename_or_string, polys, input_ring, c_skew = 0.001, verbose = False): """ Returns the filename which contains path tracking output. EXAMPLES:: sage: from sage.interfaces.phc import * sage: R2.<x,y> = PolynomialRing(QQ,2) sage: start_sys = [x^6-y^2,y^5-1] sage: sol = phc.blackbox(start_sys, R2) # optional -- phc sage: start_save = sol.save_as_start() # optional -- phc sage: end_sys = [x^7-2,y^5-x^2] # optional -- phc sage: path_track_filename = phc._path_track_file(start_save, end_sys, R2, c_skew = .001) # optional -- phc sage: sol_paths = phc._parse_path_file(path_track_filename) # optional -- phc sage: len(sol_paths) # optional -- phc 30 """ # Probably unnecessarily redundant from the start_from function if start_filename_or_string.find('THE SOLUTIONS') != -1: start_filename = tmp_filename() start_file = open(start_filename, 'w') start_file.write(start_filename_or_string) start_file.close() elif os.path.exists(start_filename_or_string): start_filename = start_filename_or_string else: raise RuntimeError("There is something wrong with your start string or filename") return self._output_from_command_list(['phc','0','0','A',start_filename, 'y','1','0','n','k','2','a','1',str(c_skew),'0','0','2'], polys, verbose = verbose)
def __call__(self, assumptions=None): """ Run 'command' and collect output. INPUT: - ``assumptions`` - ignored, accepted for compatibility with other solvers (default: ``None``) TESTS: This class is not meant to be called directly:: sage: from sage.sat.solvers.dimacs import DIMACS sage: fn = tmp_filename() sage: solver = DIMACS(filename=fn) sage: solver.add_clause( (1, -2 , 3) ) sage: solver() Traceback (most recent call last): ... ValueError: No SAT solver command selected. """ if assumptions is not None: raise NotImplementedError("Assumptions are not supported for DIMACS based solvers.") self.write() output_filename = None self._output = [] command = self._command.strip() if not command: raise ValueError("No SAT solver command selected.") if "{output}" in command: output_filename = tmp_filename() command = command.format(input=self._headname, output=output_filename) args = shlex.split(command) try: process = subprocess.Popen(args, stdout=subprocess.PIPE) except OSError: raise OSError("Could run '%s', perhaps you need to add your SAT solver to $PATH?"%(" ".join(args))) try: while process.poll() is None: for line in iter(process.stdout.readline,''): if get_verbose() or self._verbosity: print line, sys.stdout.flush() self._output.append(line) sleep(0.1) if output_filename: self._output.extend(open(output_filename).readlines()) except BaseException: process.kill() raise
def __call__(self, assumptions=None): """ Run 'command' and collect output. INPUT: - ``assumptions`` - ignored, accepted for compatibility with other solvers (default: ``None``) TESTS: This class is not meant to be called directly:: sage: from sage.sat.solvers.dimacs import DIMACS sage: fn = tmp_filename() sage: solver = DIMACS(filename=fn) sage: solver.add_clause( (1, -2 , 3) ) sage: solver() Traceback (most recent call last): ... ValueError: No SAT solver command selected. """ if assumptions is not None: raise NotImplementedError("Assumptions are not supported for DIMACS based solvers.") self.write() output_filename = None self._output = [] command = self._command.strip() if not command: raise ValueError("No SAT solver command selected.") if "{output}" in command: output_filename = tmp_filename() command = command.format(input=self._headname, output=output_filename) args = shlex.split(command) try: process = subprocess.Popen(args, stdout=subprocess.PIPE) except OSError: raise OSError("Could run '%s', perhaps you need to add your SAT solver to $PATH?"%(" ".join(args))) try: while process.poll() is None: for line in iter(process.stdout.readline,''): if get_verbose() or self._verbosity: print(line) sys.stdout.flush() self._output.append(line) sleep(0.1) if output_filename: self._output.extend(open(output_filename).readlines()) except BaseException: process.kill() raise
def __init__(self, command=None, filename=None, verbosity=0, **kwds): """ Construct a new generic DIMACS solver. INPUT: - ``command`` - a named format string with the command to run. The string must contain {input} and may contain {output} if the solvers writes the solution to an output file. For example "sat-solver {input}" is a valid command. If ``None`` then the class variable ``command`` is used. (default: ``None``) - ``filename`` - a filename to write clauses to in DIMACS format, must be writable. If ``None`` a temporary filename is chosen automatically. (default: ``None``) - ``verbosity`` - a verbosity level, where zero means silent and anything else means verbose output. (default: ``0``) - ``**kwds`` - accepted for compatibility with other solves, ignored. TESTS:: sage: from sage.sat.solvers.dimacs import DIMACS sage: DIMACS() DIMACS Solver: '' """ if filename is None: filename = tmp_filename() self._headname = filename self._verbosity = verbosity if command is not None: self._command = command else: self._command = self.__class__.command self._tail = open(tmp_filename(), 'w') self._var = 0 self._lit = 0
def __init__(self, command=None, filename=None, verbosity=0, **kwds): """ Construct a new generic DIMACS solver. INPUT: - ``command`` - a named format string with the command to run. The string must contain {input} and may contain {output} if the solvers writes the solution to an output file. For example "sat-solver {input}" is a valid command. If ``None`` then the class variable ``command`` is used. (default: ``None``) - ``filename`` - a filename to write clauses to in DIMACS format, must be writable. If ``None`` a temporary filename is chosen automatically. (default: ``None``) - ``verbosity`` - a verbosity level, where zero means silent and anything else means verbose output. (default: ``0``) - ``**kwds`` - accepted for compatibility with other solves, ignored. TESTS:: sage: from sage.sat.solvers.dimacs import DIMACS sage: DIMACS() DIMACS Solver: '' """ if filename is None: filename = tmp_filename() self._headname = filename self._verbosity = verbosity if command is not None: self._command = command else: self._command = self.__class__.command self._tail = open(tmp_filename(),'w') self._var = 0 self._lit = 0
def __add__(self, other): if not isinstance(other, Polytope): raise TypeError, "other (=%s) must be a polytope" % other output_file = tmp_filename() infile1 = tmp_filename() open(infile1, 'w').write(self.__data) infile2 = tmp_filename() open(infile2, 'w').write(other.__data) cmd = "minkowski_sum %s 1 %s 1 %s" % (output_file, infile1, infile2) stdin, stdout, stderr = os.popen3(cmd) stdin.close() err = stderr.read() if len(err) > 0: raise RuntimeError, err print stdout.read(), err S = polymake.from_data(open(output_file).read()) os.unlink(infile1) os.unlink(infile2) os.unlink(output_file) return S
def __add__(self, other): if not isinstance(other, Polytope): raise TypeError("other (=%s) must be a polytope"%other) output_file = tmp_filename() infile1 = tmp_filename() open(infile1,'w').write(self.__data) infile2 = tmp_filename() open(infile2,'w').write(other.__data) cmd = "minkowski_sum %s 1 %s 1 %s"%(output_file, infile1, infile2) stdin, stdout, stderr = os.popen3(cmd) stdin.close() err = stderr.read() if len(err): raise RuntimeError(err) print(stdout.read(), err) S = polymake.from_data(open(output_file).read()) os.unlink(infile1) os.unlink(infile2) os.unlink(output_file) return S
def dump_to_tmpfile(s): """ Utility function to dump a string to a temporary file. EXAMPLE:: sage: from sage.combinat.designs import ext_rep sage: file_loc = ext_rep.dump_to_tmpfile("boo") sage: os.remove(file_loc) """ file_loc = tmp_filename() f = open(file_loc, "w") f.write(v2_b2_k2_icgsa) f.close() return file_loc
def dump_to_tmpfile(s): """ Utility function to dump a string to a temporary file. EXAMPLE:: sage: from sage.combinat.designs import ext_rep sage: file_loc = ext_rep.dump_to_tmpfile("boo") sage: os.remove(file_loc) """ file_loc = tmp_filename() f = open(file_loc,"w") f.write(v2_b2_k2_icgsa) f.close() return file_loc
def blackbox(self, polys, input_ring, verbose = False): """ Returns as a string the result of running PHC with the given polynomials under blackbox mode (the '-b' option). INPUT: - polys -- a list of multivariate polynomials (elements of a multivariate polynomial ring). - input_ring -- for coercion of the variables into the desired ring. - verbose -- print lots of verbose information about what this function does. OUTPUT: - a PHC_Object object containing the phcpack output string. EXAMPLES:: sage: from sage.interfaces.phc import * sage: R2.<x,y> = PolynomialRing(QQ,2) sage: start_sys = [x^6-y^2,y^5-1] sage: sol = phc.blackbox(start_sys, R2) # optional -- phc sage: len(sol.solutions()) # optional -- phc 30 """ # Get three temporary file names (these will be in SAGE_HOME/.sage/tmp/pid) input_filename = tmp_filename() output_filename = input_filename + ".phc" log_filename = tmp_filename() # Get the input polynomial text input = self._input_file(polys) if verbose: print("Writing the input file to %s" % input_filename) open(input_filename, 'w').write(input) if verbose: print("The following file will be the input polynomial file to phc.") print(input) # Create the phc command line> cmd = 'phc -b %s %s'%(input_filename, output_filename) if verbose: print("The phc command line is:") print(cmd) # Do it -- make the system call. e = os.system(cmd) # Was there an error? if e: from sage.misc.sage_ostools import have_program if not have_program('phc'): print(os.system('which phc') + ' PHC needs to be installed and in your path') raise RuntimeError # todo -- why? etc. raise RuntimeError(open(log_filename).read() + "\nError running phc.") if not os.path.exists(output_filename): raise RuntimeError("The output file does not exist; something went wrong running phc.") # Read the output produced by PHC out = open(output_filename).read() # All done return PHC_Object(out, input_ring)
def start_from(self, start_filename_or_string, polys, input_ring, path_track_file = None, verbose = False): """ This computes solutions starting from a phcpack solution file. INPUT: - start_filename_or_string -- the filename for a phcpack start system, or the contents of such a file as a string. Variable names must match the inputring variables. The value of the homotopy variable t should be 1, not 0. - polys -- a list of multivariate polynomials (elements of a multivariate polynomial ring). - input_ring: for coercion of the variables into the desired ring. - path_track_file: whether to save path-tracking information - verbose -- print lots of verbose information about what this function does. OUTPUT: - A solution in the form of a PHCObject. EXAMPLES:: sage: from sage.interfaces.phc import * sage: R2.<x,y> = PolynomialRing(QQ,2) sage: start_sys = [x^6-y^2,y^5-1] sage: sol = phc.blackbox(start_sys, R2) # optional -- phc sage: start_save = sol.save_as_start() # optional -- phc sage: end_sys = [x^7-2,y^5-x^2] # optional -- phc sage: sol = phc.start_from(start_save, end_sys, R2) # optional -- phc sage: len(sol.solutions()) # optional -- phc 30 """ input_filename = tmp_filename() output_filename = tmp_filename() if start_filename_or_string.find('THE SOLUTIONS') != -1: start_filename = tmp_filename() start_file = open(start_filename,'w') start_file.write(start_filename_or_string) start_file.close() elif os.path.exists(start_filename_or_string): start_filename = start_filename_or_string else: raise RuntimeError("There is something wrong with your start string or filename") # Get the input polynomial text input = self._input_file(polys) if verbose: print("Writing the input file to %s" % input_filename) open(input_filename, 'w').write(input) if verbose: print("The following file will be the input polynomial file to phc.") print(input) # Create a phc process child_phc = pexpect.spawn('phc') child_phc.sendline('y') child_phc.sendline(input_filename) child_phc.sendline(output_filename) child_phc.sendline('0') child_phc.sendline('0') child_phc.expect('Nonlinear Reduction') child_phc.sendline('A') child_phc.sendline(start_filename) child_phc.sendline('y') child_phc.sendline('1') child_phc.sendline('0') if verbose: phc_dialog = child_phc.read(size = 40) print(phc_dialog) child_phc.sendline('n') child_phc.sendline('0') if verbose: child_phc.expect('CURRENT CONTINUATION') phc_dialog = child_phc.read(size = 40) print(phc_dialog) child_phc.sendline('0') if path_track_file is None: child_phc.sendline('0') else: child_phc.sendline('2') child_phc.expect('results') dots = child_phc.read() if verbose: print("should be . : " + dots) #close down the process: child_phc.close() if not os.path.exists(output_filename): raise RuntimeError("The output file does not exist; something went wrong running phc.") # Read the output produced by PHC out = open(output_filename).read() # Delete the temporary files os.unlink(output_filename) os.unlink(input_filename) # All done return PHC_Object(out, input_ring)