repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
bpython/curtsies | examples/tttplaybitboard.py | evaluate | def evaluate(grid):
"Return the value for the player to move, assuming perfect play."
if is_won(grid): return -1
succs = successors(grid)
return -min(map(evaluate, succs)) if succs else 0 | python | def evaluate(grid):
"Return the value for the player to move, assuming perfect play."
if is_won(grid): return -1
succs = successors(grid)
return -min(map(evaluate, succs)) if succs else 0 | [
"def",
"evaluate",
"(",
"grid",
")",
":",
"if",
"is_won",
"(",
"grid",
")",
":",
"return",
"-",
"1",
"succs",
"=",
"successors",
"(",
"grid",
")",
"return",
"-",
"min",
"(",
"map",
"(",
"evaluate",
",",
"succs",
")",
")",
"if",
"succs",
"else",
"... | Return the value for the player to move, assuming perfect play. | [
"Return",
"the",
"value",
"for",
"the",
"player",
"to",
"move",
"assuming",
"perfect",
"play",
"."
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L119-L123 |
bpython/curtsies | examples/tttplaybitboard.py | is_won | def is_won(grid):
"Did the latest move win the game?"
p, q = grid
return any(way == (way & q) for way in ways_to_win) | python | def is_won(grid):
"Did the latest move win the game?"
p, q = grid
return any(way == (way & q) for way in ways_to_win) | [
"def",
"is_won",
"(",
"grid",
")",
":",
"p",
",",
"q",
"=",
"grid",
"return",
"any",
"(",
"way",
"==",
"(",
"way",
"&",
"q",
")",
"for",
"way",
"in",
"ways_to_win",
")"
] | Did the latest move win the game? | [
"Did",
"the",
"latest",
"move",
"win",
"the",
"game?"
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L139-L142 |
bpython/curtsies | examples/tttplaybitboard.py | apply_move | def apply_move(grid, move):
"Try to move: return a new grid, or None if illegal."
p, q = grid
bit = 1 << move
return (q, p | bit) if 0 == (bit & (p | q)) else None | python | def apply_move(grid, move):
"Try to move: return a new grid, or None if illegal."
p, q = grid
bit = 1 << move
return (q, p | bit) if 0 == (bit & (p | q)) else None | [
"def",
"apply_move",
"(",
"grid",
",",
"move",
")",
":",
"p",
",",
"q",
"=",
"grid",
"bit",
"=",
"1",
"<<",
"move",
"return",
"(",
"q",
",",
"p",
"|",
"bit",
")",
"if",
"0",
"==",
"(",
"bit",
"&",
"(",
"p",
"|",
"q",
")",
")",
"else",
"No... | Try to move: return a new grid, or None if illegal. | [
"Try",
"to",
"move",
":",
"return",
"a",
"new",
"grid",
"or",
"None",
"if",
"illegal",
"."
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L161-L165 |
bpython/curtsies | examples/tttplaybitboard.py | player_marks | def player_marks(grid):
"Return two results: the player's mark and their opponent's."
p, q = grid
return 'XO' if sum(player_bits(p)) == sum(player_bits(q)) else 'OX' | python | def player_marks(grid):
"Return two results: the player's mark and their opponent's."
p, q = grid
return 'XO' if sum(player_bits(p)) == sum(player_bits(q)) else 'OX' | [
"def",
"player_marks",
"(",
"grid",
")",
":",
"p",
",",
"q",
"=",
"grid",
"return",
"'XO'",
"if",
"sum",
"(",
"player_bits",
"(",
"p",
")",
")",
"==",
"sum",
"(",
"player_bits",
"(",
"q",
")",
")",
"else",
"'OX'"
] | Return two results: the player's mark and their opponent's. | [
"Return",
"two",
"results",
":",
"the",
"player",
"s",
"mark",
"and",
"their",
"opponent",
"s",
"."
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L181-L184 |
bpython/curtsies | examples/tttplaybitboard.py | view | def view(grid):
"Show a grid human-readably."
p_mark, q_mark = player_marks(grid)
return grid_format % tuple(p_mark if by_p else q_mark if by_q else '.'
for by_p, by_q in zip(*map(player_bits, grid))) | python | def view(grid):
"Show a grid human-readably."
p_mark, q_mark = player_marks(grid)
return grid_format % tuple(p_mark if by_p else q_mark if by_q else '.'
for by_p, by_q in zip(*map(player_bits, grid))) | [
"def",
"view",
"(",
"grid",
")",
":",
"p_mark",
",",
"q_mark",
"=",
"player_marks",
"(",
"grid",
")",
"return",
"grid_format",
"%",
"tuple",
"(",
"p_mark",
"if",
"by_p",
"else",
"q_mark",
"if",
"by_q",
"else",
"'.'",
"for",
"by_p",
",",
"by_q",
"in",
... | Show a grid human-readably. | [
"Show",
"a",
"grid",
"human",
"-",
"readably",
"."
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L189-L193 |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdpa_utils.py | read_sdpa_out | def read_sdpa_out(filename, solutionmatrix=False, status=False,
sdp=None):
"""Helper function to parse the output file of SDPA.
:param filename: The name of the SDPA output file.
:type filename: str.
:param solutionmatrix: Optional parameter for retrieving the solution.
:type solu... | python | def read_sdpa_out(filename, solutionmatrix=False, status=False,
sdp=None):
"""Helper function to parse the output file of SDPA.
:param filename: The name of the SDPA output file.
:type filename: str.
:param solutionmatrix: Optional parameter for retrieving the solution.
:type solu... | [
"def",
"read_sdpa_out",
"(",
"filename",
",",
"solutionmatrix",
"=",
"False",
",",
"status",
"=",
"False",
",",
"sdp",
"=",
"None",
")",
":",
"primal",
"=",
"None",
"dual",
"=",
"None",
"x_mat",
"=",
"None",
"y_mat",
"=",
"None",
"status_string",
"=",
... | Helper function to parse the output file of SDPA.
:param filename: The name of the SDPA output file.
:type filename: str.
:param solutionmatrix: Optional parameter for retrieving the solution.
:type solutionmatrix: bool.
:param status: Optional parameter for retrieving the status.
:type status:... | [
"Helper",
"function",
"to",
"parse",
"the",
"output",
"file",
"of",
"SDPA",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdpa_utils.py#L47-L119 |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdpa_utils.py | solve_with_sdpa | def solve_with_sdpa(sdp, solverparameters=None):
"""Helper function to write out the SDP problem to a temporary
file, call the solver, and parse the output.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param solverparameters: Optional parameters to SDPA.
:ty... | python | def solve_with_sdpa(sdp, solverparameters=None):
"""Helper function to write out the SDP problem to a temporary
file, call the solver, and parse the output.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param solverparameters: Optional parameters to SDPA.
:ty... | [
"def",
"solve_with_sdpa",
"(",
"sdp",
",",
"solverparameters",
"=",
"None",
")",
":",
"solverexecutable",
"=",
"detect_sdpa",
"(",
"solverparameters",
")",
"if",
"solverexecutable",
"is",
"None",
":",
"raise",
"OSError",
"(",
"\"SDPA is not in the path or the executab... | Helper function to write out the SDP problem to a temporary
file, call the solver, and parse the output.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param solverparameters: Optional parameters to SDPA.
:type solverparameters: dict of str.
:returns: tuple of... | [
"Helper",
"function",
"to",
"write",
"out",
"the",
"SDP",
"problem",
"to",
"a",
"temporary",
"file",
"call",
"the",
"solver",
"and",
"parse",
"the",
"output",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdpa_utils.py#L148-L191 |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdpa_utils.py | convert_row_to_sdpa_index | def convert_row_to_sdpa_index(block_struct, row_offsets, row):
"""Helper function to map to sparse SDPA index values.
"""
block_index = bisect_left(row_offsets[1:], row + 1)
width = block_struct[block_index]
row = row - row_offsets[block_index]
i, j = divmod(row, width)
return block_index, i... | python | def convert_row_to_sdpa_index(block_struct, row_offsets, row):
"""Helper function to map to sparse SDPA index values.
"""
block_index = bisect_left(row_offsets[1:], row + 1)
width = block_struct[block_index]
row = row - row_offsets[block_index]
i, j = divmod(row, width)
return block_index, i... | [
"def",
"convert_row_to_sdpa_index",
"(",
"block_struct",
",",
"row_offsets",
",",
"row",
")",
":",
"block_index",
"=",
"bisect_left",
"(",
"row_offsets",
"[",
"1",
":",
"]",
",",
"row",
"+",
"1",
")",
"width",
"=",
"block_struct",
"[",
"block_index",
"]",
... | Helper function to map to sparse SDPA index values. | [
"Helper",
"function",
"to",
"map",
"to",
"sparse",
"SDPA",
"index",
"values",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdpa_utils.py#L194-L201 |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdpa_utils.py | write_to_sdpa | def write_to_sdpa(sdp, filename):
"""Write the SDP relaxation to SDPA format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param filename: The name of the file. It must have the suffix ".dat-s"
:type filename: str.
"""
# Coefficient matrices
row_offsets ... | python | def write_to_sdpa(sdp, filename):
"""Write the SDP relaxation to SDPA format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param filename: The name of the file. It must have the suffix ".dat-s"
:type filename: str.
"""
# Coefficient matrices
row_offsets ... | [
"def",
"write_to_sdpa",
"(",
"sdp",
",",
"filename",
")",
":",
"# Coefficient matrices",
"row_offsets",
"=",
"[",
"0",
"]",
"cumulative_sum",
"=",
"0",
"for",
"block_size",
"in",
"sdp",
".",
"block_struct",
":",
"cumulative_sum",
"+=",
"block_size",
"**",
"2",... | Write the SDP relaxation to SDPA format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param filename: The name of the file. It must have the suffix ".dat-s"
:type filename: str. | [
"Write",
"the",
"SDP",
"relaxation",
"to",
"SDPA",
"format",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdpa_utils.py#L204-L273 |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdpa_utils.py | convert_to_human_readable | def convert_to_human_readable(sdp):
"""Convert the SDP relaxation to a human-readable format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:returns: tuple of the objective function in a string and a matrix of
strings as the symbolic representation of the mo... | python | def convert_to_human_readable(sdp):
"""Convert the SDP relaxation to a human-readable format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:returns: tuple of the objective function in a string and a matrix of
strings as the symbolic representation of the mo... | [
"def",
"convert_to_human_readable",
"(",
"sdp",
")",
":",
"objective",
"=",
"\"\"",
"indices_in_objective",
"=",
"[",
"]",
"for",
"i",
",",
"tmp",
"in",
"enumerate",
"(",
"sdp",
".",
"obj_facvar",
")",
":",
"candidates",
"=",
"[",
"key",
"for",
"key",
",... | Convert the SDP relaxation to a human-readable format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:returns: tuple of the objective function in a string and a matrix of
strings as the symbolic representation of the moment matrix | [
"Convert",
"the",
"SDP",
"relaxation",
"to",
"a",
"human",
"-",
"readable",
"format",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdpa_utils.py#L276-L341 |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdpa_utils.py | write_to_human_readable | def write_to_human_readable(sdp, filename):
"""Write the SDP relaxation to a human-readable format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param filename: The name of the file.
:type filename: str.
"""
objective, matrix = convert_to_human_readable(sdp)... | python | def write_to_human_readable(sdp, filename):
"""Write the SDP relaxation to a human-readable format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param filename: The name of the file.
:type filename: str.
"""
objective, matrix = convert_to_human_readable(sdp)... | [
"def",
"write_to_human_readable",
"(",
"sdp",
",",
"filename",
")",
":",
"objective",
",",
"matrix",
"=",
"convert_to_human_readable",
"(",
"sdp",
")",
"f",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"\"Objective:\"",
"+",
"obje... | Write the SDP relaxation to a human-readable format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param filename: The name of the file.
:type filename: str. | [
"Write",
"the",
"SDP",
"relaxation",
"to",
"a",
"human",
"-",
"readable",
"format",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdpa_utils.py#L344-L359 |
bpython/curtsies | examples/initial_input_with_cursor.py | main | def main():
"""Ideally we shouldn't lose the first second of events"""
with Input() as input_generator:
def extra_bytes_callback(string):
print('got extra bytes', repr(string))
print('type:', type(string))
input_generator.unget_bytes(string)
time.sleep(1)
... | python | def main():
"""Ideally we shouldn't lose the first second of events"""
with Input() as input_generator:
def extra_bytes_callback(string):
print('got extra bytes', repr(string))
print('type:', type(string))
input_generator.unget_bytes(string)
time.sleep(1)
... | [
"def",
"main",
"(",
")",
":",
"with",
"Input",
"(",
")",
"as",
"input_generator",
":",
"def",
"extra_bytes_callback",
"(",
"string",
")",
":",
"print",
"(",
"'got extra bytes'",
",",
"repr",
"(",
"string",
")",
")",
"print",
"(",
"'type:'",
",",
"type",
... | Ideally we shouldn't lose the first second of events | [
"Ideally",
"we",
"shouldn",
"t",
"lose",
"the",
"first",
"second",
"of",
"events"
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/initial_input_with_cursor.py#L5-L16 |
kmn/coincheck | coincheck/utils.py | make_header | def make_header(url,
access_key=None,
secret_key=None):
''' create request header function
:param url: URL for the new :class:`Request` object.
'''
nonce = nounce()
url = url
message = nonce + url
signature = hmac.new(secret_key.encode('utf-8'), message.enc... | python | def make_header(url,
access_key=None,
secret_key=None):
''' create request header function
:param url: URL for the new :class:`Request` object.
'''
nonce = nounce()
url = url
message = nonce + url
signature = hmac.new(secret_key.encode('utf-8'), message.enc... | [
"def",
"make_header",
"(",
"url",
",",
"access_key",
"=",
"None",
",",
"secret_key",
"=",
"None",
")",
":",
"nonce",
"=",
"nounce",
"(",
")",
"url",
"=",
"url",
"message",
"=",
"nonce",
"+",
"url",
"signature",
"=",
"hmac",
".",
"new",
"(",
"secret_k... | create request header function
:param url: URL for the new :class:`Request` object. | [
"create",
"request",
"header",
"function",
":",
"param",
"url",
":",
"URL",
"for",
"the",
"new",
":",
"class",
":",
"Request",
"object",
"."
] | train | https://github.com/kmn/coincheck/blob/4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc/coincheck/utils.py#L14-L29 |
bpython/curtsies | curtsies/input.py | Input.unget_bytes | def unget_bytes(self, string):
"""Adds bytes to be internal buffer to be read
This method is for reporting bytes from an in_stream read
not initiated by this Input object"""
self.unprocessed_bytes.extend(string[i:i + 1]
for i in range(len(string))) | python | def unget_bytes(self, string):
"""Adds bytes to be internal buffer to be read
This method is for reporting bytes from an in_stream read
not initiated by this Input object"""
self.unprocessed_bytes.extend(string[i:i + 1]
for i in range(len(string))) | [
"def",
"unget_bytes",
"(",
"self",
",",
"string",
")",
":",
"self",
".",
"unprocessed_bytes",
".",
"extend",
"(",
"string",
"[",
"i",
":",
"i",
"+",
"1",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"string",
")",
")",
")"
] | Adds bytes to be internal buffer to be read
This method is for reporting bytes from an in_stream read
not initiated by this Input object | [
"Adds",
"bytes",
"to",
"be",
"internal",
"buffer",
"to",
"be",
"read"
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L120-L127 |
bpython/curtsies | curtsies/input.py | Input._wait_for_read_ready_or_timeout | def _wait_for_read_ready_or_timeout(self, timeout):
"""Returns tuple of whether stdin is ready to read and an event.
If an event is returned, that event is more pressing than reading
bytes on stdin to create a keyboard input event.
If stdin is ready, either there are bytes to read or a ... | python | def _wait_for_read_ready_or_timeout(self, timeout):
"""Returns tuple of whether stdin is ready to read and an event.
If an event is returned, that event is more pressing than reading
bytes on stdin to create a keyboard input event.
If stdin is ready, either there are bytes to read or a ... | [
"def",
"_wait_for_read_ready_or_timeout",
"(",
"self",
",",
"timeout",
")",
":",
"remaining_timeout",
"=",
"timeout",
"t0",
"=",
"time",
".",
"time",
"(",
")",
"while",
"True",
":",
"try",
":",
"(",
"rs",
",",
"_",
",",
"_",
")",
"=",
"select",
".",
... | Returns tuple of whether stdin is ready to read and an event.
If an event is returned, that event is more pressing than reading
bytes on stdin to create a keyboard input event.
If stdin is ready, either there are bytes to read or a SIGTSTP
triggered by dsusp has been received | [
"Returns",
"tuple",
"of",
"whether",
"stdin",
"is",
"ready",
"to",
"read",
"and",
"an",
"event",
"."
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L129-L162 |
bpython/curtsies | curtsies/input.py | Input.send | def send(self, timeout=None):
"""Returns an event or None if no events occur before timeout."""
if self.sigint_event and is_main_thread():
with ReplacedSigIntHandler(self.sigint_handler):
return self._send(timeout)
else:
return self._send(timeout) | python | def send(self, timeout=None):
"""Returns an event or None if no events occur before timeout."""
if self.sigint_event and is_main_thread():
with ReplacedSigIntHandler(self.sigint_handler):
return self._send(timeout)
else:
return self._send(timeout) | [
"def",
"send",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"self",
".",
"sigint_event",
"and",
"is_main_thread",
"(",
")",
":",
"with",
"ReplacedSigIntHandler",
"(",
"self",
".",
"sigint_handler",
")",
":",
"return",
"self",
".",
"_send",
"... | Returns an event or None if no events occur before timeout. | [
"Returns",
"an",
"event",
"or",
"None",
"if",
"no",
"events",
"occur",
"before",
"timeout",
"."
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L164-L170 |
bpython/curtsies | curtsies/input.py | Input._nonblocking_read | def _nonblocking_read(self):
"""Returns the number of characters read and adds them to self.unprocessed_bytes"""
with Nonblocking(self.in_stream):
if PY3:
try:
data = os.read(self.in_stream.fileno(), READ_SIZE)
except BlockingIOError:
... | python | def _nonblocking_read(self):
"""Returns the number of characters read and adds them to self.unprocessed_bytes"""
with Nonblocking(self.in_stream):
if PY3:
try:
data = os.read(self.in_stream.fileno(), READ_SIZE)
except BlockingIOError:
... | [
"def",
"_nonblocking_read",
"(",
"self",
")",
":",
"with",
"Nonblocking",
"(",
"self",
".",
"in_stream",
")",
":",
"if",
"PY3",
":",
"try",
":",
"data",
"=",
"os",
".",
"read",
"(",
"self",
".",
"in_stream",
".",
"fileno",
"(",
")",
",",
"READ_SIZE",... | Returns the number of characters read and adds them to self.unprocessed_bytes | [
"Returns",
"the",
"number",
"of",
"characters",
"read",
"and",
"adds",
"them",
"to",
"self",
".",
"unprocessed_bytes"
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L245-L265 |
bpython/curtsies | curtsies/input.py | Input.event_trigger | def event_trigger(self, event_type):
"""Returns a callback that creates events.
Returned callback function will add an event of type event_type
to a queue which will be checked the next time an event is requested."""
def callback(**kwargs):
self.queued_events.append(event_ty... | python | def event_trigger(self, event_type):
"""Returns a callback that creates events.
Returned callback function will add an event of type event_type
to a queue which will be checked the next time an event is requested."""
def callback(**kwargs):
self.queued_events.append(event_ty... | [
"def",
"event_trigger",
"(",
"self",
",",
"event_type",
")",
":",
"def",
"callback",
"(",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"queued_events",
".",
"append",
"(",
"event_type",
"(",
"*",
"*",
"kwargs",
")",
")",
"return",
"callback"
] | Returns a callback that creates events.
Returned callback function will add an event of type event_type
to a queue which will be checked the next time an event is requested. | [
"Returns",
"a",
"callback",
"that",
"creates",
"events",
"."
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L267-L274 |
bpython/curtsies | curtsies/input.py | Input.scheduled_event_trigger | def scheduled_event_trigger(self, event_type):
"""Returns a callback that schedules events for the future.
Returned callback function will add an event of type event_type
to a queue which will be checked the next time an event is requested."""
def callback(when, **kwargs):
s... | python | def scheduled_event_trigger(self, event_type):
"""Returns a callback that schedules events for the future.
Returned callback function will add an event of type event_type
to a queue which will be checked the next time an event is requested."""
def callback(when, **kwargs):
s... | [
"def",
"scheduled_event_trigger",
"(",
"self",
",",
"event_type",
")",
":",
"def",
"callback",
"(",
"when",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"queued_scheduled_events",
".",
"append",
"(",
"(",
"when",
",",
"event_type",
"(",
"when",
"=",
"... | Returns a callback that schedules events for the future.
Returned callback function will add an event of type event_type
to a queue which will be checked the next time an event is requested. | [
"Returns",
"a",
"callback",
"that",
"schedules",
"events",
"for",
"the",
"future",
"."
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L276-L283 |
bpython/curtsies | curtsies/input.py | Input.threadsafe_event_trigger | def threadsafe_event_trigger(self, event_type):
"""Returns a callback to creates events, interrupting current event requests.
Returned callback function will create an event of type event_type
which will interrupt an event request if one
is concurrently occuring, otherwise adding the ev... | python | def threadsafe_event_trigger(self, event_type):
"""Returns a callback to creates events, interrupting current event requests.
Returned callback function will create an event of type event_type
which will interrupt an event request if one
is concurrently occuring, otherwise adding the ev... | [
"def",
"threadsafe_event_trigger",
"(",
"self",
",",
"event_type",
")",
":",
"readfd",
",",
"writefd",
"=",
"os",
".",
"pipe",
"(",
")",
"self",
".",
"readers",
".",
"append",
"(",
"readfd",
")",
"def",
"callback",
"(",
"*",
"*",
"kwargs",
")",
":",
... | Returns a callback to creates events, interrupting current event requests.
Returned callback function will create an event of type event_type
which will interrupt an event request if one
is concurrently occuring, otherwise adding the event to a queue
that will be checked on the next eve... | [
"Returns",
"a",
"callback",
"to",
"creates",
"events",
"interrupting",
"current",
"event",
"requests",
"."
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L285-L299 |
peterwittek/ncpol2sdpa | ncpol2sdpa/solver_common.py | solve_sdp | def solve_sdp(sdp, solver=None, solverparameters=None):
"""Call a solver on the SDP relaxation. Upon successful solution, it
returns the primal and dual objective values along with the solution
matrices.
:param sdpRelaxation: The SDP relaxation to be solved.
:type sdpRelaxation: :class:`ncpol2sdpa.... | python | def solve_sdp(sdp, solver=None, solverparameters=None):
"""Call a solver on the SDP relaxation. Upon successful solution, it
returns the primal and dual objective values along with the solution
matrices.
:param sdpRelaxation: The SDP relaxation to be solved.
:type sdpRelaxation: :class:`ncpol2sdpa.... | [
"def",
"solve_sdp",
"(",
"sdp",
",",
"solver",
"=",
"None",
",",
"solverparameters",
"=",
"None",
")",
":",
"solvers",
"=",
"autodetect_solvers",
"(",
"solverparameters",
")",
"solver",
"=",
"solver",
".",
"lower",
"(",
")",
"if",
"solver",
"is",
"not",
... | Call a solver on the SDP relaxation. Upon successful solution, it
returns the primal and dual objective values along with the solution
matrices.
:param sdpRelaxation: The SDP relaxation to be solved.
:type sdpRelaxation: :class:`ncpol2sdpa.SdpRelaxation`.
:param solver: The solver to be called, eit... | [
"Call",
"a",
"solver",
"on",
"the",
"SDP",
"relaxation",
".",
"Upon",
"successful",
"solution",
"it",
"returns",
"the",
"primal",
"and",
"dual",
"objective",
"values",
"along",
"with",
"the",
"solution",
"matrices",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/solver_common.py#L46-L140 |
peterwittek/ncpol2sdpa | ncpol2sdpa/solver_common.py | find_solution_ranks | def find_solution_ranks(sdp, xmat=None, baselevel=0):
"""Helper function to detect rank loop in the solution matrix.
:param sdp: The SDP relaxation.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param x_mat: Optional parameter providing the primal solution of the
moment matrix. If not provided... | python | def find_solution_ranks(sdp, xmat=None, baselevel=0):
"""Helper function to detect rank loop in the solution matrix.
:param sdp: The SDP relaxation.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param x_mat: Optional parameter providing the primal solution of the
moment matrix. If not provided... | [
"def",
"find_solution_ranks",
"(",
"sdp",
",",
"xmat",
"=",
"None",
",",
"baselevel",
"=",
"0",
")",
":",
"if",
"sdp",
".",
"status",
"==",
"\"unsolved\"",
"and",
"xmat",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"The SDP relaxation is unsolved and no pr... | Helper function to detect rank loop in the solution matrix.
:param sdp: The SDP relaxation.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param x_mat: Optional parameter providing the primal solution of the
moment matrix. If not provided, the solution is extracted
from the sdp ob... | [
"Helper",
"function",
"to",
"detect",
"rank",
"loop",
"in",
"the",
"solution",
"matrix",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/solver_common.py#L143-L181 |
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
... | 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
... | [
"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
... | [
"Given",
"a",
"solution",
"of",
"the",
"dual",
"problem",
"it",
"returns",
"the",
"SOS",
"decomposition",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/solver_common.py#L184-L236 |
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:`ncpol2sd... | 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:`ncpol2sd... | [
"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 va... | [
"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",... | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/solver_common.py#L344-L386 |
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.choic... | 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.choic... | [
"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"
] | train | https://github.com/chris1610/barnum-proj/blob/0a38f24bde66373553d02fbf67b733c1d55ada33/barnum/gencc.py#L63-L90 |
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:
... | 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:
... | [
"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"
] | train | https://github.com/laike9m/ezcf/blob/30b0f7ecfd4062e9b9a2f8f13ae1f2fd9f21fa12/ezcf/type_json.py#L32-L53 |
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,... | 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,... | [
"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"
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/gameexample.py#L57-L65 |
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):... | 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):... | [
"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"
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/gameexample.py#L67-L83 |
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"
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L76-L79 |
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 to... | 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 to... | [
"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... | [
"Renders",
"array",
"to",
"terminal",
"and",
"places",
"(",
"0",
"-",
"indexed",
")",
"cursor"
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L144-L204 |
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)
... | 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",
"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"
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L271-L318 |
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... | 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... | [
"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 sig... | [
"Returns",
"the",
"how",
"far",
"down",
"the",
"cursor",
"moved",
"since",
"last",
"render",
"."
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L320-L347 |
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_cur... | 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_cur... | [
"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",
"."
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L349-L368 |
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 wid... | 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 wid... | [
"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... | [
"Renders",
"array",
"to",
"terminal",
"returns",
"the",
"number",
"of",
"lines",
"scrolled",
"offscreen"
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L370-L461 |
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 informa... | 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 informa... | [
"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 so... | [
"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... | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L65-L109 |
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_monom... | 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_monom... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L269-L322 |
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... | 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... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L359-L433 |
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:
... | 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:
... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L463-L511 |
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
... | 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
... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L513-L534 |
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_var... | 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_var... | [
"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... | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L536-L556 |
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 relaxatio... | 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 relaxatio... | [
"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"
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L558-L620 |
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 equal... | 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 equal... | [
"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"
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L622-L694 |
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 ... | 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 ... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L696-L729 |
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 outp... | python | def _calculate_block_structure(self, inequalities, equalities,
momentinequalities, momentequalities,
extramomentmatrix, removeequalities,
block_struct=None):
"""Calculates the block_struct array for the outp... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L843-L935 |
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 ... | 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 ... | [
"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 in... | [
"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",
"... | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1007-L1074 |
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 ... | 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 ... | [
"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 combina... | [
"Set",
"or",
"change",
"the",
"objective",
"function",
"of",
"the",
"polynomial",
"optimization",
"problem",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1076-L1120 |
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
... | 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
... | [
"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 ... | [
"Helper",
"function",
"to",
"detect",
"rank",
"loop",
"in",
"the",
"solution",
"matrix",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1167-L1183 |
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 d... | 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 d... | [
"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... | [
"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"... | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1185-L1212 |
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.
... | 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.
... | [
"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: Optiona... | [
"Write",
"the",
"relaxation",
"to",
"a",
"file",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1214-L1247 |
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,
... | python | def get_relaxation(self, level, objective=None, inequalities=None,
equalities=None, substitutions=None,
momentinequalities=None, momentequalities=None,
momentsubstitutions=None,
removeequalities=False, extramonomials=None,
... | [
"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... | [
"Get",
"the",
"SDP",
"relaxation",
"of",
"a",
"noncommutative",
"polynomial",
"optimization",
"problem",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1290-L1434 |
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... | 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... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L16-L32 |
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)
... | 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)
... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L35-L54 |
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:
... | 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:
... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L81-L96 |
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)
... | 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)
... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L99-L121 |
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_... | 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_... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L124-L143 |
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... | 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... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L146-L165 |
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... | 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... | [
"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 degre... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L168-L185 |
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:
... | 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:
... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L188-L214 |
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.
:p... | 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.
:p... | [
"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_su... | [
"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"... | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L217-L352 |
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... | 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... | [
"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.
... | [
"Generates",
"a",
"number",
"of",
"commutative",
"or",
"noncommutative",
"variables"
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L355-L395 |
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-... | 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-... | [
"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.
... | [
"Generates",
"a",
"number",
"of",
"commutative",
"or",
"noncommutative",
"operators"
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L398-L434 |
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.physi... | 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.physi... | [
"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`.
:... | [
"Generates",
"all",
"noncommutative",
"monomials",
"up",
"to",
"a",
"degree"
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L437-L469 |
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):
ret... | 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):
ret... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L472-L493 |
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)):... | 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)):... | [
"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"
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L496-L513 |
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 removesubs... | 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 removesubs... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L516-L530 |
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 ord... | 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 ord... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L533-L541 |
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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L544-L551 |
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... | 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... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L562-L577 |
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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L580-L590 |
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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L593-L601 |
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 o... | 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 o... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L604-L614 |
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', '... | 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', '... | [
"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', ' '], [' ', ' ', '... | [
"Returns",
"the",
"value",
"of",
"a",
"board",
">>>",
"b",
"=",
"Board",
"()",
";",
"b",
".",
"_rows",
"=",
"[[",
"x",
"x",
"x",
"]",
"[",
"x",
"x",
"x",
"]",
"[",
"x",
"x",
"x",
"]]",
">>>",
"value",
"(",
"b",
")",
"1",
">>>",
"b",
"=",
... | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tictactoeexample.py#L68-L94 |
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"
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tictactoeexample.py#L96-L104 |
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"
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tictactoeexample.py#L40-L46 |
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 Bo... | 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 Bo... | [
"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: T... | [
"Get",
"the",
"sparse",
"SDP",
"relaxation",
"of",
"a",
"Bell",
"inequality",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/faacets_relaxation.py#L63-L91 |
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/permis... | 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/permis... | [
"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",
"."
] | train | https://github.com/zeekay/soundcloud-cli/blob/8a83013683e1acf32f093239bbb6d3c02bc50b37/soundcloud_cli/api/share.py#L7-L34 |
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", "cvxo... | 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", "cvxo... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/picos_utils.py#L13-L34 |
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... | 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... | [
"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: T... | [
"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",
... | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/picos_utils.py#L37-L125 |
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... | 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... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/cvxpy_utils.py#L14-L48 |
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 bl... | 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 bl... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/cvxpy_utils.py#L51-L94 |
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: Option... | 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: Option... | [
"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: O... | [
"Get",
"the",
"forward",
"neighbors",
"of",
"a",
"site",
"in",
"a",
"lattice",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L17-L44 |
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 l... | 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 l... | [
"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.
... | [
"Get",
"the",
"forward",
"neighbors",
"at",
"a",
"given",
"distance",
"of",
"a",
"site",
"or",
"set",
"of",
"sites",
"in",
"a",
"lattice",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L47-L79 |
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):
... | 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):
... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L82-L99 |
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)... | 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)... | [
"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",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L102-L121 |
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.phys... | 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.phys... | [
"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`... | [
"Return",
"a",
"set",
"of",
"constraints",
"that",
"define",
"Pauli",
"spin",
"operators",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L124-L163 |
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 o... | 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 o... | [
"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.ope... | [
"Generate",
"variables",
"that",
"behave",
"like",
"measurements",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L166-L181 |
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: substitut... | 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: substitut... | [
"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
... | [
"Return",
"a",
"set",
"of",
"constraints",
"that",
"define",
"projective",
"measurements",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L184-L216 |
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 `Probabi... | 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 `Probabi... | [
"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 ... | [
"Define",
"a",
"polynomial",
"using",
"measurements",
"and",
"an",
"I",
"matrix",
"describing",
"a",
"Bell",
"inequality",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L219-L260 |
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... | 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... | [
"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.HermitianOp... | [
"Correlators",
"between",
"the",
"probabilities",
"of",
"two",
"parties",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L263-L288 |
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_configu... | 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_configu... | [
"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-Gi... | [
"Get",
"the",
"maximum",
"violation",
"of",
"a",
"two",
"-",
"party",
"Bell",
"inequality",
"."
] | train | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L291-L316 |
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"')
... | 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"')
... | [
"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",
"."
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L67-L76 |
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
e... | 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
e... | [
"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"
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L635-L648 |
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_... | 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_... | [
"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"
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L651-L671 |
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
... | 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
... | [
"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.
>>> linespl... | [
"Returns",
"a",
"list",
"of",
"lines",
"split",
"on",
"the",
"last",
"possible",
"space",
"of",
"each",
"line",
"."
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L674-L705 |
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,... | 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,... | [
"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",
"."
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L707-L726 |
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... | 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... | [
"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"
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L728-L759 |
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... | 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... | [
"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"
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L761-L778 |
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
continu... | 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
continu... | [
"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",
"."
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L106-L120 |
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 (... | 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 (... | [
"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",
"."
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L144-L152 |
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)
... | 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)
... | [
"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",
"."
] | train | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L180-L220 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.