repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
peterwittek/ncpol2sdpa
ncpol2sdpa/solver_common.py
get_sos_decomposition
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
python
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
[ "def", "get_sos_decomposition", "(", "sdp", ",", "y_mat", "=", "None", ",", "threshold", "=", "0.0", ")", ":", "if", "len", "(", "sdp", ".", "monomial_sets", ")", "!=", "1", ":", "raise", "Exception", "(", "\"Cannot automatically match primal and dual \"", "+"...
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`.
[ "Given", "a", "solution", "of", "the", "dual", "problem", "it", "returns", "the", "SOS", "decomposition", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/solver_common.py#L184-L236
train
peterwittek/ncpol2sdpa
ncpol2sdpa/solver_common.py
extract_dual_value
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
python
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
[ "def", "extract_dual_value", "(", "sdp", ",", "monomial", ",", "blocks", "=", "None", ")", ":", "if", "sdp", ".", "status", "==", "\"unsolved\"", ":", "raise", "Exception", "(", "\"The SDP relaxation is unsolved!\"", ")", "if", "blocks", "is", "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.
[ "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",...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/solver_common.py#L344-L386
train
chris1610/barnum-proj
barnum/gencc.py
completed_number
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)
python
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)
[ "def", "completed_number", "(", "prefix", ",", "length", ")", ":", "ccnumber", "=", "prefix", "# generate digits", "while", "len", "(", "ccnumber", ")", "<", "(", "length", "-", "1", ")", ":", "digit", "=", "random", ".", "choice", "(", "[", "'0'", ","...
'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
[ "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" ]
0a38f24bde66373553d02fbf67b733c1d55ada33
https://github.com/chris1610/barnum-proj/blob/0a38f24bde66373553d02fbf67b733c1d55ada33/barnum/gencc.py#L63-L90
train
laike9m/ezcf
ezcf/type_json.py
JsonLoader.load_module
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
python
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
[ "def", "load_module", "(", "self", ",", "fullname", ")", ":", "mod", "=", "super", "(", "JsonLoader", ",", "self", ")", ".", "load_module", "(", "fullname", ")", "try", ":", "with", "codecs", ".", "open", "(", "self", ".", "cfg_file", ",", "'r'", ","...
load_module is always called with the same argument as finder's find_module, see "How Import Works"
[ "load_module", "is", "always", "called", "with", "the", "same", "argument", "as", "finder", "s", "find_module", "see", "How", "Import", "Works" ]
30b0f7ecfd4062e9b9a2f8f13ae1f2fd9f21fa12
https://github.com/laike9m/ezcf/blob/30b0f7ecfd4062e9b9a2f8f13ae1f2fd9f21fa12/ezcf/type_json.py#L32-L53
train
bpython/curtsies
examples/gameexample.py
World.process_event
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()
python
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()
[ "def", "process_event", "(", "self", ",", "c", ")", ":", "if", "c", "==", "\"\u0004\"", ":", "sys", ".", "exit", "(", ")", "elif", "c", "in", "key_directions", ":", "self", ".", "move_entity", "(", "self", ".", "player", ",", "*", "vscale", "(", "s...
Returns a message from tick() to be displayed if game is over
[ "Returns", "a", "message", "from", "tick", "()", "to", "be", "displayed", "if", "game", "is", "over" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/gameexample.py#L57-L65
train
bpython/curtsies
examples/gameexample.py
World.tick
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))))
python
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))))
[ "def", "tick", "(", "self", ")", ":", "for", "npc", "in", "self", ".", "npcs", ":", "self", ".", "move_entity", "(", "npc", ",", "*", "npc", ".", "towards", "(", "self", ".", "player", ")", ")", "for", "entity1", ",", "entity2", "in", "itertools", ...
Returns a message to be displayed if game is over, else None
[ "Returns", "a", "message", "to", "be", "displayed", "if", "game", "is", "over", "else", "None" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/gameexample.py#L67-L83
train
bpython/curtsies
curtsies/window.py
BaseWindow.array_from_text
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)
python
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)
[ "def", "array_from_text", "(", "self", ",", "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
[ "Returns", "a", "FSArray", "of", "the", "size", "of", "the", "window", "containing", "msg" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L76-L79
train
bpython/curtsies
curtsies/window.py
FullscreenWindow.render_to_terminal
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)
python
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)
[ "def", "render_to_terminal", "(", "self", ",", "array", ",", "cursor_pos", "=", "(", "0", ",", "0", ")", ")", ":", "# TODO there's a race condition here - these height and widths are", "# super fresh - they might change between the array being constructed", "# and rendered", "#...
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)
[ "Renders", "array", "to", "terminal", "and", "places", "(", "0", "-", "indexed", ")", "cursor" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L144-L204
train
bpython/curtsies
curtsies/window.py
CursorAwareWindow.get_cursor_position
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)
python
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)
[ "def", "get_cursor_position", "(", "self", ")", ":", "# 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",...
Returns the terminal (row, column) of the cursor 0-indexed, like blessings cursor positions
[ "Returns", "the", "terminal", "(", "row", "column", ")", "of", "the", "cursor" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L271-L318
train
bpython/curtsies
curtsies/window.py
CursorAwareWindow.get_cursor_vertical_diff
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
python
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
[ "def", "get_cursor_vertical_diff", "(", "self", ")", ":", "# 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 ...
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.)
[ "Returns", "the", "how", "far", "down", "the", "cursor", "moved", "since", "last", "render", "." ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L320-L347
train
bpython/curtsies
curtsies/window.py
CursorAwareWindow._get_cursor_vertical_diff_once
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
python
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
[ "def", "_get_cursor_vertical_diff_once", "(", "self", ")", ":", "old_top_usable_row", "=", "self", ".", "top_usable_row", "row", ",", "col", "=", "self", ".", "get_cursor_position", "(", ")", "if", "self", ".", "_last_cursor_row", "is", "None", ":", "cursor_dy",...
Returns the how far down the cursor moved.
[ "Returns", "the", "how", "far", "down", "the", "cursor", "moved", "." ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L349-L368
train
bpython/curtsies
curtsies/window.py
CursorAwareWindow.render_to_terminal
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
python
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
[ "def", "render_to_terminal", "(", "self", ",", "array", ",", "cursor_pos", "=", "(", "0", ",", "0", ")", ")", ":", "for_stdout", "=", "self", ".", "fmtstr_to_stdout_xform", "(", ")", "# caching of write and tc (avoiding the self. lookups etc) made", "# no significant ...
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
[ "Renders", "array", "to", "terminal", "returns", "the", "number", "of", "lines", "scrolled", "offscreen" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L370-L461
train
peterwittek/ncpol2sdpa
ncpol2sdpa/sdp_relaxation.py
Relaxation.solve
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)
python
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)
[ "def", "solve", "(", "self", ",", "solver", "=", "None", ",", "solverparameters", "=", "None", ")", ":", "if", "self", ".", "F", "is", "None", ":", "raise", "Exception", "(", "\"Relaxation is not generated yet. Call \"", "\"'SdpRelaxation.get_relaxation' first\"", ...
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.
[ "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", "value...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L65-L109
train
peterwittek/ncpol2sdpa
ncpol2sdpa/sdp_relaxation.py
SdpRelaxation._process_monomial
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
python
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
[ "def", "_process_monomial", "(", "self", ",", "monomial", ",", "n_vars", ")", ":", "processed_monomial", ",", "coeff", "=", "separate_scalar_factor", "(", "monomial", ")", "# Are we substituting this moment?", "try", ":", "substitute", "=", "self", ".", "moment_subs...
Process a single monomial when building the moment matrix.
[ "Process", "a", "single", "monomial", "when", "building", "the", "moment", "matrix", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L269-L322
train
peterwittek/ncpol2sdpa
ncpol2sdpa/sdp_relaxation.py
SdpRelaxation._generate_moment_matrix
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
python
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
[ "def", "_generate_moment_matrix", "(", "self", ",", "n_vars", ",", "block_index", ",", "processed_entries", ",", "monomialsA", ",", "monomialsB", ",", "ppt", "=", "False", ")", ":", "row_offset", "=", "0", "if", "block_index", ">", "0", ":", "for", "block_si...
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
[ "Generate", "the", "moment", "matrix", "of", "monomials", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L359-L433
train
peterwittek/ncpol2sdpa
ncpol2sdpa/sdp_relaxation.py
SdpRelaxation._get_index_of_monomial
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
python
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
[ "def", "_get_index_of_monomial", "(", "self", ",", "element", ",", "enablesubstitution", "=", "True", ",", "daggered", "=", "False", ")", ":", "result", "=", "[", "]", "processed_element", ",", "coeff1", "=", "separate_scalar_factor", "(", "element", ")", "if"...
Returns the index of a monomial.
[ "Returns", "the", "index", "of", "a", "monomial", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L463-L511
train
peterwittek/ncpol2sdpa
ncpol2sdpa/sdp_relaxation.py
SdpRelaxation.__push_facvar_sparse
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
python
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
[ "def", "__push_facvar_sparse", "(", "self", ",", "polynomial", ",", "block_index", ",", "row_offset", ",", "i", ",", "j", ")", ":", "width", "=", "self", ".", "block_struct", "[", "block_index", "-", "1", "]", "# Preprocess the polynomial for uniform handling late...
Calculate the sparse vector representation of a polynomial and pushes it to the F structure.
[ "Calculate", "the", "sparse", "vector", "representation", "of", "a", "polynomial", "and", "pushes", "it", "to", "the", "F", "structure", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L513-L534
train
peterwittek/ncpol2sdpa
ncpol2sdpa/sdp_relaxation.py
SdpRelaxation._get_facvar
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
python
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
[ "def", "_get_facvar", "(", "self", ",", "polynomial", ")", ":", "facvar", "=", "[", "0", "]", "*", "(", "self", ".", "n_vars", "+", "1", ")", "# Preprocess the polynomial for uniform handling later", "if", "is_number_type", "(", "polynomial", ")", ":", "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.
[ "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", "return...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L536-L556
train
peterwittek/ncpol2sdpa
ncpol2sdpa/sdp_relaxation.py
SdpRelaxation.__process_inequalities
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
python
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
[ "def", "__process_inequalities", "(", "self", ",", "block_index", ")", ":", "initial_block_index", "=", "block_index", "row_offsets", "=", "[", "0", "]", "for", "block", ",", "block_size", "in", "enumerate", "(", "self", ".", "block_struct", ")", ":", "row_off...
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
[ "Generate", "localizing", "matrices" ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L558-L620
train
peterwittek/ncpol2sdpa
ncpol2sdpa/sdp_relaxation.py
SdpRelaxation.__process_equalities
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
python
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
[ "def", "__process_equalities", "(", "self", ",", "equalities", ",", "momentequalities", ")", ":", "monomial_sets", "=", "[", "]", "n_rows", "=", "0", "le", "=", "0", "if", "equalities", "is", "not", "None", ":", "for", "equality", "in", "equalities", ":", ...
Generate localizing matrices Arguments: equalities -- list of equality constraints equalities -- list of moment equality constraints
[ "Generate", "localizing", "matrices" ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L622-L694
train
peterwittek/ncpol2sdpa
ncpol2sdpa/sdp_relaxation.py
SdpRelaxation.__remove_equalities
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)
python
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)
[ "def", "__remove_equalities", "(", "self", ",", "equalities", ",", "momentequalities", ")", ":", "A", "=", "self", ".", "__process_equalities", "(", "equalities", ",", "momentequalities", ")", "if", "min", "(", "A", ".", "shape", "!=", "np", ".", "linalg", ...
Attempt to remove equalities by solving the linear equations.
[ "Attempt", "to", "remove", "equalities", "by", "solving", "the", "linear", "equations", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L696-L729
train
peterwittek/ncpol2sdpa
ncpol2sdpa/sdp_relaxation.py
SdpRelaxation._calculate_block_structure
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
python
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
[ "def", "_calculate_block_structure", "(", "self", ",", "inequalities", ",", "equalities", ",", "momentinequalities", ",", "momentequalities", ",", "extramomentmatrix", ",", "removeequalities", ",", "block_struct", "=", "None", ")", ":", "if", "block_struct", "is", "...
Calculates the block_struct array for the output file.
[ "Calculates", "the", "block_struct", "array", "for", "the", "output", "file", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L843-L935
train
peterwittek/ncpol2sdpa
ncpol2sdpa/sdp_relaxation.py
SdpRelaxation.process_constraints
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)
python
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)
[ "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.
[ "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", "...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1007-L1074
train
peterwittek/ncpol2sdpa
ncpol2sdpa/sdp_relaxation.py
SdpRelaxation.set_objective
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]
python
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]
[ "def", "set_objective", "(", "self", ",", "objective", ",", "extraobjexpr", "=", "None", ")", ":", "if", "objective", "is", "not", "None", ":", "facvar", "=", "self", ".", "_get_facvar", "(", "simplify_polynomial", "(", "objective", ",", "self", ".", "subs...
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.
[ "Set", "or", "change", "the", "objective", "function", "of", "the", "polynomial", "optimization", "problem", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1076-L1120
train
peterwittek/ncpol2sdpa
ncpol2sdpa/sdp_relaxation.py
SdpRelaxation.find_solution_ranks
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)
python
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)
[ "def", "find_solution_ranks", "(", "self", ",", "xmat", "=", "None", ",", "baselevel", "=", "0", ")", ":", "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.
[ "Helper", "function", "to", "detect", "rank", "loop", "in", "the", "solution", "matrix", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1167-L1183
train
peterwittek/ncpol2sdpa
ncpol2sdpa/sdp_relaxation.py
SdpRelaxation.get_dual
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]]
python
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]]
[ "def", "get_dual", "(", "self", ",", "constraint", ",", "ymat", "=", "None", ")", ":", "if", "not", "isinstance", "(", "constraint", ",", "Expr", ")", ":", "raise", "Exception", "(", "\"Not a monomial or polynomial!\"", ")", "elif", "self", ".", "status", ...
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.
[ "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"...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1185-L1212
train
peterwittek/ncpol2sdpa
ncpol2sdpa/sdp_relaxation.py
SdpRelaxation.write_to_file
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")
python
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")
[ "def", "write_to_file", "(", "self", ",", "filename", ",", "filetype", "=", "None", ")", ":", "if", "filetype", "==", "\"sdpa\"", "and", "not", "filename", ".", "endswith", "(", "\".dat-s\"", ")", ":", "raise", "Exception", "(", "\"SDPA files must have .dat-s ...
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.
[ "Write", "the", "relaxation", "to", "a", "file", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1214-L1247
train
peterwittek/ncpol2sdpa
ncpol2sdpa/sdp_relaxation.py
SdpRelaxation.get_relaxation
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)
python
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)
[ "def", "get_relaxation", "(", "self", ",", "level", ",", "objective", "=", "None", ",", "inequalities", "=", "None", ",", "equalities", "=", "None", ",", "substitutions", "=", "None", ",", "momentinequalities", "=", "None", ",", "momentequalities", "=", "Non...
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.
[ "Get", "the", "SDP", "relaxation", "of", "a", "noncommutative", "polynomial", "optimization", "problem", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1290-L1434
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
flatten
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
python
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
[ "def", "flatten", "(", "lol", ")", ":", "new_list", "=", "[", "]", "for", "element", "in", "lol", ":", "if", "element", "is", "None", ":", "continue", "elif", "not", "isinstance", "(", "element", ",", "list", ")", "and", "not", "isinstance", "(", "el...
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.
[ "Flatten", "a", "list", "of", "lists", "to", "a", "list", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L16-L32
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
simplify_polynomial
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
python
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
[ "def", "simplify_polynomial", "(", "polynomial", ",", "monomial_substitutions", ")", ":", "if", "isinstance", "(", "polynomial", ",", "(", "int", ",", "float", ",", "complex", ")", ")", ":", "return", "polynomial", "polynomial", "=", "(", "1.0", "*", "polyno...
Simplify a polynomial for uniform handling later.
[ "Simplify", "a", "polynomial", "for", "uniform", "handling", "later", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L35-L54
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
__separate_scalar_factor
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
python
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
[ "def", "__separate_scalar_factor", "(", "monomial", ")", ":", "scalar_factor", "=", "1", "if", "is_number_type", "(", "monomial", ")", ":", "return", "S", ".", "One", ",", "monomial", "if", "monomial", "==", "0", ":", "return", "S", ".", "One", ",", "0",...
Separate the constant factor from a monomial.
[ "Separate", "the", "constant", "factor", "from", "a", "monomial", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L81-L96
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
get_support
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
python
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
[ "def", "get_support", "(", "variables", ",", "polynomial", ")", ":", "support", "=", "[", "]", "if", "is_number_type", "(", "polynomial", ")", ":", "support", ".", "append", "(", "[", "0", "]", "*", "len", "(", "variables", ")", ")", "return", "support...
Gets the support of a polynomial.
[ "Gets", "the", "support", "of", "a", "polynomial", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L99-L121
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
get_support_variables
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
python
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
[ "def", "get_support_variables", "(", "polynomial", ")", ":", "support", "=", "[", "]", "if", "is_number_type", "(", "polynomial", ")", ":", "return", "support", "for", "monomial", "in", "polynomial", ".", "expand", "(", ")", ".", "as_coefficients_dict", "(", ...
Gets the support of a polynomial.
[ "Gets", "the", "support", "of", "a", "polynomial", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L124-L143
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
separate_scalar_factor
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
python
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
[ "def", "separate_scalar_factor", "(", "element", ")", ":", "coeff", "=", "1.0", "monomial", "=", "S", ".", "One", "if", "isinstance", "(", "element", ",", "(", "int", ",", "float", ",", "complex", ")", ")", ":", "coeff", "*=", "element", "return", "mon...
Construct a monomial with the coefficient separated from an element in a polynomial.
[ "Construct", "a", "monomial", "with", "the", "coefficient", "separated", "from", "an", "element", "in", "a", "polynomial", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L146-L165
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
count_ncmonomials
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
python
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
[ "def", "count_ncmonomials", "(", "monomials", ",", "degree", ")", ":", "ncmoncount", "=", "0", "for", "monomial", "in", "monomials", ":", "if", "ncdegree", "(", "monomial", ")", "<=", "degree", ":", "ncmoncount", "+=", "1", "else", ":", "break", "return", ...
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.
[ "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", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L168-L185
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
apply_substitutions
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
python
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
[ "def", "apply_substitutions", "(", "monomial", ",", "monomial_substitutions", ",", "pure", "=", "False", ")", ":", "if", "is_number_type", "(", "monomial", ")", ":", "return", "monomial", "original_monomial", "=", "monomial", "changed", "=", "True", "if", "not",...
Helper function to remove monomials from the basis.
[ "Helper", "function", "to", "remove", "monomials", "from", "the", "basis", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L188-L214
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
fast_substitute
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
python
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
[ "def", "fast_substitute", "(", "monomial", ",", "old_sub", ",", "new_sub", ")", ":", "if", "is_number_type", "(", "monomial", ")", ":", "return", "monomial", "if", "monomial", ".", "is_Add", ":", "return", "sum", "(", "[", "fast_substitute", "(", "element", ...
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.
[ "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"...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L217-L352
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
generate_variables
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
python
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
[ "def", "generate_variables", "(", "name", ",", "n_vars", "=", "1", ",", "hermitian", "=", "None", ",", "commutative", "=", "True", ")", ":", "variables", "=", "[", "]", "for", "i", "in", "range", "(", "n_vars", ")", ":", "if", "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. :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]
[ "Generates", "a", "number", "of", "commutative", "or", "noncommutative", "variables" ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L355-L395
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
generate_operators
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
python
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
[ "def", "generate_operators", "(", "name", ",", "n_vars", "=", "1", ",", "hermitian", "=", "None", ",", "commutative", "=", "False", ")", ":", "variables", "=", "[", "]", "for", "i", "in", "range", "(", "n_vars", ")", ":", "if", "n_vars", ">", "1", ...
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]
[ "Generates", "a", "number", "of", "commutative", "or", "noncommutative", "operators" ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L398-L434
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
get_monomials
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
python
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
[ "def", "get_monomials", "(", "variables", ",", "degree", ")", ":", "if", "degree", "==", "-", "1", ":", "return", "[", "]", "if", "not", "variables", ":", "return", "[", "S", ".", "One", "]", "else", ":", "_variables", "=", "variables", "[", ":", "...
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.
[ "Generates", "all", "noncommutative", "monomials", "up", "to", "a", "degree" ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L437-L469
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
ncdegree
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
python
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
[ "def", "ncdegree", "(", "polynomial", ")", ":", "degree", "=", "0", "if", "is_number_type", "(", "polynomial", ")", ":", "return", "degree", "polynomial", "=", "polynomial", ".", "expand", "(", ")", "for", "monomial", "in", "polynomial", ".", "as_coefficient...
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.
[ "Returns", "the", "degree", "of", "a", "noncommutative", "polynomial", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L472-L493
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
iscomplex
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
python
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
[ "def", "iscomplex", "(", "polynomial", ")", ":", "if", "isinstance", "(", "polynomial", ",", "(", "int", ",", "float", ")", ")", ":", "return", "False", "if", "isinstance", "(", "polynomial", ",", "complex", ")", ":", "return", "True", "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.
[ "Returns", "whether", "the", "polynomial", "has", "complex", "coefficients" ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L496-L513
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
get_all_monomials
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
python
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
[ "def", "get_all_monomials", "(", "variables", ",", "extramonomials", ",", "substitutions", ",", "degree", ",", "removesubstitutions", "=", "True", ")", ":", "monomials", "=", "get_monomials", "(", "variables", ",", "degree", ")", "if", "extramonomials", "is", "n...
Return the monomials of a certain degree.
[ "Return", "the", "monomials", "of", "a", "certain", "degree", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L516-L530
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
pick_monomials_up_to_degree
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
python
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
[ "def", "pick_monomials_up_to_degree", "(", "monomials", ",", "degree", ")", ":", "ordered_monomials", "=", "[", "]", "if", "degree", ">=", "0", ":", "ordered_monomials", ".", "append", "(", "S", ".", "One", ")", "for", "deg", "in", "range", "(", "1", ","...
Collect monomials up to a given degree.
[ "Collect", "monomials", "up", "to", "a", "given", "degree", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L533-L541
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
pick_monomials_of_degree
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
python
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
[ "def", "pick_monomials_of_degree", "(", "monomials", ",", "degree", ")", ":", "selected_monomials", "=", "[", "]", "for", "monomial", "in", "monomials", ":", "if", "ncdegree", "(", "monomial", ")", "==", "degree", ":", "selected_monomials", ".", "append", "(",...
Collect all monomials up of a given degree.
[ "Collect", "all", "monomials", "up", "of", "a", "given", "degree", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L544-L551
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
save_monomial_index
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()
python
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()
[ "def", "save_monomial_index", "(", "filename", ",", "monomial_index", ")", ":", "monomial_translation", "=", "[", "''", "]", "*", "(", "len", "(", "monomial_index", ")", "+", "1", ")", "for", "key", ",", "k", "in", "monomial_index", ".", "items", "(", ")...
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", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L562-L577
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
unique
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
python
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
[ "def", "unique", "(", "seq", ")", ":", "seen", "=", "{", "}", "result", "=", "[", "]", "for", "item", "in", "seq", ":", "marker", "=", "item", "if", "marker", "in", "seen", ":", "continue", "seen", "[", "marker", "]", "=", "1", "result", ".", "...
Helper function to include only unique monomials in a basis.
[ "Helper", "function", "to", "include", "only", "unique", "monomials", "in", "a", "basis", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L580-L590
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
build_permutation_matrix
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
python
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
[ "def", "build_permutation_matrix", "(", "permutation", ")", ":", "matrix", "=", "lil_matrix", "(", "(", "len", "(", "permutation", ")", ",", "len", "(", "permutation", ")", ")", ")", "column", "=", "0", "for", "row", "in", "permutation", ":", "matrix", "...
Build a permutation matrix for a permutation.
[ "Build", "a", "permutation", "matrix", "for", "a", "permutation", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L593-L601
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
convert_relational
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!")
python
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!")
[ "def", "convert_relational", "(", "relational", ")", ":", "rel", "=", "relational", ".", "rel_op", "if", "rel", "in", "[", "'=='", ",", "'>='", ",", "'>'", "]", ":", "return", "relational", ".", "lhs", "-", "relational", ".", "rhs", "elif", "rel", "in"...
Convert all inequalities to >=0 form.
[ "Convert", "all", "inequalities", "to", ">", "=", "0", "form", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L604-L614
train
bpython/curtsies
examples/tictactoeexample.py
value
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()])
python
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()])
[ "def", "value", "(", "board", ",", "who", "=", "'x'", ")", ":", "w", "=", "board", ".", "winner", "(", ")", "if", "w", "==", "who", ":", "return", "1", "if", "w", "==", "opp", "(", "who", ")", ":", "return", "-", "1", "if", "board", ".", "t...
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
[ "Returns", "the", "value", "of", "a", "board", ">>>", "b", "=", "Board", "()", ";", "b", ".", "_rows", "=", "[[", "x", "x", "x", "]", "[", "x", "x", "x", "]", "[", "x", "x", "x", "]]", ">>>", "value", "(", "b", ")", "1", ">>>", "b", "=", ...
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tictactoeexample.py#L68-L94
train
bpython/curtsies
examples/tictactoeexample.py
ai
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]
python
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]
[ "def", "ai", "(", "board", ",", "who", "=", "'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..| >
[ "Returns", "best", "next", "board" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tictactoeexample.py#L96-L104
train
bpython/curtsies
examples/tictactoeexample.py
Board.winner
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
python
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
[ "def", "winner", "(", "self", ")", ":", "for", "c", "in", "'xo'", ":", "for", "comb", "in", "[", "(", "0", ",", "3", ",", "6", ")", ",", "(", "1", ",", "4", ",", "7", ")", ",", "(", "2", ",", "5", ",", "8", ")", ",", "(", "0", ",", ...
Returns either x or o if one of them won, otherwise None
[ "Returns", "either", "x", "or", "o", "if", "one", "of", "them", "won", "otherwise", "None" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tictactoeexample.py#L40-L46
train
peterwittek/ncpol2sdpa
ncpol2sdpa/faacets_relaxation.py
FaacetsRelaxation.get_relaxation
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]
python
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]
[ "def", "get_relaxation", "(", "self", ",", "A_configuration", ",", "B_configuration", ",", "I", ")", ":", "coefficients", "=", "collinsgisin_to_faacets", "(", "I", ")", "M", ",", "ncIndices", "=", "get_faacets_moment_matrix", "(", "A_configuration", ",", "B_config...
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.
[ "Get", "the", "sparse", "SDP", "relaxation", "of", "a", "Bell", "inequality", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/faacets_relaxation.py#L63-L91
train
zeekay/soundcloud-cli
soundcloud_cli/api/share.py
share
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)
python
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)
[ "def", "share", "(", "track_id", "=", "None", ",", "url", "=", "None", ",", "users", "=", "None", ")", ":", "client", "=", "get_client", "(", ")", "if", "url", ":", "track_id", "=", "client", ".", "get", "(", "'/resolve'", ",", "url", "=", "url", ...
Returns list of users track has been shared with. Either track or url need to be provided.
[ "Returns", "list", "of", "users", "track", "has", "been", "shared", "with", ".", "Either", "track", "or", "url", "need", "to", "be", "provided", "." ]
8a83013683e1acf32f093239bbb6d3c02bc50b37
https://github.com/zeekay/soundcloud-cli/blob/8a83013683e1acf32f093239bbb6d3c02bc50b37/soundcloud_cli/api/share.py#L7-L34
train
peterwittek/ncpol2sdpa
ncpol2sdpa/picos_utils.py
solve_with_cvxopt
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"]
python
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"]
[ "def", "solve_with_cvxopt", "(", "sdp", ",", "solverparameters", "=", "None", ")", ":", "P", "=", "convert_to_picos", "(", "sdp", ")", "P", ".", "set_option", "(", "\"solver\"", ",", "\"cvxopt\"", ")", "P", ".", "set_option", "(", "\"verbose\"", ",", "sdp"...
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`.
[ "Helper", "function", "to", "convert", "the", "SDP", "problem", "to", "PICOS", "and", "call", "CVXOPT", "solver", "and", "parse", "the", "output", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/picos_utils.py#L13-L34
train
peterwittek/ncpol2sdpa
ncpol2sdpa/picos_utils.py
convert_to_picos
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
python
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
[ "def", "convert_to_picos", "(", "sdp", ",", "duplicate_moment_matrix", "=", "False", ")", ":", "import", "picos", "as", "pic", "import", "cvxopt", "as", "cvx", "P", "=", "pic", ".", "Problem", "(", "verbose", "=", "sdp", ".", "verbose", ")", "block_size", ...
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`.
[ "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", ...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/picos_utils.py#L37-L125
train
peterwittek/ncpol2sdpa
ncpol2sdpa/cvxpy_utils.py
solve_with_cvxpy
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
python
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
[ "def", "solve_with_cvxpy", "(", "sdp", ",", "solverparameters", "=", "None", ")", ":", "problem", "=", "convert_to_cvxpy", "(", "sdp", ")", "if", "solverparameters", "is", "not", "None", "and", "'solver'", "in", "solverparameters", ":", "solver", "=", "solverp...
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`.
[ "Helper", "function", "to", "convert", "the", "SDP", "problem", "to", "CVXPY", "and", "call", "the", "solver", "and", "parse", "the", "output", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/cvxpy_utils.py#L14-L48
train
peterwittek/ncpol2sdpa
ncpol2sdpa/cvxpy_utils.py
convert_to_cvxpy
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
python
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
[ "def", "convert_to_cvxpy", "(", "sdp", ")", ":", "from", "cvxpy", "import", "Minimize", ",", "Problem", ",", "Variable", "row_offsets", "=", "[", "0", "]", "cumulative_sum", "=", "0", "for", "block_size", "in", "sdp", ".", "block_struct", ":", "cumulative_su...
Convert an SDP relaxation to a CVXPY problem. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: :class:`cvxpy.Problem`.
[ "Convert", "an", "SDP", "relaxation", "to", "a", "CVXPY", "problem", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/cvxpy_utils.py#L51-L94
train
peterwittek/ncpol2sdpa
ncpol2sdpa/physics_utils.py
get_neighbors
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
python
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
[ "def", "get_neighbors", "(", "index", ",", "lattice_length", ",", "width", "=", "0", ",", "periodic", "=", "False", ")", ":", "if", "width", "==", "0", ":", "width", "=", "lattice_length", "neighbors", "=", "[", "]", "coords", "=", "divmod", "(", "inde...
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.
[ "Get", "the", "forward", "neighbors", "of", "a", "site", "in", "a", "lattice", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L17-L44
train
peterwittek/ncpol2sdpa
ncpol2sdpa/physics_utils.py
get_next_neighbors
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)
python
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)
[ "def", "get_next_neighbors", "(", "indices", ",", "lattice_length", ",", "width", "=", "0", ",", "distance", "=", "1", ",", "periodic", "=", "False", ")", ":", "if", "not", "isinstance", "(", "indices", ",", "list", ")", ":", "indices", "=", "[", "indi...
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.
[ "Get", "the", "forward", "neighbors", "at", "a", "given", "distance", "of", "a", "site", "or", "set", "of", "sites", "in", "a", "lattice", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L47-L79
train
peterwittek/ncpol2sdpa
ncpol2sdpa/physics_utils.py
bosonic_constraints
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
python
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
[ "def", "bosonic_constraints", "(", "a", ")", ":", "substitutions", "=", "{", "}", "for", "i", ",", "ai", "in", "enumerate", "(", "a", ")", ":", "substitutions", "[", "ai", "*", "Dagger", "(", "ai", ")", "]", "=", "1.0", "+", "Dagger", "(", "ai", ...
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.
[ "Return", "a", "set", "of", "constraints", "that", "define", "fermionic", "ladder", "operators", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L82-L99
train
peterwittek/ncpol2sdpa
ncpol2sdpa/physics_utils.py
fermionic_constraints
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
python
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
[ "def", "fermionic_constraints", "(", "a", ")", ":", "substitutions", "=", "{", "}", "for", "i", ",", "ai", "in", "enumerate", "(", "a", ")", ":", "substitutions", "[", "ai", "**", "2", "]", "=", "0", "substitutions", "[", "Dagger", "(", "ai", ")", ...
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.
[ "Return", "a", "set", "of", "constraints", "that", "define", "fermionic", "ladder", "operators", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L102-L121
train
peterwittek/ncpol2sdpa
ncpol2sdpa/physics_utils.py
pauli_constraints
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
python
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
[ "def", "pauli_constraints", "(", "X", ",", "Y", ",", "Z", ")", ":", "substitutions", "=", "{", "}", "n_vars", "=", "len", "(", "X", ")", "for", "i", "in", "range", "(", "n_vars", ")", ":", "# They square to the identity", "substitutions", "[", "X", "["...
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.
[ "Return", "a", "set", "of", "constraints", "that", "define", "Pauli", "spin", "operators", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L124-L163
train
peterwittek/ncpol2sdpa
ncpol2sdpa/physics_utils.py
generate_measurements
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
python
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
[ "def", "generate_measurements", "(", "party", ",", "label", ")", ":", "measurements", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "party", ")", ")", ":", "measurements", ".", "append", "(", "generate_operators", "(", "label", "+", "'%s'", ...
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`.
[ "Generate", "variables", "that", "behave", "like", "measurements", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L166-L181
train
peterwittek/ncpol2sdpa
ncpol2sdpa/physics_utils.py
projective_measurement_constraints
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
python
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
[ "def", "projective_measurement_constraints", "(", "*", "parties", ")", ":", "substitutions", "=", "{", "}", "# Idempotency and orthogonality of projectors", "if", "isinstance", "(", "parties", "[", "0", "]", "[", "0", "]", "[", "0", "]", ",", "list", ")", ":",...
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.
[ "Return", "a", "set", "of", "constraints", "that", "define", "projective", "measurements", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L184-L216
train
peterwittek/ncpol2sdpa
ncpol2sdpa/physics_utils.py
define_objective_with_I
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
python
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
[ "def", "define_objective_with_I", "(", "I", ",", "*", "args", ")", ":", "objective", "=", "I", "[", "0", "]", "[", "0", "]", "if", "len", "(", "args", ")", ">", "2", "or", "len", "(", "args", ")", "==", "0", ":", "raise", "Exception", "(", "\"W...
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.
[ "Define", "a", "polynomial", "using", "measurements", "and", "an", "I", "matrix", "describing", "a", "Bell", "inequality", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L219-L260
train
peterwittek/ncpol2sdpa
ncpol2sdpa/physics_utils.py
correlator
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
python
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
[ "def", "correlator", "(", "A", ",", "B", ")", ":", "correlators", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "A", ")", ")", ":", "correlator_row", "=", "[", "]", "for", "j", "in", "range", "(", "len", "(", "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", "between", "the", "probabilities", "of", "two", "parties", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L263-L288
train
peterwittek/ncpol2sdpa
ncpol2sdpa/physics_utils.py
maximum_violation
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
python
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
[ "def", "maximum_violation", "(", "A_configuration", ",", "B_configuration", ",", "I", ",", "level", ",", "extra", "=", "None", ")", ":", "P", "=", "Probability", "(", "A_configuration", ",", "B_configuration", ")", "objective", "=", "define_objective_with_I", "(...
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.
[ "Get", "the", "maximum", "violation", "of", "a", "two", "-", "party", "Bell", "inequality", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L291-L316
train
bpython/curtsies
curtsies/formatstring.py
stable_format_dict
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
python
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
[ "def", "stable_format_dict", "(", "d", ")", ":", "inner", "=", "', '", ".", "join", "(", "'{}: {}'", ".", "format", "(", "repr", "(", "k", ")", "[", "1", ":", "]", "if", "repr", "(", "k", ")", ".", "startswith", "(", "u\"u'\"", ")", "or", "repr",...
A sorted, python2/3 stable formatting of a dictionary. Does not work for dicts with unicode strings as values.
[ "A", "sorted", "python2", "/", "3", "stable", "formatting", "of", "a", "dictionary", "." ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L67-L76
train
bpython/curtsies
curtsies/formatstring.py
interval_overlap
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
python
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
[ "def", "interval_overlap", "(", "a", ",", "b", ",", "x", ",", "y", ")", ":", "if", "b", "<=", "x", "or", "a", ">=", "y", ":", "return", "0", "elif", "x", "<=", "a", "<=", "y", ":", "return", "min", "(", "b", ",", "y", ")", "-", "a", "elif...
Returns by how much two intervals overlap assumed that a <= b and x <= y
[ "Returns", "by", "how", "much", "two", "intervals", "overlap" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L635-L648
train
bpython/curtsies
curtsies/formatstring.py
width_aware_slice
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)
python
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)
[ "def", "width_aware_slice", "(", "s", ",", "start", ",", "end", ",", "replacement_char", "=", "u' '", ")", ":", "# type: (Text, int, int, Text)", "divides", "=", "[", "0", "]", "for", "c", "in", "s", ":", "divides", ".", "append", "(", "divides", "[", "-...
>>> width_aware_slice(u'a\uff25iou', 0, 2)[1] == u' ' True
[ ">>>", "width_aware_slice", "(", "u", "a", "\\", "uff25iou", "0", "2", ")", "[", "1", "]", "==", "u", "True" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L651-L671
train
bpython/curtsies
curtsies/formatstring.py
linesplit
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
python
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
[ "def", "linesplit", "(", "string", ",", "columns", ")", ":", "# type: (Union[Text, FmtStr], int) -> List[FmtStr]", "if", "not", "isinstance", "(", "string", ",", "FmtStr", ")", ":", "string", "=", "fmtstr", "(", "string", ")", "string_s", "=", "string", ".", "...
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')]
[ "Returns", "a", "list", "of", "lines", "split", "on", "the", "last", "possible", "space", "of", "each", "line", "." ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L674-L705
train
bpython/curtsies
curtsies/formatstring.py
normalize_slice
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
python
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
[ "def", "normalize_slice", "(", "length", ",", "index", ")", ":", "is_int", "=", "False", "if", "isinstance", "(", "index", ",", "int", ")", ":", "is_int", "=", "True", "index", "=", "slice", "(", "index", ",", "index", "+", "1", ")", "if", "index", ...
Fill in the Nones in a slice.
[ "Fill", "in", "the", "Nones", "in", "a", "slice", "." ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L707-L726
train
bpython/curtsies
curtsies/formatstring.py
parse_args
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
python
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
[ "def", "parse_args", "(", "args", ",", "kwargs", ")", ":", "if", "'style'", "in", "kwargs", ":", "args", "+=", "(", "kwargs", "[", "'style'", "]", ",", ")", "del", "kwargs", "[", "'style'", "]", "for", "arg", "in", "args", ":", "if", "not", "isinst...
Returns a kwargs dictionary by turning args into kwargs
[ "Returns", "a", "kwargs", "dictionary", "by", "turning", "args", "into", "kwargs" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L728-L759
train
bpython/curtsies
curtsies/formatstring.py
fmtstr
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)
python
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)
[ "def", "fmtstr", "(", "string", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# type: (Union[Text, bytes, FmtStr], *Any, **Any) -> FmtStr", "atts", "=", "parse_args", "(", "args", ",", "kwargs", ")", "if", "isinstance", "(", "string", ",", "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" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L761-L778
train
bpython/curtsies
curtsies/formatstring.py
Chunk.color_str
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
python
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
[ "def", "color_str", "(", "self", ")", ":", "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...
Return an escape-coded string to write to the terminal.
[ "Return", "an", "escape", "-", "coded", "string", "to", "write", "to", "the", "terminal", "." ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L106-L120
train
bpython/curtsies
curtsies/formatstring.py
Chunk.repr_part
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))
python
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))
[ "def", "repr_part", "(", "self", ")", ":", "def", "pp_att", "(", "att", ")", ":", "if", "att", "==", "'fg'", ":", "return", "FG_NUMBER_TO_COLOR", "[", "self", ".", "atts", "[", "att", "]", "]", "elif", "att", "==", "'bg'", ":", "return", "'on_'", "...
FmtStr repr is build by concatenating these.
[ "FmtStr", "repr", "is", "build", "by", "concatenating", "these", "." ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L144-L152
train
bpython/curtsies
curtsies/formatstring.py
ChunkSplitter.request
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
python
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
[ "def", "request", "(", "self", ",", "max_width", ")", ":", "# type: (int) -> Optional[Tuple[int, Chunk]]", "if", "max_width", "<", "1", ":", "raise", "ValueError", "(", "'requires positive integer max_width'", ")", "s", "=", "self", ".", "chunk", ".", "s", "length...
Requests a sub-chunk of max_width or shorter. Returns None if no chunks left.
[ "Requests", "a", "sub", "-", "chunk", "of", "max_width", "or", "shorter", ".", "Returns", "None", "if", "no", "chunks", "left", "." ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L180-L220
train
bpython/curtsies
curtsies/formatstring.py
FmtStr.from_str
def from_str(cls, s): # type: (Union[Text, bytes]) -> FmtStr r""" Return a FmtStr representing input. The str() of a FmtStr is guaranteed to produced the same FmtStr. Other input with escape sequences may not be preserved. >>> fmtstr("|"+fmtstr("hey", fg='red', bg='blue')+"|") '|'+on_blue(red('hey'))+'|' >>> fmtstr('|\x1b[31m\x1b[44mhey\x1b[49m\x1b[39m|') '|'+on_blue(red('hey'))+'|' """ if '\x1b[' in s: try: tokens_and_strings = parse(s) except ValueError: return FmtStr(Chunk(remove_ansi(s))) else: chunks = [] cur_fmt = {} for x in tokens_and_strings: if isinstance(x, dict): cur_fmt.update(x) elif isinstance(x, (bytes, unicode)): atts = parse_args('', dict((k, v) for k, v in cur_fmt.items() if v is not None)) chunks.append(Chunk(x, atts=atts)) else: raise Exception("logic error") return FmtStr(*chunks) else: return FmtStr(Chunk(s))
python
def from_str(cls, s): # type: (Union[Text, bytes]) -> FmtStr r""" Return a FmtStr representing input. The str() of a FmtStr is guaranteed to produced the same FmtStr. Other input with escape sequences may not be preserved. >>> fmtstr("|"+fmtstr("hey", fg='red', bg='blue')+"|") '|'+on_blue(red('hey'))+'|' >>> fmtstr('|\x1b[31m\x1b[44mhey\x1b[49m\x1b[39m|') '|'+on_blue(red('hey'))+'|' """ if '\x1b[' in s: try: tokens_and_strings = parse(s) except ValueError: return FmtStr(Chunk(remove_ansi(s))) else: chunks = [] cur_fmt = {} for x in tokens_and_strings: if isinstance(x, dict): cur_fmt.update(x) elif isinstance(x, (bytes, unicode)): atts = parse_args('', dict((k, v) for k, v in cur_fmt.items() if v is not None)) chunks.append(Chunk(x, atts=atts)) else: raise Exception("logic error") return FmtStr(*chunks) else: return FmtStr(Chunk(s))
[ "def", "from_str", "(", "cls", ",", "s", ")", ":", "# type: (Union[Text, bytes]) -> FmtStr", "if", "'\\x1b['", "in", "s", ":", "try", ":", "tokens_and_strings", "=", "parse", "(", "s", ")", "except", "ValueError", ":", "return", "FmtStr", "(", "Chunk", "(", ...
r""" Return a FmtStr representing input. The str() of a FmtStr is guaranteed to produced the same FmtStr. Other input with escape sequences may not be preserved. >>> fmtstr("|"+fmtstr("hey", fg='red', bg='blue')+"|") '|'+on_blue(red('hey'))+'|' >>> fmtstr('|\x1b[31m\x1b[44mhey\x1b[49m\x1b[39m|') '|'+on_blue(red('hey'))+'|'
[ "r", "Return", "a", "FmtStr", "representing", "input", "." ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L239-L273
train
bpython/curtsies
curtsies/formatstring.py
FmtStr.copy_with_new_str
def copy_with_new_str(self, new_str): """Copies the current FmtStr's attributes while changing its string.""" # What to do when there are multiple Chunks with conflicting atts? old_atts = dict((att, value) for bfs in self.chunks for (att, value) in bfs.atts.items()) return FmtStr(Chunk(new_str, old_atts))
python
def copy_with_new_str(self, new_str): """Copies the current FmtStr's attributes while changing its string.""" # What to do when there are multiple Chunks with conflicting atts? old_atts = dict((att, value) for bfs in self.chunks for (att, value) in bfs.atts.items()) return FmtStr(Chunk(new_str, old_atts))
[ "def", "copy_with_new_str", "(", "self", ",", "new_str", ")", ":", "# What to do when there are multiple Chunks with conflicting atts?", "old_atts", "=", "dict", "(", "(", "att", ",", "value", ")", "for", "bfs", "in", "self", ".", "chunks", "for", "(", "att", ",...
Copies the current FmtStr's attributes while changing its string.
[ "Copies", "the", "current", "FmtStr", "s", "attributes", "while", "changing", "its", "string", "." ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L275-L280
train
bpython/curtsies
curtsies/formatstring.py
FmtStr.setitem
def setitem(self, startindex, fs): """Shim for easily converting old __setitem__ calls""" return self.setslice_with_length(startindex, startindex+1, fs, len(self))
python
def setitem(self, startindex, fs): """Shim for easily converting old __setitem__ calls""" return self.setslice_with_length(startindex, startindex+1, fs, len(self))
[ "def", "setitem", "(", "self", ",", "startindex", ",", "fs", ")", ":", "return", "self", ".", "setslice_with_length", "(", "startindex", ",", "startindex", "+", "1", ",", "fs", ",", "len", "(", "self", ")", ")" ]
Shim for easily converting old __setitem__ calls
[ "Shim", "for", "easily", "converting", "old", "__setitem__", "calls" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L282-L284
train
bpython/curtsies
curtsies/formatstring.py
FmtStr.setslice_with_length
def setslice_with_length(self, startindex, endindex, fs, length): """Shim for easily converting old __setitem__ calls""" if len(self) < startindex: fs = ' '*(startindex - len(self)) + fs if len(self) > endindex: fs = fs + ' '*(endindex - startindex - len(fs)) assert len(fs) == endindex - startindex, (len(fs), startindex, endindex) result = self.splice(fs, startindex, endindex) assert len(result) <= length return result
python
def setslice_with_length(self, startindex, endindex, fs, length): """Shim for easily converting old __setitem__ calls""" if len(self) < startindex: fs = ' '*(startindex - len(self)) + fs if len(self) > endindex: fs = fs + ' '*(endindex - startindex - len(fs)) assert len(fs) == endindex - startindex, (len(fs), startindex, endindex) result = self.splice(fs, startindex, endindex) assert len(result) <= length return result
[ "def", "setslice_with_length", "(", "self", ",", "startindex", ",", "endindex", ",", "fs", ",", "length", ")", ":", "if", "len", "(", "self", ")", "<", "startindex", ":", "fs", "=", "' '", "*", "(", "startindex", "-", "len", "(", "self", ")", ")", ...
Shim for easily converting old __setitem__ calls
[ "Shim", "for", "easily", "converting", "old", "__setitem__", "calls" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L286-L295
train
bpython/curtsies
curtsies/formatstring.py
FmtStr.splice
def splice(self, new_str, start, end=None): """Returns a new FmtStr with the input string spliced into the the original FmtStr at start and end. If end is provided, new_str will replace the substring self.s[start:end-1]. """ if len(new_str) == 0: return self new_fs = new_str if isinstance(new_str, FmtStr) else fmtstr(new_str) assert len(new_fs.chunks) > 0, (new_fs.chunks, new_fs) new_components = [] inserted = False if end is None: end = start tail = None for bfs, bfs_start, bfs_end in zip(self.chunks, self.divides[:-1], self.divides[1:]): if end == bfs_start == 0: new_components.extend(new_fs.chunks) new_components.append(bfs) inserted = True elif bfs_start <= start < bfs_end: divide = start - bfs_start head = Chunk(bfs.s[:divide], atts=bfs.atts) tail = Chunk(bfs.s[end - bfs_start:], atts=bfs.atts) new_components.extend([head] + new_fs.chunks) inserted = True if bfs_start < end < bfs_end: tail = Chunk(bfs.s[end - bfs_start:], atts=bfs.atts) new_components.append(tail) elif bfs_start < end < bfs_end: divide = start - bfs_start tail = Chunk(bfs.s[end - bfs_start:], atts=bfs.atts) new_components.append(tail) elif bfs_start >= end or bfs_end <= start: new_components.append(bfs) if not inserted: new_components.extend(new_fs.chunks) inserted = True return FmtStr(*[s for s in new_components if s.s])
python
def splice(self, new_str, start, end=None): """Returns a new FmtStr with the input string spliced into the the original FmtStr at start and end. If end is provided, new_str will replace the substring self.s[start:end-1]. """ if len(new_str) == 0: return self new_fs = new_str if isinstance(new_str, FmtStr) else fmtstr(new_str) assert len(new_fs.chunks) > 0, (new_fs.chunks, new_fs) new_components = [] inserted = False if end is None: end = start tail = None for bfs, bfs_start, bfs_end in zip(self.chunks, self.divides[:-1], self.divides[1:]): if end == bfs_start == 0: new_components.extend(new_fs.chunks) new_components.append(bfs) inserted = True elif bfs_start <= start < bfs_end: divide = start - bfs_start head = Chunk(bfs.s[:divide], atts=bfs.atts) tail = Chunk(bfs.s[end - bfs_start:], atts=bfs.atts) new_components.extend([head] + new_fs.chunks) inserted = True if bfs_start < end < bfs_end: tail = Chunk(bfs.s[end - bfs_start:], atts=bfs.atts) new_components.append(tail) elif bfs_start < end < bfs_end: divide = start - bfs_start tail = Chunk(bfs.s[end - bfs_start:], atts=bfs.atts) new_components.append(tail) elif bfs_start >= end or bfs_end <= start: new_components.append(bfs) if not inserted: new_components.extend(new_fs.chunks) inserted = True return FmtStr(*[s for s in new_components if s.s])
[ "def", "splice", "(", "self", ",", "new_str", ",", "start", ",", "end", "=", "None", ")", ":", "if", "len", "(", "new_str", ")", "==", "0", ":", "return", "self", "new_fs", "=", "new_str", "if", "isinstance", "(", "new_str", ",", "FmtStr", ")", "el...
Returns a new FmtStr with the input string spliced into the the original FmtStr at start and end. If end is provided, new_str will replace the substring self.s[start:end-1].
[ "Returns", "a", "new", "FmtStr", "with", "the", "input", "string", "spliced", "into", "the", "the", "original", "FmtStr", "at", "start", "and", "end", ".", "If", "end", "is", "provided", "new_str", "will", "replace", "the", "substring", "self", ".", "s", ...
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L297-L343
train
bpython/curtsies
curtsies/formatstring.py
FmtStr.copy_with_new_atts
def copy_with_new_atts(self, **attributes): """Returns a new FmtStr with the same content but new formatting""" return FmtStr(*[Chunk(bfs.s, bfs.atts.extend(attributes)) for bfs in self.chunks])
python
def copy_with_new_atts(self, **attributes): """Returns a new FmtStr with the same content but new formatting""" return FmtStr(*[Chunk(bfs.s, bfs.atts.extend(attributes)) for bfs in self.chunks])
[ "def", "copy_with_new_atts", "(", "self", ",", "*", "*", "attributes", ")", ":", "return", "FmtStr", "(", "*", "[", "Chunk", "(", "bfs", ".", "s", ",", "bfs", ".", "atts", ".", "extend", "(", "attributes", ")", ")", "for", "bfs", "in", "self", ".",...
Returns a new FmtStr with the same content but new formatting
[ "Returns", "a", "new", "FmtStr", "with", "the", "same", "content", "but", "new", "formatting" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L348-L351
train
bpython/curtsies
curtsies/formatstring.py
FmtStr.join
def join(self, iterable): """Joins an iterable yielding strings or FmtStrs with self as separator""" before = [] chunks = [] for i, s in enumerate(iterable): chunks.extend(before) before = self.chunks if isinstance(s, FmtStr): chunks.extend(s.chunks) elif isinstance(s, (bytes, unicode)): chunks.extend(fmtstr(s).chunks) #TODO just make a chunk directly else: raise TypeError("expected str or FmtStr, %r found" % type(s)) return FmtStr(*chunks)
python
def join(self, iterable): """Joins an iterable yielding strings or FmtStrs with self as separator""" before = [] chunks = [] for i, s in enumerate(iterable): chunks.extend(before) before = self.chunks if isinstance(s, FmtStr): chunks.extend(s.chunks) elif isinstance(s, (bytes, unicode)): chunks.extend(fmtstr(s).chunks) #TODO just make a chunk directly else: raise TypeError("expected str or FmtStr, %r found" % type(s)) return FmtStr(*chunks)
[ "def", "join", "(", "self", ",", "iterable", ")", ":", "before", "=", "[", "]", "chunks", "=", "[", "]", "for", "i", ",", "s", "in", "enumerate", "(", "iterable", ")", ":", "chunks", ".", "extend", "(", "before", ")", "before", "=", "self", ".", ...
Joins an iterable yielding strings or FmtStrs with self as separator
[ "Joins", "an", "iterable", "yielding", "strings", "or", "FmtStrs", "with", "self", "as", "separator" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L353-L366
train
bpython/curtsies
curtsies/formatstring.py
FmtStr.split
def split(self, sep=None, maxsplit=None, regex=False): """Split based on seperator, optionally using a regex Capture groups are ignored in regex, the whole pattern is matched and used to split the original FmtStr.""" if maxsplit is not None: raise NotImplementedError('no maxsplit yet') s = self.s if sep is None: sep = r'\s+' elif not regex: sep = re.escape(sep) matches = list(re.finditer(sep, s)) return [self[start:end] for start, end in zip( [0] + [m.end() for m in matches], [m.start() for m in matches] + [len(s)])]
python
def split(self, sep=None, maxsplit=None, regex=False): """Split based on seperator, optionally using a regex Capture groups are ignored in regex, the whole pattern is matched and used to split the original FmtStr.""" if maxsplit is not None: raise NotImplementedError('no maxsplit yet') s = self.s if sep is None: sep = r'\s+' elif not regex: sep = re.escape(sep) matches = list(re.finditer(sep, s)) return [self[start:end] for start, end in zip( [0] + [m.end() for m in matches], [m.start() for m in matches] + [len(s)])]
[ "def", "split", "(", "self", ",", "sep", "=", "None", ",", "maxsplit", "=", "None", ",", "regex", "=", "False", ")", ":", "if", "maxsplit", "is", "not", "None", ":", "raise", "NotImplementedError", "(", "'no maxsplit yet'", ")", "s", "=", "self", ".", ...
Split based on seperator, optionally using a regex Capture groups are ignored in regex, the whole pattern is matched and used to split the original FmtStr.
[ "Split", "based", "on", "seperator", "optionally", "using", "a", "regex" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L369-L384
train
bpython/curtsies
curtsies/formatstring.py
FmtStr.splitlines
def splitlines(self, keepends=False): """Return a list of lines, split on newline characters, include line boundaries, if keepends is true.""" lines = self.split('\n') return [line+'\n' for line in lines] if keepends else ( lines if lines[-1] else lines[:-1])
python
def splitlines(self, keepends=False): """Return a list of lines, split on newline characters, include line boundaries, if keepends is true.""" lines = self.split('\n') return [line+'\n' for line in lines] if keepends else ( lines if lines[-1] else lines[:-1])
[ "def", "splitlines", "(", "self", ",", "keepends", "=", "False", ")", ":", "lines", "=", "self", ".", "split", "(", "'\\n'", ")", "return", "[", "line", "+", "'\\n'", "for", "line", "in", "lines", "]", "if", "keepends", "else", "(", "lines", "if", ...
Return a list of lines, split on newline characters, include line boundaries, if keepends is true.
[ "Return", "a", "list", "of", "lines", "split", "on", "newline", "characters", "include", "line", "boundaries", "if", "keepends", "is", "true", "." ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L386-L391
train
bpython/curtsies
curtsies/formatstring.py
FmtStr.ljust
def ljust(self, width, fillchar=None): """S.ljust(width[, fillchar]) -> string If a fillchar is provided, less formatting information will be preserved """ if fillchar is not None: return fmtstr(self.s.ljust(width, fillchar), **self.shared_atts) to_add = ' ' * (width - len(self.s)) shared = self.shared_atts if 'bg' in shared: return self + fmtstr(to_add, bg=shared[str('bg')]) if to_add else self else: uniform = self.new_with_atts_removed('bg') return uniform + fmtstr(to_add, **self.shared_atts) if to_add else uniform
python
def ljust(self, width, fillchar=None): """S.ljust(width[, fillchar]) -> string If a fillchar is provided, less formatting information will be preserved """ if fillchar is not None: return fmtstr(self.s.ljust(width, fillchar), **self.shared_atts) to_add = ' ' * (width - len(self.s)) shared = self.shared_atts if 'bg' in shared: return self + fmtstr(to_add, bg=shared[str('bg')]) if to_add else self else: uniform = self.new_with_atts_removed('bg') return uniform + fmtstr(to_add, **self.shared_atts) if to_add else uniform
[ "def", "ljust", "(", "self", ",", "width", ",", "fillchar", "=", "None", ")", ":", "if", "fillchar", "is", "not", "None", ":", "return", "fmtstr", "(", "self", ".", "s", ".", "ljust", "(", "width", ",", "fillchar", ")", ",", "*", "*", "self", "."...
S.ljust(width[, fillchar]) -> string If a fillchar is provided, less formatting information will be preserved
[ "S", ".", "ljust", "(", "width", "[", "fillchar", "]", ")", "-", ">", "string" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L395-L408
train
bpython/curtsies
curtsies/formatstring.py
FmtStr.width
def width(self): """The number of columns it would take to display this string""" if self._width is not None: return self._width self._width = sum(fs.width for fs in self.chunks) return self._width
python
def width(self): """The number of columns it would take to display this string""" if self._width is not None: return self._width self._width = sum(fs.width for fs in self.chunks) return self._width
[ "def", "width", "(", "self", ")", ":", "if", "self", ".", "_width", "is", "not", "None", ":", "return", "self", ".", "_width", "self", ".", "_width", "=", "sum", "(", "fs", ".", "width", "for", "fs", "in", "self", ".", "chunks", ")", "return", "s...
The number of columns it would take to display this string
[ "The", "number", "of", "columns", "it", "would", "take", "to", "display", "this", "string" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L447-L452
train
bpython/curtsies
curtsies/formatstring.py
FmtStr.width_at_offset
def width_at_offset(self, n): """Returns the horizontal position of character n of the string""" #TODO make more efficient? width = wcswidth(self.s[:n]) assert width != -1 return width
python
def width_at_offset(self, n): """Returns the horizontal position of character n of the string""" #TODO make more efficient? width = wcswidth(self.s[:n]) assert width != -1 return width
[ "def", "width_at_offset", "(", "self", ",", "n", ")", ":", "#TODO make more efficient?", "width", "=", "wcswidth", "(", "self", ".", "s", "[", ":", "n", "]", ")", "assert", "width", "!=", "-", "1", "return", "width" ]
Returns the horizontal position of character n of the string
[ "Returns", "the", "horizontal", "position", "of", "character", "n", "of", "the", "string" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L454-L459
train
bpython/curtsies
curtsies/formatstring.py
FmtStr.shared_atts
def shared_atts(self): """Gets atts shared among all nonzero length component Chunk""" #TODO cache this, could get ugly for large FmtStrs atts = {} first = self.chunks[0] for att in sorted(first.atts): #TODO how to write this without the '???'? if all(fs.atts.get(att, '???') == first.atts[att] for fs in self.chunks if len(fs) > 0): atts[att] = first.atts[att] return atts
python
def shared_atts(self): """Gets atts shared among all nonzero length component Chunk""" #TODO cache this, could get ugly for large FmtStrs atts = {} first = self.chunks[0] for att in sorted(first.atts): #TODO how to write this without the '???'? if all(fs.atts.get(att, '???') == first.atts[att] for fs in self.chunks if len(fs) > 0): atts[att] = first.atts[att] return atts
[ "def", "shared_atts", "(", "self", ")", ":", "#TODO cache this, could get ugly for large FmtStrs", "atts", "=", "{", "}", "first", "=", "self", ".", "chunks", "[", "0", "]", "for", "att", "in", "sorted", "(", "first", ".", "atts", ")", ":", "#TODO how to wri...
Gets atts shared among all nonzero length component Chunk
[ "Gets", "atts", "shared", "among", "all", "nonzero", "length", "component", "Chunk" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L494-L503
train
bpython/curtsies
curtsies/formatstring.py
FmtStr.new_with_atts_removed
def new_with_atts_removed(self, *attributes): """Returns a new FmtStr with the same content but some attributes removed""" return FmtStr(*[Chunk(bfs.s, bfs.atts.remove(*attributes)) for bfs in self.chunks])
python
def new_with_atts_removed(self, *attributes): """Returns a new FmtStr with the same content but some attributes removed""" return FmtStr(*[Chunk(bfs.s, bfs.atts.remove(*attributes)) for bfs in self.chunks])
[ "def", "new_with_atts_removed", "(", "self", ",", "*", "attributes", ")", ":", "return", "FmtStr", "(", "*", "[", "Chunk", "(", "bfs", ".", "s", ",", "bfs", ".", "atts", ".", "remove", "(", "*", "attributes", ")", ")", "for", "bfs", "in", "self", "...
Returns a new FmtStr with the same content but some attributes removed
[ "Returns", "a", "new", "FmtStr", "with", "the", "same", "content", "but", "some", "attributes", "removed" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L505-L508
train
bpython/curtsies
curtsies/formatstring.py
FmtStr.divides
def divides(self): """List of indices of divisions between the constituent chunks.""" acc = [0] for s in self.chunks: acc.append(acc[-1] + len(s)) return acc
python
def divides(self): """List of indices of divisions between the constituent chunks.""" acc = [0] for s in self.chunks: acc.append(acc[-1] + len(s)) return acc
[ "def", "divides", "(", "self", ")", ":", "acc", "=", "[", "0", "]", "for", "s", "in", "self", ".", "chunks", ":", "acc", ".", "append", "(", "acc", "[", "-", "1", "]", "+", "len", "(", "s", ")", ")", "return", "acc" ]
List of indices of divisions between the constituent chunks.
[ "List", "of", "indices", "of", "divisions", "between", "the", "constituent", "chunks", "." ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L525-L530
train
bpython/curtsies
curtsies/formatstring.py
FmtStr.width_aware_slice
def width_aware_slice(self, index): """Slice based on the number of columns it would take to display the substring.""" if wcswidth(self.s) == -1: raise ValueError('bad values for width aware slicing') index = normalize_slice(self.width, index) counter = 0 parts = [] for chunk in self.chunks: if index.start < counter + chunk.width and index.stop > counter: start = max(0, index.start - counter) end = min(index.stop - counter, chunk.width) if end - start == chunk.width: parts.append(chunk) else: s_part = width_aware_slice(chunk.s, max(0, index.start - counter), index.stop - counter) parts.append(Chunk(s_part, chunk.atts)) counter += chunk.width if index.stop < counter: break return FmtStr(*parts) if parts else fmtstr('')
python
def width_aware_slice(self, index): """Slice based on the number of columns it would take to display the substring.""" if wcswidth(self.s) == -1: raise ValueError('bad values for width aware slicing') index = normalize_slice(self.width, index) counter = 0 parts = [] for chunk in self.chunks: if index.start < counter + chunk.width and index.stop > counter: start = max(0, index.start - counter) end = min(index.stop - counter, chunk.width) if end - start == chunk.width: parts.append(chunk) else: s_part = width_aware_slice(chunk.s, max(0, index.start - counter), index.stop - counter) parts.append(Chunk(s_part, chunk.atts)) counter += chunk.width if index.stop < counter: break return FmtStr(*parts) if parts else fmtstr('')
[ "def", "width_aware_slice", "(", "self", ",", "index", ")", ":", "if", "wcswidth", "(", "self", ".", "s", ")", "==", "-", "1", ":", "raise", "ValueError", "(", "'bad values for width aware slicing'", ")", "index", "=", "normalize_slice", "(", "self", ".", ...
Slice based on the number of columns it would take to display the substring.
[ "Slice", "based", "on", "the", "number", "of", "columns", "it", "would", "take", "to", "display", "the", "substring", "." ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L557-L576
train
bpython/curtsies
curtsies/formatstring.py
FmtStr.width_aware_splitlines
def width_aware_splitlines(self, columns): # type: (int) -> Iterator[FmtStr] """Split into lines, pushing doublewidth characters at the end of a line to the next line. When a double-width character is pushed to the next line, a space is added to pad out the line. """ if columns < 2: raise ValueError("Column width %s is too narrow." % columns) if wcswidth(self.s) == -1: raise ValueError('bad values for width aware slicing') return self._width_aware_splitlines(columns)
python
def width_aware_splitlines(self, columns): # type: (int) -> Iterator[FmtStr] """Split into lines, pushing doublewidth characters at the end of a line to the next line. When a double-width character is pushed to the next line, a space is added to pad out the line. """ if columns < 2: raise ValueError("Column width %s is too narrow." % columns) if wcswidth(self.s) == -1: raise ValueError('bad values for width aware slicing') return self._width_aware_splitlines(columns)
[ "def", "width_aware_splitlines", "(", "self", ",", "columns", ")", ":", "# type: (int) -> Iterator[FmtStr]", "if", "columns", "<", "2", ":", "raise", "ValueError", "(", "\"Column width %s is too narrow.\"", "%", "columns", ")", "if", "wcswidth", "(", "self", ".", ...
Split into lines, pushing doublewidth characters at the end of a line to the next line. When a double-width character is pushed to the next line, a space is added to pad out the line.
[ "Split", "into", "lines", "pushing", "doublewidth", "characters", "at", "the", "end", "of", "a", "line", "to", "the", "next", "line", "." ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L578-L588
train
bpython/curtsies
curtsies/formatstring.py
FmtStr._getitem_normalized
def _getitem_normalized(self, index): """Builds the more compact fmtstrs by using fromstr( of the control sequences)""" index = normalize_slice(len(self), index) counter = 0 output = '' for fs in self.chunks: if index.start < counter + len(fs) and index.stop > counter: s_part = fs.s[max(0, index.start - counter):index.stop - counter] piece = Chunk(s_part, fs.atts).color_str output += piece counter += len(fs) if index.stop < counter: break return fmtstr(output)
python
def _getitem_normalized(self, index): """Builds the more compact fmtstrs by using fromstr( of the control sequences)""" index = normalize_slice(len(self), index) counter = 0 output = '' for fs in self.chunks: if index.start < counter + len(fs) and index.stop > counter: s_part = fs.s[max(0, index.start - counter):index.stop - counter] piece = Chunk(s_part, fs.atts).color_str output += piece counter += len(fs) if index.stop < counter: break return fmtstr(output)
[ "def", "_getitem_normalized", "(", "self", ",", "index", ")", ":", "index", "=", "normalize_slice", "(", "len", "(", "self", ")", ",", "index", ")", "counter", "=", "0", "output", "=", "''", "for", "fs", "in", "self", ".", "chunks", ":", "if", "index...
Builds the more compact fmtstrs by using fromstr( of the control sequences)
[ "Builds", "the", "more", "compact", "fmtstrs", "by", "using", "fromstr", "(", "of", "the", "control", "sequences", ")" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L613-L626
train
peterwittek/ncpol2sdpa
ncpol2sdpa/moroder_hierarchy.py
MoroderHierarchy._calculate_block_structure
def _calculate_block_structure(self, inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=None): """Calculates the block_struct array for the output file. """ block_struct = [] if self.verbose > 0: print("Calculating block structure...") block_struct.append(len(self.monomial_sets[0]) * len(self.monomial_sets[1])) if extramomentmatrix is not None: for _ in extramomentmatrix: block_struct.append(len(self.monomial_sets[0]) * len(self.monomial_sets[1])) super(MoroderHierarchy, self).\ _calculate_block_structure(inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=block_struct)
python
def _calculate_block_structure(self, inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=None): """Calculates the block_struct array for the output file. """ block_struct = [] if self.verbose > 0: print("Calculating block structure...") block_struct.append(len(self.monomial_sets[0]) * len(self.monomial_sets[1])) if extramomentmatrix is not None: for _ in extramomentmatrix: block_struct.append(len(self.monomial_sets[0]) * len(self.monomial_sets[1])) super(MoroderHierarchy, self).\ _calculate_block_structure(inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=block_struct)
[ "def", "_calculate_block_structure", "(", "self", ",", "inequalities", ",", "equalities", ",", "momentinequalities", ",", "momentequalities", ",", "extramomentmatrix", ",", "removeequalities", ",", "block_struct", "=", "None", ")", ":", "block_struct", "=", "[", "]"...
Calculates the block_struct array for the output file.
[ "Calculates", "the", "block_struct", "array", "for", "the", "output", "file", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/moroder_hierarchy.py#L81-L101
train
bpython/curtsies
examples/initial_input.py
main
def main(): """Ideally we shouldn't lose the first second of events""" time.sleep(1) with Input() as input_generator: for e in input_generator: print(repr(e))
python
def main(): """Ideally we shouldn't lose the first second of events""" time.sleep(1) with Input() as input_generator: for e in input_generator: print(repr(e))
[ "def", "main", "(", ")", ":", "time", ".", "sleep", "(", "1", ")", "with", "Input", "(", ")", "as", "input_generator", ":", "for", "e", "in", "input_generator", ":", "print", "(", "repr", "(", "e", ")", ")" ]
Ideally we shouldn't lose the first second of events
[ "Ideally", "we", "shouldn", "t", "lose", "the", "first", "second", "of", "events" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/initial_input.py#L5-L10
train
peterwittek/ncpol2sdpa
ncpol2sdpa/steering_hierarchy.py
SteeringHierarchy._process_monomial
def _process_monomial(self, monomial, n_vars): """Process a single monomial when building the moment matrix. """ coeff, monomial = monomial.as_coeff_Mul() k = 0 # Have we seen this monomial before? conjugate = False try: # If yes, then we improve sparsity by reusing the # previous variable to denote this entry in the matrix k = self.monomial_index[monomial] except KeyError: # An extra round of substitutions is granted on the conjugate of # the monomial if all the variables are Hermitian daggered_monomial = \ apply_substitutions(Dagger(monomial), self.substitutions, self.pure_substitution_rules) try: k = self.monomial_index[daggered_monomial] conjugate = True 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[monomial] = k if conjugate: k = -k return k, coeff
python
def _process_monomial(self, monomial, n_vars): """Process a single monomial when building the moment matrix. """ coeff, monomial = monomial.as_coeff_Mul() k = 0 # Have we seen this monomial before? conjugate = False try: # If yes, then we improve sparsity by reusing the # previous variable to denote this entry in the matrix k = self.monomial_index[monomial] except KeyError: # An extra round of substitutions is granted on the conjugate of # the monomial if all the variables are Hermitian daggered_monomial = \ apply_substitutions(Dagger(monomial), self.substitutions, self.pure_substitution_rules) try: k = self.monomial_index[daggered_monomial] conjugate = True 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[monomial] = k if conjugate: k = -k return k, coeff
[ "def", "_process_monomial", "(", "self", ",", "monomial", ",", "n_vars", ")", ":", "coeff", ",", "monomial", "=", "monomial", ".", "as_coeff_Mul", "(", ")", "k", "=", "0", "# Have we seen this monomial before?", "conjugate", "=", "False", "try", ":", "# If yes...
Process a single monomial when building the moment matrix.
[ "Process", "a", "single", "monomial", "when", "building", "the", "moment", "matrix", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/steering_hierarchy.py#L80-L108
train
peterwittek/ncpol2sdpa
ncpol2sdpa/steering_hierarchy.py
SteeringHierarchy.__get_trace_facvar
def __get_trace_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) F = {} for i in range(self.matrix_var_dim): for j in range(self.matrix_var_dim): for key, value in \ polynomial[i, j].as_coefficients_dict().items(): skey = apply_substitutions(key, self.substitutions, self.pure_substitution_rules) try: Fk = F[skey] except KeyError: Fk = zeros(self.matrix_var_dim, self.matrix_var_dim) Fk[i, j] += value F[skey] = Fk # This is the tracing part for key, Fk in F.items(): if key == S.One: k = 1 else: k = self.monomial_index[key] for i in range(self.matrix_var_dim): for j in range(self.matrix_var_dim): sym_matrix = zeros(self.matrix_var_dim, self.matrix_var_dim) sym_matrix[i, j] = 1 facvar[k+i*self.matrix_var_dim+j] = (sym_matrix*Fk).trace() facvar = [float(f) for f in facvar] return facvar
python
def __get_trace_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) F = {} for i in range(self.matrix_var_dim): for j in range(self.matrix_var_dim): for key, value in \ polynomial[i, j].as_coefficients_dict().items(): skey = apply_substitutions(key, self.substitutions, self.pure_substitution_rules) try: Fk = F[skey] except KeyError: Fk = zeros(self.matrix_var_dim, self.matrix_var_dim) Fk[i, j] += value F[skey] = Fk # This is the tracing part for key, Fk in F.items(): if key == S.One: k = 1 else: k = self.monomial_index[key] for i in range(self.matrix_var_dim): for j in range(self.matrix_var_dim): sym_matrix = zeros(self.matrix_var_dim, self.matrix_var_dim) sym_matrix[i, j] = 1 facvar[k+i*self.matrix_var_dim+j] = (sym_matrix*Fk).trace() facvar = [float(f) for f in facvar] return facvar
[ "def", "__get_trace_facvar", "(", "self", ",", "polynomial", ")", ":", "facvar", "=", "[", "0", "]", "*", "(", "self", ".", "n_vars", "+", "1", ")", "F", "=", "{", "}", "for", "i", "in", "range", "(", "self", ".", "matrix_var_dim", ")", ":", "for...
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.
[ "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", "return...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/steering_hierarchy.py#L186-L219
train