text_prompt
stringlengths 157
13.1k
| code_prompt
stringlengths 7
19.8k
⌀ |
---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(files, temp_folder):
"""Check isort errors in the code base. For the --quiet option, at least isort >= 4.1.1 is required. https://github.com/timothycrosley/isort/blob/develop/CHANGELOG.md#411 """ |
try:
import isort # NOQA
except ImportError:
return NO_ISORT_MSG
py_files = filter_python_files(files)
# --quiet because isort >= 4.1 outputs its logo in the console by default.
return bash('isort -df --quiet {0}'.format(' '.join(py_files))).value() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def run(files, temp_folder, arg=None):
"Check we're not committing to a blocked branch"
parser = get_parser()
argos = parser.parse_args(arg.split())
current_branch = bash('git symbolic-ref HEAD').value()
current_branch = current_branch.replace('refs/heads/', '').strip()
if current_branch in argos.branches:
return ("Branch '{0}' is blocked from being "
"committed to.".format(current_branch)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def run(files, temp_folder, arg=None):
"Check coding convention of the code base."
try:
import pylint
except ImportError:
return NO_PYLINT_MSG
# set default level of threshold
arg = arg or SCORE
py_files = filter_python_files(files)
if not py_files:
return False
str_py_files = " ".join(py_files)
cmd = "{0} {1}".format(PYLINT_CMD, str_py_files)
output = bash(cmd).value()
if 'rated' not in output:
return False
score = float(re.search("(\d.\d\d)/10", output).group(1))
if score >= float(arg):
return False
return ("Pylint appreciated your {0} as {1},"
"required threshold is {2}".format(PYLINT_TARGET, score, arg)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def run(files, temp_folder):
"Check to see if python files are py3 compatible"
errors = []
for py_file in filter_python_files(files):
# We only want to show errors if we CAN'T compile to py3.
# but we want to show all the errors at once.
b = bash('python3 -m py_compile {0}'.format(py_file))
if b.stderr:
b = bash('2to3-2.7 {file}'.format(file=py_file))
errors.append(b.value())
return "\n".join(errors) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def run(files, temp_folder):
"Check flake8 errors in the code base."
try:
import flake8 # NOQA
except ImportError:
return NO_FLAKE_MSG
try:
from flake8.engine import get_style_guide
except ImportError:
# We're on a new version of flake8
from flake8.api.legacy import get_style_guide
py_files = filter_python_files(files)
if not py_files:
return
DEFAULT_CONFIG = join(temp_folder, get_config_file())
with change_folder(temp_folder):
flake8_style = get_style_guide(config_file=DEFAULT_CONFIG)
out, err = StringIO(), StringIO()
with redirected(out, err):
flake8_style.check_files(py_files)
return out.getvalue().strip() + err.getvalue().strip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def tictactoe(w, i, player, opponent, grid=None):
"Put two strategies to a classic battle of wits."
grid = grid or empty_grid
while True:
w.render_to_terminal(w.array_from_text(view(grid)))
if is_won(grid):
print(whose_move(grid), "wins.")
break
if not successors(grid):
print("A draw.")
break
grid = player(w, i, grid)
player, opponent = opponent, player |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def memo(f):
"Return a function like f that remembers and reuses results of past calls."
table = {}
def memo_f(*args):
try:
return table[args]
except KeyError:
table[args] = value = f(*args)
return value
return memo_f |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def human_play(w, i, grid):
"Just ask for a move."
plaint = ''
prompt = whose_move(grid) + " move? [1-9] "
while True:
w.render_to_terminal(w.array_from_text(view(grid)
+ '\n\n' + plaint + prompt))
key = c = i.next()
try:
move = int(key)
except ValueError:
pass
else:
if 1 <= move <= 9:
successor = apply_move(grid, from_human_move(move))
if successor: return successor
plaint = ("Hey, that's illegal. Give me one of these digits:\n\n"
+ (grid_format
% tuple(move if apply_move(grid, from_human_move(move)) else '-'
for move in range(1, 10))
+ '\n\n')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def max_play(w, i, grid):
"Play like Spock, except breaking ties by drunk_value."
return min(successors(grid),
key=lambda succ: (evaluate(succ), drunk_value(succ))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def drunk_value(grid):
"Return the expected value to the player if both players play at random."
if is_won(grid): return -1
succs = successors(grid)
return -average(map(drunk_value, succs)) if succs else 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_sdpa_out(filename, solutionmatrix=False, status=False, sdp=None):
"""Helper function to parse the output file of SDPA. :param filename: The name of the SDPA output file. :type filename: str. :param solutionmatrix: Optional parameter for retrieving the solution. :type solutionmatrix: bool. :param status: Optional parameter for retrieving the status. :type status: bool. :param sdp: Optional parameter to add the solution to a relaxation. :type sdp: sdp. :returns: tuple of two floats and optionally two lists of `numpy.array` and a status string """ |
primal = None
dual = None
x_mat = None
y_mat = None
status_string = None
with open(filename, 'r') as file_:
for line in file_:
if line.find("objValPrimal") > -1:
primal = float((line.split())[2])
if line.find("objValDual") > -1:
dual = float((line.split())[2])
if solutionmatrix:
if line.find("xMat =") > -1:
x_mat = parse_solution_matrix(file_)
if line.find("yMat =") > -1:
y_mat = parse_solution_matrix(file_)
if line.find("phase.value") > -1:
if line.find("pdOPT") > -1:
status_string = 'optimal'
elif line.find("pFEAS") > -1:
status_string = 'primal feasible'
elif line.find("pdFEAS") > -1:
status_string = 'primal-dual feasible'
elif line.find("dFEAS") > -1:
status_string = 'dual feasible'
elif line.find("INF") > -1:
status_string = 'infeasible'
elif line.find("UNBD") > -1:
status_string = 'unbounded'
else:
status_string = 'unknown'
for var in [primal, dual, status_string]:
if var is None:
status_string = 'invalid'
break
if solutionmatrix:
for var in [x_mat, y_mat]:
if var is None:
status_string = 'invalid'
break
if sdp is not None:
sdp.primal = primal
sdp.dual = dual
sdp.x_mat = x_mat
sdp.y_mat = y_mat
sdp.status = status_string
if solutionmatrix and status:
return primal, dual, x_mat, y_mat, status_string
elif solutionmatrix:
return primal, dual, x_mat, y_mat
elif status:
return primal, dual, status_string
else:
return primal, dual |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve_with_sdpa(sdp, solverparameters=None):
"""Helper function to write out the SDP problem to a temporary file, call the solver, and parse the output. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`. :param solverparameters: Optional parameters to SDPA. :type solverparameters: dict of str. :returns: tuple of float and list -- the primal and dual solution of the SDP, respectively, and a status string. """ |
solverexecutable = detect_sdpa(solverparameters)
if solverexecutable is None:
raise OSError("SDPA is not in the path or the executable provided is" +
" not correct")
primal, dual = 0, 0
tempfile_ = tempfile.NamedTemporaryFile()
tmp_filename = tempfile_.name
tempfile_.close()
tmp_dats_filename = tmp_filename + ".dat-s"
tmp_out_filename = tmp_filename + ".out"
write_to_sdpa(sdp, tmp_dats_filename)
command_line = [solverexecutable, "-ds", tmp_dats_filename,
"-o", tmp_out_filename]
if solverparameters is not None:
for key, value in list(solverparameters.items()):
if key == "executable":
continue
elif key == "paramsfile":
command_line.extend(["-p", value])
else:
raise ValueError("Unknown parameter for SDPA: " + key)
if sdp.verbose < 1:
with open(os.devnull, "w") as fnull:
call(command_line, stdout=fnull, stderr=fnull)
else:
call(command_line)
primal, dual, x_mat, y_mat, status = read_sdpa_out(tmp_out_filename, True,
True)
if sdp.verbose < 2:
os.remove(tmp_dats_filename)
os.remove(tmp_out_filename)
return primal+sdp.constant_term, \
dual+sdp.constant_term, x_mat, y_mat, status |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_row_to_sdpa_index(block_struct, row_offsets, row):
"""Helper function to map to sparse SDPA index values. """ |
block_index = bisect_left(row_offsets[1:], row + 1)
width = block_struct[block_index]
row = row - row_offsets[block_index]
i, j = divmod(row, width)
return block_index, i, j |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_to_human_readable(sdp):
"""Convert the SDP relaxation to a human-readable format. :param sdp: The SDP relaxation to write. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: tuple of the objective function in a string and a matrix of strings as the symbolic representation of the moment matrix """ |
objective = ""
indices_in_objective = []
for i, tmp in enumerate(sdp.obj_facvar):
candidates = [key for key, v in
sdp.monomial_index.items() if v == i+1]
if len(candidates) > 0:
monomial = convert_monomial_to_string(candidates[0])
else:
monomial = ""
if tmp > 0:
objective += "+"+str(tmp)+monomial
indices_in_objective.append(i)
elif tmp < 0:
objective += str(tmp)+monomial
indices_in_objective.append(i)
matrix_size = 0
cumulative_sum = 0
row_offsets = [0]
block_offset = [0]
for bs in sdp.block_struct:
matrix_size += abs(bs)
cumulative_sum += bs ** 2
row_offsets.append(cumulative_sum)
block_offset.append(matrix_size)
matrix = []
for i in range(matrix_size):
matrix_line = ["0"] * matrix_size
matrix.append(matrix_line)
for row in range(len(sdp.F.rows)):
if len(sdp.F.rows[row]) > 0:
col_index = 0
for k in sdp.F.rows[row]:
value = sdp.F.data[row][col_index]
col_index += 1
block_index, i, j = convert_row_to_sdpa_index(
sdp.block_struct, row_offsets, row)
candidates = [key for key, v in
sdp.monomial_index.items()
if v == k]
if len(candidates) > 0:
monomial = convert_monomial_to_string(candidates[0])
else:
monomial = ""
offset = block_offset[block_index]
if matrix[offset+i][offset+j] == "0":
matrix[offset+i][offset+j] = ("%s%s" % (value, monomial))
else:
if value.real > 0:
matrix[offset+i][offset+j] += ("+%s%s" % (value,
monomial))
else:
matrix[offset+i][offset+j] += ("%s%s" % (value,
monomial))
return objective, matrix |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_to_human_readable(sdp, filename):
"""Write the SDP relaxation to a human-readable format. :param sdp: The SDP relaxation to write. :type sdp: :class:`ncpol2sdpa.sdp`. :param filename: The name of the file. :type filename: str. """ |
objective, matrix = convert_to_human_readable(sdp)
f = open(filename, 'w')
f.write("Objective:" + objective + "\n")
for matrix_line in matrix:
f.write(str(list(matrix_line)).replace('[', '').replace(']', '')
.replace('\'', ''))
f.write('\n')
f.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _wait_for_read_ready_or_timeout(self, timeout):
"""Returns tuple of whether stdin is ready to read and an event. If an event is returned, that event is more pressing than reading bytes on stdin to create a keyboard input event. If stdin is ready, either there are bytes to read or a SIGTSTP triggered by dsusp has been received""" |
remaining_timeout = timeout
t0 = time.time()
while True:
try:
(rs, _, _) = select.select(
[self.in_stream.fileno()] + self.readers,
[], [], remaining_timeout)
if not rs:
return False, None
r = rs[0] # if there's more than one, get it in the next loop
if r == self.in_stream.fileno():
return True, None
else:
os.read(r, 1024)
if self.queued_interrupting_events:
return False, self.queued_interrupting_events.pop(0)
elif remaining_timeout is not None:
remaining_timeout = max(0, t0 + timeout - time.time())
continue
else:
continue
except select.error:
if self.sigints:
return False, self.sigints.pop()
if remaining_timeout is not None:
remaining_timeout = max(timeout - (time.time() - t0), 0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _nonblocking_read(self):
"""Returns the number of characters read and adds them to self.unprocessed_bytes""" |
with Nonblocking(self.in_stream):
if PY3:
try:
data = os.read(self.in_stream.fileno(), READ_SIZE)
except BlockingIOError:
return 0
if data:
self.unprocessed_bytes.extend(data[i:i+1] for i in range(len(data)))
return len(data)
else:
return 0
else:
try:
data = os.read(self.in_stream.fileno(), READ_SIZE)
except OSError:
return 0
else:
self.unprocessed_bytes.extend(data)
return len(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def event_trigger(self, event_type):
"""Returns a callback that creates events. Returned callback function will add an event of type event_type to a queue which will be checked the next time an event is requested.""" |
def callback(**kwargs):
self.queued_events.append(event_type(**kwargs))
return callback |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scheduled_event_trigger(self, event_type):
"""Returns a callback that schedules events for the future. Returned callback function will add an event of type event_type to a queue which will be checked the next time an event is requested.""" |
def callback(when, **kwargs):
self.queued_scheduled_events.append((when, event_type(when=when, **kwargs)))
return callback |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def threadsafe_event_trigger(self, event_type):
"""Returns a callback to creates events, interrupting current event requests. Returned callback function will create an event of type event_type which will interrupt an event request if one is concurrently occuring, otherwise adding the event to a queue that will be checked on the next event request.""" |
readfd, writefd = os.pipe()
self.readers.append(readfd)
def callback(**kwargs):
self.queued_interrupting_events.append(event_type(**kwargs)) #TODO use a threadsafe queue for this
logger.warning('added event to events list %r', self.queued_interrupting_events)
os.write(writefd, b'interrupting event!')
return callback |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve_sdp(sdp, solver=None, solverparameters=None):
"""Call a solver on the SDP relaxation. Upon successful solution, it returns the primal and dual objective values along with the solution matrices. :param sdpRelaxation: The SDP relaxation to be solved. :type sdpRelaxation: :class:`ncpol2sdpa.SdpRelaxation`. :param solver: The solver to be called, either `None`, "sdpa", "mosek", "cvxpy", "scs", or "cvxopt". The default is `None`, which triggers autodetect. :type solver: str. :param solverparameters: Parameters to be passed to the solver. Actual options depend on the solver: SDPA: - `"executable"`: Specify the executable for SDPA. E.g., `"executable":"/usr/local/bin/sdpa"`, or `"executable":"sdpa_gmp"` - `"paramsfile"`: Specify the parameter file Mosek: Refer to the Mosek documentation. All arguments are passed on. Cvxopt: Refer to the PICOS documentation. All arguments are passed on. Cvxpy: Refer to the Cvxpy documentation. All arguments are passed on. SCS: Refer to the Cvxpy documentation. All arguments are passed on. :type solverparameters: dict of str. :returns: tuple of the primal and dual optimum, and the solutions for the primal and dual. :rtype: (float, float, list of `numpy.array`, list of `numpy.array`) """ |
solvers = autodetect_solvers(solverparameters)
solver = solver.lower() if solver is not None else solver
if solvers == []:
raise Exception("Could not find any SDP solver. Please install SDPA," +
" Mosek, Cvxpy, or Picos with Cvxopt")
elif solver is not None and solver not in solvers:
print("Available solvers: " + str(solvers))
if solver == "cvxopt":
try:
import cvxopt
except ImportError:
pass
else:
raise Exception("Cvxopt is detected, but Picos is not. "
"Please install Picos to use Cvxopt")
raise Exception("Could not detect requested " + solver)
elif solver is None:
solver = solvers[0]
primal, dual, x_mat, y_mat, status = None, None, None, None, None
tstart = time.time()
if solver == "sdpa":
primal, dual, x_mat, y_mat, status = \
solve_with_sdpa(sdp, solverparameters)
elif solver == "cvxpy":
primal, dual, x_mat, y_mat, status = \
solve_with_cvxpy(sdp, solverparameters)
elif solver == "scs":
if solverparameters is None:
solverparameters_ = {"solver": "SCS"}
else:
solverparameters_ = solverparameters.copy()
solverparameters_["solver"] = "SCS"
primal, dual, x_mat, y_mat, status = \
solve_with_cvxpy(sdp, solverparameters_)
elif solver == "mosek":
primal, dual, x_mat, y_mat, status = \
solve_with_mosek(sdp, solverparameters)
elif solver == "cvxopt":
primal, dual, x_mat, y_mat, status = \
solve_with_cvxopt(sdp, solverparameters)
# We have to compensate for the equality constraints
for constraint in sdp.constraints[sdp._n_inequalities:]:
idx = sdp._constraint_to_block_index[constraint]
sdp._constraint_to_block_index[constraint] = (idx[0],)
else:
raise Exception("Unkown solver: " + solver)
sdp.solution_time = time.time() - tstart
sdp.primal = primal
sdp.dual = dual
sdp.x_mat = x_mat
sdp.y_mat = y_mat
sdp.status = status
return primal, dual, x_mat, y_mat |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_sos_decomposition(sdp, y_mat=None, threshold=0.0):
"""Given a solution of the dual problem, it returns the SOS decomposition. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`. :param y_mat: Optional parameter providing the dual solution of the moment matrix. If not provided, the solution is extracted from the sdp object. :type y_mat: :class:`numpy.array`. :param threshold: Optional parameter for specifying the threshold value below which the eigenvalues and entries of the eigenvectors are disregarded. :type threshold: float. :rtype: list of :class:`sympy.core.exp.Expr`. """ |
if len(sdp.monomial_sets) != 1:
raise Exception("Cannot automatically match primal and dual " +
"variables.")
elif len(sdp.y_mat[1:]) != len(sdp.constraints):
raise Exception("Cannot automatically match constraints with blocks " +
"in the dual solution.")
elif sdp.status == "unsolved" and y_mat is None:
raise Exception("The SDP relaxation is unsolved and dual solution " +
"is not provided!")
elif sdp.status != "unsolved" and y_mat is None:
y_mat = sdp.y_mat
sos = []
for y_mat_block in y_mat:
term = 0
vals, vecs = np.linalg.eigh(y_mat_block)
for j, val in enumerate(vals):
if val < -0.001:
raise Exception("Large negative eigenvalue: " + val +
". Matrix cannot be positive.")
elif val > 0:
sub_term = 0
for i, entry in enumerate(vecs[:, j]):
sub_term += entry * sdp.monomial_sets[0][i]
term += val * sub_term**2
term = expand(term)
new_term = 0
if term.is_Mul:
elements = [term]
else:
elements = term.as_coeff_mul()[1][0].as_coeff_add()[1]
for element in elements:
_, coeff = separate_scalar_factor(element)
if abs(coeff) > threshold:
new_term += element
sos.append(new_term)
return sos |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_dual_value(sdp, monomial, blocks=None):
"""Given a solution of the dual problem and a monomial, it returns the inner product of the corresponding coefficient matrix and the dual solution. It can be restricted to certain blocks. :param sdp: The SDP relaxation. :type sdp: :class:`ncpol2sdpa.sdp`. :param monomial: The monomial for which the value is requested. :type monomial: :class:`sympy.core.exp.Expr`. :param monomial: The monomial for which the value is requested. :type monomial: :class:`sympy.core.exp.Expr`. :param blocks: Optional parameter to specify the blocks to be included. :type blocks: list of `int`. :returns: The value of the monomial in the solved relaxation. :rtype: float. """ |
if sdp.status == "unsolved":
raise Exception("The SDP relaxation is unsolved!")
if blocks is None:
blocks = [i for i, _ in enumerate(sdp.block_struct)]
if is_number_type(monomial):
index = 0
else:
index = sdp.monomial_index[monomial]
row_offsets = [0]
cumulative_sum = 0
for block_size in sdp.block_struct:
cumulative_sum += block_size ** 2
row_offsets.append(cumulative_sum)
result = 0
for row in range(len(sdp.F.rows)):
if len(sdp.F.rows[row]) > 0:
col_index = 0
for k in sdp.F.rows[row]:
if k != index:
continue
value = sdp.F.data[row][col_index]
col_index += 1
block_index, i, j = convert_row_to_sdpa_index(
sdp.block_struct, row_offsets, row)
if block_index in blocks:
result += -value*sdp.y_mat[block_index][i][j]
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_module(self, fullname):
""" load_module is always called with the same argument as finder's find_module, see "How Import Works" """ |
mod = super(JsonLoader, self).load_module(fullname)
try:
with codecs.open(self.cfg_file, 'r', 'utf-8') as f:
mod.__dict__.update(json.load(f))
except ValueError:
# if raise here, traceback will contain ValueError
self.e = "ValueError"
self.err_msg = sys.exc_info()[1]
if self.e == "ValueError":
err_msg = "\nJson file not valid: "
err_msg += self.cfg_file + '\n'
err_msg += str(self.err_msg)
raise InvalidJsonError(err_msg)
return mod |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tick(self):
"""Returns a message to be displayed if game is over, else None""" |
for npc in self.npcs:
self.move_entity(npc, *npc.towards(self.player))
for entity1, entity2 in itertools.combinations(self.entities, 2):
if (entity1.x, entity1.y) == (entity2.x, entity2.y):
if self.player in (entity1, entity2):
return 'you lost on turn %d' % self.turn
entity1.die()
entity2.die()
if all(npc.speed == 0 for npc in self.npcs):
return 'you won on turn %d' % self.turn
self.turn += 1
if self.turn % 20 == 0:
self.player.speed = max(1, self.player.speed - 1)
self.player.display = on_blue(green(bold(unicode_str(self.player.speed)))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_cursor_vertical_diff(self):
"""Returns the how far down the cursor moved since last render. Note: If another get_cursor_vertical_diff call is already in progress, immediately returns zero. (This situation is likely if get_cursor_vertical_diff is called from a SIGWINCH signal handler, since sigwinches can happen in rapid succession and terminal emulators seem not to respond to cursor position queries before the next sigwinch occurs.) """ |
# Probably called by a SIGWINCH handler, and therefore
# will do cursor querying until a SIGWINCH doesn't happen during
# the query. Calls to the function from a signal handler COULD STILL
# HAPPEN out of order -
# they just can't interrupt the actual cursor query.
if self.in_get_cursor_diff:
self.another_sigwinch = True
return 0
cursor_dy = 0
while True:
self.in_get_cursor_diff = True
self.another_sigwinch = False
cursor_dy += self._get_cursor_vertical_diff_once()
self.in_get_cursor_diff = False
if not self.another_sigwinch:
return cursor_dy |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_cursor_vertical_diff_once(self):
"""Returns the how far down the cursor moved.""" |
old_top_usable_row = self.top_usable_row
row, col = self.get_cursor_position()
if self._last_cursor_row is None:
cursor_dy = 0
else:
cursor_dy = row - self._last_cursor_row
logger.info('cursor moved %d lines down' % cursor_dy)
while self.top_usable_row > -1 and cursor_dy > 0:
self.top_usable_row += 1
cursor_dy -= 1
while self.top_usable_row > 1 and cursor_dy < 0:
self.top_usable_row -= 1
cursor_dy += 1
logger.info('top usable row changed from %d to %d', old_top_usable_row,
self.top_usable_row)
logger.info('returning cursor dy of %d from curtsies' % cursor_dy)
self._last_cursor_row = row
return cursor_dy |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_to_terminal(self, array, cursor_pos=(0, 0)):
"""Renders array to terminal, returns the number of lines scrolled offscreen Returns: Number of times scrolled Args: array (FSArray):
Grid of styled characters to be rendered. If array received is of width too small, render it anyway if array received is of width too large, render it anyway if array received is of height too small, render it anyway if array received is of height too large, render it, scroll down, and render the rest of it, then return how much we scrolled down """ |
for_stdout = self.fmtstr_to_stdout_xform()
# caching of write and tc (avoiding the self. lookups etc) made
# no significant performance difference here
if not self.hide_cursor:
self.write(self.t.hide_cursor)
# TODO race condition here?
height, width = self.t.height, self.t.width
if (height != self._last_rendered_height or
width != self._last_rendered_width):
self.on_terminal_size_change(height, width)
current_lines_by_row = {}
rows_for_use = list(range(self.top_usable_row, height))
# rows which we have content for and don't require scrolling
# TODO rename shared
shared = min(len(array), len(rows_for_use))
for row, line in zip(rows_for_use[:shared], array[:shared]):
current_lines_by_row[row] = line
if line == self._last_lines_by_row.get(row, None):
continue
self.write(self.t.move(row, 0))
self.write(for_stdout(line))
if len(line) < width:
self.write(self.t.clear_eol)
# rows already on screen that we don't have content for
rest_of_lines = array[shared:]
rest_of_rows = rows_for_use[shared:]
for row in rest_of_rows: # if array too small
if self._last_lines_by_row and row not in self._last_lines_by_row:
continue
self.write(self.t.move(row, 0))
self.write(self.t.clear_eol)
# TODO probably not necessary - is first char cleared?
self.write(self.t.clear_bol)
current_lines_by_row[row] = None
# lines for which we need to scroll down to render
offscreen_scrolls = 0
for line in rest_of_lines: # if array too big
self.scroll_down()
if self.top_usable_row > 0:
self.top_usable_row -= 1
else:
offscreen_scrolls += 1
current_lines_by_row = dict(
(k - 1, v) for k, v in current_lines_by_row.items()
)
logger.debug('new top_usable_row: %d' % self.top_usable_row)
# since scrolling moves the cursor
self.write(self.t.move(height - 1, 0))
self.write(for_stdout(line))
current_lines_by_row[height - 1] = line
logger.debug(
'lines in last lines by row: %r' % self._last_lines_by_row.keys()
)
logger.debug(
'lines in current lines by row: %r' % current_lines_by_row.keys()
)
self._last_cursor_row = max(
0, cursor_pos[0] - offscreen_scrolls + self.top_usable_row
)
self._last_cursor_column = cursor_pos[1]
self.write(
self.t.move(self._last_cursor_row, self._last_cursor_column)
)
self._last_lines_by_row = current_lines_by_row
if not self.hide_cursor:
self.write(self.t.normal_cursor)
return offscreen_scrolls |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve(self, solver=None, solverparameters=None):
"""Call a solver on the SDP relaxation. Upon successful solution, it returns the primal and dual objective values along with the solution matrices. It also sets these values in the `sdpRelaxation` object, along with some status information. :param sdpRelaxation: The SDP relaxation to be solved. :type sdpRelaxation: :class:`ncpol2sdpa.SdpRelaxation`. :param solver: The solver to be called, either `None`, "sdpa", "mosek", "cvxpy", "scs", or "cvxopt". The default is `None`, which triggers autodetect. :type solver: str. :param solverparameters: Parameters to be passed to the solver. Actual options depend on the solver: SDPA: - `"executable"`: Specify the executable for SDPA. E.g., `"executable":"/usr/local/bin/sdpa"`, or `"executable":"sdpa_gmp"` - `"paramsfile"`: Specify the parameter file Mosek: Refer to the Mosek documentation. All arguments are passed on. Cvxopt: Refer to the PICOS documentation. All arguments are passed on. Cvxpy: Refer to the Cvxpy documentation. All arguments are passed on. SCS: Refer to the Cvxpy documentation. All arguments are passed on. :type solverparameters: dict of str. """ |
if self.F is None:
raise Exception("Relaxation is not generated yet. Call "
"'SdpRelaxation.get_relaxation' first")
solve_sdp(self, solver, solverparameters) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_index_of_monomial(self, element, enablesubstitution=True, daggered=False):
"""Returns the index of a monomial. """ |
result = []
processed_element, coeff1 = separate_scalar_factor(element)
if processed_element in self.moment_substitutions:
r = self._get_index_of_monomial(self.moment_substitutions[processed_element], enablesubstitution)
return [(k, coeff*coeff1) for k, coeff in r]
if enablesubstitution:
processed_element = \
apply_substitutions(processed_element, self.substitutions,
self.pure_substitution_rules)
# Given the monomial, we need its mapping L_y(w) to push it into
# a corresponding constraint matrix
if is_number_type(processed_element):
return [(0, coeff1)]
elif processed_element.is_Add:
monomials = processed_element.args
else:
monomials = [processed_element]
for monomial in monomials:
monomial, coeff2 = separate_scalar_factor(monomial)
coeff = coeff1*coeff2
if is_number_type(monomial):
result.append((0, coeff))
continue
k = -1
if monomial != 0:
if monomial.as_coeff_Mul()[0] < 0:
monomial = -monomial
coeff = -1.0 * coeff
try:
new_element = self.moment_substitutions[monomial]
r = self._get_index_of_monomial(self.moment_substitutions[new_element], enablesubstitution)
result += [(k, coeff*coeff3) for k, coeff3 in r]
except KeyError:
try:
k = self.monomial_index[monomial]
result.append((k, coeff))
except KeyError:
if not daggered:
dag_result = self._get_index_of_monomial(monomial.adjoint(),
daggered=True)
result += [(k, coeff0*coeff) for k, coeff0 in dag_result]
else:
raise RuntimeError("The requested monomial " +
str(monomial) + " could not be found.")
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __push_facvar_sparse(self, polynomial, block_index, row_offset, i, j):
"""Calculate the sparse vector representation of a polynomial and pushes it to the F structure. """ |
width = self.block_struct[block_index - 1]
# Preprocess the polynomial for uniform handling later
# DO NOT EXPAND THE POLYNOMIAL HERE!!!!!!!!!!!!!!!!!!!
# The simplify_polynomial bypasses the problem.
# Simplifying here will trigger a bug in SymPy related to
# the powers of daggered variables.
# polynomial = polynomial.expand()
if is_number_type(polynomial) or polynomial.is_Mul:
elements = [polynomial]
else:
elements = polynomial.as_coeff_mul()[1][0].as_coeff_add()[1]
# Identify its constituent monomials
for element in elements:
results = self._get_index_of_monomial(element)
# k identifies the mapped value of a word (monomial) w
for (k, coeff) in results:
if k > -1 and coeff != 0:
self.F[row_offset + i * width + j, k] += coeff |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __remove_equalities(self, equalities, momentequalities):
"""Attempt to remove equalities by solving the linear equations. """ |
A = self.__process_equalities(equalities, momentequalities)
if min(A.shape != np.linalg.matrix_rank(A)):
print("Warning: equality constraints are linearly dependent! "
"Results might be incorrect.", file=sys.stderr)
if A.shape[0] == 0:
return
c = np.array(self.obj_facvar)
if self.verbose > 0:
print("QR decomposition...")
Q, R = np.linalg.qr(A[:, 1:].T, mode='complete')
n = np.max(np.nonzero(np.sum(np.abs(R), axis=1) > 0)) + 1
x = np.dot(Q[:, :n], np.linalg.solve(np.transpose(R[:n, :]), -A[:, 0]))
self._new_basis = lil_matrix(Q[:, n:])
# Transforming the objective function
self._original_obj_facvar = self.obj_facvar
self._original_constant_term = self.constant_term
self.obj_facvar = self._new_basis.T.dot(c)
self.constant_term += c.dot(x)
x = np.append(1, x)
# Transforming the moment matrix and localizing matrices
new_F = lil_matrix((self.F.shape[0], self._new_basis.shape[1] + 1))
new_F[:, 0] = self.F[:, :self.n_vars+1].dot(x).reshape((new_F.shape[0],
1))
new_F[:, 1:] = self.F[:, 1:self.n_vars+1].\
dot(self._new_basis)
self._original_F = self.F
self.F = new_F
self.n_vars = self._new_basis.shape[1]
if self.verbose > 0:
print("Number of variables after solving the linear equations: %d"
% self.n_vars) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_constraints(self, inequalities=None, equalities=None, momentinequalities=None, momentequalities=None, block_index=0, removeequalities=False):
"""Process the constraints and generate localizing matrices. Useful only if the moment matrix already exists. Call it if you want to replace your constraints. The number of the respective types of constraints and the maximum degree of each constraint must remain the same. :param inequalities: Optional parameter to list inequality constraints. :type inequalities: list of :class:`sympy.core.exp.Expr`. :param equalities: Optional parameter to list equality constraints. :type equalities: list of :class:`sympy.core.exp.Expr`. :param momentinequalities: Optional parameter of inequalities defined on moments. :type momentinequalities: list of :class:`sympy.core.exp.Expr`. :param momentequalities: Optional parameter of equalities defined on moments. :type momentequalities: list of :class:`sympy.core.exp.Expr`. :param removeequalities: Optional parameter to attempt removing the equalities by solving the linear equations. :param removeequalities: Optional parameter to attempt removing the equalities by solving the linear equations. :type removeequalities: bool. """ |
self.status = "unsolved"
if block_index == 0:
if self._original_F is not None:
self.F = self._original_F
self.obj_facvar = self._original_obj_facvar
self.constant_term = self._original_constant_term
self.n_vars = len(self.obj_facvar)
self._new_basis = None
block_index = self.constraint_starting_block
self.__wipe_F_from_constraints()
self.constraints = flatten([inequalities])
self._constraint_to_block_index = {}
for constraint in self.constraints:
self._constraint_to_block_index[constraint] = (block_index, )
block_index += 1
if momentinequalities is not None:
for mineq in momentinequalities:
self.constraints.append(mineq)
self._constraint_to_block_index[mineq] = (block_index, )
block_index += 1
if not (removeequalities or equalities is None):
# Equalities are converted to pairs of inequalities
for k, equality in enumerate(equalities):
if equality.is_Relational:
equality = convert_relational(equality)
self.constraints.append(equality)
self.constraints.append(-equality)
ln = len(self.localizing_monomial_sets[block_index-
self.constraint_starting_block])
self._constraint_to_block_index[equality] = (block_index,
block_index+ln*(ln+1)//2)
block_index += ln*(ln+1)
if momentequalities is not None and not removeequalities:
for meq in momentequalities:
self.constraints += [meq, flip_sign(meq)]
self._constraint_to_block_index[meq] = (block_index,
block_index+1)
block_index += 2
block_index = self.constraint_starting_block
self.__process_inequalities(block_index)
if removeequalities:
self.__remove_equalities(equalities, momentequalities) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_dual(self, constraint, ymat=None):
"""Given a solution of the dual problem and a constraint of any type, it returns the corresponding block in the dual solution. If it is an equality constraint that was converted to a pair of inequalities, it returns a two-tuple of the matching dual blocks. :param constraint: The constraint. :type index: `sympy.core.exp.Expr` :param y_mat: Optional parameter providing the dual solution of the SDP. If not provided, the solution is extracted from the sdpRelaxation object. :type y_mat: :class:`numpy.array`. :returns: The corresponding block in the dual solution. :rtype: :class:`numpy.array` or a tuple thereof. """ |
if not isinstance(constraint, Expr):
raise Exception("Not a monomial or polynomial!")
elif self.status == "unsolved" and ymat is None:
raise Exception("SDP relaxation is not solved yet!")
elif ymat is None:
ymat = self.y_mat
index = self._constraint_to_block_index.get(constraint)
if index is None:
raise Exception("Constraint is not in the dual!")
if len(index) == 2:
return ymat[index[0]], self.y_mat[index[1]]
else:
return ymat[index[0]] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_relaxation(self, level, objective=None, inequalities=None, equalities=None, substitutions=None, momentinequalities=None, momentequalities=None, momentsubstitutions=None, removeequalities=False, extramonomials=None, extramomentmatrices=None, extraobjexpr=None, localizing_monomials=None, chordal_extension=False):
"""Get the SDP relaxation of a noncommutative polynomial optimization problem. :param level: The level of the relaxation. The value -1 will skip automatic monomial generation and use only the monomials supplied by the option `extramonomials`. :type level: int. :param obj: Optional parameter to describe the objective function. :type obj: :class:`sympy.core.exp.Expr`. :param inequalities: Optional parameter to list inequality constraints. :type inequalities: list of :class:`sympy.core.exp.Expr`. :param equalities: Optional parameter to list equality constraints. :type equalities: list of :class:`sympy.core.exp.Expr`. :param substitutions: Optional parameter containing monomials that can be replaced (e.g., idempotent variables). :type substitutions: dict of :class:`sympy.core.exp.Expr`. :param momentinequalities: Optional parameter of inequalities defined on moments. :type momentinequalities: list of :class:`sympy.core.exp.Expr`. :param momentequalities: Optional parameter of equalities defined on moments. :type momentequalities: list of :class:`sympy.core.exp.Expr`. :param momentsubstitutions: Optional parameter containing moments that can be replaced. :type momentsubstitutions: dict of :class:`sympy.core.exp.Expr`. :param removeequalities: Optional parameter to attempt removing the equalities by solving the linear equations. :type removeequalities: bool. :param extramonomials: Optional paramter of monomials to be included, on top of the requested level of relaxation. :type extramonomials: list of :class:`sympy.core.exp.Expr`. :param extramomentmatrices: Optional paramter of duplicating or adding moment matrices. A new moment matrix can be unconstrained (""), a copy of the first one ("copy"), and satisfying a partial positivity constraint ("ppt"). Each new moment matrix is requested as a list of string of these options. For instance, adding a single new moment matrix as a copy of the first would be ``extramomentmatrices=[["copy"]]``. :type extramomentmatrices: list of list of str. :param extraobjexpr: Optional parameter of a string expression of a linear combination of moment matrix elements to be included in the objective function. :type extraobjexpr: str. :param localizing_monomials: Optional parameter to specify sets of localizing monomials for each constraint. The internal order of constraints is inequalities first, followed by the equalities. If the parameter is specified, but for a certain constraint the automatic localization is requested, leave None in its place in this parameter. :type localizing_monomials: list of list of `sympy.core.exp.Expr`. :param chordal_extension: Optional parameter to request a sparse chordal extension. :type chordal_extension: bool. """ |
if self.level < -1:
raise Exception("Invalid level of relaxation")
self.level = level
if substitutions is None:
self.substitutions = {}
else:
self.substitutions = substitutions
for lhs, rhs in substitutions.items():
if not is_pure_substitution_rule(lhs, rhs):
self.pure_substitution_rules = False
if iscomplex(lhs) or iscomplex(rhs):
self.complex_matrix = True
if momentsubstitutions is not None:
self.moment_substitutions = momentsubstitutions.copy()
# If we have a real-valued problem, the moment matrix is symmetric
# and moment substitutions also apply to the conjugate monomials
if not self.complex_matrix:
for key, val in self.moment_substitutions.copy().items():
adjoint_monomial = apply_substitutions(key.adjoint(),
self.substitutions)
self.moment_substitutions[adjoint_monomial] = val
if chordal_extension:
self.variables = find_variable_cliques(self.variables, objective,
inequalities, equalities,
momentinequalities,
momentequalities)
self.__generate_monomial_sets(extramonomials)
self.localizing_monomial_sets = localizing_monomials
# Figure out basic structure of the SDP
self._calculate_block_structure(inequalities, equalities,
momentinequalities, momentequalities,
extramomentmatrices,
removeequalities)
self._estimate_n_vars()
if extramomentmatrices is not None:
for parameters in extramomentmatrices:
copy = False
for parameter in parameters:
if parameter == "copy":
copy = True
if copy:
self.n_vars += self.n_vars + 1
else:
self.n_vars += (self.block_struct[0]**2)/2
if self.complex_matrix:
dtype = np.complex128
else:
dtype = np.float64
self.F = lil_matrix((sum([bs**2 for bs in self.block_struct]),
self.n_vars + 1), dtype=dtype)
if self.verbose > 0:
print(('Estimated number of SDP variables: %d' % self.n_vars))
print('Generating moment matrix...')
# Generate moment matrices
new_n_vars, block_index = self.__add_parameters()
self._time0 = time.time()
new_n_vars, block_index = \
self._generate_all_moment_matrix_blocks(new_n_vars, block_index)
if extramomentmatrices is not None:
new_n_vars, block_index = \
self.__add_extra_momentmatrices(extramomentmatrices,
new_n_vars, block_index)
# The initial estimate for the size of F was overly generous.
self.n_vars = new_n_vars
# We don't correct the size of F, because that would trigger
# memory copies, and extra columns in lil_matrix are free anyway.
# self.F = self.F[:, 0:self.n_vars + 1]
if self.verbose > 0:
print(('Reduced number of SDP variables: %d' % self.n_vars))
# Objective function
self.set_objective(objective, extraobjexpr)
# Process constraints
self.constraint_starting_block = block_index
self.process_constraints(inequalities, equalities, momentinequalities,
momentequalities, block_index,
removeequalities) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatten(lol):
"""Flatten a list of lists to a list. :param lol: A list of lists in arbitrary depth. :type lol: list of list. :returns: flat list of elements. """ |
new_list = []
for element in lol:
if element is None:
continue
elif not isinstance(element, list) and not isinstance(element, tuple):
new_list.append(element)
elif len(element) > 0:
new_list.extend(flatten(element))
return new_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def simplify_polynomial(polynomial, monomial_substitutions):
"""Simplify a polynomial for uniform handling later. """ |
if isinstance(polynomial, (int, float, complex)):
return polynomial
polynomial = (1.0 * polynomial).expand(mul=True,
multinomial=True)
if is_number_type(polynomial):
return polynomial
if polynomial.is_Mul:
elements = [polynomial]
else:
elements = polynomial.as_coeff_mul()[1][0].as_coeff_add()[1]
new_polynomial = 0
# Identify its constituent monomials
for element in elements:
monomial, coeff = separate_scalar_factor(element)
monomial = apply_substitutions(monomial, monomial_substitutions)
new_polynomial += coeff * monomial
return new_polynomial |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __separate_scalar_factor(monomial):
"""Separate the constant factor from a monomial. """ |
scalar_factor = 1
if is_number_type(monomial):
return S.One, monomial
if monomial == 0:
return S.One, 0
comm_factors, _ = split_commutative_parts(monomial)
if len(comm_factors) > 0:
if isinstance(comm_factors[0], Number):
scalar_factor = comm_factors[0]
if scalar_factor != 1:
return monomial / scalar_factor, scalar_factor
else:
return monomial, scalar_factor |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def separate_scalar_factor(element):
"""Construct a monomial with the coefficient separated from an element in a polynomial. """ |
coeff = 1.0
monomial = S.One
if isinstance(element, (int, float, complex)):
coeff *= element
return monomial, coeff
for var in element.as_coeff_mul()[1]:
if not (var.is_Number or var.is_imaginary):
monomial = monomial * var
else:
if var.is_Number:
coeff = float(var)
# If not, then it is imaginary
else:
coeff = 1j * coeff
coeff = float(element.as_coeff_mul()[0]) * coeff
return monomial, coeff |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count_ncmonomials(monomials, degree):
"""Given a list of monomials, it counts those that have a certain degree, or less. The function is useful when certain monomials were eliminated from the basis. :param variables: The noncommutative variables making up the monomials :param monomials: List of monomials (the monomial basis). :param degree: Maximum degree to count. :returns: The count of appropriate monomials. """ |
ncmoncount = 0
for monomial in monomials:
if ncdegree(monomial) <= degree:
ncmoncount += 1
else:
break
return ncmoncount |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_substitutions(monomial, monomial_substitutions, pure=False):
"""Helper function to remove monomials from the basis.""" |
if is_number_type(monomial):
return monomial
original_monomial = monomial
changed = True
if not pure:
substitutions = monomial_substitutions
else:
substitutions = {}
for lhs, rhs in monomial_substitutions.items():
irrelevant = False
for atom in lhs.atoms():
if atom.is_Number:
continue
if not monomial.has(atom):
irrelevant = True
break
if not irrelevant:
substitutions[lhs] = rhs
while changed:
for lhs, rhs in substitutions.items():
monomial = fast_substitute(monomial, lhs, rhs)
if original_monomial == monomial:
changed = False
original_monomial = monomial
return monomial |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_variables(name, n_vars=1, hermitian=None, commutative=True):
"""Generates a number of commutative or noncommutative variables :param name: The prefix in the symbolic representation of the noncommuting variables. This will be suffixed by a number from 0 to n_vars-1 if n_vars > 1. :type name: str. :param n_vars: The number of variables. :type n_vars: int. :param hermitian: Optional parameter to request Hermitian variables . :type hermitian: bool. :param commutative: Optional parameter to request commutative variables. Commutative variables are Hermitian by default. :type commutative: bool. :returns: list of :class:`sympy.physics.quantum.operator.Operator` or :class:`sympy.physics.quantum.operator.HermitianOperator` variables or `sympy.Symbol` :Example: [y0, y1] """ |
variables = []
for i in range(n_vars):
if n_vars > 1:
var_name = '%s%s' % (name, i)
else:
var_name = '%s' % name
if commutative:
if hermitian is None or hermitian:
variables.append(Symbol(var_name, real=True))
else:
variables.append(Symbol(var_name, complex=True))
elif hermitian is not None and hermitian:
variables.append(HermitianOperator(var_name))
else:
variables.append(Operator(var_name))
return variables |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_operators(name, n_vars=1, hermitian=None, commutative=False):
"""Generates a number of commutative or noncommutative operators :param name: The prefix in the symbolic representation of the noncommuting variables. This will be suffixed by a number from 0 to n_vars-1 if n_vars > 1. :type name: str. :param n_vars: The number of variables. :type n_vars: int. :param hermitian: Optional parameter to request Hermitian variables . :type hermitian: bool. :param commutative: Optional parameter to request commutative variables. Commutative variables are Hermitian by default. :type commutative: bool. :returns: list of :class:`sympy.physics.quantum.operator.Operator` or :class:`sympy.physics.quantum.operator.HermitianOperator` variables :Example: [y0, y1] """ |
variables = []
for i in range(n_vars):
if n_vars > 1:
var_name = '%s%s' % (name, i)
else:
var_name = '%s' % name
if hermitian is not None and hermitian:
variables.append(HermitianOperator(var_name))
else:
variables.append(Operator(var_name))
variables[-1].is_commutative = commutative
return variables |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_monomials(variables, degree):
"""Generates all noncommutative monomials up to a degree :param variables: The noncommutative variables to generate monomials from :type variables: list of :class:`sympy.physics.quantum.operator.Operator` or :class:`sympy.physics.quantum.operator.HermitianOperator`. :param degree: The maximum degree. :type degree: int. :returns: list of monomials. """ |
if degree == -1:
return []
if not variables:
return [S.One]
else:
_variables = variables[:]
_variables.insert(0, 1)
ncmonomials = [S.One]
ncmonomials.extend(var for var in variables)
for var in variables:
if not is_hermitian(var):
ncmonomials.append(var.adjoint())
for _ in range(1, degree):
temp = []
for var in _variables:
for new_var in ncmonomials:
temp.append(var * new_var)
if var != 1 and not is_hermitian(var):
temp.append(var.adjoint() * new_var)
ncmonomials = unique(temp[:])
return ncmonomials |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ncdegree(polynomial):
"""Returns the degree of a noncommutative polynomial. :param polynomial: Polynomial of noncommutive variables. :type polynomial: :class:`sympy.core.expr.Expr`. :returns: int -- the degree of the polynomial. """ |
degree = 0
if is_number_type(polynomial):
return degree
polynomial = polynomial.expand()
for monomial in polynomial.as_coefficients_dict():
subdegree = 0
for variable in monomial.as_coeff_mul()[1]:
if isinstance(variable, Pow):
subdegree += variable.exp
elif not isinstance(variable, Number) and variable != I:
subdegree += 1
if subdegree > degree:
degree = subdegree
return degree |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iscomplex(polynomial):
"""Returns whether the polynomial has complex coefficients :param polynomial: Polynomial of noncommutive variables. :type polynomial: :class:`sympy.core.expr.Expr`. :returns: bool -- whether there is a complex coefficient. """ |
if isinstance(polynomial, (int, float)):
return False
if isinstance(polynomial, complex):
return True
polynomial = polynomial.expand()
for monomial in polynomial.as_coefficients_dict():
for variable in monomial.as_coeff_mul()[1]:
if isinstance(variable, complex) or variable == I:
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all_monomials(variables, extramonomials, substitutions, degree, removesubstitutions=True):
"""Return the monomials of a certain degree. """ |
monomials = get_monomials(variables, degree)
if extramonomials is not None:
monomials.extend(extramonomials)
if removesubstitutions and substitutions is not None:
monomials = [monomial for monomial in monomials if monomial not
in substitutions]
monomials = [remove_scalar_factor(apply_substitutions(monomial,
substitutions))
for monomial in monomials]
monomials = unique(monomials)
return monomials |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pick_monomials_up_to_degree(monomials, degree):
"""Collect monomials up to a given degree. """ |
ordered_monomials = []
if degree >= 0:
ordered_monomials.append(S.One)
for deg in range(1, degree + 1):
ordered_monomials.extend(pick_monomials_of_degree(monomials, deg))
return ordered_monomials |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_monomial_index(filename, monomial_index):
"""Save a monomial dictionary for debugging purposes. :param filename: The name of the file to save to. :type filename: str. :param monomial_index: The monomial index of the SDP relaxation. :type monomial_index: dict of :class:`sympy.core.expr.Expr`. """ |
monomial_translation = [''] * (len(monomial_index) + 1)
for key, k in monomial_index.items():
monomial_translation[k] = convert_monomial_to_string(key)
file_ = open(filename, 'w')
for k in range(len(monomial_translation)):
file_.write('%s %s\n' % (k, monomial_translation[k]))
file_.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_relational(relational):
"""Convert all inequalities to >=0 form. """ |
rel = relational.rel_op
if rel in ['==', '>=', '>']:
return relational.lhs-relational.rhs
elif rel in ['<=', '<']:
return relational.rhs-relational.lhs
else:
raise Exception("The relational operation ' + rel + ' is not "
"implemented!") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ai(board, who='x'):
""" Returns best next board < Board |xo.xo.x..| > """ |
return sorted(board.possible(), key=lambda b: value(b, who))[-1] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_relaxation(self, A_configuration, B_configuration, I):
"""Get the sparse SDP relaxation of a Bell inequality. :param A_configuration: The definition of measurements of Alice. :type A_configuration: list of list of int. :param B_configuration: The definition of measurements of Bob. :type B_configuration: list of list of int. :param I: The matrix describing the Bell inequality in the Collins-Gisin picture. :type I: list of list of int. """ |
coefficients = collinsgisin_to_faacets(I)
M, ncIndices = get_faacets_moment_matrix(A_configuration,
B_configuration, coefficients)
self.n_vars = M.max() - 1
bs = len(M) # The block size
self.block_struct = [bs]
self.F = lil_matrix((bs**2, self.n_vars + 1))
# Constructing the internal representation of the constraint matrices
# See Section 2.1 in the SDPA manual and also Yalmip's internal
# representation
for i in range(bs):
for j in range(i, bs):
if M[i, j] != 0:
self.F[i*bs+j, abs(M[i, j])-1] = copysign(1, M[i, j])
self.obj_facvar = [0 for _ in range(self.n_vars)]
for i in range(1, len(ncIndices)):
self.obj_facvar[abs(ncIndices[i])-2] += \
copysign(1, ncIndices[i])*coefficients[i] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def share(track_id=None, url=None, users=None):
""" Returns list of users track has been shared with. Either track or url need to be provided. """ |
client = get_client()
if url:
track_id = client.get('/resolve', url=url).id
if not users:
return client.get('/tracks/%d/permissions' % track_id)
permissions = {'user_id': []}
for username in users:
# check cache for user
user = settings.users.get(username, None)
if user:
permissions['user_id'].append(user['id'])
else:
user = client.get('/resolve', url='http://soundcloud.com/%s' % username)
permissions['user_id'].append(user.id)
settings.users[username] = user.obj
settings.save()
return client.put('/tracks/%d/permissions' % track_id, permissions=permissions) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve_with_cvxopt(sdp, solverparameters=None):
"""Helper function to convert the SDP problem to PICOS and call CVXOPT solver, and parse the output. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`. """ |
P = convert_to_picos(sdp)
P.set_option("solver", "cvxopt")
P.set_option("verbose", sdp.verbose)
if solverparameters is not None:
for key, value in solverparameters.items():
P.set_option(key, value)
solution = P.solve()
x_mat = [np.array(P.get_valued_variable('X'))]
y_mat = [np.array(P.get_constraint(i).dual)
for i in range(len(P.constraints))]
return -solution["cvxopt_sol"]["primal objective"] + \
sdp.constant_term, \
-solution["cvxopt_sol"]["dual objective"] + \
sdp.constant_term, \
x_mat, y_mat, solution["status"] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve_with_cvxpy(sdp, solverparameters=None):
"""Helper function to convert the SDP problem to CVXPY and call the solver, and parse the output. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`. """ |
problem = convert_to_cvxpy(sdp)
if solverparameters is not None and 'solver' in solverparameters:
solver = solverparameters.pop('solver')
v = problem.solve(solver=solver, verbose=(sdp.verbose > 0))
else:
v = problem.solve(verbose=(sdp.verbose > 0))
if v is None:
status = "infeasible"
x_mat, y_mat = [], []
elif v == float("inf") or v == -float("inf"):
status = "unbounded"
x_mat, y_mat = [], []
else:
status = "optimal"
x_pre = sdp.F[:, 1:sdp.n_vars+1].dot(problem.variables()[0].value)
x_pre += sdp.F[:, 0]
row_offsets = [0]
cumulative_sum = 0
for block_size in sdp.block_struct:
cumulative_sum += block_size ** 2
row_offsets.append(cumulative_sum)
x_mat = []
for bi, bs in enumerate(sdp.block_struct):
x = x_pre[row_offsets[bi]:row_offsets[bi+1]].reshape((bs, bs))
x += x.T - np.diag(np.array(x.diagonal())[0])
x_mat.append(x)
y_mat = [constraint.dual_value for constraint in problem.constraints]
return v+sdp.constant_term, v+sdp.constant_term, x_mat, y_mat, status |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_to_cvxpy(sdp):
"""Convert an SDP relaxation to a CVXPY problem. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: :class:`cvxpy.Problem`. """ |
from cvxpy import Minimize, Problem, Variable
row_offsets = [0]
cumulative_sum = 0
for block_size in sdp.block_struct:
cumulative_sum += block_size ** 2
row_offsets.append(cumulative_sum)
x = Variable(sdp.n_vars)
# The moment matrices are the first blocks of identical size
constraints = []
for idx, bs in enumerate(sdp.block_struct):
nonzero_set = set()
F = [lil_matrix((bs, bs)) for _ in range(sdp.n_vars+1)]
for ri, row in enumerate(sdp.F.rows[row_offsets[idx]:
row_offsets[idx+1]],
row_offsets[idx]):
block_index, i, j = convert_row_to_sdpa_index(sdp.block_struct,
row_offsets, ri)
for col_index, k in enumerate(row):
value = sdp.F.data[ri][col_index]
F[k][i, j] = value
F[k][j, i] = value
nonzero_set.add(k)
if bs > 1:
sum_ = sum(F[k]*x[k-1] for k in nonzero_set if k > 0)
if not isinstance(sum_, (int, float)):
if F[0].getnnz() > 0:
sum_ += F[0]
constraints.append(sum_ >> 0)
else:
sum_ = sum(F[k][0, 0]*x[k-1] for k in nonzero_set if k > 0)
if not isinstance(sum_, (int, float)):
sum_ += F[0][0, 0]
constraints.append(sum_ >= 0)
obj = sum(ci*xi for ci, xi in zip(sdp.obj_facvar, x) if ci != 0)
problem = Problem(Minimize(obj), constraints)
return problem |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_neighbors(index, lattice_length, width=0, periodic=False):
"""Get the forward neighbors of a site in a lattice. :param index: Linear index of operator. :type index: int. :param lattice_length: The size of the 2D lattice in either dimension :type lattice_length: int. :param width: Optional parameter to define width. :type width: int. :param periodic: Optional parameter to indicate periodic boundary conditions. :type periodic: bool :returns: list of int -- the neighbors in linear index. """ |
if width == 0:
width = lattice_length
neighbors = []
coords = divmod(index, width)
if coords[1] < width - 1:
neighbors.append(index + 1)
elif periodic and width > 1:
neighbors.append(index - width + 1)
if coords[0] < lattice_length - 1:
neighbors.append(index + width)
elif periodic:
neighbors.append(index - (lattice_length - 1) * width)
return neighbors |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_next_neighbors(indices, lattice_length, width=0, distance=1, periodic=False):
"""Get the forward neighbors at a given distance of a site or set of sites in a lattice. :param index: Linear index of operator. :type index: int. :param lattice_length: The size of the 2D lattice in either dimension :type lattice_length: int. :param width: Optional parameter to define width. :type width: int. :param distance: Optional parameter to define distance. :type width: int. :param periodic: Optional parameter to indicate periodic boundary conditions. :type periodic: bool :returns: list of int -- the neighbors at given distance in linear index. """ |
if not isinstance(indices, list):
indices = [indices]
if distance == 1:
return flatten(get_neighbors(index, lattice_length, width, periodic)
for index in indices)
else:
s1 = set(flatten(get_next_neighbors(get_neighbors(index,
lattice_length,
width, periodic),
lattice_length, width, distance-1,
periodic) for index in indices))
s2 = set(get_next_neighbors(indices, lattice_length, width, distance-1,
periodic))
return list(s1 - s2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pauli_constraints(X, Y, Z):
"""Return a set of constraints that define Pauli spin operators. :param X: List of Pauli X operator on sites. :type X: list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param Y: List of Pauli Y operator on sites. :type Y: list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param Z: List of Pauli Z operator on sites. :type Z: list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :returns: tuple of substitutions and equalities. """ |
substitutions = {}
n_vars = len(X)
for i in range(n_vars):
# They square to the identity
substitutions[X[i] * X[i]] = 1
substitutions[Y[i] * Y[i]] = 1
substitutions[Z[i] * Z[i]] = 1
# Anticommutation relations
substitutions[Y[i] * X[i]] = - X[i] * Y[i]
substitutions[Z[i] * X[i]] = - X[i] * Z[i]
substitutions[Z[i] * Y[i]] = - Y[i] * Z[i]
# Commutation relations.
# equalities.append(X[i]*Y[i] - 1j*Z[i])
# equalities.append(X[i]*Z[i] + 1j*Y[i])
# equalities.append(Y[i]*Z[i] - 1j*X[i])
# They commute between the sites
for j in range(i + 1, n_vars):
substitutions[X[j] * X[i]] = X[i] * X[j]
substitutions[Y[j] * Y[i]] = Y[i] * Y[j]
substitutions[Y[j] * X[i]] = X[i] * Y[j]
substitutions[Y[i] * X[j]] = X[j] * Y[i]
substitutions[Z[j] * Z[i]] = Z[i] * Z[j]
substitutions[Z[j] * X[i]] = X[i] * Z[j]
substitutions[Z[i] * X[j]] = X[j] * Z[i]
substitutions[Z[j] * Y[i]] = Y[i] * Z[j]
substitutions[Z[i] * Y[j]] = Y[j] * Z[i]
return substitutions |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_measurements(party, label):
"""Generate variables that behave like measurements. :param party: The list of number of measurement outputs a party has. :type party: list of int. :param label: The label to be given to the symbolic variables. :type label: str. :returns: list of list of :class:`sympy.physics.quantum.operator.HermitianOperator`. """ |
measurements = []
for i in range(len(party)):
measurements.append(generate_operators(label + '%s' % i, party[i] - 1,
hermitian=True))
return measurements |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def projective_measurement_constraints(*parties):
"""Return a set of constraints that define projective measurements. :param parties: Measurements of different parties. :type A: list or tuple of list of list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :returns: substitutions containing idempotency, orthogonality and commutation relations. """ |
substitutions = {}
# Idempotency and orthogonality of projectors
if isinstance(parties[0][0][0], list):
parties = parties[0]
for party in parties:
for measurement in party:
for projector1 in measurement:
for projector2 in measurement:
if projector1 == projector2:
substitutions[projector1**2] = projector1
else:
substitutions[projector1*projector2] = 0
substitutions[projector2*projector1] = 0
# Projectors commute between parties in a partition
for n1 in range(len(parties)):
for n2 in range(n1+1, len(parties)):
for measurement1 in parties[n1]:
for measurement2 in parties[n2]:
for projector1 in measurement1:
for projector2 in measurement2:
substitutions[projector2*projector1] = \
projector1*projector2
return substitutions |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def define_objective_with_I(I, *args):
"""Define a polynomial using measurements and an I matrix describing a Bell inequality. :param I: The I matrix of a Bell inequality in the Collins-Gisin notation. :type I: list of list of int. :param args: Either the measurements of Alice and Bob or a `Probability` class describing their measurement operators. :type A: tuple of list of list of :class:`sympy.physics.quantum.operator.HermitianOperator` or :class:`ncpol2sdpa.Probability` :returns: :class:`sympy.core.expr.Expr` -- the objective function to be solved as a minimization problem to find the maximum quantum violation. Note that the sign is flipped compared to the Bell inequality. """ |
objective = I[0][0]
if len(args) > 2 or len(args) == 0:
raise Exception("Wrong number of arguments!")
elif len(args) == 1:
A = args[0].parties[0]
B = args[0].parties[1]
else:
A = args[0]
B = args[1]
i, j = 0, 1 # Row and column index in I
for m_Bj in B: # Define first row
for Bj in m_Bj:
objective += I[i][j] * Bj
j += 1
i += 1
for m_Ai in A:
for Ai in m_Ai:
objective += I[i][0] * Ai
j = 1
for m_Bj in B:
for Bj in m_Bj:
objective += I[i][j] * Ai * Bj
j += 1
i += 1
return -objective |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def correlator(A, B):
"""Correlators between the probabilities of two parties. :param A: Measurements of Alice. :type A: list of list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param B: Measurements of Bob. :type B: list of list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :returns: list of correlators. """ |
correlators = []
for i in range(len(A)):
correlator_row = []
for j in range(len(B)):
corr = 0
for k in range(len(A[i])):
for l in range(len(B[j])):
if k == l:
corr += A[i][k] * B[j][l]
else:
corr -= A[i][k] * B[j][l]
correlator_row.append(corr)
correlators.append(correlator_row)
return correlators |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maximum_violation(A_configuration, B_configuration, I, level, extra=None):
"""Get the maximum violation of a two-party Bell inequality. :param A_configuration: Measurement settings of Alice. :type A_configuration: list of int. :param B_configuration: Measurement settings of Bob. :type B_configuration: list of int. :param I: The I matrix of a Bell inequality in the Collins-Gisin notation. :type I: list of list of int. :param level: Level of relaxation. :type level: int. :returns: tuple of primal and dual solutions of the SDP relaxation. """ |
P = Probability(A_configuration, B_configuration)
objective = define_objective_with_I(I, P)
if extra is None:
extramonomials = []
else:
extramonomials = P.get_extra_monomials(extra)
sdpRelaxation = SdpRelaxation(P.get_all_operators(), verbose=0)
sdpRelaxation.get_relaxation(level, objective=objective,
substitutions=P.substitutions,
extramonomials=extramonomials)
solve_sdp(sdpRelaxation)
return sdpRelaxation.primal, sdpRelaxation.dual |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interval_overlap(a, b, x, y):
"""Returns by how much two intervals overlap assumed that a <= b and x <= y""" |
if b <= x or a >= y:
return 0
elif x <= a <= y:
return min(b, y) - a
elif x <= b <= y:
return b - max(a, x)
elif a >= x and b <= y:
return b - a
else:
assert False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def linesplit(string, columns):
# type: (Union[Text, FmtStr], int) -> List[FmtStr] """Returns a list of lines, split on the last possible space of each line. Split spaces will be removed. Whitespaces will be normalized to one space. Spaces will be the color of the first whitespace character of the normalized whitespace. If a word extends beyond the line, wrap it anyway. [blue('home')+blue(' ')+blue('is'), blue('where')+blue(' ')+blue('the'), blue('heart-eati'), blue('ng')+blue(' ')+blue('mummy'), blue('is')] """ |
if not isinstance(string, FmtStr):
string = fmtstr(string)
string_s = string.s
matches = list(re.finditer(r'\s+', string_s))
spaces = [string[m.start():m.end()] for m in matches if m.start() != 0 and m.end() != len(string_s)]
words = [string[start:end] for start, end in zip(
[0] + [m.end() for m in matches],
[m.start() for m in matches] + [len(string_s)]) if start != end]
word_to_lines = lambda word: [word[columns*i:columns*(i+1)] for i in range((len(word) - 1) // columns + 1)]
lines = word_to_lines(words[0])
for word, space in zip(words[1:], spaces):
if len(lines[-1]) + len(word) < columns:
lines[-1] += fmtstr(' ', **space.shared_atts)
lines[-1] += word
else:
lines.extend(word_to_lines(word))
return lines |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def normalize_slice(length, index):
"Fill in the Nones in a slice."
is_int = False
if isinstance(index, int):
is_int = True
index = slice(index, index+1)
if index.start is None:
index = slice(0, index.stop, index.step)
if index.stop is None:
index = slice(index.start, length, index.step)
if index.start < -1: # XXX why must this be -1?
index = slice(length - index.start, index.stop, index.step)
if index.stop < -1: # XXX why must this be -1?
index = slice(index.start, length - index.stop, index.step)
if index.step is not None:
raise NotImplementedError("You can't use steps with slicing yet")
if is_int:
if index.start < 0 or index.start > length:
raise IndexError("index out of bounds: %r for length %s" % (index, length))
return index |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_args(args, kwargs):
"""Returns a kwargs dictionary by turning args into kwargs""" |
if 'style' in kwargs:
args += (kwargs['style'],)
del kwargs['style']
for arg in args:
if not isinstance(arg, (bytes, unicode)):
raise ValueError("args must be strings:" + repr(args))
if arg.lower() in FG_COLORS:
if 'fg' in kwargs: raise ValueError("fg specified twice")
kwargs['fg'] = FG_COLORS[arg]
elif arg.lower().startswith('on_') and arg[3:].lower() in BG_COLORS:
if 'bg' in kwargs: raise ValueError("fg specified twice")
kwargs['bg'] = BG_COLORS[arg[3:]]
elif arg.lower() in STYLES:
kwargs[arg] = True
else:
raise ValueError("couldn't process arg: "+repr(arg))
for k in kwargs:
if k not in ['fg', 'bg'] + list(STYLES.keys()):
raise ValueError("Can't apply that transformation")
if 'fg' in kwargs:
if kwargs['fg'] in FG_COLORS:
kwargs['fg'] = FG_COLORS[kwargs['fg']]
if kwargs['fg'] not in list(FG_COLORS.values()):
raise ValueError("Bad fg value: %r" % kwargs['fg'])
if 'bg' in kwargs:
if kwargs['bg'] in BG_COLORS:
kwargs['bg'] = BG_COLORS[kwargs['bg']]
if kwargs['bg'] not in list(BG_COLORS.values()):
raise ValueError("Bad bg value: %r" % kwargs['bg'])
return kwargs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fmtstr(string, *args, **kwargs):
# type: (Union[Text, bytes, FmtStr], *Any, **Any) -> FmtStr """ Convenience function for creating a FmtStr on_red(bold(blue('asdf'))) on_red(bold(blue('blarg'))) """ |
atts = parse_args(args, kwargs)
if isinstance(string, FmtStr):
pass
elif isinstance(string, (bytes, unicode)):
string = FmtStr.from_str(string)
else:
raise ValueError("Bad Args: %r (of type %s), %r, %r" % (string, type(string), args, kwargs))
return string.copy_with_new_atts(**atts) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def color_str(self):
"Return an escape-coded string to write to the terminal."
s = self.s
for k, v in sorted(self.atts.items()):
# (self.atts sorted for the sake of always acting the same.)
if k not in xforms:
# Unsupported SGR code
continue
elif v is False:
continue
elif v is True:
s = xforms[k](s)
else:
s = xforms[k](s, v)
return s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def repr_part(self):
"""FmtStr repr is build by concatenating these.""" |
def pp_att(att):
if att == 'fg': return FG_NUMBER_TO_COLOR[self.atts[att]]
elif att == 'bg': return 'on_' + BG_NUMBER_TO_COLOR[self.atts[att]]
else: return att
atts_out = dict((k, v) for (k, v) in self.atts.items() if v)
return (''.join(pp_att(att)+'(' for att in sorted(atts_out))
+ (repr(self.s) if PY3 else repr(self.s)[1:]) + ')'*len(atts_out)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request(self, max_width):
# type: (int) -> Optional[Tuple[int, Chunk]] """Requests a sub-chunk of max_width or shorter. Returns None if no chunks left.""" |
if max_width < 1:
raise ValueError('requires positive integer max_width')
s = self.chunk.s
length = len(s)
if self.internal_offset == len(s):
return None
width = 0
start_offset = i = self.internal_offset
replacement_char = u' '
while True:
w = wcswidth(s[i])
# If adding a character puts us over the requested width, return what we've got so far
if width + w > max_width:
self.internal_offset = i # does not include ith character
self.internal_width += width
# if not adding it us makes us short, this must have been a double-width character
if width < max_width:
assert width + 1 == max_width, 'unicode character width of more than 2!?!'
assert w == 2, 'unicode character of width other than 2?'
return (width + 1, Chunk(s[start_offset:self.internal_offset] + replacement_char,
atts=self.chunk.atts))
return (width, Chunk(s[start_offset:self.internal_offset], atts=self.chunk.atts))
# otherwise add this width
width += w
# If one more char would put us over, return whatever we've got
if i + 1 == length:
self.internal_offset = i + 1 # beware the fencepost, i is an index not an offset
self.internal_width += width
return (width, Chunk(s[start_offset:self.internal_offset], atts=self.chunk.atts))
# otherwise attempt to add the next character
i += 1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_str(cls, s):
# type: (Union[Text, bytes]) -> FmtStr r""" Return a FmtStr representing input. The str() of a FmtStr is guaranteed to produced the same FmtStr. Other input with escape sequences may not be preserved. '|'+on_blue(red('hey'))+'|' '|'+on_blue(red('hey'))+'|' """ |
if '\x1b[' in s:
try:
tokens_and_strings = parse(s)
except ValueError:
return FmtStr(Chunk(remove_ansi(s)))
else:
chunks = []
cur_fmt = {}
for x in tokens_and_strings:
if isinstance(x, dict):
cur_fmt.update(x)
elif isinstance(x, (bytes, unicode)):
atts = parse_args('', dict((k, v)
for k, v in cur_fmt.items()
if v is not None))
chunks.append(Chunk(x, atts=atts))
else:
raise Exception("logic error")
return FmtStr(*chunks)
else:
return FmtStr(Chunk(s)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy_with_new_str(self, new_str):
"""Copies the current FmtStr's attributes while changing its string.""" |
# What to do when there are multiple Chunks with conflicting atts?
old_atts = dict((att, value) for bfs in self.chunks
for (att, value) in bfs.atts.items())
return FmtStr(Chunk(new_str, old_atts)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy_with_new_atts(self, **attributes):
"""Returns a new FmtStr with the same content but new formatting""" |
return FmtStr(*[Chunk(bfs.s, bfs.atts.extend(attributes))
for bfs in self.chunks]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def join(self, iterable):
"""Joins an iterable yielding strings or FmtStrs with self as separator""" |
before = []
chunks = []
for i, s in enumerate(iterable):
chunks.extend(before)
before = self.chunks
if isinstance(s, FmtStr):
chunks.extend(s.chunks)
elif isinstance(s, (bytes, unicode)):
chunks.extend(fmtstr(s).chunks) #TODO just make a chunk directly
else:
raise TypeError("expected str or FmtStr, %r found" % type(s))
return FmtStr(*chunks) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split(self, sep=None, maxsplit=None, regex=False):
"""Split based on seperator, optionally using a regex Capture groups are ignored in regex, the whole pattern is matched and used to split the original FmtStr.""" |
if maxsplit is not None:
raise NotImplementedError('no maxsplit yet')
s = self.s
if sep is None:
sep = r'\s+'
elif not regex:
sep = re.escape(sep)
matches = list(re.finditer(sep, s))
return [self[start:end] for start, end in zip(
[0] + [m.end() for m in matches],
[m.start() for m in matches] + [len(s)])] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def splitlines(self, keepends=False):
"""Return a list of lines, split on newline characters, include line boundaries, if keepends is true.""" |
lines = self.split('\n')
return [line+'\n' for line in lines] if keepends else (
lines if lines[-1] else lines[:-1]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def width(self):
"""The number of columns it would take to display this string""" |
if self._width is not None:
return self._width
self._width = sum(fs.width for fs in self.chunks)
return self._width |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def width_at_offset(self, n):
"""Returns the horizontal position of character n of the string""" |
#TODO make more efficient?
width = wcswidth(self.s[:n])
assert width != -1
return width |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shared_atts(self):
"""Gets atts shared among all nonzero length component Chunk""" |
#TODO cache this, could get ugly for large FmtStrs
atts = {}
first = self.chunks[0]
for att in sorted(first.atts):
#TODO how to write this without the '???'?
if all(fs.atts.get(att, '???') == first.atts[att] for fs in self.chunks if len(fs) > 0):
atts[att] = first.atts[att]
return atts |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new_with_atts_removed(self, *attributes):
"""Returns a new FmtStr with the same content but some attributes removed""" |
return FmtStr(*[Chunk(bfs.s, bfs.atts.remove(*attributes))
for bfs in self.chunks]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def divides(self):
"""List of indices of divisions between the constituent chunks.""" |
acc = [0]
for s in self.chunks:
acc.append(acc[-1] + len(s))
return acc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def width_aware_slice(self, index):
"""Slice based on the number of columns it would take to display the substring.""" |
if wcswidth(self.s) == -1:
raise ValueError('bad values for width aware slicing')
index = normalize_slice(self.width, index)
counter = 0
parts = []
for chunk in self.chunks:
if index.start < counter + chunk.width and index.stop > counter:
start = max(0, index.start - counter)
end = min(index.stop - counter, chunk.width)
if end - start == chunk.width:
parts.append(chunk)
else:
s_part = width_aware_slice(chunk.s, max(0, index.start - counter), index.stop - counter)
parts.append(Chunk(s_part, chunk.atts))
counter += chunk.width
if index.stop < counter:
break
return FmtStr(*parts) if parts else fmtstr('') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def width_aware_splitlines(self, columns):
# type: (int) -> Iterator[FmtStr] """Split into lines, pushing doublewidth characters at the end of a line to the next line. When a double-width character is pushed to the next line, a space is added to pad out the line. """ |
if columns < 2:
raise ValueError("Column width %s is too narrow." % columns)
if wcswidth(self.s) == -1:
raise ValueError('bad values for width aware slicing')
return self._width_aware_splitlines(columns) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def public_api(self,url):
''' template function of public api'''
try :
url in api_urls
return ast.literal_eval(requests.get(base_url + api_urls.get(url)).text)
except Exception as e:
print(e) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(s):
r""" Returns a list of strings or format dictionaries to describe the strings. May raise a ValueError if it can't be parsed. """ |
stuff = []
rest = s
while True:
front, token, rest = peel_off_esc_code(rest)
if front:
stuff.append(front)
if token:
try:
tok = token_type(token)
if tok:
stuff.extend(tok)
except ValueError:
raise ValueError("Can't parse escape sequence: %r %r %r %r" % (s, repr(front), token, repr(rest)))
if not rest:
break
return stuff |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def peel_off_esc_code(s):
r"""Returns processed text, the next token, and unprocessed text ('some', 'stuff') True """ |
p = r"""(?P<front>.*?)
(?P<seq>
(?P<csi>
(?:[]\[)
|
["""+'\x9b' + r"""])
(?P<private>)
(?P<numbers>
(?:\d+;)*
(?:\d+)?)
(?P<intermed>""" + '[\x20-\x2f]*)' + r"""
(?P<command>""" + '[\x40-\x7e]))' + r"""
(?P<rest>.*)"""
m1 = re.match(p, s, re.VERBOSE) # multibyte esc seq
m2 = re.match('(?P<front>.*?)(?P<seq>(?P<csi>)(?P<command>[\x40-\x5f]))(?P<rest>.*)', s) # 2 byte escape sequence
if m1 and m2:
m = m1 if len(m1.groupdict()['front']) <= len(m2.groupdict()['front']) else m2
# choose the match which has less processed text in order to get the
# first escape sequence
elif m1: m = m1
elif m2: m = m2
else: m = None
if m:
d = m.groupdict()
del d['front']
del d['rest']
if 'numbers' in d and all(d['numbers'].split(';')):
d['numbers'] = [int(x) for x in d['numbers'].split(';')]
return m.groupdict()['front'], d, m.groupdict()['rest']
else:
return s, None, '' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_key(bytes_, encoding, keynames='curtsies', full=False):
"""Return key pressed from bytes_ or None Return a key name or None meaning it's an incomplete sequence of bytes (more bytes needed to determine the key pressed) encoding is how the bytes should be translated to unicode - it should match the terminal encoding. keynames is a string describing how keys should be named: * curtsies uses unicode strings like <F8> * curses uses unicode strings similar to those returned by the Python ncurses window.getkey function, like KEY_F(8), plus a nonstandard representation of meta keys (bytes 128-255) because returning the corresponding unicode code point would be indistinguishable from the multibyte sequence that encodes that character in the current encoding * bytes returns the original bytes from stdin (NOT unicode) if full, match a key even if it could be a prefix to another key (useful for detecting a plain escape key for instance, since escape is also a prefix to a bunch of char sequences for other keys) Events are subclasses of Event, or unicode strings Precondition: get_key(prefix, keynames) is None for all proper prefixes of bytes. This means get_key should be called on progressively larger inputs (for 'asdf', first on 'a', then on 'as', then on 'asd' - until a non-None value is returned) """ |
if not all(isinstance(c, type(b'')) for c in bytes_):
raise ValueError("get key expects bytes, got %r" % bytes_) # expects raw bytes
if keynames not in ['curtsies', 'curses', 'bytes']:
raise ValueError("keynames must be one of 'curtsies', 'curses' or 'bytes'")
seq = b''.join(bytes_)
if len(seq) > MAX_KEYPRESS_SIZE:
raise ValueError('unable to decode bytes %r' % seq)
def key_name():
if keynames == 'curses':
if seq in CURSES_NAMES: # may not be here (and still not decodable) curses names incomplete
return CURSES_NAMES[seq]
# Otherwise, there's no special curses name for this
try:
return seq.decode(encoding) # for normal decodable text or a special curtsies sequence with bytes that can be decoded
except UnicodeDecodeError:
# this sequence can't be decoded with this encoding, so we need to represent the bytes
if len(seq) == 1:
return u'x%02X' % ord(seq)
#TODO figure out a better thing to return here
else:
raise NotImplementedError("are multibyte unnameable sequences possible?")
return u'bytes: ' + u'-'.join(u'x%02X' % ord(seq[i:i+1]) for i in range(len(seq)))
#TODO if this isn't possible, return multiple meta keys as a paste event if paste events enabled
elif keynames == 'curtsies':
if seq in CURTSIES_NAMES:
return CURTSIES_NAMES[seq]
return seq.decode(encoding) #assumes that curtsies names are a subset of curses ones
else:
assert keynames == 'bytes'
return seq
key_known = seq in CURTSIES_NAMES or seq in CURSES_NAMES or decodable(seq, encoding)
if full and key_known:
return key_name()
elif seq in KEYMAP_PREFIXES or could_be_unfinished_char(seq, encoding):
return None # need more input to make up a full keypress
elif key_known:
return key_name()
else:
seq.decode(encoding) # this will raise a unicode error (they're annoying to raise ourselves)
assert False, 'should have raised an unicode decode error' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def could_be_unfinished_char(seq, encoding):
"""Whether seq bytes might create a char in encoding if more bytes were added""" |
if decodable(seq, encoding):
return False # any sensible encoding surely doesn't require lookahead (right?)
# (if seq bytes encoding a character, adding another byte shouldn't also encode something)
if encodings.codecs.getdecoder('utf8') is encodings.codecs.getdecoder(encoding):
return could_be_unfinished_utf8(seq)
elif encodings.codecs.getdecoder('ascii') is encodings.codecs.getdecoder(encoding):
return False
else:
return True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.