sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def evaluate(grid): "Return the value for the player to move, assuming perfect play." if is_won(grid): return -1 succs = successors(grid) return -min(map(evaluate, succs)) if succs else 0
Return the value for the player to move, assuming perfect play.
entailment
def is_won(grid): "Did the latest move win the game?" p, q = grid return any(way == (way & q) for way in ways_to_win)
Did the latest move win the game?
entailment
def apply_move(grid, move): "Try to move: return a new grid, or None if illegal." p, q = grid bit = 1 << move return (q, p | bit) if 0 == (bit & (p | q)) else None
Try to move: return a new grid, or None if illegal.
entailment
def player_marks(grid): "Return two results: the player's mark and their opponent's." p, q = grid return 'XO' if sum(player_bits(p)) == sum(player_bits(q)) else 'OX'
Return two results: the player's mark and their opponent's.
entailment
def view(grid): "Show a grid human-readably." p_mark, q_mark = player_marks(grid) return grid_format % tuple(p_mark if by_p else q_mark if by_q else '.' for by_p, by_q in zip(*map(player_bits, grid)))
Show a grid human-readably.
entailment
def read_sdpa_out(filename, solutionmatrix=False, status=False, sdp=None): """Helper function to parse the output file of SDPA. :param filename: The name of the SDPA output file. :type filename: str. :param solutionmatrix: Optional parameter for retrieving the solution. :type solutionmatrix: bool. :param status: Optional parameter for retrieving the status. :type status: bool. :param sdp: Optional parameter to add the solution to a relaxation. :type sdp: sdp. :returns: tuple of two floats and optionally two lists of `numpy.array` and a status string """ primal = None dual = None x_mat = None y_mat = None status_string = None with open(filename, 'r') as file_: for line in file_: if line.find("objValPrimal") > -1: primal = float((line.split())[2]) if line.find("objValDual") > -1: dual = float((line.split())[2]) if solutionmatrix: if line.find("xMat =") > -1: x_mat = parse_solution_matrix(file_) if line.find("yMat =") > -1: y_mat = parse_solution_matrix(file_) if line.find("phase.value") > -1: if line.find("pdOPT") > -1: status_string = 'optimal' elif line.find("pFEAS") > -1: status_string = 'primal feasible' elif line.find("pdFEAS") > -1: status_string = 'primal-dual feasible' elif line.find("dFEAS") > -1: status_string = 'dual feasible' elif line.find("INF") > -1: status_string = 'infeasible' elif line.find("UNBD") > -1: status_string = 'unbounded' else: status_string = 'unknown' for var in [primal, dual, status_string]: if var is None: status_string = 'invalid' break if solutionmatrix: for var in [x_mat, y_mat]: if var is None: status_string = 'invalid' break if sdp is not None: sdp.primal = primal sdp.dual = dual sdp.x_mat = x_mat sdp.y_mat = y_mat sdp.status = status_string if solutionmatrix and status: return primal, dual, x_mat, y_mat, status_string elif solutionmatrix: return primal, dual, x_mat, y_mat elif status: return primal, dual, status_string else: return primal, dual
Helper function to parse the output file of SDPA. :param filename: The name of the SDPA output file. :type filename: str. :param solutionmatrix: Optional parameter for retrieving the solution. :type solutionmatrix: bool. :param status: Optional parameter for retrieving the status. :type status: bool. :param sdp: Optional parameter to add the solution to a relaxation. :type sdp: sdp. :returns: tuple of two floats and optionally two lists of `numpy.array` and a status string
entailment
def solve_with_sdpa(sdp, solverparameters=None): """Helper function to write out the SDP problem to a temporary file, call the solver, and parse the output. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`. :param solverparameters: Optional parameters to SDPA. :type solverparameters: dict of str. :returns: tuple of float and list -- the primal and dual solution of the SDP, respectively, and a status string. """ solverexecutable = detect_sdpa(solverparameters) if solverexecutable is None: raise OSError("SDPA is not in the path or the executable provided is" + " not correct") primal, dual = 0, 0 tempfile_ = tempfile.NamedTemporaryFile() tmp_filename = tempfile_.name tempfile_.close() tmp_dats_filename = tmp_filename + ".dat-s" tmp_out_filename = tmp_filename + ".out" write_to_sdpa(sdp, tmp_dats_filename) command_line = [solverexecutable, "-ds", tmp_dats_filename, "-o", tmp_out_filename] if solverparameters is not None: for key, value in list(solverparameters.items()): if key == "executable": continue elif key == "paramsfile": command_line.extend(["-p", value]) else: raise ValueError("Unknown parameter for SDPA: " + key) if sdp.verbose < 1: with open(os.devnull, "w") as fnull: call(command_line, stdout=fnull, stderr=fnull) else: call(command_line) primal, dual, x_mat, y_mat, status = read_sdpa_out(tmp_out_filename, True, True) if sdp.verbose < 2: os.remove(tmp_dats_filename) os.remove(tmp_out_filename) return primal+sdp.constant_term, \ dual+sdp.constant_term, x_mat, y_mat, status
Helper function to write out the SDP problem to a temporary file, call the solver, and parse the output. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`. :param solverparameters: Optional parameters to SDPA. :type solverparameters: dict of str. :returns: tuple of float and list -- the primal and dual solution of the SDP, respectively, and a status string.
entailment
def convert_row_to_sdpa_index(block_struct, row_offsets, row): """Helper function to map to sparse SDPA index values. """ block_index = bisect_left(row_offsets[1:], row + 1) width = block_struct[block_index] row = row - row_offsets[block_index] i, j = divmod(row, width) return block_index, i, j
Helper function to map to sparse SDPA index values.
entailment
def write_to_sdpa(sdp, filename): """Write the SDP relaxation to SDPA format. :param sdp: The SDP relaxation to write. :type sdp: :class:`ncpol2sdpa.sdp`. :param filename: The name of the file. It must have the suffix ".dat-s" :type filename: str. """ # Coefficient matrices row_offsets = [0] cumulative_sum = 0 for block_size in sdp.block_struct: cumulative_sum += block_size ** 2 row_offsets.append(cumulative_sum) multiplier = 1 if sdp.F.dtype == np.complex128: multiplier = 2 lines = [[] for _ in range(multiplier*sdp.n_vars+1)] for row in range(len(sdp.F.rows)): if len(sdp.F.rows[row]) > 0: col_index = 0 block_index, i, j = convert_row_to_sdpa_index(sdp.block_struct, row_offsets, row) for k in sdp.F.rows[row]: value = sdp.F.data[row][col_index] col_index += 1 if k == 0: value *= -1 if sdp.F.dtype == np.float64: lines[k].append('{0}\t{1}\t{2}\t{3}\n'.format( block_index + 1, i + 1, j + 1, value)) else: bs = sdp.block_struct[block_index] if value.real != 0: lines[k].append('{0}\t{1}\t{2}\t{3}\n'.format( block_index + 1, i + 1, j + 1, value.real)) lines[k].append('{0}\t{1}\t{2}\t{3}\n'.format( block_index + 1, i + bs + 1, j + bs + 1, value.real)) if value.imag != 0: lines[k + sdp.n_vars].append( '{0}\t{1}\t{2}\t{3}\n'.format( block_index + 1, i + 1, j + bs + 1, value.imag)) lines[k + sdp.n_vars].append( '{0}\t{1}\t{2}\t{3}\n'.format( block_index + 1, j + 1, i + bs + 1, -value.imag)) file_ = open(filename, 'w') file_.write('"file ' + filename + ' generated by ncpol2sdpa"\n') file_.write(str(multiplier*sdp.n_vars) + ' = number of vars\n') # bloc structure block_struct = [multiplier*blk_size for blk_size in sdp.block_struct] file_.write(str(len(block_struct)) + ' = number of blocs\n') file_.write(str(block_struct).replace('[', '(') .replace(']', ')')) file_.write(' = BlocStructure\n') # c vector (objective) objective = \ str(list(sdp.obj_facvar)).replace('[', '').replace(']', '') if multiplier == 2: objective += ', ' + objective file_.write('{'+objective+'}\n') for k, line in enumerate(lines): if line == []: continue for item in line: file_.write('{0}\t'.format(k)+item) file_.close()
Write the SDP relaxation to SDPA format. :param sdp: The SDP relaxation to write. :type sdp: :class:`ncpol2sdpa.sdp`. :param filename: The name of the file. It must have the suffix ".dat-s" :type filename: str.
entailment
def convert_to_human_readable(sdp): """Convert the SDP relaxation to a human-readable format. :param sdp: The SDP relaxation to write. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: tuple of the objective function in a string and a matrix of strings as the symbolic representation of the moment matrix """ objective = "" indices_in_objective = [] for i, tmp in enumerate(sdp.obj_facvar): candidates = [key for key, v in sdp.monomial_index.items() if v == i+1] if len(candidates) > 0: monomial = convert_monomial_to_string(candidates[0]) else: monomial = "" if tmp > 0: objective += "+"+str(tmp)+monomial indices_in_objective.append(i) elif tmp < 0: objective += str(tmp)+monomial indices_in_objective.append(i) matrix_size = 0 cumulative_sum = 0 row_offsets = [0] block_offset = [0] for bs in sdp.block_struct: matrix_size += abs(bs) cumulative_sum += bs ** 2 row_offsets.append(cumulative_sum) block_offset.append(matrix_size) matrix = [] for i in range(matrix_size): matrix_line = ["0"] * matrix_size matrix.append(matrix_line) for row in range(len(sdp.F.rows)): if len(sdp.F.rows[row]) > 0: col_index = 0 for k in sdp.F.rows[row]: value = sdp.F.data[row][col_index] col_index += 1 block_index, i, j = convert_row_to_sdpa_index( sdp.block_struct, row_offsets, row) candidates = [key for key, v in sdp.monomial_index.items() if v == k] if len(candidates) > 0: monomial = convert_monomial_to_string(candidates[0]) else: monomial = "" offset = block_offset[block_index] if matrix[offset+i][offset+j] == "0": matrix[offset+i][offset+j] = ("%s%s" % (value, monomial)) else: if value.real > 0: matrix[offset+i][offset+j] += ("+%s%s" % (value, monomial)) else: matrix[offset+i][offset+j] += ("%s%s" % (value, monomial)) return objective, matrix
Convert the SDP relaxation to a human-readable format. :param sdp: The SDP relaxation to write. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: tuple of the objective function in a string and a matrix of strings as the symbolic representation of the moment matrix
entailment
def write_to_human_readable(sdp, filename): """Write the SDP relaxation to a human-readable format. :param sdp: The SDP relaxation to write. :type sdp: :class:`ncpol2sdpa.sdp`. :param filename: The name of the file. :type filename: str. """ objective, matrix = convert_to_human_readable(sdp) f = open(filename, 'w') f.write("Objective:" + objective + "\n") for matrix_line in matrix: f.write(str(list(matrix_line)).replace('[', '').replace(']', '') .replace('\'', '')) f.write('\n') f.close()
Write the SDP relaxation to a human-readable format. :param sdp: The SDP relaxation to write. :type sdp: :class:`ncpol2sdpa.sdp`. :param filename: The name of the file. :type filename: str.
entailment
def main(): """Ideally we shouldn't lose the first second of events""" with Input() as input_generator: def extra_bytes_callback(string): print('got extra bytes', repr(string)) print('type:', type(string)) input_generator.unget_bytes(string) time.sleep(1) with CursorAwareWindow(extra_bytes_callback=extra_bytes_callback) as window: window.get_cursor_position() for e in input_generator: print(repr(e))
Ideally we shouldn't lose the first second of events
entailment
def make_header(url, access_key=None, secret_key=None): ''' create request header function :param url: URL for the new :class:`Request` object. ''' nonce = nounce() url = url message = nonce + url signature = hmac.new(secret_key.encode('utf-8'), message.encode('utf-8'), hashlib.sha256).hexdigest() headers = { 'ACCESS-KEY' : access_key, 'ACCESS-NONCE' : nonce, 'ACCESS-SIGNATURE': signature } return headers
create request header function :param url: URL for the new :class:`Request` object.
entailment
def unget_bytes(self, string): """Adds bytes to be internal buffer to be read This method is for reporting bytes from an in_stream read not initiated by this Input object""" self.unprocessed_bytes.extend(string[i:i + 1] for i in range(len(string)))
Adds bytes to be internal buffer to be read This method is for reporting bytes from an in_stream read not initiated by this Input object
entailment
def _wait_for_read_ready_or_timeout(self, timeout): """Returns tuple of whether stdin is ready to read and an event. If an event is returned, that event is more pressing than reading bytes on stdin to create a keyboard input event. If stdin is ready, either there are bytes to read or a SIGTSTP triggered by dsusp has been received""" remaining_timeout = timeout t0 = time.time() while True: try: (rs, _, _) = select.select( [self.in_stream.fileno()] + self.readers, [], [], remaining_timeout) if not rs: return False, None r = rs[0] # if there's more than one, get it in the next loop if r == self.in_stream.fileno(): return True, None else: os.read(r, 1024) if self.queued_interrupting_events: return False, self.queued_interrupting_events.pop(0) elif remaining_timeout is not None: remaining_timeout = max(0, t0 + timeout - time.time()) continue else: continue except select.error: if self.sigints: return False, self.sigints.pop() if remaining_timeout is not None: remaining_timeout = max(timeout - (time.time() - t0), 0)
Returns tuple of whether stdin is ready to read and an event. If an event is returned, that event is more pressing than reading bytes on stdin to create a keyboard input event. If stdin is ready, either there are bytes to read or a SIGTSTP triggered by dsusp has been received
entailment
def send(self, timeout=None): """Returns an event or None if no events occur before timeout.""" if self.sigint_event and is_main_thread(): with ReplacedSigIntHandler(self.sigint_handler): return self._send(timeout) else: return self._send(timeout)
Returns an event or None if no events occur before timeout.
entailment
def _nonblocking_read(self): """Returns the number of characters read and adds them to self.unprocessed_bytes""" with Nonblocking(self.in_stream): if PY3: try: data = os.read(self.in_stream.fileno(), READ_SIZE) except BlockingIOError: return 0 if data: self.unprocessed_bytes.extend(data[i:i+1] for i in range(len(data))) return len(data) else: return 0 else: try: data = os.read(self.in_stream.fileno(), READ_SIZE) except OSError: return 0 else: self.unprocessed_bytes.extend(data) return len(data)
Returns the number of characters read and adds them to self.unprocessed_bytes
entailment
def event_trigger(self, event_type): """Returns a callback that creates events. Returned callback function will add an event of type event_type to a queue which will be checked the next time an event is requested.""" def callback(**kwargs): self.queued_events.append(event_type(**kwargs)) return callback
Returns a callback that creates events. Returned callback function will add an event of type event_type to a queue which will be checked the next time an event is requested.
entailment
def scheduled_event_trigger(self, event_type): """Returns a callback that schedules events for the future. Returned callback function will add an event of type event_type to a queue which will be checked the next time an event is requested.""" def callback(when, **kwargs): self.queued_scheduled_events.append((when, event_type(when=when, **kwargs))) return callback
Returns a callback that schedules events for the future. Returned callback function will add an event of type event_type to a queue which will be checked the next time an event is requested.
entailment
def threadsafe_event_trigger(self, event_type): """Returns a callback to creates events, interrupting current event requests. Returned callback function will create an event of type event_type which will interrupt an event request if one is concurrently occuring, otherwise adding the event to a queue that will be checked on the next event request.""" readfd, writefd = os.pipe() self.readers.append(readfd) def callback(**kwargs): self.queued_interrupting_events.append(event_type(**kwargs)) #TODO use a threadsafe queue for this logger.warning('added event to events list %r', self.queued_interrupting_events) os.write(writefd, b'interrupting event!') return callback
Returns a callback to creates events, interrupting current event requests. Returned callback function will create an event of type event_type which will interrupt an event request if one is concurrently occuring, otherwise adding the event to a queue that will be checked on the next event request.
entailment
def solve_sdp(sdp, solver=None, solverparameters=None): """Call a solver on the SDP relaxation. Upon successful solution, it returns the primal and dual objective values along with the solution matrices. :param sdpRelaxation: The SDP relaxation to be solved. :type sdpRelaxation: :class:`ncpol2sdpa.SdpRelaxation`. :param solver: The solver to be called, either `None`, "sdpa", "mosek", "cvxpy", "scs", or "cvxopt". The default is `None`, which triggers autodetect. :type solver: str. :param solverparameters: Parameters to be passed to the solver. Actual options depend on the solver: SDPA: - `"executable"`: Specify the executable for SDPA. E.g., `"executable":"/usr/local/bin/sdpa"`, or `"executable":"sdpa_gmp"` - `"paramsfile"`: Specify the parameter file Mosek: Refer to the Mosek documentation. All arguments are passed on. Cvxopt: Refer to the PICOS documentation. All arguments are passed on. Cvxpy: Refer to the Cvxpy documentation. All arguments are passed on. SCS: Refer to the Cvxpy documentation. All arguments are passed on. :type solverparameters: dict of str. :returns: tuple of the primal and dual optimum, and the solutions for the primal and dual. :rtype: (float, float, list of `numpy.array`, list of `numpy.array`) """ solvers = autodetect_solvers(solverparameters) solver = solver.lower() if solver is not None else solver if solvers == []: raise Exception("Could not find any SDP solver. Please install SDPA," + " Mosek, Cvxpy, or Picos with Cvxopt") elif solver is not None and solver not in solvers: print("Available solvers: " + str(solvers)) if solver == "cvxopt": try: import cvxopt except ImportError: pass else: raise Exception("Cvxopt is detected, but Picos is not. " "Please install Picos to use Cvxopt") raise Exception("Could not detect requested " + solver) elif solver is None: solver = solvers[0] primal, dual, x_mat, y_mat, status = None, None, None, None, None tstart = time.time() if solver == "sdpa": primal, dual, x_mat, y_mat, status = \ solve_with_sdpa(sdp, solverparameters) elif solver == "cvxpy": primal, dual, x_mat, y_mat, status = \ solve_with_cvxpy(sdp, solverparameters) elif solver == "scs": if solverparameters is None: solverparameters_ = {"solver": "SCS"} else: solverparameters_ = solverparameters.copy() solverparameters_["solver"] = "SCS" primal, dual, x_mat, y_mat, status = \ solve_with_cvxpy(sdp, solverparameters_) elif solver == "mosek": primal, dual, x_mat, y_mat, status = \ solve_with_mosek(sdp, solverparameters) elif solver == "cvxopt": primal, dual, x_mat, y_mat, status = \ solve_with_cvxopt(sdp, solverparameters) # We have to compensate for the equality constraints for constraint in sdp.constraints[sdp._n_inequalities:]: idx = sdp._constraint_to_block_index[constraint] sdp._constraint_to_block_index[constraint] = (idx[0],) else: raise Exception("Unkown solver: " + solver) sdp.solution_time = time.time() - tstart sdp.primal = primal sdp.dual = dual sdp.x_mat = x_mat sdp.y_mat = y_mat sdp.status = status return primal, dual, x_mat, y_mat
Call a solver on the SDP relaxation. Upon successful solution, it returns the primal and dual objective values along with the solution matrices. :param sdpRelaxation: The SDP relaxation to be solved. :type sdpRelaxation: :class:`ncpol2sdpa.SdpRelaxation`. :param solver: The solver to be called, either `None`, "sdpa", "mosek", "cvxpy", "scs", or "cvxopt". The default is `None`, which triggers autodetect. :type solver: str. :param solverparameters: Parameters to be passed to the solver. Actual options depend on the solver: SDPA: - `"executable"`: Specify the executable for SDPA. E.g., `"executable":"/usr/local/bin/sdpa"`, or `"executable":"sdpa_gmp"` - `"paramsfile"`: Specify the parameter file Mosek: Refer to the Mosek documentation. All arguments are passed on. Cvxopt: Refer to the PICOS documentation. All arguments are passed on. Cvxpy: Refer to the Cvxpy documentation. All arguments are passed on. SCS: Refer to the Cvxpy documentation. All arguments are passed on. :type solverparameters: dict of str. :returns: tuple of the primal and dual optimum, and the solutions for the primal and dual. :rtype: (float, float, list of `numpy.array`, list of `numpy.array`)
entailment
def find_solution_ranks(sdp, xmat=None, baselevel=0): """Helper function to detect rank loop in the solution matrix. :param sdp: The SDP relaxation. :type sdp: :class:`ncpol2sdpa.sdp`. :param x_mat: Optional parameter providing the primal solution of the moment matrix. If not provided, the solution is extracted from the sdp object. :type x_mat: :class:`numpy.array`. :param base_level: Optional parameter for specifying the lower level relaxation for which the rank loop should be tested against. :type base_level: int. :returns: list of int -- the ranks of the solution matrix with in the order of increasing degree. """ if sdp.status == "unsolved" and xmat is None: raise Exception("The SDP relaxation is unsolved and no primal " + "solution is provided!") elif sdp.status != "unsolved" and xmat is None: xmat = sdp.x_mat[0] else: xmat = sdp.x_mat[0] if sdp.status == "unsolved": raise Exception("The SDP relaxation is unsolved!") ranks = [] from numpy.linalg import matrix_rank if baselevel == 0: levels = range(1, sdp.level + 1) else: levels = [baselevel] for level in levels: base_monomials = \ pick_monomials_up_to_degree(sdp.monomial_sets[0], level) ranks.append(matrix_rank(xmat[:len(base_monomials), :len(base_monomials)])) if xmat.shape != (len(base_monomials), len(base_monomials)): ranks.append(matrix_rank(xmat)) return ranks
Helper function to detect rank loop in the solution matrix. :param sdp: The SDP relaxation. :type sdp: :class:`ncpol2sdpa.sdp`. :param x_mat: Optional parameter providing the primal solution of the moment matrix. If not provided, the solution is extracted from the sdp object. :type x_mat: :class:`numpy.array`. :param base_level: Optional parameter for specifying the lower level relaxation for which the rank loop should be tested against. :type base_level: int. :returns: list of int -- the ranks of the solution matrix with in the order of increasing degree.
entailment
def get_sos_decomposition(sdp, y_mat=None, threshold=0.0): """Given a solution of the dual problem, it returns the SOS decomposition. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`. :param y_mat: Optional parameter providing the dual solution of the moment matrix. If not provided, the solution is extracted from the sdp object. :type y_mat: :class:`numpy.array`. :param threshold: Optional parameter for specifying the threshold value below which the eigenvalues and entries of the eigenvectors are disregarded. :type threshold: float. :returns: The SOS decomposition of [sigma_0, sigma_1, ..., sigma_m] :rtype: list of :class:`sympy.core.exp.Expr`. """ if len(sdp.monomial_sets) != 1: raise Exception("Cannot automatically match primal and dual " + "variables.") elif len(sdp.y_mat[1:]) != len(sdp.constraints): raise Exception("Cannot automatically match constraints with blocks " + "in the dual solution.") elif sdp.status == "unsolved" and y_mat is None: raise Exception("The SDP relaxation is unsolved and dual solution " + "is not provided!") elif sdp.status != "unsolved" and y_mat is None: y_mat = sdp.y_mat sos = [] for y_mat_block in y_mat: term = 0 vals, vecs = np.linalg.eigh(y_mat_block) for j, val in enumerate(vals): if val < -0.001: raise Exception("Large negative eigenvalue: " + val + ". Matrix cannot be positive.") elif val > 0: sub_term = 0 for i, entry in enumerate(vecs[:, j]): sub_term += entry * sdp.monomial_sets[0][i] term += val * sub_term**2 term = expand(term) new_term = 0 if term.is_Mul: elements = [term] else: elements = term.as_coeff_mul()[1][0].as_coeff_add()[1] for element in elements: _, coeff = separate_scalar_factor(element) if abs(coeff) > threshold: new_term += element sos.append(new_term) return sos
Given a solution of the dual problem, it returns the SOS decomposition. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`. :param y_mat: Optional parameter providing the dual solution of the moment matrix. If not provided, the solution is extracted from the sdp object. :type y_mat: :class:`numpy.array`. :param threshold: Optional parameter for specifying the threshold value below which the eigenvalues and entries of the eigenvectors are disregarded. :type threshold: float. :returns: The SOS decomposition of [sigma_0, sigma_1, ..., sigma_m] :rtype: list of :class:`sympy.core.exp.Expr`.
entailment
def extract_dual_value(sdp, monomial, blocks=None): """Given a solution of the dual problem and a monomial, it returns the inner product of the corresponding coefficient matrix and the dual solution. It can be restricted to certain blocks. :param sdp: The SDP relaxation. :type sdp: :class:`ncpol2sdpa.sdp`. :param monomial: The monomial for which the value is requested. :type monomial: :class:`sympy.core.exp.Expr`. :param monomial: The monomial for which the value is requested. :type monomial: :class:`sympy.core.exp.Expr`. :param blocks: Optional parameter to specify the blocks to be included. :type blocks: list of `int`. :returns: The value of the monomial in the solved relaxation. :rtype: float. """ if sdp.status == "unsolved": raise Exception("The SDP relaxation is unsolved!") if blocks is None: blocks = [i for i, _ in enumerate(sdp.block_struct)] if is_number_type(monomial): index = 0 else: index = sdp.monomial_index[monomial] row_offsets = [0] cumulative_sum = 0 for block_size in sdp.block_struct: cumulative_sum += block_size ** 2 row_offsets.append(cumulative_sum) result = 0 for row in range(len(sdp.F.rows)): if len(sdp.F.rows[row]) > 0: col_index = 0 for k in sdp.F.rows[row]: if k != index: continue value = sdp.F.data[row][col_index] col_index += 1 block_index, i, j = convert_row_to_sdpa_index( sdp.block_struct, row_offsets, row) if block_index in blocks: result += -value*sdp.y_mat[block_index][i][j] return result
Given a solution of the dual problem and a monomial, it returns the inner product of the corresponding coefficient matrix and the dual solution. It can be restricted to certain blocks. :param sdp: The SDP relaxation. :type sdp: :class:`ncpol2sdpa.sdp`. :param monomial: The monomial for which the value is requested. :type monomial: :class:`sympy.core.exp.Expr`. :param monomial: The monomial for which the value is requested. :type monomial: :class:`sympy.core.exp.Expr`. :param blocks: Optional parameter to specify the blocks to be included. :type blocks: list of `int`. :returns: The value of the monomial in the solved relaxation. :rtype: float.
entailment
def completed_number(prefix, length): """ 'prefix' is the start of the CC number as a string, any number of digits. 'length' is the length of the CC number to generate. Typically 13 or 16 """ ccnumber = prefix # generate digits while len(ccnumber) < (length - 1): digit = random.choice(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']) ccnumber.append(digit) # Calculate sum sum = 0 pos = 0 reversedCCnumber = [] reversedCCnumber.extend(ccnumber) reversedCCnumber.reverse() while pos < length - 1: odd = int( reversedCCnumber[pos] ) * 2 if odd > 9: odd -= 9 sum += odd if pos != (length - 2): sum += int( reversedCCnumber[pos+1] ) pos += 2 # Calculate check digit checkdigit = ((sum / 10 + 1) * 10 - sum) % 10 ccnumber.append( str(int(checkdigit)) ) return ''.join(ccnumber)
'prefix' is the start of the CC number as a string, any number of digits. 'length' is the length of the CC number to generate. Typically 13 or 16
entailment
def load_module(self, fullname): """ load_module is always called with the same argument as finder's find_module, see "How Import Works" """ mod = super(JsonLoader, self).load_module(fullname) try: with codecs.open(self.cfg_file, 'r', 'utf-8') as f: mod.__dict__.update(json.load(f)) except ValueError: # if raise here, traceback will contain ValueError self.e = "ValueError" self.err_msg = sys.exc_info()[1] if self.e == "ValueError": err_msg = "\nJson file not valid: " err_msg += self.cfg_file + '\n' err_msg += str(self.err_msg) raise InvalidJsonError(err_msg) return mod
load_module is always called with the same argument as finder's find_module, see "How Import Works"
entailment
def process_event(self, c): """Returns a message from tick() to be displayed if game is over""" if c == "": sys.exit() elif c in key_directions: self.move_entity(self.player, *vscale(self.player.speed, key_directions[c])) else: return "try arrow keys, w, a, s, d, or ctrl-D (you pressed %r)" % c return self.tick()
Returns a message from tick() to be displayed if game is over
entailment
def tick(self): """Returns a message to be displayed if game is over, else None""" for npc in self.npcs: self.move_entity(npc, *npc.towards(self.player)) for entity1, entity2 in itertools.combinations(self.entities, 2): if (entity1.x, entity1.y) == (entity2.x, entity2.y): if self.player in (entity1, entity2): return 'you lost on turn %d' % self.turn entity1.die() entity2.die() if all(npc.speed == 0 for npc in self.npcs): return 'you won on turn %d' % self.turn self.turn += 1 if self.turn % 20 == 0: self.player.speed = max(1, self.player.speed - 1) self.player.display = on_blue(green(bold(unicode_str(self.player.speed))))
Returns a message to be displayed if game is over, else None
entailment
def array_from_text(self, msg): """Returns a FSArray of the size of the window containing msg""" rows, columns = self.t.height, self.t.width return self.array_from_text_rc(msg, rows, columns)
Returns a FSArray of the size of the window containing msg
entailment
def render_to_terminal(self, array, cursor_pos=(0, 0)): """Renders array to terminal and places (0-indexed) cursor Args: array (FSArray): Grid of styled characters to be rendered. * If array received is of width too small, render it anyway * If array received is of width too large, * render the renderable portion * If array received is of height too small, render it anyway * If array received is of height too large, * render the renderable portion (no scroll) """ # TODO there's a race condition here - these height and widths are # super fresh - they might change between the array being constructed # and rendered # Maybe the right behavior is to throw away the render # in the signal handler? height, width = self.height, self.width for_stdout = self.fmtstr_to_stdout_xform() if not self.hide_cursor: self.write(self.t.hide_cursor) if (height != self._last_rendered_height or width != self._last_rendered_width): self.on_terminal_size_change(height, width) current_lines_by_row = {} rows = list(range(height)) rows_for_use = rows[:len(array)] rest_of_rows = rows[len(array):] # rows which we have content for and don't require scrolling for row, line in zip(rows_for_use, array): current_lines_by_row[row] = line if line == self._last_lines_by_row.get(row, None): continue self.write(self.t.move(row, 0)) self.write(for_stdout(line)) if len(line) < width: self.write(self.t.clear_eol) # rows onscreen that we don't have content for for row in rest_of_rows: if self._last_lines_by_row and row not in self._last_lines_by_row: continue self.write(self.t.move(row, 0)) self.write(self.t.clear_eol) self.write(self.t.clear_bol) current_lines_by_row[row] = None logger.debug( 'lines in last lines by row: %r' % self._last_lines_by_row.keys() ) logger.debug( 'lines in current lines by row: %r' % current_lines_by_row.keys() ) self.write(self.t.move(*cursor_pos)) self._last_lines_by_row = current_lines_by_row if not self.hide_cursor: self.write(self.t.normal_cursor)
Renders array to terminal and places (0-indexed) cursor Args: array (FSArray): Grid of styled characters to be rendered. * If array received is of width too small, render it anyway * If array received is of width too large, * render the renderable portion * If array received is of height too small, render it anyway * If array received is of height too large, * render the renderable portion (no scroll)
entailment
def get_cursor_position(self): """Returns the terminal (row, column) of the cursor 0-indexed, like blessings cursor positions""" # TODO would this be cleaner as a parameter? in_stream = self.in_stream query_cursor_position = u"\x1b[6n" self.write(query_cursor_position) def retrying_read(): while True: try: c = in_stream.read(1) if c == '': raise ValueError("Stream should be blocking - should't" " return ''. Returned %r so far", (resp,)) return c except IOError: raise ValueError( 'cursor get pos response read interrupted' ) # find out if this ever really happens - if so, continue resp = '' while True: c = retrying_read() resp += c m = re.search('(?P<extra>.*)' '(?P<CSI>\x1b\[|\x9b)' '(?P<row>\\d+);(?P<column>\\d+)R', resp, re.DOTALL) if m: row = int(m.groupdict()['row']) col = int(m.groupdict()['column']) extra = m.groupdict()['extra'] if extra: if self.extra_bytes_callback: self.extra_bytes_callback( extra.encode(in_stream.encoding) ) else: raise ValueError(("Bytes preceding cursor position " "query response thrown out:\n%r\n" "Pass an extra_bytes_callback to " "CursorAwareWindow to prevent this") % (extra,)) return (row - 1, col - 1)
Returns the terminal (row, column) of the cursor 0-indexed, like blessings cursor positions
entailment
def get_cursor_vertical_diff(self): """Returns the how far down the cursor moved since last render. Note: If another get_cursor_vertical_diff call is already in progress, immediately returns zero. (This situation is likely if get_cursor_vertical_diff is called from a SIGWINCH signal handler, since sigwinches can happen in rapid succession and terminal emulators seem not to respond to cursor position queries before the next sigwinch occurs.) """ # Probably called by a SIGWINCH handler, and therefore # will do cursor querying until a SIGWINCH doesn't happen during # the query. Calls to the function from a signal handler COULD STILL # HAPPEN out of order - # they just can't interrupt the actual cursor query. if self.in_get_cursor_diff: self.another_sigwinch = True return 0 cursor_dy = 0 while True: self.in_get_cursor_diff = True self.another_sigwinch = False cursor_dy += self._get_cursor_vertical_diff_once() self.in_get_cursor_diff = False if not self.another_sigwinch: return cursor_dy
Returns the how far down the cursor moved since last render. Note: If another get_cursor_vertical_diff call is already in progress, immediately returns zero. (This situation is likely if get_cursor_vertical_diff is called from a SIGWINCH signal handler, since sigwinches can happen in rapid succession and terminal emulators seem not to respond to cursor position queries before the next sigwinch occurs.)
entailment
def _get_cursor_vertical_diff_once(self): """Returns the how far down the cursor moved.""" old_top_usable_row = self.top_usable_row row, col = self.get_cursor_position() if self._last_cursor_row is None: cursor_dy = 0 else: cursor_dy = row - self._last_cursor_row logger.info('cursor moved %d lines down' % cursor_dy) while self.top_usable_row > -1 and cursor_dy > 0: self.top_usable_row += 1 cursor_dy -= 1 while self.top_usable_row > 1 and cursor_dy < 0: self.top_usable_row -= 1 cursor_dy += 1 logger.info('top usable row changed from %d to %d', old_top_usable_row, self.top_usable_row) logger.info('returning cursor dy of %d from curtsies' % cursor_dy) self._last_cursor_row = row return cursor_dy
Returns the how far down the cursor moved.
entailment
def render_to_terminal(self, array, cursor_pos=(0, 0)): """Renders array to terminal, returns the number of lines scrolled offscreen Returns: Number of times scrolled Args: array (FSArray): Grid of styled characters to be rendered. If array received is of width too small, render it anyway if array received is of width too large, render it anyway if array received is of height too small, render it anyway if array received is of height too large, render it, scroll down, and render the rest of it, then return how much we scrolled down """ for_stdout = self.fmtstr_to_stdout_xform() # caching of write and tc (avoiding the self. lookups etc) made # no significant performance difference here if not self.hide_cursor: self.write(self.t.hide_cursor) # TODO race condition here? height, width = self.t.height, self.t.width if (height != self._last_rendered_height or width != self._last_rendered_width): self.on_terminal_size_change(height, width) current_lines_by_row = {} rows_for_use = list(range(self.top_usable_row, height)) # rows which we have content for and don't require scrolling # TODO rename shared shared = min(len(array), len(rows_for_use)) for row, line in zip(rows_for_use[:shared], array[:shared]): current_lines_by_row[row] = line if line == self._last_lines_by_row.get(row, None): continue self.write(self.t.move(row, 0)) self.write(for_stdout(line)) if len(line) < width: self.write(self.t.clear_eol) # rows already on screen that we don't have content for rest_of_lines = array[shared:] rest_of_rows = rows_for_use[shared:] for row in rest_of_rows: # if array too small if self._last_lines_by_row and row not in self._last_lines_by_row: continue self.write(self.t.move(row, 0)) self.write(self.t.clear_eol) # TODO probably not necessary - is first char cleared? self.write(self.t.clear_bol) current_lines_by_row[row] = None # lines for which we need to scroll down to render offscreen_scrolls = 0 for line in rest_of_lines: # if array too big self.scroll_down() if self.top_usable_row > 0: self.top_usable_row -= 1 else: offscreen_scrolls += 1 current_lines_by_row = dict( (k - 1, v) for k, v in current_lines_by_row.items() ) logger.debug('new top_usable_row: %d' % self.top_usable_row) # since scrolling moves the cursor self.write(self.t.move(height - 1, 0)) self.write(for_stdout(line)) current_lines_by_row[height - 1] = line logger.debug( 'lines in last lines by row: %r' % self._last_lines_by_row.keys() ) logger.debug( 'lines in current lines by row: %r' % current_lines_by_row.keys() ) self._last_cursor_row = max( 0, cursor_pos[0] - offscreen_scrolls + self.top_usable_row ) self._last_cursor_column = cursor_pos[1] self.write( self.t.move(self._last_cursor_row, self._last_cursor_column) ) self._last_lines_by_row = current_lines_by_row if not self.hide_cursor: self.write(self.t.normal_cursor) return offscreen_scrolls
Renders array to terminal, returns the number of lines scrolled offscreen Returns: Number of times scrolled Args: array (FSArray): Grid of styled characters to be rendered. If array received is of width too small, render it anyway if array received is of width too large, render it anyway if array received is of height too small, render it anyway if array received is of height too large, render it, scroll down, and render the rest of it, then return how much we scrolled down
entailment
def solve(self, solver=None, solverparameters=None): """Call a solver on the SDP relaxation. Upon successful solution, it returns the primal and dual objective values along with the solution matrices. It also sets these values in the `sdpRelaxation` object, along with some status information. :param sdpRelaxation: The SDP relaxation to be solved. :type sdpRelaxation: :class:`ncpol2sdpa.SdpRelaxation`. :param solver: The solver to be called, either `None`, "sdpa", "mosek", "cvxpy", "scs", or "cvxopt". The default is `None`, which triggers autodetect. :type solver: str. :param solverparameters: Parameters to be passed to the solver. Actual options depend on the solver: SDPA: - `"executable"`: Specify the executable for SDPA. E.g., `"executable":"/usr/local/bin/sdpa"`, or `"executable":"sdpa_gmp"` - `"paramsfile"`: Specify the parameter file Mosek: Refer to the Mosek documentation. All arguments are passed on. Cvxopt: Refer to the PICOS documentation. All arguments are passed on. Cvxpy: Refer to the Cvxpy documentation. All arguments are passed on. SCS: Refer to the Cvxpy documentation. All arguments are passed on. :type solverparameters: dict of str. """ if self.F is None: raise Exception("Relaxation is not generated yet. Call " "'SdpRelaxation.get_relaxation' first") solve_sdp(self, solver, solverparameters)
Call a solver on the SDP relaxation. Upon successful solution, it returns the primal and dual objective values along with the solution matrices. It also sets these values in the `sdpRelaxation` object, along with some status information. :param sdpRelaxation: The SDP relaxation to be solved. :type sdpRelaxation: :class:`ncpol2sdpa.SdpRelaxation`. :param solver: The solver to be called, either `None`, "sdpa", "mosek", "cvxpy", "scs", or "cvxopt". The default is `None`, which triggers autodetect. :type solver: str. :param solverparameters: Parameters to be passed to the solver. Actual options depend on the solver: SDPA: - `"executable"`: Specify the executable for SDPA. E.g., `"executable":"/usr/local/bin/sdpa"`, or `"executable":"sdpa_gmp"` - `"paramsfile"`: Specify the parameter file Mosek: Refer to the Mosek documentation. All arguments are passed on. Cvxopt: Refer to the PICOS documentation. All arguments are passed on. Cvxpy: Refer to the Cvxpy documentation. All arguments are passed on. SCS: Refer to the Cvxpy documentation. All arguments are passed on. :type solverparameters: dict of str.
entailment
def _process_monomial(self, monomial, n_vars): """Process a single monomial when building the moment matrix. """ processed_monomial, coeff = separate_scalar_factor(monomial) # Are we substituting this moment? try: substitute = self.moment_substitutions[processed_monomial] if not isinstance(substitute, (int, float, complex)): result = [] if not isinstance(substitute, Add): args = [substitute] else: args = substitute.args for arg in args: if is_number_type(arg): if iscomplex(arg): result.append((0, coeff*complex(arg))) else: result.append((0, coeff*float(arg))) else: result += [(k, coeff*c2) for k, c2 in self._process_monomial(arg, n_vars)] else: result = [(0, coeff*substitute)] except KeyError: # Have we seen this monomial before? try: # If yes, then we improve sparsity by reusing the # previous variable to denote this entry in the matrix k = self.monomial_index[processed_monomial] except KeyError: # If no, it still may be possible that we have already seen its # conjugate. If the problem is real-valued, a monomial and its # conjugate should be equal (Hermiticity becomes symmetry) if not self.complex_matrix: try: # If we have seen the conjugate before, we just use the # conjugate monomial instead processed_monomial_adjoint = \ apply_substitutions(processed_monomial.adjoint(), self.substitutions) k = self.monomial_index[processed_monomial_adjoint] except KeyError: # Otherwise we define a new entry in the associated # array recording the monomials, and add an entry in # the moment matrix k = n_vars + 1 self.monomial_index[processed_monomial] = k else: k = n_vars + 1 self.monomial_index[processed_monomial] = k result = [(k, coeff)] return result
Process a single monomial when building the moment matrix.
entailment
def _generate_moment_matrix(self, n_vars, block_index, processed_entries, monomialsA, monomialsB, ppt=False): """Generate the moment matrix of monomials. Arguments: n_vars -- current number of variables block_index -- current block index in the SDP matrix monomials -- |W_d| set of words of length up to the relaxation level """ row_offset = 0 if block_index > 0: for block_size in self.block_struct[0:block_index]: row_offset += block_size ** 2 N = len(monomialsA)*len(monomialsB) func = partial(assemble_monomial_and_do_substitutions, monomialsA=monomialsA, monomialsB=monomialsB, ppt=ppt, substitutions=self.substitutions, pure_substitution_rules=self.pure_substitution_rules) if self._parallel: pool = Pool() # This is just a guess and can be optimized chunksize = int(max(int(np.sqrt(len(monomialsA) * len(monomialsB) * len(monomialsA) / 2) / cpu_count()), 1)) for rowA in range(len(monomialsA)): if self._parallel: iter_ = pool.map(func, [(rowA, columnA, rowB, columnB) for rowB in range(len(monomialsB)) for columnA in range(rowA, len(monomialsA)) for columnB in range((rowA == columnA)*rowB, len(monomialsB))], chunksize) print_criterion = processed_entries + len(iter_) else: iter_ = imap(func, [(rowA, columnA, rowB, columnB) for columnA in range(rowA, len(monomialsA)) for rowB in range(len(monomialsB)) for columnB in range((rowA == columnA)*rowB, len(monomialsB))]) for columnA, rowB, columnB, monomial in iter_: processed_entries += 1 n_vars = self._push_monomial(monomial, n_vars, row_offset, rowA, columnA, N, rowB, columnB, len(monomialsB), prevent_substitutions=True) if self.verbose > 0 and (not self._parallel or processed_entries == self.n_vars or processed_entries == print_criterion): percentage = processed_entries / self.n_vars time_used = time.time()-self._time0 eta = (1.0 / percentage) * time_used - time_used hours = int(eta/3600) minutes = int((eta-3600*hours)/60) seconds = eta-3600*hours-minutes*60 msg = "" if self.verbose > 1 and self._parallel: msg = ", working on block {:0} with {:0} processes with a chunksize of {:0d}"\ .format(block_index, cpu_count(), chunksize) msg = "{:0} (done: {:.2%}, ETA {:02d}:{:02d}:{:03.1f}"\ .format(n_vars, percentage, hours, minutes, seconds) + \ msg msg = "\r\x1b[KCurrent number of SDP variables: " + msg + ")" sys.stdout.write(msg) sys.stdout.flush() if self._parallel: pool.close() pool.join() if self.verbose > 0: sys.stdout.write("\r") return n_vars, block_index + 1, processed_entries
Generate the moment matrix of monomials. Arguments: n_vars -- current number of variables block_index -- current block index in the SDP matrix monomials -- |W_d| set of words of length up to the relaxation level
entailment
def _get_index_of_monomial(self, element, enablesubstitution=True, daggered=False): """Returns the index of a monomial. """ result = [] processed_element, coeff1 = separate_scalar_factor(element) if processed_element in self.moment_substitutions: r = self._get_index_of_monomial(self.moment_substitutions[processed_element], enablesubstitution) return [(k, coeff*coeff1) for k, coeff in r] if enablesubstitution: processed_element = \ apply_substitutions(processed_element, self.substitutions, self.pure_substitution_rules) # Given the monomial, we need its mapping L_y(w) to push it into # a corresponding constraint matrix if is_number_type(processed_element): return [(0, coeff1)] elif processed_element.is_Add: monomials = processed_element.args else: monomials = [processed_element] for monomial in monomials: monomial, coeff2 = separate_scalar_factor(monomial) coeff = coeff1*coeff2 if is_number_type(monomial): result.append((0, coeff)) continue k = -1 if monomial != 0: if monomial.as_coeff_Mul()[0] < 0: monomial = -monomial coeff = -1.0 * coeff try: new_element = self.moment_substitutions[monomial] r = self._get_index_of_monomial(self.moment_substitutions[new_element], enablesubstitution) result += [(k, coeff*coeff3) for k, coeff3 in r] except KeyError: try: k = self.monomial_index[monomial] result.append((k, coeff)) except KeyError: if not daggered: dag_result = self._get_index_of_monomial(monomial.adjoint(), daggered=True) result += [(k, coeff0*coeff) for k, coeff0 in dag_result] else: raise RuntimeError("The requested monomial " + str(monomial) + " could not be found.") return result
Returns the index of a monomial.
entailment
def __push_facvar_sparse(self, polynomial, block_index, row_offset, i, j): """Calculate the sparse vector representation of a polynomial and pushes it to the F structure. """ width = self.block_struct[block_index - 1] # Preprocess the polynomial for uniform handling later # DO NOT EXPAND THE POLYNOMIAL HERE!!!!!!!!!!!!!!!!!!! # The simplify_polynomial bypasses the problem. # Simplifying here will trigger a bug in SymPy related to # the powers of daggered variables. # polynomial = polynomial.expand() if is_number_type(polynomial) or polynomial.is_Mul: elements = [polynomial] else: elements = polynomial.as_coeff_mul()[1][0].as_coeff_add()[1] # Identify its constituent monomials for element in elements: results = self._get_index_of_monomial(element) # k identifies the mapped value of a word (monomial) w for (k, coeff) in results: if k > -1 and coeff != 0: self.F[row_offset + i * width + j, k] += coeff
Calculate the sparse vector representation of a polynomial and pushes it to the F structure.
entailment
def _get_facvar(self, polynomial): """Return dense vector representation of a polynomial. This function is nearly identical to __push_facvar_sparse, but instead of pushing sparse entries to the constraint matrices, it returns a dense vector. """ facvar = [0] * (self.n_vars + 1) # Preprocess the polynomial for uniform handling later if is_number_type(polynomial): facvar[0] = polynomial return facvar polynomial = polynomial.expand() if polynomial.is_Mul: elements = [polynomial] else: elements = polynomial.as_coeff_mul()[1][0].as_coeff_add()[1] for element in elements: results = self._get_index_of_monomial(element) for (k, coeff) in results: facvar[k] += coeff return facvar
Return dense vector representation of a polynomial. This function is nearly identical to __push_facvar_sparse, but instead of pushing sparse entries to the constraint matrices, it returns a dense vector.
entailment
def __process_inequalities(self, block_index): """Generate localizing matrices Arguments: inequalities -- list of inequality constraints monomials -- localizing monomials block_index -- the current block index in constraint matrices of the SDP relaxation """ initial_block_index = block_index row_offsets = [0] for block, block_size in enumerate(self.block_struct): row_offsets.append(row_offsets[block] + block_size ** 2) if self._parallel: pool = Pool() for k, ineq in enumerate(self.constraints): block_index += 1 monomials = self.localizing_monomial_sets[block_index - initial_block_index-1] lm = len(monomials) if isinstance(ineq, str): self.__parse_expression(ineq, row_offsets[block_index-1]) continue if ineq.is_Relational: ineq = convert_relational(ineq) func = partial(moment_of_entry, monomials=monomials, ineq=ineq, substitutions=self.substitutions) if self._parallel and lm > 1: chunksize = max(int(np.sqrt(lm*lm/2) / cpu_count()), 1) iter_ = pool.map(func, ([row, column] for row in range(lm) for column in range(row, lm)), chunksize) else: iter_ = imap(func, ([row, column] for row in range(lm) for column in range(row, lm))) if block_index > self.constraint_starting_block + \ self._n_inequalities and lm > 1: is_equality = True else: is_equality = False for row, column, polynomial in iter_: if is_equality: row, column = 0, 0 self.__push_facvar_sparse(polynomial, block_index, row_offsets[block_index-1], row, column) if is_equality: block_index += 1 if is_equality: block_index -= 1 if self.verbose > 0: sys.stdout.write("\r\x1b[KProcessing %d/%d constraints..." % (k+1, len(self.constraints))) sys.stdout.flush() if self._parallel: pool.close() pool.join() if self.verbose > 0: sys.stdout.write("\n") return block_index
Generate localizing matrices Arguments: inequalities -- list of inequality constraints monomials -- localizing monomials block_index -- the current block index in constraint matrices of the SDP relaxation
entailment
def __process_equalities(self, equalities, momentequalities): """Generate localizing matrices Arguments: equalities -- list of equality constraints equalities -- list of moment equality constraints """ monomial_sets = [] n_rows = 0 le = 0 if equalities is not None: for equality in equalities: le += 1 # Find the order of the localizing matrix if equality.is_Relational: equality = convert_relational(equality) eq_order = ncdegree(equality) if eq_order > 2 * self.level: raise Exception("An equality constraint has degree %d. " "Choose a higher level of relaxation." % eq_order) localization_order = (2 * self.level - eq_order)//2 index = find_variable_set(self.variables, equality) localizing_monomials = \ pick_monomials_up_to_degree(self.monomial_sets[index], localization_order) if len(localizing_monomials) == 0: localizing_monomials = [S.One] localizing_monomials = unique(localizing_monomials) monomial_sets.append(localizing_monomials) n_rows += len(localizing_monomials) * \ (len(localizing_monomials) + 1) // 2 if momentequalities is not None: for _ in momentequalities: le += 1 monomial_sets.append([S.One]) n_rows += 1 A = np.zeros((n_rows, self.n_vars + 1), dtype=self.F.dtype) n_rows = 0 if self._parallel: pool = Pool() for i, equality in enumerate(flatten([equalities, momentequalities])): func = partial(moment_of_entry, monomials=monomial_sets[i], ineq=equality, substitutions=self.substitutions) lm = len(monomial_sets[i]) if self._parallel and lm > 1: chunksize = max(int(np.sqrt(lm*lm/2) / cpu_count()), 1) iter_ = pool.map(func, ([row, column] for row in range(lm) for column in range(row, lm)), chunksize) else: iter_ = imap(func, ([row, column] for row in range(lm) for column in range(row, lm))) # Process M_y(gy)(u,w) entries for row, column, polynomial in iter_: # Calculate the moments of polynomial entries if isinstance(polynomial, str): self.__parse_expression(equality, -1, A[n_rows]) else: A[n_rows] = self._get_facvar(polynomial) n_rows += 1 if self.verbose > 0: sys.stdout.write("\r\x1b[KProcessing %d/%d equalities..." % (i+1, le)) sys.stdout.flush() if self._parallel: pool.close() pool.join() if self.verbose > 0: sys.stdout.write("\n") return A
Generate localizing matrices Arguments: equalities -- list of equality constraints equalities -- list of moment equality constraints
entailment
def __remove_equalities(self, equalities, momentequalities): """Attempt to remove equalities by solving the linear equations. """ A = self.__process_equalities(equalities, momentequalities) if min(A.shape != np.linalg.matrix_rank(A)): print("Warning: equality constraints are linearly dependent! " "Results might be incorrect.", file=sys.stderr) if A.shape[0] == 0: return c = np.array(self.obj_facvar) if self.verbose > 0: print("QR decomposition...") Q, R = np.linalg.qr(A[:, 1:].T, mode='complete') n = np.max(np.nonzero(np.sum(np.abs(R), axis=1) > 0)) + 1 x = np.dot(Q[:, :n], np.linalg.solve(np.transpose(R[:n, :]), -A[:, 0])) self._new_basis = lil_matrix(Q[:, n:]) # Transforming the objective function self._original_obj_facvar = self.obj_facvar self._original_constant_term = self.constant_term self.obj_facvar = self._new_basis.T.dot(c) self.constant_term += c.dot(x) x = np.append(1, x) # Transforming the moment matrix and localizing matrices new_F = lil_matrix((self.F.shape[0], self._new_basis.shape[1] + 1)) new_F[:, 0] = self.F[:, :self.n_vars+1].dot(x).reshape((new_F.shape[0], 1)) new_F[:, 1:] = self.F[:, 1:self.n_vars+1].\ dot(self._new_basis) self._original_F = self.F self.F = new_F self.n_vars = self._new_basis.shape[1] if self.verbose > 0: print("Number of variables after solving the linear equations: %d" % self.n_vars)
Attempt to remove equalities by solving the linear equations.
entailment
def _calculate_block_structure(self, inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=None): """Calculates the block_struct array for the output file. """ if block_struct is None: if self.verbose > 0: print("Calculating block structure...") self.block_struct = [] if self.parameters is not None: self.block_struct += [1 for _ in self.parameters] for monomials in self.monomial_sets: if len(monomials) > 0 and isinstance(monomials[0], list): self.block_struct.append(len(monomials[0])) else: self.block_struct.append(len(monomials)) if extramomentmatrix is not None: for _ in extramomentmatrix: for monomials in self.monomial_sets: if len(monomials) > 0 and \ isinstance(monomials[0], list): self.block_struct.append(len(monomials[0])) else: self.block_struct.append(len(monomials)) else: self.block_struct = block_struct degree_warning = False if inequalities is not None: self._n_inequalities = len(inequalities) n_tmp_inequalities = len(inequalities) else: self._n_inequalities = 0 n_tmp_inequalities = 0 constraints = flatten([inequalities]) if momentinequalities is not None: self._n_inequalities += len(momentinequalities) constraints += momentinequalities if not removeequalities: constraints += flatten([equalities]) monomial_sets = [] for k, constraint in enumerate(constraints): # Find the order of the localizing matrix if k < n_tmp_inequalities or k >= self._n_inequalities: if isinstance(constraint, str): ineq_order = 2 * self.level else: if constraint.is_Relational: constraint = convert_relational(constraint) ineq_order = ncdegree(constraint) if iscomplex(constraint): self.complex_matrix = True if ineq_order > 2 * self.level: degree_warning = True localization_order = (2*self.level - ineq_order)//2 if self.level == -1: localization_order = 0 if self.localizing_monomial_sets is not None and \ self.localizing_monomial_sets[k] is not None: localizing_monomials = self.localizing_monomial_sets[k] else: index = find_variable_set(self.variables, constraint) localizing_monomials = \ pick_monomials_up_to_degree(self.monomial_sets[index], localization_order) ln = len(localizing_monomials) if ln == 0: localizing_monomials = [S.One] else: localizing_monomials = [S.One] ln = 1 localizing_monomials = unique(localizing_monomials) monomial_sets.append(localizing_monomials) if k < self._n_inequalities: self.block_struct.append(ln) else: monomial_sets += [None for _ in range(ln*(ln+1)//2-1)] monomial_sets.append(localizing_monomials) monomial_sets += [None for _ in range(ln*(ln+1)//2-1)] self.block_struct += [1 for _ in range(ln*(ln+1))] if degree_warning and self.verbose > 0: print("A constraint has degree %d. Either choose a higher level " "relaxation or ensure that a mixed-order relaxation has the" " necessary monomials" % (ineq_order), file=sys.stderr) if momentequalities is not None: for moment_eq in momentequalities: self._moment_equalities.append(moment_eq) if not removeequalities: monomial_sets += [[S.One], [S.One]] self.block_struct += [1, 1] self.localizing_monomial_sets = monomial_sets
Calculates the block_struct array for the output file.
entailment
def process_constraints(self, inequalities=None, equalities=None, momentinequalities=None, momentequalities=None, block_index=0, removeequalities=False): """Process the constraints and generate localizing matrices. Useful only if the moment matrix already exists. Call it if you want to replace your constraints. The number of the respective types of constraints and the maximum degree of each constraint must remain the same. :param inequalities: Optional parameter to list inequality constraints. :type inequalities: list of :class:`sympy.core.exp.Expr`. :param equalities: Optional parameter to list equality constraints. :type equalities: list of :class:`sympy.core.exp.Expr`. :param momentinequalities: Optional parameter of inequalities defined on moments. :type momentinequalities: list of :class:`sympy.core.exp.Expr`. :param momentequalities: Optional parameter of equalities defined on moments. :type momentequalities: list of :class:`sympy.core.exp.Expr`. :param removeequalities: Optional parameter to attempt removing the equalities by solving the linear equations. :param removeequalities: Optional parameter to attempt removing the equalities by solving the linear equations. :type removeequalities: bool. """ self.status = "unsolved" if block_index == 0: if self._original_F is not None: self.F = self._original_F self.obj_facvar = self._original_obj_facvar self.constant_term = self._original_constant_term self.n_vars = len(self.obj_facvar) self._new_basis = None block_index = self.constraint_starting_block self.__wipe_F_from_constraints() self.constraints = flatten([inequalities]) self._constraint_to_block_index = {} for constraint in self.constraints: self._constraint_to_block_index[constraint] = (block_index, ) block_index += 1 if momentinequalities is not None: for mineq in momentinequalities: self.constraints.append(mineq) self._constraint_to_block_index[mineq] = (block_index, ) block_index += 1 if not (removeequalities or equalities is None): # Equalities are converted to pairs of inequalities for k, equality in enumerate(equalities): if equality.is_Relational: equality = convert_relational(equality) self.constraints.append(equality) self.constraints.append(-equality) ln = len(self.localizing_monomial_sets[block_index- self.constraint_starting_block]) self._constraint_to_block_index[equality] = (block_index, block_index+ln*(ln+1)//2) block_index += ln*(ln+1) if momentequalities is not None and not removeequalities: for meq in momentequalities: self.constraints += [meq, flip_sign(meq)] self._constraint_to_block_index[meq] = (block_index, block_index+1) block_index += 2 block_index = self.constraint_starting_block self.__process_inequalities(block_index) if removeequalities: self.__remove_equalities(equalities, momentequalities)
Process the constraints and generate localizing matrices. Useful only if the moment matrix already exists. Call it if you want to replace your constraints. The number of the respective types of constraints and the maximum degree of each constraint must remain the same. :param inequalities: Optional parameter to list inequality constraints. :type inequalities: list of :class:`sympy.core.exp.Expr`. :param equalities: Optional parameter to list equality constraints. :type equalities: list of :class:`sympy.core.exp.Expr`. :param momentinequalities: Optional parameter of inequalities defined on moments. :type momentinequalities: list of :class:`sympy.core.exp.Expr`. :param momentequalities: Optional parameter of equalities defined on moments. :type momentequalities: list of :class:`sympy.core.exp.Expr`. :param removeequalities: Optional parameter to attempt removing the equalities by solving the linear equations. :param removeequalities: Optional parameter to attempt removing the equalities by solving the linear equations. :type removeequalities: bool.
entailment
def set_objective(self, objective, extraobjexpr=None): """Set or change the objective function of the polynomial optimization problem. :param objective: Describes the objective function. :type objective: :class:`sympy.core.expr.Expr` :param extraobjexpr: Optional parameter of a string expression of a linear combination of moment matrix elements to be included in the objective function :type extraobjexpr: str. """ if objective is not None: facvar = \ self._get_facvar(simplify_polynomial(objective, self.substitutions)) self.obj_facvar = facvar[1:] self.constant_term = facvar[0] if self.verbose > 0 and facvar[0] != 0: print("Warning: The objective function has a non-zero %s " "constant term. It is not included in the SDP objective." % facvar[0], file=sys.stderr) else: self.obj_facvar = self._get_facvar(0)[1:] if extraobjexpr is not None: for sub_expr in extraobjexpr.split(']'): startindex = 0 if sub_expr.startswith('-') or sub_expr.startswith('+'): startindex = 1 ind = sub_expr.find('[') if ind > -1: idx = sub_expr[ind+1:].split(",") i, j = int(idx[0]), int(idx[1]) mm_ind = int(sub_expr[startindex:ind]) if sub_expr.find('*') > -1: value = float(sub_expr[:sub_expr.find('*')]) elif sub_expr.startswith('-'): value = -1.0 else: value = 1.0 base_row_offset = sum([bs**2 for bs in self.block_struct[:mm_ind]]) width = self.block_struct[mm_ind] for column in self.F[base_row_offset + i*width + j].rows[0]: self.obj_facvar[column-1] = \ value*self.F[base_row_offset + i*width + j, column]
Set or change the objective function of the polynomial optimization problem. :param objective: Describes the objective function. :type objective: :class:`sympy.core.expr.Expr` :param extraobjexpr: Optional parameter of a string expression of a linear combination of moment matrix elements to be included in the objective function :type extraobjexpr: str.
entailment
def find_solution_ranks(self, xmat=None, baselevel=0): """Helper function to detect rank loop in the solution matrix. :param sdpRelaxation: The SDP relaxation. :type sdpRelaxation: :class:`ncpol2sdpa.SdpRelaxation`. :param x_mat: Optional parameter providing the primal solution of the moment matrix. If not provided, the solution is extracted from the sdpRelaxation object. :type x_mat: :class:`numpy.array`. :param base_level: Optional parameter for specifying the lower level relaxation for which the rank loop should be tested against. :type base_level: int. :returns: list of int -- the ranks of the solution matrix with in the order of increasing degree. """ return find_solution_ranks(self, xmat=xmat, baselevel=baselevel)
Helper function to detect rank loop in the solution matrix. :param sdpRelaxation: The SDP relaxation. :type sdpRelaxation: :class:`ncpol2sdpa.SdpRelaxation`. :param x_mat: Optional parameter providing the primal solution of the moment matrix. If not provided, the solution is extracted from the sdpRelaxation object. :type x_mat: :class:`numpy.array`. :param base_level: Optional parameter for specifying the lower level relaxation for which the rank loop should be tested against. :type base_level: int. :returns: list of int -- the ranks of the solution matrix with in the order of increasing degree.
entailment
def get_dual(self, constraint, ymat=None): """Given a solution of the dual problem and a constraint of any type, it returns the corresponding block in the dual solution. If it is an equality constraint that was converted to a pair of inequalities, it returns a two-tuple of the matching dual blocks. :param constraint: The constraint. :type index: `sympy.core.exp.Expr` :param y_mat: Optional parameter providing the dual solution of the SDP. If not provided, the solution is extracted from the sdpRelaxation object. :type y_mat: :class:`numpy.array`. :returns: The corresponding block in the dual solution. :rtype: :class:`numpy.array` or a tuple thereof. """ if not isinstance(constraint, Expr): raise Exception("Not a monomial or polynomial!") elif self.status == "unsolved" and ymat is None: raise Exception("SDP relaxation is not solved yet!") elif ymat is None: ymat = self.y_mat index = self._constraint_to_block_index.get(constraint) if index is None: raise Exception("Constraint is not in the dual!") if len(index) == 2: return ymat[index[0]], self.y_mat[index[1]] else: return ymat[index[0]]
Given a solution of the dual problem and a constraint of any type, it returns the corresponding block in the dual solution. If it is an equality constraint that was converted to a pair of inequalities, it returns a two-tuple of the matching dual blocks. :param constraint: The constraint. :type index: `sympy.core.exp.Expr` :param y_mat: Optional parameter providing the dual solution of the SDP. If not provided, the solution is extracted from the sdpRelaxation object. :type y_mat: :class:`numpy.array`. :returns: The corresponding block in the dual solution. :rtype: :class:`numpy.array` or a tuple thereof.
entailment
def write_to_file(self, filename, filetype=None): """Write the relaxation to a file. :param filename: The name of the file to write to. The type can be autodetected from the extension: .dat-s for SDPA, .task for mosek or .csv for human readable format. :type filename: str. :param filetype: Optional parameter to define the filetype. It can be "sdpa" for SDPA , "mosek" for Mosek, or "csv" for human readable format. :type filetype: str. """ if filetype == "sdpa" and not filename.endswith(".dat-s"): raise Exception("SDPA files must have .dat-s extension!") if filetype == "mosek" and not filename.endswith(".task"): raise Exception("Mosek files must have .task extension!") elif filetype is None and filename.endswith(".dat-s"): filetype = "sdpa" elif filetype is None and filename.endswith(".csv"): filetype = "csv" elif filetype is None and filename.endswith(".task"): filetype = "mosek" elif filetype is None: raise Exception("Cannot detect filetype from extension!") if filetype == "sdpa": write_to_sdpa(self, filename) elif filetype == "mosek": task = convert_to_mosek(self) task.writedata(filename) elif filetype == "csv": write_to_human_readable(self, filename) else: raise Exception("Unknown filetype")
Write the relaxation to a file. :param filename: The name of the file to write to. The type can be autodetected from the extension: .dat-s for SDPA, .task for mosek or .csv for human readable format. :type filename: str. :param filetype: Optional parameter to define the filetype. It can be "sdpa" for SDPA , "mosek" for Mosek, or "csv" for human readable format. :type filetype: str.
entailment
def get_relaxation(self, level, objective=None, inequalities=None, equalities=None, substitutions=None, momentinequalities=None, momentequalities=None, momentsubstitutions=None, removeequalities=False, extramonomials=None, extramomentmatrices=None, extraobjexpr=None, localizing_monomials=None, chordal_extension=False): """Get the SDP relaxation of a noncommutative polynomial optimization problem. :param level: The level of the relaxation. The value -1 will skip automatic monomial generation and use only the monomials supplied by the option `extramonomials`. :type level: int. :param obj: Optional parameter to describe the objective function. :type obj: :class:`sympy.core.exp.Expr`. :param inequalities: Optional parameter to list inequality constraints. :type inequalities: list of :class:`sympy.core.exp.Expr`. :param equalities: Optional parameter to list equality constraints. :type equalities: list of :class:`sympy.core.exp.Expr`. :param substitutions: Optional parameter containing monomials that can be replaced (e.g., idempotent variables). :type substitutions: dict of :class:`sympy.core.exp.Expr`. :param momentinequalities: Optional parameter of inequalities defined on moments. :type momentinequalities: list of :class:`sympy.core.exp.Expr`. :param momentequalities: Optional parameter of equalities defined on moments. :type momentequalities: list of :class:`sympy.core.exp.Expr`. :param momentsubstitutions: Optional parameter containing moments that can be replaced. :type momentsubstitutions: dict of :class:`sympy.core.exp.Expr`. :param removeequalities: Optional parameter to attempt removing the equalities by solving the linear equations. :type removeequalities: bool. :param extramonomials: Optional paramter of monomials to be included, on top of the requested level of relaxation. :type extramonomials: list of :class:`sympy.core.exp.Expr`. :param extramomentmatrices: Optional paramter of duplicating or adding moment matrices. A new moment matrix can be unconstrained (""), a copy of the first one ("copy"), and satisfying a partial positivity constraint ("ppt"). Each new moment matrix is requested as a list of string of these options. For instance, adding a single new moment matrix as a copy of the first would be ``extramomentmatrices=[["copy"]]``. :type extramomentmatrices: list of list of str. :param extraobjexpr: Optional parameter of a string expression of a linear combination of moment matrix elements to be included in the objective function. :type extraobjexpr: str. :param localizing_monomials: Optional parameter to specify sets of localizing monomials for each constraint. The internal order of constraints is inequalities first, followed by the equalities. If the parameter is specified, but for a certain constraint the automatic localization is requested, leave None in its place in this parameter. :type localizing_monomials: list of list of `sympy.core.exp.Expr`. :param chordal_extension: Optional parameter to request a sparse chordal extension. :type chordal_extension: bool. """ if self.level < -1: raise Exception("Invalid level of relaxation") self.level = level if substitutions is None: self.substitutions = {} else: self.substitutions = substitutions for lhs, rhs in substitutions.items(): if not is_pure_substitution_rule(lhs, rhs): self.pure_substitution_rules = False if iscomplex(lhs) or iscomplex(rhs): self.complex_matrix = True if momentsubstitutions is not None: self.moment_substitutions = momentsubstitutions.copy() # If we have a real-valued problem, the moment matrix is symmetric # and moment substitutions also apply to the conjugate monomials if not self.complex_matrix: for key, val in self.moment_substitutions.copy().items(): adjoint_monomial = apply_substitutions(key.adjoint(), self.substitutions) self.moment_substitutions[adjoint_monomial] = val if chordal_extension: self.variables = find_variable_cliques(self.variables, objective, inequalities, equalities, momentinequalities, momentequalities) self.__generate_monomial_sets(extramonomials) self.localizing_monomial_sets = localizing_monomials # Figure out basic structure of the SDP self._calculate_block_structure(inequalities, equalities, momentinequalities, momentequalities, extramomentmatrices, removeequalities) self._estimate_n_vars() if extramomentmatrices is not None: for parameters in extramomentmatrices: copy = False for parameter in parameters: if parameter == "copy": copy = True if copy: self.n_vars += self.n_vars + 1 else: self.n_vars += (self.block_struct[0]**2)/2 if self.complex_matrix: dtype = np.complex128 else: dtype = np.float64 self.F = lil_matrix((sum([bs**2 for bs in self.block_struct]), self.n_vars + 1), dtype=dtype) if self.verbose > 0: print(('Estimated number of SDP variables: %d' % self.n_vars)) print('Generating moment matrix...') # Generate moment matrices new_n_vars, block_index = self.__add_parameters() self._time0 = time.time() new_n_vars, block_index = \ self._generate_all_moment_matrix_blocks(new_n_vars, block_index) if extramomentmatrices is not None: new_n_vars, block_index = \ self.__add_extra_momentmatrices(extramomentmatrices, new_n_vars, block_index) # The initial estimate for the size of F was overly generous. self.n_vars = new_n_vars # We don't correct the size of F, because that would trigger # memory copies, and extra columns in lil_matrix are free anyway. # self.F = self.F[:, 0:self.n_vars + 1] if self.verbose > 0: print(('Reduced number of SDP variables: %d' % self.n_vars)) # Objective function self.set_objective(objective, extraobjexpr) # Process constraints self.constraint_starting_block = block_index self.process_constraints(inequalities, equalities, momentinequalities, momentequalities, block_index, removeequalities)
Get the SDP relaxation of a noncommutative polynomial optimization problem. :param level: The level of the relaxation. The value -1 will skip automatic monomial generation and use only the monomials supplied by the option `extramonomials`. :type level: int. :param obj: Optional parameter to describe the objective function. :type obj: :class:`sympy.core.exp.Expr`. :param inequalities: Optional parameter to list inequality constraints. :type inequalities: list of :class:`sympy.core.exp.Expr`. :param equalities: Optional parameter to list equality constraints. :type equalities: list of :class:`sympy.core.exp.Expr`. :param substitutions: Optional parameter containing monomials that can be replaced (e.g., idempotent variables). :type substitutions: dict of :class:`sympy.core.exp.Expr`. :param momentinequalities: Optional parameter of inequalities defined on moments. :type momentinequalities: list of :class:`sympy.core.exp.Expr`. :param momentequalities: Optional parameter of equalities defined on moments. :type momentequalities: list of :class:`sympy.core.exp.Expr`. :param momentsubstitutions: Optional parameter containing moments that can be replaced. :type momentsubstitutions: dict of :class:`sympy.core.exp.Expr`. :param removeequalities: Optional parameter to attempt removing the equalities by solving the linear equations. :type removeequalities: bool. :param extramonomials: Optional paramter of monomials to be included, on top of the requested level of relaxation. :type extramonomials: list of :class:`sympy.core.exp.Expr`. :param extramomentmatrices: Optional paramter of duplicating or adding moment matrices. A new moment matrix can be unconstrained (""), a copy of the first one ("copy"), and satisfying a partial positivity constraint ("ppt"). Each new moment matrix is requested as a list of string of these options. For instance, adding a single new moment matrix as a copy of the first would be ``extramomentmatrices=[["copy"]]``. :type extramomentmatrices: list of list of str. :param extraobjexpr: Optional parameter of a string expression of a linear combination of moment matrix elements to be included in the objective function. :type extraobjexpr: str. :param localizing_monomials: Optional parameter to specify sets of localizing monomials for each constraint. The internal order of constraints is inequalities first, followed by the equalities. If the parameter is specified, but for a certain constraint the automatic localization is requested, leave None in its place in this parameter. :type localizing_monomials: list of list of `sympy.core.exp.Expr`. :param chordal_extension: Optional parameter to request a sparse chordal extension. :type chordal_extension: bool.
entailment
def flatten(lol): """Flatten a list of lists to a list. :param lol: A list of lists in arbitrary depth. :type lol: list of list. :returns: flat list of elements. """ new_list = [] for element in lol: if element is None: continue elif not isinstance(element, list) and not isinstance(element, tuple): new_list.append(element) elif len(element) > 0: new_list.extend(flatten(element)) return new_list
Flatten a list of lists to a list. :param lol: A list of lists in arbitrary depth. :type lol: list of list. :returns: flat list of elements.
entailment
def simplify_polynomial(polynomial, monomial_substitutions): """Simplify a polynomial for uniform handling later. """ if isinstance(polynomial, (int, float, complex)): return polynomial polynomial = (1.0 * polynomial).expand(mul=True, multinomial=True) if is_number_type(polynomial): return polynomial if polynomial.is_Mul: elements = [polynomial] else: elements = polynomial.as_coeff_mul()[1][0].as_coeff_add()[1] new_polynomial = 0 # Identify its constituent monomials for element in elements: monomial, coeff = separate_scalar_factor(element) monomial = apply_substitutions(monomial, monomial_substitutions) new_polynomial += coeff * monomial return new_polynomial
Simplify a polynomial for uniform handling later.
entailment
def __separate_scalar_factor(monomial): """Separate the constant factor from a monomial. """ scalar_factor = 1 if is_number_type(monomial): return S.One, monomial if monomial == 0: return S.One, 0 comm_factors, _ = split_commutative_parts(monomial) if len(comm_factors) > 0: if isinstance(comm_factors[0], Number): scalar_factor = comm_factors[0] if scalar_factor != 1: return monomial / scalar_factor, scalar_factor else: return monomial, scalar_factor
Separate the constant factor from a monomial.
entailment
def get_support(variables, polynomial): """Gets the support of a polynomial. """ support = [] if is_number_type(polynomial): support.append([0] * len(variables)) return support for monomial in polynomial.expand().as_coefficients_dict(): tmp_support = [0] * len(variables) mon, _ = __separate_scalar_factor(monomial) symbolic_support = flatten(split_commutative_parts(mon)) for s in symbolic_support: if isinstance(s, Pow): base = s.base if is_adjoint(base): base = base.adjoint() tmp_support[variables.index(base)] = s.exp elif is_adjoint(s): tmp_support[variables.index(s.adjoint())] = 1 elif isinstance(s, (Operator, Symbol)): tmp_support[variables.index(s)] = 1 support.append(tmp_support) return support
Gets the support of a polynomial.
entailment
def get_support_variables(polynomial): """Gets the support of a polynomial. """ support = [] if is_number_type(polynomial): return support for monomial in polynomial.expand().as_coefficients_dict(): mon, _ = __separate_scalar_factor(monomial) symbolic_support = flatten(split_commutative_parts(mon)) for s in symbolic_support: if isinstance(s, Pow): base = s.base if is_adjoint(base): base = base.adjoint() support.append(base) elif is_adjoint(s): support.append(s.adjoint()) elif isinstance(s, Operator): support.append(s) return support
Gets the support of a polynomial.
entailment
def separate_scalar_factor(element): """Construct a monomial with the coefficient separated from an element in a polynomial. """ coeff = 1.0 monomial = S.One if isinstance(element, (int, float, complex)): coeff *= element return monomial, coeff for var in element.as_coeff_mul()[1]: if not (var.is_Number or var.is_imaginary): monomial = monomial * var else: if var.is_Number: coeff = float(var) # If not, then it is imaginary else: coeff = 1j * coeff coeff = float(element.as_coeff_mul()[0]) * coeff return monomial, coeff
Construct a monomial with the coefficient separated from an element in a polynomial.
entailment
def count_ncmonomials(monomials, degree): """Given a list of monomials, it counts those that have a certain degree, or less. The function is useful when certain monomials were eliminated from the basis. :param variables: The noncommutative variables making up the monomials :param monomials: List of monomials (the monomial basis). :param degree: Maximum degree to count. :returns: The count of appropriate monomials. """ ncmoncount = 0 for monomial in monomials: if ncdegree(monomial) <= degree: ncmoncount += 1 else: break return ncmoncount
Given a list of monomials, it counts those that have a certain degree, or less. The function is useful when certain monomials were eliminated from the basis. :param variables: The noncommutative variables making up the monomials :param monomials: List of monomials (the monomial basis). :param degree: Maximum degree to count. :returns: The count of appropriate monomials.
entailment
def apply_substitutions(monomial, monomial_substitutions, pure=False): """Helper function to remove monomials from the basis.""" if is_number_type(monomial): return monomial original_monomial = monomial changed = True if not pure: substitutions = monomial_substitutions else: substitutions = {} for lhs, rhs in monomial_substitutions.items(): irrelevant = False for atom in lhs.atoms(): if atom.is_Number: continue if not monomial.has(atom): irrelevant = True break if not irrelevant: substitutions[lhs] = rhs while changed: for lhs, rhs in substitutions.items(): monomial = fast_substitute(monomial, lhs, rhs) if original_monomial == monomial: changed = False original_monomial = monomial return monomial
Helper function to remove monomials from the basis.
entailment
def fast_substitute(monomial, old_sub, new_sub): """Experimental fast substitution routine that considers only restricted cases of noncommutative algebras. In rare cases, it fails to find a substitution. Use it with proper testing. :param monomial: The monomial with parts need to be substituted. :param old_sub: The part to be replaced. :param new_sub: The replacement. """ if is_number_type(monomial): return monomial if monomial.is_Add: return sum([fast_substitute(element, old_sub, new_sub) for element in monomial.as_ordered_terms()]) comm_factors, ncomm_factors = split_commutative_parts(monomial) old_comm_factors, old_ncomm_factors = split_commutative_parts(old_sub) # This is a temporary hack if not isinstance(new_sub, (int, float, complex)): new_comm_factors, _ = split_commutative_parts(new_sub) else: new_comm_factors = [new_sub] comm_monomial = 1 is_constant_term = False if comm_factors != (): if len(comm_factors) == 1 and is_number_type(comm_factors[0]): is_constant_term = True comm_monomial = comm_factors[0] else: for comm_factor in comm_factors: comm_monomial *= comm_factor if old_comm_factors != (): comm_old_sub = 1 for comm_factor in old_comm_factors: comm_old_sub *= comm_factor comm_new_sub = 1 for comm_factor in new_comm_factors: comm_new_sub *= comm_factor # Dummy heuristic to get around retarded SymPy bug if isinstance(comm_old_sub, Pow): # In this case, we are in trouble old_base = comm_old_sub.base if comm_monomial.has(old_base): old_degree = comm_old_sub.exp new_monomial = 1 match = False for factor in comm_monomial.as_ordered_factors(): if factor.has(old_base): if isinstance(factor, Pow): degree = factor.exp if degree >= old_degree: match = True new_monomial *= \ old_base**(degree-old_degree) * \ comm_new_sub else: new_monomial *= factor else: new_monomial *= factor if match: comm_monomial = new_monomial else: comm_monomial = comm_monomial.subs(comm_old_sub, comm_new_sub) if ncomm_factors == () or old_ncomm_factors == (): return comm_monomial # old_factors = old_sub.as_ordered_factors() # factors = monomial.as_ordered_factors() new_var_list = [] new_monomial = 1 left_remainder = 1 right_remainder = 1 for i in range(len(ncomm_factors) - len(old_ncomm_factors) + 1): for j, old_ncomm_factor in enumerate(old_ncomm_factors): ncomm_factor = ncomm_factors[i + j] if isinstance(ncomm_factor, Symbol) and \ (isinstance(old_ncomm_factor, Operator) or (isinstance(old_ncomm_factor, Symbol) and ncomm_factor != old_ncomm_factor)): break if isinstance(ncomm_factor, Operator) and \ ((isinstance(old_ncomm_factor, Operator) and ncomm_factor != old_ncomm_factor) or isinstance(old_ncomm_factor, Pow)): break if is_adjoint(ncomm_factor): if not is_adjoint(old_ncomm_factor) or \ ncomm_factor != old_ncomm_factor: break else: if not isinstance(ncomm_factor, Pow): if is_adjoint(old_ncomm_factor): break else: if isinstance(old_ncomm_factor, Pow): old_base = old_ncomm_factor.base old_degree = old_ncomm_factor.exp else: old_base = old_ncomm_factor old_degree = 1 if old_base != ncomm_factor.base: break if old_degree > ncomm_factor.exp: break if old_degree < ncomm_factor.exp: if j != len(old_ncomm_factors) - 1: if j != 0: break else: left_remainder = old_base ** ( ncomm_factor.exp - old_degree) else: right_remainder = old_base ** ( ncomm_factor.exp - old_degree) else: new_monomial = 1 for var in new_var_list: new_monomial *= var new_monomial *= left_remainder * new_sub * right_remainder for j in range(i + len(old_ncomm_factors), len(ncomm_factors)): new_monomial *= ncomm_factors[j] new_monomial *= comm_monomial break new_var_list.append(ncomm_factors[i]) else: if not is_constant_term and comm_factors != (): new_monomial = comm_monomial for factor in ncomm_factors: new_monomial *= factor else: return monomial if not isinstance(new_sub, (float, int, complex)) and new_sub.is_Add: return expand(new_monomial) else: return new_monomial
Experimental fast substitution routine that considers only restricted cases of noncommutative algebras. In rare cases, it fails to find a substitution. Use it with proper testing. :param monomial: The monomial with parts need to be substituted. :param old_sub: The part to be replaced. :param new_sub: The replacement.
entailment
def generate_variables(name, n_vars=1, hermitian=None, commutative=True): """Generates a number of commutative or noncommutative variables :param name: The prefix in the symbolic representation of the noncommuting variables. This will be suffixed by a number from 0 to n_vars-1 if n_vars > 1. :type name: str. :param n_vars: The number of variables. :type n_vars: int. :param hermitian: Optional parameter to request Hermitian variables . :type hermitian: bool. :param commutative: Optional parameter to request commutative variables. Commutative variables are Hermitian by default. :type commutative: bool. :returns: list of :class:`sympy.physics.quantum.operator.Operator` or :class:`sympy.physics.quantum.operator.HermitianOperator` variables or `sympy.Symbol` :Example: >>> generate_variables('y', 2, commutative=True) [y0, y1] """ variables = [] for i in range(n_vars): if n_vars > 1: var_name = '%s%s' % (name, i) else: var_name = '%s' % name if commutative: if hermitian is None or hermitian: variables.append(Symbol(var_name, real=True)) else: variables.append(Symbol(var_name, complex=True)) elif hermitian is not None and hermitian: variables.append(HermitianOperator(var_name)) else: variables.append(Operator(var_name)) return variables
Generates a number of commutative or noncommutative variables :param name: The prefix in the symbolic representation of the noncommuting variables. This will be suffixed by a number from 0 to n_vars-1 if n_vars > 1. :type name: str. :param n_vars: The number of variables. :type n_vars: int. :param hermitian: Optional parameter to request Hermitian variables . :type hermitian: bool. :param commutative: Optional parameter to request commutative variables. Commutative variables are Hermitian by default. :type commutative: bool. :returns: list of :class:`sympy.physics.quantum.operator.Operator` or :class:`sympy.physics.quantum.operator.HermitianOperator` variables or `sympy.Symbol` :Example: >>> generate_variables('y', 2, commutative=True) [y0, y1]
entailment
def generate_operators(name, n_vars=1, hermitian=None, commutative=False): """Generates a number of commutative or noncommutative operators :param name: The prefix in the symbolic representation of the noncommuting variables. This will be suffixed by a number from 0 to n_vars-1 if n_vars > 1. :type name: str. :param n_vars: The number of variables. :type n_vars: int. :param hermitian: Optional parameter to request Hermitian variables . :type hermitian: bool. :param commutative: Optional parameter to request commutative variables. Commutative variables are Hermitian by default. :type commutative: bool. :returns: list of :class:`sympy.physics.quantum.operator.Operator` or :class:`sympy.physics.quantum.operator.HermitianOperator` variables :Example: >>> generate_variables('y', 2, commutative=True) [y0, y1] """ variables = [] for i in range(n_vars): if n_vars > 1: var_name = '%s%s' % (name, i) else: var_name = '%s' % name if hermitian is not None and hermitian: variables.append(HermitianOperator(var_name)) else: variables.append(Operator(var_name)) variables[-1].is_commutative = commutative return variables
Generates a number of commutative or noncommutative operators :param name: The prefix in the symbolic representation of the noncommuting variables. This will be suffixed by a number from 0 to n_vars-1 if n_vars > 1. :type name: str. :param n_vars: The number of variables. :type n_vars: int. :param hermitian: Optional parameter to request Hermitian variables . :type hermitian: bool. :param commutative: Optional parameter to request commutative variables. Commutative variables are Hermitian by default. :type commutative: bool. :returns: list of :class:`sympy.physics.quantum.operator.Operator` or :class:`sympy.physics.quantum.operator.HermitianOperator` variables :Example: >>> generate_variables('y', 2, commutative=True) [y0, y1]
entailment
def get_monomials(variables, degree): """Generates all noncommutative monomials up to a degree :param variables: The noncommutative variables to generate monomials from :type variables: list of :class:`sympy.physics.quantum.operator.Operator` or :class:`sympy.physics.quantum.operator.HermitianOperator`. :param degree: The maximum degree. :type degree: int. :returns: list of monomials. """ if degree == -1: return [] if not variables: return [S.One] else: _variables = variables[:] _variables.insert(0, 1) ncmonomials = [S.One] ncmonomials.extend(var for var in variables) for var in variables: if not is_hermitian(var): ncmonomials.append(var.adjoint()) for _ in range(1, degree): temp = [] for var in _variables: for new_var in ncmonomials: temp.append(var * new_var) if var != 1 and not is_hermitian(var): temp.append(var.adjoint() * new_var) ncmonomials = unique(temp[:]) return ncmonomials
Generates all noncommutative monomials up to a degree :param variables: The noncommutative variables to generate monomials from :type variables: list of :class:`sympy.physics.quantum.operator.Operator` or :class:`sympy.physics.quantum.operator.HermitianOperator`. :param degree: The maximum degree. :type degree: int. :returns: list of monomials.
entailment
def ncdegree(polynomial): """Returns the degree of a noncommutative polynomial. :param polynomial: Polynomial of noncommutive variables. :type polynomial: :class:`sympy.core.expr.Expr`. :returns: int -- the degree of the polynomial. """ degree = 0 if is_number_type(polynomial): return degree polynomial = polynomial.expand() for monomial in polynomial.as_coefficients_dict(): subdegree = 0 for variable in monomial.as_coeff_mul()[1]: if isinstance(variable, Pow): subdegree += variable.exp elif not isinstance(variable, Number) and variable != I: subdegree += 1 if subdegree > degree: degree = subdegree return degree
Returns the degree of a noncommutative polynomial. :param polynomial: Polynomial of noncommutive variables. :type polynomial: :class:`sympy.core.expr.Expr`. :returns: int -- the degree of the polynomial.
entailment
def iscomplex(polynomial): """Returns whether the polynomial has complex coefficients :param polynomial: Polynomial of noncommutive variables. :type polynomial: :class:`sympy.core.expr.Expr`. :returns: bool -- whether there is a complex coefficient. """ if isinstance(polynomial, (int, float)): return False if isinstance(polynomial, complex): return True polynomial = polynomial.expand() for monomial in polynomial.as_coefficients_dict(): for variable in monomial.as_coeff_mul()[1]: if isinstance(variable, complex) or variable == I: return True return False
Returns whether the polynomial has complex coefficients :param polynomial: Polynomial of noncommutive variables. :type polynomial: :class:`sympy.core.expr.Expr`. :returns: bool -- whether there is a complex coefficient.
entailment
def get_all_monomials(variables, extramonomials, substitutions, degree, removesubstitutions=True): """Return the monomials of a certain degree. """ monomials = get_monomials(variables, degree) if extramonomials is not None: monomials.extend(extramonomials) if removesubstitutions and substitutions is not None: monomials = [monomial for monomial in monomials if monomial not in substitutions] monomials = [remove_scalar_factor(apply_substitutions(monomial, substitutions)) for monomial in monomials] monomials = unique(monomials) return monomials
Return the monomials of a certain degree.
entailment
def pick_monomials_up_to_degree(monomials, degree): """Collect monomials up to a given degree. """ ordered_monomials = [] if degree >= 0: ordered_monomials.append(S.One) for deg in range(1, degree + 1): ordered_monomials.extend(pick_monomials_of_degree(monomials, deg)) return ordered_monomials
Collect monomials up to a given degree.
entailment
def pick_monomials_of_degree(monomials, degree): """Collect all monomials up of a given degree. """ selected_monomials = [] for monomial in monomials: if ncdegree(monomial) == degree: selected_monomials.append(monomial) return selected_monomials
Collect all monomials up of a given degree.
entailment
def save_monomial_index(filename, monomial_index): """Save a monomial dictionary for debugging purposes. :param filename: The name of the file to save to. :type filename: str. :param monomial_index: The monomial index of the SDP relaxation. :type monomial_index: dict of :class:`sympy.core.expr.Expr`. """ monomial_translation = [''] * (len(monomial_index) + 1) for key, k in monomial_index.items(): monomial_translation[k] = convert_monomial_to_string(key) file_ = open(filename, 'w') for k in range(len(monomial_translation)): file_.write('%s %s\n' % (k, monomial_translation[k])) file_.close()
Save a monomial dictionary for debugging purposes. :param filename: The name of the file to save to. :type filename: str. :param monomial_index: The monomial index of the SDP relaxation. :type monomial_index: dict of :class:`sympy.core.expr.Expr`.
entailment
def unique(seq): """Helper function to include only unique monomials in a basis.""" seen = {} result = [] for item in seq: marker = item if marker in seen: continue seen[marker] = 1 result.append(item) return result
Helper function to include only unique monomials in a basis.
entailment
def build_permutation_matrix(permutation): """Build a permutation matrix for a permutation. """ matrix = lil_matrix((len(permutation), len(permutation))) column = 0 for row in permutation: matrix[row, column] = 1 column += 1 return matrix
Build a permutation matrix for a permutation.
entailment
def convert_relational(relational): """Convert all inequalities to >=0 form. """ rel = relational.rel_op if rel in ['==', '>=', '>']: return relational.lhs-relational.rhs elif rel in ['<=', '<']: return relational.rhs-relational.lhs else: raise Exception("The relational operation ' + rel + ' is not " "implemented!")
Convert all inequalities to >=0 form.
entailment
def value(board, who='x'): """Returns the value of a board >>> b = Board(); b._rows = [['x', 'x', 'x'], ['x', 'x', 'x'], ['x', 'x', 'x']] >>> value(b) 1 >>> b = Board(); b._rows = [['o', 'o', 'o'], ['o', 'o', 'o'], ['o', 'o', 'o']] >>> value(b) -1 >>> b = Board(); b._rows = [['x', 'o', ' '], ['x', 'o', ' '], [' ', ' ', ' ']] >>> value(b) 1 >>> b._rows[0][2] = 'x' >>> value(b) -1 """ w = board.winner() if w == who: return 1 if w == opp(who): return -1 if board.turn == 9: return 0 if who == board.whose_turn: return max([value(b, who) for b in board.possible()]) else: return min([value(b, who) for b in board.possible()])
Returns the value of a board >>> b = Board(); b._rows = [['x', 'x', 'x'], ['x', 'x', 'x'], ['x', 'x', 'x']] >>> value(b) 1 >>> b = Board(); b._rows = [['o', 'o', 'o'], ['o', 'o', 'o'], ['o', 'o', 'o']] >>> value(b) -1 >>> b = Board(); b._rows = [['x', 'o', ' '], ['x', 'o', ' '], [' ', ' ', ' ']] >>> value(b) 1 >>> b._rows[0][2] = 'x' >>> value(b) -1
entailment
def ai(board, who='x'): """ Returns best next board >>> b = Board(); b._rows = [['x', 'o', ' '], ['x', 'o', ' '], [' ', ' ', ' ']] >>> ai(b) < Board |xo.xo.x..| > """ return sorted(board.possible(), key=lambda b: value(b, who))[-1]
Returns best next board >>> b = Board(); b._rows = [['x', 'o', ' '], ['x', 'o', ' '], [' ', ' ', ' ']] >>> ai(b) < Board |xo.xo.x..| >
entailment
def winner(self): """Returns either x or o if one of them won, otherwise None""" for c in 'xo': for comb in [(0,3,6), (1,4,7), (2,5,8), (0,1,2), (3,4,5), (6,7,8), (0,4,8), (2,4,6)]: if all(self.spots[p] == c for p in comb): return c return None
Returns either x or o if one of them won, otherwise None
entailment
def get_relaxation(self, A_configuration, B_configuration, I): """Get the sparse SDP relaxation of a Bell inequality. :param A_configuration: The definition of measurements of Alice. :type A_configuration: list of list of int. :param B_configuration: The definition of measurements of Bob. :type B_configuration: list of list of int. :param I: The matrix describing the Bell inequality in the Collins-Gisin picture. :type I: list of list of int. """ coefficients = collinsgisin_to_faacets(I) M, ncIndices = get_faacets_moment_matrix(A_configuration, B_configuration, coefficients) self.n_vars = M.max() - 1 bs = len(M) # The block size self.block_struct = [bs] self.F = lil_matrix((bs**2, self.n_vars + 1)) # Constructing the internal representation of the constraint matrices # See Section 2.1 in the SDPA manual and also Yalmip's internal # representation for i in range(bs): for j in range(i, bs): if M[i, j] != 0: self.F[i*bs+j, abs(M[i, j])-1] = copysign(1, M[i, j]) self.obj_facvar = [0 for _ in range(self.n_vars)] for i in range(1, len(ncIndices)): self.obj_facvar[abs(ncIndices[i])-2] += \ copysign(1, ncIndices[i])*coefficients[i]
Get the sparse SDP relaxation of a Bell inequality. :param A_configuration: The definition of measurements of Alice. :type A_configuration: list of list of int. :param B_configuration: The definition of measurements of Bob. :type B_configuration: list of list of int. :param I: The matrix describing the Bell inequality in the Collins-Gisin picture. :type I: list of list of int.
entailment
def share(track_id=None, url=None, users=None): """ Returns list of users track has been shared with. Either track or url need to be provided. """ client = get_client() if url: track_id = client.get('/resolve', url=url).id if not users: return client.get('/tracks/%d/permissions' % track_id) permissions = {'user_id': []} for username in users: # check cache for user user = settings.users.get(username, None) if user: permissions['user_id'].append(user['id']) else: user = client.get('/resolve', url='http://soundcloud.com/%s' % username) permissions['user_id'].append(user.id) settings.users[username] = user.obj settings.save() return client.put('/tracks/%d/permissions' % track_id, permissions=permissions)
Returns list of users track has been shared with. Either track or url need to be provided.
entailment
def solve_with_cvxopt(sdp, solverparameters=None): """Helper function to convert the SDP problem to PICOS and call CVXOPT solver, and parse the output. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`. """ P = convert_to_picos(sdp) P.set_option("solver", "cvxopt") P.set_option("verbose", sdp.verbose) if solverparameters is not None: for key, value in solverparameters.items(): P.set_option(key, value) solution = P.solve() x_mat = [np.array(P.get_valued_variable('X'))] y_mat = [np.array(P.get_constraint(i).dual) for i in range(len(P.constraints))] return -solution["cvxopt_sol"]["primal objective"] + \ sdp.constant_term, \ -solution["cvxopt_sol"]["dual objective"] + \ sdp.constant_term, \ x_mat, y_mat, solution["status"]
Helper function to convert the SDP problem to PICOS and call CVXOPT solver, and parse the output. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`.
entailment
def convert_to_picos(sdp, duplicate_moment_matrix=False): """Convert an SDP relaxation to a PICOS problem such that the exported .dat-s file is extremely sparse, there is not penalty imposed in terms of SDP variables or number of constraints. This conversion can be used for imposing extra constraints on the moment matrix, such as partial transpose. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :param duplicate_moment_matrix: Optional parameter to add an unconstrained moment matrix to the problem with the same structure as the moment matrix with the PSD constraint. :type duplicate_moment_matrix: bool. :returns: :class:`picos.Problem`. """ import picos as pic import cvxopt as cvx P = pic.Problem(verbose=sdp.verbose) block_size = sdp.block_struct[0] if sdp.F.dtype == np.float64: X = P.add_variable('X', (block_size, block_size), vtype="symmetric") if duplicate_moment_matrix: Y = P.add_variable('Y', (block_size, block_size), vtype="symmetric") else: X = P.add_variable('X', (block_size, block_size), vtype="hermitian") if duplicate_moment_matrix: Y = P.add_variable('X', (block_size, block_size), vtype="hermitian") row_offset = 0 theoretical_n_vars = sdp.block_struct[0]**2 eq_block_start = sdp.constraint_starting_block+sdp._n_inequalities block_idx = 0 while (block_idx < len(sdp.block_struct)): block_size = sdp.block_struct[block_idx] x, Ix, Jx = [], [], [] c, Ic, Jc = [], [], [] for i, row in enumerate(sdp.F.rows[row_offset:row_offset + block_size**2]): for j, column in enumerate(row): if column > 0: x.append(sdp.F.data[row_offset+i][j]) Ix.append(i) Jx.append(column-1) i0 = (i//block_size)+(i % block_size)*block_size if i != i0: x.append(sdp.F.data[row_offset+i][j]) Ix.append(i0) Jx.append(column-1) else: c.append(sdp.F.data[row_offset+i][j]) Ic.append(i%block_size) Jc.append(i//block_size) permutation = cvx.spmatrix(x, Ix, Jx, (block_size**2, theoretical_n_vars)) constant = cvx.spmatrix(c, Ic, Jc, (block_size, block_size)) if duplicate_moment_matrix: constraint = X else: constraint = X.copy() for k in constraint.factors: constraint.factors[k] = permutation constraint._size = (block_size, block_size) if block_idx < eq_block_start: P.add_constraint(constant + constraint >> 0) else: P.add_constraint(constant + constraint == 0) row_offset += block_size**2 block_idx += 1 if duplicate_moment_matrix and \ block_size == sdp.block_struct[0]: for k in Y.factors: Y.factors[k] = permutation row_offset += block_size**2 block_idx += 1 if len(np.nonzero(sdp.obj_facvar)[0]) > 0: x, Ix, Jx = [], [], [] for k, val in enumerate(sdp.obj_facvar): if val != 0: x.append(val) Ix.append(0) Jx.append(k) permutation = cvx.spmatrix(x, Ix, Jx) objective = X.copy() for k in objective.factors: objective.factors[k] = permutation objective._size = (1, 1) P.set_objective('min', objective) return P
Convert an SDP relaxation to a PICOS problem such that the exported .dat-s file is extremely sparse, there is not penalty imposed in terms of SDP variables or number of constraints. This conversion can be used for imposing extra constraints on the moment matrix, such as partial transpose. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :param duplicate_moment_matrix: Optional parameter to add an unconstrained moment matrix to the problem with the same structure as the moment matrix with the PSD constraint. :type duplicate_moment_matrix: bool. :returns: :class:`picos.Problem`.
entailment
def solve_with_cvxpy(sdp, solverparameters=None): """Helper function to convert the SDP problem to CVXPY and call the solver, and parse the output. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`. """ problem = convert_to_cvxpy(sdp) if solverparameters is not None and 'solver' in solverparameters: solver = solverparameters.pop('solver') v = problem.solve(solver=solver, verbose=(sdp.verbose > 0)) else: v = problem.solve(verbose=(sdp.verbose > 0)) if v is None: status = "infeasible" x_mat, y_mat = [], [] elif v == float("inf") or v == -float("inf"): status = "unbounded" x_mat, y_mat = [], [] else: status = "optimal" x_pre = sdp.F[:, 1:sdp.n_vars+1].dot(problem.variables()[0].value) x_pre += sdp.F[:, 0] row_offsets = [0] cumulative_sum = 0 for block_size in sdp.block_struct: cumulative_sum += block_size ** 2 row_offsets.append(cumulative_sum) x_mat = [] for bi, bs in enumerate(sdp.block_struct): x = x_pre[row_offsets[bi]:row_offsets[bi+1]].reshape((bs, bs)) x += x.T - np.diag(np.array(x.diagonal())[0]) x_mat.append(x) y_mat = [constraint.dual_value for constraint in problem.constraints] return v+sdp.constant_term, v+sdp.constant_term, x_mat, y_mat, status
Helper function to convert the SDP problem to CVXPY and call the solver, and parse the output. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`.
entailment
def convert_to_cvxpy(sdp): """Convert an SDP relaxation to a CVXPY problem. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: :class:`cvxpy.Problem`. """ from cvxpy import Minimize, Problem, Variable row_offsets = [0] cumulative_sum = 0 for block_size in sdp.block_struct: cumulative_sum += block_size ** 2 row_offsets.append(cumulative_sum) x = Variable(sdp.n_vars) # The moment matrices are the first blocks of identical size constraints = [] for idx, bs in enumerate(sdp.block_struct): nonzero_set = set() F = [lil_matrix((bs, bs)) for _ in range(sdp.n_vars+1)] for ri, row in enumerate(sdp.F.rows[row_offsets[idx]: row_offsets[idx+1]], row_offsets[idx]): block_index, i, j = convert_row_to_sdpa_index(sdp.block_struct, row_offsets, ri) for col_index, k in enumerate(row): value = sdp.F.data[ri][col_index] F[k][i, j] = value F[k][j, i] = value nonzero_set.add(k) if bs > 1: sum_ = sum(F[k]*x[k-1] for k in nonzero_set if k > 0) if not isinstance(sum_, (int, float)): if F[0].getnnz() > 0: sum_ += F[0] constraints.append(sum_ >> 0) else: sum_ = sum(F[k][0, 0]*x[k-1] for k in nonzero_set if k > 0) if not isinstance(sum_, (int, float)): sum_ += F[0][0, 0] constraints.append(sum_ >= 0) obj = sum(ci*xi for ci, xi in zip(sdp.obj_facvar, x) if ci != 0) problem = Problem(Minimize(obj), constraints) return problem
Convert an SDP relaxation to a CVXPY problem. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: :class:`cvxpy.Problem`.
entailment
def get_neighbors(index, lattice_length, width=0, periodic=False): """Get the forward neighbors of a site in a lattice. :param index: Linear index of operator. :type index: int. :param lattice_length: The size of the 2D lattice in either dimension :type lattice_length: int. :param width: Optional parameter to define width. :type width: int. :param periodic: Optional parameter to indicate periodic boundary conditions. :type periodic: bool :returns: list of int -- the neighbors in linear index. """ if width == 0: width = lattice_length neighbors = [] coords = divmod(index, width) if coords[1] < width - 1: neighbors.append(index + 1) elif periodic and width > 1: neighbors.append(index - width + 1) if coords[0] < lattice_length - 1: neighbors.append(index + width) elif periodic: neighbors.append(index - (lattice_length - 1) * width) return neighbors
Get the forward neighbors of a site in a lattice. :param index: Linear index of operator. :type index: int. :param lattice_length: The size of the 2D lattice in either dimension :type lattice_length: int. :param width: Optional parameter to define width. :type width: int. :param periodic: Optional parameter to indicate periodic boundary conditions. :type periodic: bool :returns: list of int -- the neighbors in linear index.
entailment
def get_next_neighbors(indices, lattice_length, width=0, distance=1, periodic=False): """Get the forward neighbors at a given distance of a site or set of sites in a lattice. :param index: Linear index of operator. :type index: int. :param lattice_length: The size of the 2D lattice in either dimension :type lattice_length: int. :param width: Optional parameter to define width. :type width: int. :param distance: Optional parameter to define distance. :type width: int. :param periodic: Optional parameter to indicate periodic boundary conditions. :type periodic: bool :returns: list of int -- the neighbors at given distance in linear index. """ if not isinstance(indices, list): indices = [indices] if distance == 1: return flatten(get_neighbors(index, lattice_length, width, periodic) for index in indices) else: s1 = set(flatten(get_next_neighbors(get_neighbors(index, lattice_length, width, periodic), lattice_length, width, distance-1, periodic) for index in indices)) s2 = set(get_next_neighbors(indices, lattice_length, width, distance-1, periodic)) return list(s1 - s2)
Get the forward neighbors at a given distance of a site or set of sites in a lattice. :param index: Linear index of operator. :type index: int. :param lattice_length: The size of the 2D lattice in either dimension :type lattice_length: int. :param width: Optional parameter to define width. :type width: int. :param distance: Optional parameter to define distance. :type width: int. :param periodic: Optional parameter to indicate periodic boundary conditions. :type periodic: bool :returns: list of int -- the neighbors at given distance in linear index.
entailment
def bosonic_constraints(a): """Return a set of constraints that define fermionic ladder operators. :param a: The non-Hermitian variables. :type a: list of :class:`sympy.physics.quantum.operator.Operator`. :returns: a dict of substitutions. """ substitutions = {} for i, ai in enumerate(a): substitutions[ai * Dagger(ai)] = 1.0 + Dagger(ai) * ai for aj in a[i+1:]: # substitutions[ai*Dagger(aj)] = -Dagger(ai)*aj substitutions[ai*Dagger(aj)] = Dagger(aj)*ai substitutions[Dagger(ai)*aj] = aj*Dagger(ai) substitutions[ai*aj] = aj*ai substitutions[Dagger(ai) * Dagger(aj)] = Dagger(aj) * Dagger(ai) return substitutions
Return a set of constraints that define fermionic ladder operators. :param a: The non-Hermitian variables. :type a: list of :class:`sympy.physics.quantum.operator.Operator`. :returns: a dict of substitutions.
entailment
def fermionic_constraints(a): """Return a set of constraints that define fermionic ladder operators. :param a: The non-Hermitian variables. :type a: list of :class:`sympy.physics.quantum.operator.Operator`. :returns: a dict of substitutions. """ substitutions = {} for i, ai in enumerate(a): substitutions[ai ** 2] = 0 substitutions[Dagger(ai) ** 2] = 0 substitutions[ai * Dagger(ai)] = 1.0 - Dagger(ai) * ai for aj in a[i+1:]: # substitutions[ai*Dagger(aj)] = -Dagger(ai)*aj substitutions[ai*Dagger(aj)] = -Dagger(aj)*ai substitutions[Dagger(ai)*aj] = -aj*Dagger(ai) substitutions[ai*aj] = -aj*ai substitutions[Dagger(ai) * Dagger(aj)] = - Dagger(aj) * Dagger(ai) return substitutions
Return a set of constraints that define fermionic ladder operators. :param a: The non-Hermitian variables. :type a: list of :class:`sympy.physics.quantum.operator.Operator`. :returns: a dict of substitutions.
entailment
def pauli_constraints(X, Y, Z): """Return a set of constraints that define Pauli spin operators. :param X: List of Pauli X operator on sites. :type X: list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param Y: List of Pauli Y operator on sites. :type Y: list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param Z: List of Pauli Z operator on sites. :type Z: list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :returns: tuple of substitutions and equalities. """ substitutions = {} n_vars = len(X) for i in range(n_vars): # They square to the identity substitutions[X[i] * X[i]] = 1 substitutions[Y[i] * Y[i]] = 1 substitutions[Z[i] * Z[i]] = 1 # Anticommutation relations substitutions[Y[i] * X[i]] = - X[i] * Y[i] substitutions[Z[i] * X[i]] = - X[i] * Z[i] substitutions[Z[i] * Y[i]] = - Y[i] * Z[i] # Commutation relations. # equalities.append(X[i]*Y[i] - 1j*Z[i]) # equalities.append(X[i]*Z[i] + 1j*Y[i]) # equalities.append(Y[i]*Z[i] - 1j*X[i]) # They commute between the sites for j in range(i + 1, n_vars): substitutions[X[j] * X[i]] = X[i] * X[j] substitutions[Y[j] * Y[i]] = Y[i] * Y[j] substitutions[Y[j] * X[i]] = X[i] * Y[j] substitutions[Y[i] * X[j]] = X[j] * Y[i] substitutions[Z[j] * Z[i]] = Z[i] * Z[j] substitutions[Z[j] * X[i]] = X[i] * Z[j] substitutions[Z[i] * X[j]] = X[j] * Z[i] substitutions[Z[j] * Y[i]] = Y[i] * Z[j] substitutions[Z[i] * Y[j]] = Y[j] * Z[i] return substitutions
Return a set of constraints that define Pauli spin operators. :param X: List of Pauli X operator on sites. :type X: list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param Y: List of Pauli Y operator on sites. :type Y: list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param Z: List of Pauli Z operator on sites. :type Z: list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :returns: tuple of substitutions and equalities.
entailment
def generate_measurements(party, label): """Generate variables that behave like measurements. :param party: The list of number of measurement outputs a party has. :type party: list of int. :param label: The label to be given to the symbolic variables. :type label: str. :returns: list of list of :class:`sympy.physics.quantum.operator.HermitianOperator`. """ measurements = [] for i in range(len(party)): measurements.append(generate_operators(label + '%s' % i, party[i] - 1, hermitian=True)) return measurements
Generate variables that behave like measurements. :param party: The list of number of measurement outputs a party has. :type party: list of int. :param label: The label to be given to the symbolic variables. :type label: str. :returns: list of list of :class:`sympy.physics.quantum.operator.HermitianOperator`.
entailment
def projective_measurement_constraints(*parties): """Return a set of constraints that define projective measurements. :param parties: Measurements of different parties. :type A: list or tuple of list of list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :returns: substitutions containing idempotency, orthogonality and commutation relations. """ substitutions = {} # Idempotency and orthogonality of projectors if isinstance(parties[0][0][0], list): parties = parties[0] for party in parties: for measurement in party: for projector1 in measurement: for projector2 in measurement: if projector1 == projector2: substitutions[projector1**2] = projector1 else: substitutions[projector1*projector2] = 0 substitutions[projector2*projector1] = 0 # Projectors commute between parties in a partition for n1 in range(len(parties)): for n2 in range(n1+1, len(parties)): for measurement1 in parties[n1]: for measurement2 in parties[n2]: for projector1 in measurement1: for projector2 in measurement2: substitutions[projector2*projector1] = \ projector1*projector2 return substitutions
Return a set of constraints that define projective measurements. :param parties: Measurements of different parties. :type A: list or tuple of list of list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :returns: substitutions containing idempotency, orthogonality and commutation relations.
entailment
def define_objective_with_I(I, *args): """Define a polynomial using measurements and an I matrix describing a Bell inequality. :param I: The I matrix of a Bell inequality in the Collins-Gisin notation. :type I: list of list of int. :param args: Either the measurements of Alice and Bob or a `Probability` class describing their measurement operators. :type A: tuple of list of list of :class:`sympy.physics.quantum.operator.HermitianOperator` or :class:`ncpol2sdpa.Probability` :returns: :class:`sympy.core.expr.Expr` -- the objective function to be solved as a minimization problem to find the maximum quantum violation. Note that the sign is flipped compared to the Bell inequality. """ objective = I[0][0] if len(args) > 2 or len(args) == 0: raise Exception("Wrong number of arguments!") elif len(args) == 1: A = args[0].parties[0] B = args[0].parties[1] else: A = args[0] B = args[1] i, j = 0, 1 # Row and column index in I for m_Bj in B: # Define first row for Bj in m_Bj: objective += I[i][j] * Bj j += 1 i += 1 for m_Ai in A: for Ai in m_Ai: objective += I[i][0] * Ai j = 1 for m_Bj in B: for Bj in m_Bj: objective += I[i][j] * Ai * Bj j += 1 i += 1 return -objective
Define a polynomial using measurements and an I matrix describing a Bell inequality. :param I: The I matrix of a Bell inequality in the Collins-Gisin notation. :type I: list of list of int. :param args: Either the measurements of Alice and Bob or a `Probability` class describing their measurement operators. :type A: tuple of list of list of :class:`sympy.physics.quantum.operator.HermitianOperator` or :class:`ncpol2sdpa.Probability` :returns: :class:`sympy.core.expr.Expr` -- the objective function to be solved as a minimization problem to find the maximum quantum violation. Note that the sign is flipped compared to the Bell inequality.
entailment
def correlator(A, B): """Correlators between the probabilities of two parties. :param A: Measurements of Alice. :type A: list of list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param B: Measurements of Bob. :type B: list of list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :returns: list of correlators. """ correlators = [] for i in range(len(A)): correlator_row = [] for j in range(len(B)): corr = 0 for k in range(len(A[i])): for l in range(len(B[j])): if k == l: corr += A[i][k] * B[j][l] else: corr -= A[i][k] * B[j][l] correlator_row.append(corr) correlators.append(correlator_row) return correlators
Correlators between the probabilities of two parties. :param A: Measurements of Alice. :type A: list of list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param B: Measurements of Bob. :type B: list of list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :returns: list of correlators.
entailment
def maximum_violation(A_configuration, B_configuration, I, level, extra=None): """Get the maximum violation of a two-party Bell inequality. :param A_configuration: Measurement settings of Alice. :type A_configuration: list of int. :param B_configuration: Measurement settings of Bob. :type B_configuration: list of int. :param I: The I matrix of a Bell inequality in the Collins-Gisin notation. :type I: list of list of int. :param level: Level of relaxation. :type level: int. :returns: tuple of primal and dual solutions of the SDP relaxation. """ P = Probability(A_configuration, B_configuration) objective = define_objective_with_I(I, P) if extra is None: extramonomials = [] else: extramonomials = P.get_extra_monomials(extra) sdpRelaxation = SdpRelaxation(P.get_all_operators(), verbose=0) sdpRelaxation.get_relaxation(level, objective=objective, substitutions=P.substitutions, extramonomials=extramonomials) solve_sdp(sdpRelaxation) return sdpRelaxation.primal, sdpRelaxation.dual
Get the maximum violation of a two-party Bell inequality. :param A_configuration: Measurement settings of Alice. :type A_configuration: list of int. :param B_configuration: Measurement settings of Bob. :type B_configuration: list of int. :param I: The I matrix of a Bell inequality in the Collins-Gisin notation. :type I: list of list of int. :param level: Level of relaxation. :type level: int. :returns: tuple of primal and dual solutions of the SDP relaxation.
entailment
def stable_format_dict(d): """A sorted, python2/3 stable formatting of a dictionary. Does not work for dicts with unicode strings as values.""" inner = ', '.join('{}: {}'.format(repr(k)[1:] if repr(k).startswith(u"u'") or repr(k).startswith(u'u"') else repr(k), v) for k, v in sorted(d.items())) return '{%s}' % inner
A sorted, python2/3 stable formatting of a dictionary. Does not work for dicts with unicode strings as values.
entailment
def interval_overlap(a, b, x, y): """Returns by how much two intervals overlap assumed that a <= b and x <= y""" if b <= x or a >= y: return 0 elif x <= a <= y: return min(b, y) - a elif x <= b <= y: return b - max(a, x) elif a >= x and b <= y: return b - a else: assert False
Returns by how much two intervals overlap assumed that a <= b and x <= y
entailment
def width_aware_slice(s, start, end, replacement_char=u' '): # type: (Text, int, int, Text) """ >>> width_aware_slice(u'a\uff25iou', 0, 2)[1] == u' ' True """ divides = [0] for c in s: divides.append(divides[-1] + wcswidth(c)) new_chunk_chars = [] for char, char_start, char_end in zip(s, divides[:-1], divides[1:]): if char_start == start and char_end == start: continue # don't use zero-width characters at the beginning of a slice # (combining characters combine with the chars before themselves) elif char_start >= start and char_end <= end: new_chunk_chars.append(char) else: new_chunk_chars.extend(replacement_char * interval_overlap(char_start, char_end, start, end)) return ''.join(new_chunk_chars)
>>> width_aware_slice(u'a\uff25iou', 0, 2)[1] == u' ' True
entailment
def linesplit(string, columns): # type: (Union[Text, FmtStr], int) -> List[FmtStr] """Returns a list of lines, split on the last possible space of each line. Split spaces will be removed. Whitespaces will be normalized to one space. Spaces will be the color of the first whitespace character of the normalized whitespace. If a word extends beyond the line, wrap it anyway. >>> linesplit(fmtstr(" home is where the heart-eating mummy is", 'blue'), 10) [blue('home')+blue(' ')+blue('is'), blue('where')+blue(' ')+blue('the'), blue('heart-eati'), blue('ng')+blue(' ')+blue('mummy'), blue('is')] """ if not isinstance(string, FmtStr): string = fmtstr(string) string_s = string.s matches = list(re.finditer(r'\s+', string_s)) spaces = [string[m.start():m.end()] for m in matches if m.start() != 0 and m.end() != len(string_s)] words = [string[start:end] for start, end in zip( [0] + [m.end() for m in matches], [m.start() for m in matches] + [len(string_s)]) if start != end] word_to_lines = lambda word: [word[columns*i:columns*(i+1)] for i in range((len(word) - 1) // columns + 1)] lines = word_to_lines(words[0]) for word, space in zip(words[1:], spaces): if len(lines[-1]) + len(word) < columns: lines[-1] += fmtstr(' ', **space.shared_atts) lines[-1] += word else: lines.extend(word_to_lines(word)) return lines
Returns a list of lines, split on the last possible space of each line. Split spaces will be removed. Whitespaces will be normalized to one space. Spaces will be the color of the first whitespace character of the normalized whitespace. If a word extends beyond the line, wrap it anyway. >>> linesplit(fmtstr(" home is where the heart-eating mummy is", 'blue'), 10) [blue('home')+blue(' ')+blue('is'), blue('where')+blue(' ')+blue('the'), blue('heart-eati'), blue('ng')+blue(' ')+blue('mummy'), blue('is')]
entailment
def normalize_slice(length, index): "Fill in the Nones in a slice." is_int = False if isinstance(index, int): is_int = True index = slice(index, index+1) if index.start is None: index = slice(0, index.stop, index.step) if index.stop is None: index = slice(index.start, length, index.step) if index.start < -1: # XXX why must this be -1? index = slice(length - index.start, index.stop, index.step) if index.stop < -1: # XXX why must this be -1? index = slice(index.start, length - index.stop, index.step) if index.step is not None: raise NotImplementedError("You can't use steps with slicing yet") if is_int: if index.start < 0 or index.start > length: raise IndexError("index out of bounds: %r for length %s" % (index, length)) return index
Fill in the Nones in a slice.
entailment
def parse_args(args, kwargs): """Returns a kwargs dictionary by turning args into kwargs""" if 'style' in kwargs: args += (kwargs['style'],) del kwargs['style'] for arg in args: if not isinstance(arg, (bytes, unicode)): raise ValueError("args must be strings:" + repr(args)) if arg.lower() in FG_COLORS: if 'fg' in kwargs: raise ValueError("fg specified twice") kwargs['fg'] = FG_COLORS[arg] elif arg.lower().startswith('on_') and arg[3:].lower() in BG_COLORS: if 'bg' in kwargs: raise ValueError("fg specified twice") kwargs['bg'] = BG_COLORS[arg[3:]] elif arg.lower() in STYLES: kwargs[arg] = True else: raise ValueError("couldn't process arg: "+repr(arg)) for k in kwargs: if k not in ['fg', 'bg'] + list(STYLES.keys()): raise ValueError("Can't apply that transformation") if 'fg' in kwargs: if kwargs['fg'] in FG_COLORS: kwargs['fg'] = FG_COLORS[kwargs['fg']] if kwargs['fg'] not in list(FG_COLORS.values()): raise ValueError("Bad fg value: %r" % kwargs['fg']) if 'bg' in kwargs: if kwargs['bg'] in BG_COLORS: kwargs['bg'] = BG_COLORS[kwargs['bg']] if kwargs['bg'] not in list(BG_COLORS.values()): raise ValueError("Bad bg value: %r" % kwargs['bg']) return kwargs
Returns a kwargs dictionary by turning args into kwargs
entailment
def fmtstr(string, *args, **kwargs): # type: (Union[Text, bytes, FmtStr], *Any, **Any) -> FmtStr """ Convenience function for creating a FmtStr >>> fmtstr('asdf', 'blue', 'on_red', 'bold') on_red(bold(blue('asdf'))) >>> fmtstr('blarg', fg='blue', bg='red', bold=True) on_red(bold(blue('blarg'))) """ atts = parse_args(args, kwargs) if isinstance(string, FmtStr): pass elif isinstance(string, (bytes, unicode)): string = FmtStr.from_str(string) else: raise ValueError("Bad Args: %r (of type %s), %r, %r" % (string, type(string), args, kwargs)) return string.copy_with_new_atts(**atts)
Convenience function for creating a FmtStr >>> fmtstr('asdf', 'blue', 'on_red', 'bold') on_red(bold(blue('asdf'))) >>> fmtstr('blarg', fg='blue', bg='red', bold=True) on_red(bold(blue('blarg')))
entailment
def color_str(self): "Return an escape-coded string to write to the terminal." s = self.s for k, v in sorted(self.atts.items()): # (self.atts sorted for the sake of always acting the same.) if k not in xforms: # Unsupported SGR code continue elif v is False: continue elif v is True: s = xforms[k](s) else: s = xforms[k](s, v) return s
Return an escape-coded string to write to the terminal.
entailment
def repr_part(self): """FmtStr repr is build by concatenating these.""" def pp_att(att): if att == 'fg': return FG_NUMBER_TO_COLOR[self.atts[att]] elif att == 'bg': return 'on_' + BG_NUMBER_TO_COLOR[self.atts[att]] else: return att atts_out = dict((k, v) for (k, v) in self.atts.items() if v) return (''.join(pp_att(att)+'(' for att in sorted(atts_out)) + (repr(self.s) if PY3 else repr(self.s)[1:]) + ')'*len(atts_out))
FmtStr repr is build by concatenating these.
entailment
def request(self, max_width): # type: (int) -> Optional[Tuple[int, Chunk]] """Requests a sub-chunk of max_width or shorter. Returns None if no chunks left.""" if max_width < 1: raise ValueError('requires positive integer max_width') s = self.chunk.s length = len(s) if self.internal_offset == len(s): return None width = 0 start_offset = i = self.internal_offset replacement_char = u' ' while True: w = wcswidth(s[i]) # If adding a character puts us over the requested width, return what we've got so far if width + w > max_width: self.internal_offset = i # does not include ith character self.internal_width += width # if not adding it us makes us short, this must have been a double-width character if width < max_width: assert width + 1 == max_width, 'unicode character width of more than 2!?!' assert w == 2, 'unicode character of width other than 2?' return (width + 1, Chunk(s[start_offset:self.internal_offset] + replacement_char, atts=self.chunk.atts)) return (width, Chunk(s[start_offset:self.internal_offset], atts=self.chunk.atts)) # otherwise add this width width += w # If one more char would put us over, return whatever we've got if i + 1 == length: self.internal_offset = i + 1 # beware the fencepost, i is an index not an offset self.internal_width += width return (width, Chunk(s[start_offset:self.internal_offset], atts=self.chunk.atts)) # otherwise attempt to add the next character i += 1
Requests a sub-chunk of max_width or shorter. Returns None if no chunks left.
entailment