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 solu...
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:...
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. :ty...
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...
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...
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 ...
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 mo...
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)...
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) ...
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.enc...
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 ...
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: ...
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_ty...
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): s...
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 ev...
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 eve...
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....
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, eit...
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...
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 ob...
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 ...
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 ...
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:`ncpol2sd...
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 va...
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.choic...
'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: ...
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,...
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):...
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 to...
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...
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) ...
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...
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 sig...
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_cur...
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 wid...
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...
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 informa...
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 so...
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_monom...
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...
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: ...
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 ...
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_var...
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 relaxatio...
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 equal...
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 ...
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 outp...
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 ...
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 in...
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 ...
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 combina...
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 ...
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 ...
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 d...
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...
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. ...
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: Optiona...
entailment
def get_relaxation(self, level, objective=None, inequalities=None, equalities=None, substitutions=None, momentinequalities=None, momentequalities=None, momentsubstitutions=None, removeequalities=False, extramonomials=None, ...
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...
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...
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) ...
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: ...
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) ...
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_...
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...
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...
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 degre...
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: ...
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. :p...
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_su...
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...
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. ...
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-...
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. ...
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.physi...
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`. :...
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): ret...
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)):...
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 removesubs...
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 ord...
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...
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 o...
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', '...
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', ' '], [' ', ' ', '...
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 Bo...
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: T...
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/permis...
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", "cvxo...
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...
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: T...
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...
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 bl...
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: Option...
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: O...
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 l...
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. ...
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): ...
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)...
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.phys...
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`...
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 o...
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.ope...
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: substitut...
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 ...
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 `Probabi...
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 ...
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...
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.HermitianOp...
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_configu...
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-Gi...
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"') ...
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 e...
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_...
>>> 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 ...
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. >>> linespl...
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,...
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...
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...
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 continu...
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 (...
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) ...
Requests a sub-chunk of max_width or shorter. Returns None if no chunks left.
entailment