Python solver error

content: Situation, Traceback/output, Math Formulation, Descriptive Formulation, Code, Software Situation I am building and solving large optimal facility location models with restricted-use census...

content: Situation, Traceback/output, Math Formulation, Descriptive Formulation, Code, Software


Situation

  • I am building and solving large optimal facility location models with restricted-use census microdata as part of my dissertation. The biggest troublemaker model is the p-center problem (a.k.a. minimax location-allocation; a mixed integer programming model for location-allocation) – [formulation, description, and code sample below]. I am working in a restricted data center environment on a large cluster where memory is not an issue (100s of GB of RAM are readily available).
  • The error message is general and does not provide information on what actually broke. My first thought was that the problem is too large/difficult to solve (which I hope I am wrong…). I have not been able to reproduce the error, and even getting the traceback approved for disclosure took some finagling
  • Problem size
    • (10,000-row; 15-column) cost matrix
    • 170,001 constraints
    • 150,016 variables
  • unclear error message
    • P=1 (choose 1 candidate facility to minimize the maximum cost) solves in roughly 45 minutes with a minimal memory footprint
    • P=2 (choose 2 candidate facilities) errors out
    • Still trying to work down from p=15
  • Will be trying to solve a much larger problem…
    • (~95,000-row; 15-column) cost matrix
    • 1,615,001 constraints
    • 1,425,016 variables
  • This model is known for being difficult to solve and unpredictable, but generally is more difficult to solve as p decreases from the maximum possible value, but is not 1.

Traceback/output

****************************************************************************************
=========================================================
			 matrix dims: (10000, 15)
=========================================================
	
	Obj. value:             0.99979419 worst case distance with 1 selected facilities
	build_time (minutes):   0.12501789728800455
        solve_time:             43.2781
	total_time (minutes):   43.40350598891576
	facilities:             ['y0']
	matrix_size (GB):       0.0

----------------------------------------
Traceback (most recent call last):
  File "./p-center_test.py", line 169, in <module>
    pcp = FacilityLocationModel('pcp', cij=cost_matrix, p=p)
  File "./p-center_test.py", line 21, in __init__
    self.solve_time = self.optimize(write_lp=write_lp)
  File "./p-center_test.py", line 33, in timer
    timed_function(*args, **kwargs)
  File "./p-center_test.py", line 103, in optimize
    self.problem.solve(pulp.PULP_CBC_CMD(fracGap=0))
  File "/apps/anaconda/envs/py3/lib/python3.6/site-packages/pulp/pulp.py", line 1664, in solve
    status = solver.actualSolve(self, **kwargs)
  File "/apps/anaconda/envs/py3/lib/python3.6/site-packages/pulp/solvers.py", line 1362, in actualSolve
    return self.solve_CBC(lp, **kwargs)
  File "/apps/anaconda/envs/py3/lib/python3.6/site-packages/pulp/solvers.py", line 1423, in solve_CBC
    self.path)
pulp.solvers.PulpSolverError: Pulp: Error while trying to execute /apps/anaconda/envs/py3/lib/python3.6/site-packages/pulp/solverdir/cbc/linux/64/cbc

----------------------------------------

Mathematical Formulation

pcenter_formulation

Descriptive Formulation

pcenter_description


Code (boiled-down sample in a class)

import pulp
import numpy as np

class FacilityLocationModel:
    """Solve a facility locatiom optimization model
    
    Parameters 
    ----------
    name : str
        Problem model name; must also be defined as a class method.
    cij : numpy.ndarray
        cost matrix from origins (index of i) to destination (index of j).
        Default is None.
    p : int
        Density of facilities to site. Default is None.
    
    Methods
    -------
    build_pcp : build p-center problem
    problem_instance : create a problem instance
    add_vars : add variables to a model
    add_constrs : add contraints to a model
    add_obj : add an objective function to a model
    optimize : solve a model
    
    Attributes
    ----------
    problem : pulp.pulp.LpProblem
        problem/model instance
    n_cli : int
        total client sites
    r_cli : range
        iterable of client sites
    n_fac : int
        total candidate facility sites
    r_fac : range
        iterable of candidate facility sites
    cli_decisions : list, np.array
        client-to-service decision variable matrix used in pmp and pcp.
    fac_vars : dict
        facility decision variables
    cli_vars : dict
        client decision variables
    W : pulp.pulp.LpVariable
        minimized maximum variable in the p-center problem formulation
    """
    
    
    def __init__(self, name, cij=None, p=None, cli_dvs=None, fac_dvs=None):
        # Set model information
        self.name = name
        
        # Set parameters and indices
        # facility parameter
        self.p = p
        
        # client count and range
        self.cij = cij
        self.n_cli = cij.shape[0]
        self.r_cli = range(self.n_cli)
        
        # facility count and range
        self.n_fac = self.cij.shape[1]
        self.r_fac = range(self.n_fac)
        
        # if client and service decision variable names are passed in the
        # class, set them as attributes here.
        if fac_dvs is not None:
            self.fac_dvs = list(fac_dvs)
        if cli_dvs is not None:
            self.cli_dvs = list(cli_dvs)
        
        # Set decision variables, constraints, and objective function
        try:
            getattr(self, 'build_'+self.name)()
        except:
            raise AttributeError(self.name,
                                 'not a defined location model.')
        # solve
        self.optimize()
    
    
    def build_pcp(self):
        """Integer programming formulation of the p-center Problem.
        
        Originally Published:
            S. L. Hakimi. 1964. Optimum Locations of Switching Centers and
            the Absolute Centers and Medians of a Graph. Operations Research.
            12 (3):450-459.
        
        Adapted from:
            Daskin, M. (1995). Network and discrete location: Models,
            algorithms, and applications. New York: John Wiley and Sons, Inc.
        """
        # Problem Instance
        self.problem_instance()
        # Decision Variables
        self.add_vars()
        # Constraints
        self.add_constrs(constr=2) # assignment constraints
        self.add_constrs(constr=3) # facility constraint
        self.add_constrs(constr=4) # opening constraints
        self.add_constrs(constr=5) # minimized maximum constraints
        # Objective Function
        self.add_obj()
    
    
    def problem_instance(self):
        """Create a problem instance and set objective sense.
        """
        # set sense
        sense = pulp.LpMinimize
        # create problem instance
        self.problem = pulp.LpProblem(self.name, sense)
    
    
    def add_vars(self):
        """Add variables to a model.
        """
        # facility decision variables
        # variable names
        if not hasattr(self, 'fac_dvs'):
            self.fac_dvs = ['y%i' % j for j in self.r_fac]
        # pulp.LpVariable objects
        self.fac_vars = [pulp.LpVariable(var_name, cat='Binary')
                                            for var_name in self.fac_dvs]
        # add variables
        self.problem.addVariables(v for v in self.fac_vars)
        
        # client decision variables
        # variable names
        if not hasattr(self, 'cli_dvs'):
            self.cli_dvs = ['x%i' % i for i in self.r_cli]
        self.cli_decisions = [['x%i_%i' % (i,j) for j in self.r_fac]
                                                for i in self.r_cli]
        # pulp.LpVariable objects
        self.cli_vars = [[pulp.LpVariable(var_name, cat='Binary')
                                         for var_name in var_row]
                                         for var_row in self.cli_decisions]
        # add variables
        self.problem.addVariables(var for var_row in self.cli_vars
                                      for var in var_row)
        
        # minimized maximum variable
        self.W = pulp.LpVariable('W', cat='Continuous')
        self.problem.addVariable(self.W)
    
    
    def add_constrs(self, constr=None):
        """ Add constraints to a model.
        
        (2) assignment constraints
                x1_1 + x1_2 + x1_3 = 1
        (3) facility constraints
                y1 + y2 + y3 = p
        (4) opening constraints
                - x1_1 + y1 >= 0
                - x2_1 + y1 >= 0
                - x3_1 + y1 >= 0
        (5) minimax constraints
                cost1_1*x1_1 + cost1_2*x1_2 + cost1_3*x1_3 - W <= 0
        
        Parameters
        ----------
        constr : int {1, 2, 3, 4, 5, 6}
            Contraint type to add to model. See above for explanation.
            Default is None.
        """
        
        # 2 - assignment constraints
        if constr == 2:
            constrs = [pulp.lpSum(self.cli_vars[i][j]
                                  for j in self.r_fac) == 1
                                  for i in self.r_cli]
        
        # 3 - facility constraint
        elif constr == 3:
            constrs = [pulp.lpSum(self.fac_vars[j]
                                  for j in self.r_fac) == self.p]
        
        # 4 - opening constraints
        elif constr == 4:
            constrs = [self.fac_vars[j] >= self.cli_vars[i][j]
                       for i in self.r_cli for j in self.r_fac]
        
        # 5 - minimax constraints
        elif constr == 5:
            constrs = [pulp.lpSum(self.cij[i,j]
                                  * self.cli_vars[i][j]
                                  for j in self.r_fac) <= self.W
                                  for i in self.r_cli]
        
        # Add constraints
        [self.problem.addConstraint(c) for c in constrs]
    
    
    def add_obj(self):
        """ Add an objective function to a model.
        """
        self.problem.setObjective(self.W)
    
    
    def optimize(self, write_lp=None):
        """ Solve the model.
        """
        self.problem.solve(pulp.PULP_CBC_CMD(fracGap=0))


if __name__ == '__main__':
    np.random.seed(0)
    clients, facilities = 5, 3
    p = 2
    # 5 by 3 matrix of small integers
    cost_matrix = np.random.randint(1,5, size=(clients,facilities))
    
    pcp = FacilityLocationModel('pcp', cij=cost_matrix, p=p)
    obj = pcp.problem.objective.value()
    
    print('Worst-case travel cost while siting %s facilities: %s' % (p, obj))
Worst-case travel cost while siting 2 facilities: 3.0

Software

  • Python 3.6.3
  • Pulp 1.6.8
  • Numpy 1.15.1
  • Red Hat Enterprise Linux 6.10 on PBS Pro cluster

Here I will put all the main questions and advice from years of solving and helping other solve problems with PuLP. Additional answers can be added via a PR.

Giving feedback and asking for help

The two ways one can ask for help or report a problem are:

  1. The PuLP Github Discussions page: https://github.com/coin-or/pulp/discussions

  2. Stack Overflow pulp tag: https://stackoverflow.com/questions/tagged/pulp

Of course, the questions /problems (and their answers/ solutions) already in these sites can (and often do) include sufficient information to solve or understand the issue. So a good look at old questions and issues is highly recommended.

Several things need to be taken into account while asking for help, some of them are common to any project, other are particular to PuLP.
General pointers (that are nonetheless, very important):

  1. Always submit a minimum reproducible example (how to here).

  2. Check this video on how to ask questions. Although aimed to another programming language, the message and recommendations are very good.

Now, specifically to PuLP:

  1. Pass the msg=1 argument to the solver, i.e., prob.solve(PULP_CBC_CMD(msg=1)). This will give you more information on the error. Share this information when asking for help.

  2. If possible, share an export version of the model. Check here how to export one.

  3. Alternatively, share a mps version of your model. To produce one, use writeMPS().

Other information that is also useful:

  1. Version of pulp.

  2. How did you install pulp (via pypi, or from github).

  3. What operating system was used.

  4. The version of the solver being used (e.g., CPLEX 12.8).

Error while trying to execute cbc.exe

The complete message is usually something like pulp.solvers.PulpSolverError: Pulp: Error while trying to execute PATH_TO_CBC/cbc.exe.

The default solver is CBC and is run via the command line.

  1. First of all, pass the msg=1 argument to the solver, to get more information.

  2. Check the precision of the numbers. If you have very big numbers (with a high precision), this generally causes problems with solvers. For example, never use a parameter that is 100000000000 inside your problem. Specially if you then have another one that has 1200.09123642123. If you do not need decimals, round your values when building the model.

  3. Duplicated variables / constraints. If you have variables that have the same coefficients in all constraints and in the objective function, this is an issue. Also, if you have two constraints that have exactly the same variables and coefficients.

  4. Memory issues. Sometimes your pc runs out of memory. Check if this is the case.

  5. python32 vs python64. Sometimes you’re using the 32-bit version of python, even if your pc is 64-bit. Try to always use the 64-bit if possible, since it handles more memory.

  6. Generate an mps file with PuLP and pass it to the cbc.exe executable directly like so.

  7. Anaconda/ conda/ jupyter notebooks see below.

And see what message you get.

  1. Finally, sometimes you may want to try PuLP with a more recent version of CBC. To do this, download the CBC binary and pass the path to it to PuLP.

Infeasible problems

  1. Add slack variables. As described in this SO post.

  2. Take out constraints and see if the problem becomes feasible.

  3. Generate lp file writeLP() for the problem and open it with a text editor to see if the constraints are correctly built.

  4. Check the solver logs to additional message from the solver regarding the constraint or variable involved. The log can be seen by giving msg= as argument or exported with the logPath argument in some cases.

Jupyter notebooks / anaconda / conda issues

There have been several issues of the default solver (CBC) not working with an error like:

pulp.solvers.PulpSolverError: Pulp: Error while trying to execute PATH_TO_CBC/cbc.exe

or

Pulp: Error while trying to execute, use msg=True for more details.

This could be caused by a combination of the following:

  • the conda / anaconda installation of PuLP is not supported and thus may bring its own problems. Try installing pulp as documented in the documentation.

  • Apparently Jupyter notebooks sometimes run in user sessions that do not have access to the PuLP installation folder. This makes it impossible to access the default solver binary. To fix this, try installing pulp in the user’s directory or giving sufficient permissions to the jupyter notebook when launching it.

Examples of these situations, some fixed are:

  • https://github.com/coin-or/pulp/issues/410

  • https://github.com/coin-or/pulp/discussions/384

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.
  • Forums

  • Homework Help

  • Engineering and Comp Sci Homework Help

Python equation solver, I’m getting a floating point error

  • Comp Sci

  • Thread starter
    Arman777

  • Start date
    Jun 15, 2019

  • Jun 15, 2019
  • #1
Homework Statement:
Solve the given equation and find the x value
Relevant Equations:
##(A times x) + (B times sqrt{x^3}) — (C times e^{-x / 50}) — D=0##
I am trying to solve the equation like this,

from sympy.solvers import solve
from sympy import Symbol
import math

x = Symbol('x')

A, B, C, D = 0.59912051, 0.64030348, 263.33721367, 387.92069617

print(solve((A * x) + (B * math.sqrt(x**3)) - (C * math.exp(-x / 50)) - D, x , numerical = True))
Traceback (most recent call last):
  File "c:/Users/***/Desktop/Python Stuff/***", line 9, in <module>
    solve((A * x) + (B * math.sqrt(x**3)) - (C * math.exp(-x / 50)) - D, x , numerical = True)
  File "C:Users***AppDataLocalProgramsPythonPython37libsite-packagessympycoreexpr.py", line 280, in __float__
    raise TypeError("can't convert expression to float")
TypeError: can't convert expression to float

Why this is happening ?Thanks

Answers and Replies

  • Jun 15, 2019
  • #2
It’s possible that what solve returns isn’t something that print can handle. I would try this:

solve((A * x) + (B * math.sqrt(x**3)) - (C * math.exp(-x / 50)) - D, x)

Also, from my reading of the docs for solve, you don’t need to include the numerical = True part, since that is the default.

  • Jun 15, 2019
  • #3
I tried that however its still giving me the same error.

  • Jun 15, 2019
  • #4
Error goes away if I remove ‘math.sqrt’ and ‘math.exp’

I find one reference saying you shouldn’t use ‘math’ in sympy, but it doesn’t give a workaround.

  • Jun 15, 2019
  • #5
Sympy is there for symbolic computations. The math library is there for numerics (typically bad ones, basically anything you’d want in there is in numpy)

so import sqrt and exp from sympy, get your final symbolic expression, then use .evalf() at the end to get it as floating point.

  • Jun 15, 2019
  • #6
I tried and it worked. However the python couldn’t solve the equation..

  • Jun 15, 2019
  • #7
I still get an error

from sympy.solvers import solve
from sympy import Symbol
from sympy import sqrt
from sympy import exp

x = Symbol('x')

A, B, C, D = 0.59912051, 0.64030348, 263.33721367, 387.92069617

print(solve((A * x) + (B * sqrt(x**3)) - C*exp(-0.02*x) - D, x , numerical = True))

line 10:
    print(solve((A * x) + (B * sqrt(x**3)) - C*exp(-0.02*x) - D, x , numerical = True))
  File "H:Program FilesPython36libsite-packagessympysolverssolvers.py", line 1171, in solve
    solution = _solve(f[0], *symbols, **flags)
  File "H:Program FilesPython36libsite-packagessympysolverssolvers.py", line 1742, in _solve
    raise NotImplementedError('n'.join([msg, not_impl_msg % f]))
NotImplementedError: multiple generators [x, exp(x/50), sqrt(x**3)]
No algorithms are implemented to solve equation 59912051*x/100000000 + 16007587*sqrt(x**3)/25000000 - 38792069617/100000000 - 26333721367*exp(-x/50)/100000000

If I leave out the exp, there is a result (66.6 and two complex numbers).

Is there a way to force x real ?

  • Jun 15, 2019
  • #8
Is there a way to force x real ?

x = Symbol('x', real = True)

you can also do things like postive = True, if so inclined

  • Jun 15, 2019
  • #9
I kind of find the condition set however I am not sure how that can help

import sympy as sym
x = sym.Symbol('x')

A, B, C, D = 0.59912051, 0.64030348, 263.33721367, 387.92069617
r = sym.solveset((A * x) + (B * sym.sqrt(x**3)) - (C * sym.exp(-x / 50)) - D, x)
print(r)

ConditionSet(x, Eq(0.40998854650011*x**3*exp(x/25) - 0.35894538550266*x**2*exp(x/25) + 315.541451511899*x*exp(x/50) + 464.822490657851*x*exp(x/25) - 204307.910508669*exp(x/50) - 150482.466517017*exp(x/25) - 69346.4881034792, 0), Complexes(Reals x Reals, False))

or in pprint form

⎧                                 x                         x
⎪                                 ──                        ──
⎨                              3  25                     2  25
⎪x | x ∊ ℂ ∧ 0.40998854650011⋅x ⋅ℯ   - 0.35894538550266⋅x ⋅ℯ   + 315.541451511
⎩

       x                        x                      x
       ──                       ──                     ──
       50                       25                     50
899⋅x⋅ℯ   + 464.822490657851⋅x⋅ℯ   - 204307.910508669⋅ℯ   - 150482.466517017⋅ℯ


x                        ⎫
──                       ⎪
25                       ⎬
   - 69346.4881034792 = 0⎪
                         ⎭

  • Jun 16, 2019
  • #10
The problem can be solved by using binary search. I solved it

Suggested for: Python equation solver, I’m getting a floating point error

  • Last Post
  • Oct 7, 2022
  • Last Post
  • Sep 23, 2022
  • Last Post
  • Oct 24, 2019
  • Last Post
  • Feb 17, 2020
  • Last Post
  • Mar 24, 2022
  • Last Post
  • Sep 30, 2022
  • Last Post
  • Apr 29, 2022
  • Last Post
  • Mar 29, 2022
  • Last Post
  • Dec 10, 2021
  • Last Post
  • Jan 30, 2021
  • Forums

  • Homework Help

  • Engineering and Comp Sci Homework Help

Total Weekly Downloads (37)

GitHub Stars

1

Forks

0

Contributors

1


Direct Usage Popularity


The PyPI package error-solver receives a total of
37 downloads a week. As such, we scored
error-solver popularity level to be Limited.

Based on project statistics from the GitHub repository for the
PyPI package error-solver, we found that it has been
starred 1 times.

The download numbers shown are the average weekly downloads from the
last 6 weeks.

Security and license risk for latest version

Release Date
Jun 4, 2019

Direct Vulnerabilities
  • 0

    C

  • 0

    H

  • 0

    M

  • 0

    L

Indirect Vulnerabilities
  • 0

    C

  • 0

    H

  • 0

    M

  • 0

    L

All security vulnerabilities belong to
production dependencies of direct and indirect
packages.


License

BSD-3-Clause


Security Policy

No

We found a way for you to contribute to the project! Looks like
error-solver is missing a security policy.


You can
connect your project’s repository to Snyk
to stay up to date on security alerts and receive automatic fix pull
requests.

Keep your project free of vulnerabilities with Snyk

Commit Frequency

Open Issues
0

Open PR
0

Last Release

4 years ago

Last Commit

4 years ago


Further analysis of the maintenance status of error-solver based on
released PyPI versions cadence, the repository activity,
and other data points determined that its maintenance is
Inactive.

An important project maintenance signal to consider for error-solver is
that it
hasn’t seen any new versions released to PyPI in the
past 12 months
, and could be considered as a discontinued project, or that which
receives low attention from its maintainers.

In the past month we didn’t find any pull request activity or change in
issues status has been detected for the GitHub repository.

Python Versions Compatibility

>=3.5


Age

4 years

Latest Release

4 years ago

Dependencies

2 Direct / 2 Total

Versions

4

Maintainers

1

Wheels

OS Independent

The Problem class is the entry point to
specifying and solving optimization problems. Each
Problem instance encapsulates an optimization
problem, i.e., an objective and a set of constraints.
The
solve() method either solves the problem
encoded by the instance, returning the optimal value and setting variables
values to optimal points, or reports that the problem was in fact infeasible or
unbounded. You can construct a problem, solve it, and inspect both its value
and the values of its variables like so:

problem = Problem(Minimize(expression), constraints)
problem.solve()
if problem.status not in ["infeasible", "unbounded"]:
    # Otherwise, problem.value is inf or -inf, respectively.
    print("Optimal value: %s" % problem.value)
    for variable in problem.variables():
        print("Variable %s: value %s" % (variable.name(), variable.value))

Problems are immutable, except through the specification of
Parameter values. This means
that you cannot modify a problem’s objective or constraints after you have
created it. If you find yourself wanting to add a constraint to an existing
problem, you should instead create a new problem using, for example, the
following idiom:

problem = Problem(Minimize(expression), constraints)
problem = Problem(problem.objective, problem.constraints + new_constraints)

Most users need not know anything about the
Problem class except how to instantiate it,
how to solve problem instances (solve()),
and how to query the solver results
(status and
value).

Information about the size of a problem instance and statistics about the most
recent solve invocation are captured by the
SizeMetrics and
SolverStats classes, respectively, and can be
accessed via the size_metrics() and
solver_stats() properties of the
Problem class.

Minimize¶

class cvxpy.Minimize(expr)[source]

An optimization objective for minimization.

Parameters:

expr (Expression) – The expression to minimize. Must be a scalar.

Raises:

ValueError – If expr is not a scalar.

is_dcp(dpp: bool = False) bool[source]

The objective must be convex.

is_dgp(dpp: bool = False) bool[source]

The objective must be log-log convex.

Maximize¶

class cvxpy.Maximize(expr)[source]

An optimization objective for maximization.

Parameters:

expr (Expression) – The expression to maximize. Must be a scalar.

Raises:

ValueError – If expr is not a scalar.

is_dcp(dpp: bool = False) bool[source]

The objective must be concave.

is_dgp(dpp: bool = False) bool[source]

The objective must be log-log concave.

Problem¶

class cvxpy.Problem(objective: Minimize | Maximize, constraints: List[Constraint] | None = None)[source]

A convex optimization problem.

Problems are immutable, save for modification through the specification
of Parameter

Parameters:
  • objective (Minimize or Maximize) – The problem’s objective.

  • constraints (list) – The constraints on the problem variables.

atoms() List[Atom][source]

Accessor method for atoms.

Returns:

A list of the atom types in the problem; note that this list
contains classes, not instances.

Return type:

list of Atom

backward() None[source]

Compute the gradient of a solution with respect to Parameters.

This method differentiates through the solution map of the problem,
obtaining the gradient of a solution with respect to the Parameters.
In other words, it calculates the sensitivities of the Parameters
with respect to perturbations in the optimal Variable values. This
can be useful for integrating CVXPY into automatic differentiation
toolkits.

backward() populates the gradient attribute of each Parameter
in the problem as a side-effect. It can only be called after calling
solve() with requires_grad=True.

Below is a simple example:

import cvxpy as cp
import numpy as np

p = cp.Parameter()
x = cp.Variable()
quadratic = cp.square(x - 2 * p)
problem = cp.Problem(cp.Minimize(quadratic), [x >= 0])
p.value = 3.0
problem.solve(requires_grad=True, eps=1e-10)
# backward() populates the gradient attribute of the parameters
problem.backward()
# Because x* = 2 * p, dx*/dp = 2
np.testing.assert_allclose(p.gradient, 2.0)

In the above example, the gradient could easily be computed by hand.
The backward() is useful because for almost all problems, the
gradient cannot be computed analytically.

This method can be used to differentiate through any DCP or DGP
problem, as long as the problem is DPP compliant (i.e.,
problem.is_dcp(dpp=True) or problem.is_dgp(dpp=True) evaluates to
True).

This method uses the chain rule to evaluate the gradients of a
scalar-valued function of the Variables with respect to the Parameters.
For example, let x be a variable and p a Parameter; x and p might be
scalars, vectors, or matrices. Let f be a scalar-valued function, with
z = f(x). Then this method computes dz/dp = (dz/dx) (dx/p). dz/dx
is chosen as the all-ones vector by default, corresponding to
choosing f to be the sum function. You can specify a custom value for
dz/dx by setting the gradient attribute on your variables. For example,

import cvxpy as cp
import numpy as np


b = cp.Parameter()
x = cp.Variable()
quadratic = cp.square(x - 2 * b)
problem = cp.Problem(cp.Minimize(quadratic), [x >= 0])
b.value = 3.
problem.solve(requires_grad=True, eps=1e-10)
x.gradient = 4.
problem.backward()
# dz/dp = dz/dx dx/dp = 4. * 2. == 8.
np.testing.assert_allclose(b.gradient, 8.)

The gradient attribute on a variable can also be interpreted as a
perturbation to its optimal value.

Raises:
  • ValueError – if solve was not called with requires_grad=True

  • SolverError – if the problem is infeasible or unbounded

constants() List[Constant][source]

Accessor method for constants.

Returns:

A list of the constants in the problem.

Return type:

list of Constant

derivative() None[source]

Apply the derivative of the solution map to perturbations in the Parameters

This method applies the derivative of the solution map to perturbations
in the Parameters to obtain perturbations in the optimal values of the
Variables. In other words, it tells you how the optimal values of the
Variables would be changed by small changes to the Parameters.

You can specify perturbations in a Parameter by setting its delta
attribute (if unspecified, the perturbation defaults to 0).

This method populates the delta attribute of the Variables as a
side-effect.

This method can only be called after calling solve() with
requires_grad=True. It is compatible with both DCP and DGP
problems (that are also DPP-compliant).

Below is a simple example:

import cvxpy as cp
import numpy as np

p = cp.Parameter()
x = cp.Variable()
quadratic = cp.square(x - 2 * p)
problem = cp.Problem(cp.Minimize(quadratic), [x >= 0])
p.value = 3.0
problem.solve(requires_grad=True, eps=1e-10)
# derivative() populates the delta attribute of the variables
p.delta = 1e-3
problem.derivative()
# Because x* = 2 * p, dx*/dp = 2, so (dx*/dp)(p.delta) == 2e-3
np.testing.assert_allclose(x.delta, 2e-3)
Raises:
  • ValueError – if solve was not called with requires_grad=True

  • SolverError – if the problem is infeasible or unbounded

get_problem_data(solver, gp: bool = False, enforce_dpp: bool = False, ignore_dpp: bool = False, verbose: bool = False, canon_backend: str | None = None, solver_opts: dict | None = None)[source]

Returns the problem data used in the call to the solver.

When a problem is solved, CVXPY creates a chain of reductions enclosed
in a SolvingChain,
and compiles it to some low-level representation that is
compatible with the targeted solver. This method returns that low-level
representation.

For some solving chains, this low-level representation is a dictionary
that contains exactly those arguments that were supplied to the solver;
however, for other solving chains, the data is an intermediate
representation that is compiled even further by the solver interfaces.

A solution to the equivalent low-level problem can be obtained via the
data by invoking the solve_via_data method of the returned solving
chain, a thin wrapper around the code external to CVXPY that further
processes and solves the problem. Invoke the unpack_results method
to recover a solution to the original problem.

For example:

objective = ...
constraints = ...
problem = cp.Problem(objective, constraints)
data, chain, inverse_data = problem.get_problem_data(cp.SCS)
# calls SCS using `data`
soln = chain.solve_via_data(problem, data)
# unpacks the solution returned by SCS into `problem`
problem.unpack_results(soln, chain, inverse_data)

Alternatively, the data dictionary returned by this method
contains enough information to bypass CVXPY and call the solver
directly.

For example:

problem = cp.Problem(objective, constraints)
data, _, _ = problem.get_problem_data(cp.SCS)

import scs
probdata = {
  'A': data['A'],
  'b': data['b'],
  'c': data['c'],
}
cone_dims = data['dims']
cones = {
    "f": cone_dims.zero,
    "l": cone_dims.nonneg,
    "q": cone_dims.soc,
    "ep": cone_dims.exp,
    "s": cone_dims.psd,
}
soln = scs.solve(data, cones)

The structure of the data dict that CVXPY returns depends on the
solver. For details, consult the solver interfaces in
cvxpy/reductions/solvers.

Parameters:
  • solver (str) – The solver the problem data is for.

  • gp (bool, optional) – If True, then parses the problem as a disciplined geometric program
    instead of a disciplined convex program.

  • enforce_dpp (bool, optional) – When True, a DPPError will be thrown when trying to parse a non-DPP
    problem (instead of just a warning). Defaults to False.

  • ignore_dpp (bool, optional) – When True, DPP problems will be treated as non-DPP,
    which may speed up compilation. Defaults to False.

  • canon_backend (str, optional) – ‘CPP’ (default) | ‘SCIPY’
    Specifies which backend to use for canonicalization, which can affect
    compilation time. Defaults to None, i.e., selecting the default
    backend.

  • verbose (bool, optional) – If True, print verbose output related to problem compilation.

  • solver_opts (dict, optional) – A dict of options that will be passed to the specific solver.
    In general, these options will override any default settings
    imposed by cvxpy.

Returns:
  • dict or object – lowest level representation of problem

  • SolvingChain – The solving chain that created the data.

  • list – The inverse data generated by the chain.

Raises:

cvxpy.error.DPPError – Raised if DPP settings are invalid.

is_dcp(dpp: bool = False) bool[source]

Does the problem satisfy DCP rules?

Parameters:

dpp (bool, optional) –

If True, enforce the disciplined parametrized programming (DPP)
ruleset; only relevant when the problem involves Parameters.
DPP is a mild restriction of DCP. When a problem involving
Parameters is DPP, subsequent solves can be much faster than
the first one. For more information, consult the documentation at

https://www.cvxpy.org/tutorial/advanced/index.html#disciplined-parametrized-programming

Returns:

True if the Expression is DCP, False otherwise.

Return type:

bool

is_dgp(dpp: bool = False) bool[source]

Does the problem satisfy DGP rules?

Parameters:

dpp (bool, optional) –

If True, enforce the disciplined parametrized programming (DPP)
ruleset; only relevant when the problem involves Parameters.
DPP is a mild restriction of DGP. When a problem involving
Parameters is DPP, subsequent solves can be much faster than
the first one. For more information, consult the documentation at

https://www.cvxpy.org/tutorial/advanced/index.html#disciplined-parametrized-programming

Returns:

True if the Expression is DGP, False otherwise.

Return type:

bool

is_dpp(context: str = ‘dcp’) bool[source]

Does the problem satisfy DPP rules?

DPP is a mild restriction of DGP. When a problem involving
Parameters is DPP, subsequent solves can be much faster than
the first one. For more information, consult the documentation at

https://www.cvxpy.org/tutorial/advanced/index.html#disciplined-parametrized-programming

Parameters:

context (str) – Whether to check DPP-compliance for DCP or DGP; context should
be either 'dcp' or 'dgp'. Calling problem.is_dpp('dcp')
is equivalent to problem.is_dcp(dpp=True), and
problem.is_dpp(‘dgp’)` is equivalent to
problem.is_dgp(dpp=True).

Returns:

Whether the problem satisfies the DPP rules.

Return type:

bool

is_dqcp() bool[source]

Does the problem satisfy the DQCP rules?

is_qp() bool[source]

Is problem a quadratic program?

parameters()[source]

Accessor method for parameters.

Returns:

A list of the parameters in the problem.

Return type:

list of Parameter

classmethod register_solve(name: str, func) None[source]

Adds a solve method to the Problem class.

Parameters:
  • name (str) – The keyword for the method.

  • func (function) – The function that executes the solve method. This function must
    take as its first argument the problem instance to solve.

solve(*args, **kwargs)[source]

Compiles and solves the problem using the specified method.

Populates the status and value attributes on the
problem object as a side-effect.

Parameters:
  • solver (str, optional) – The solver to use. For example, ‘ECOS’, ‘SCS’, or ‘OSQP’.

  • verbose (bool, optional) – Overrides the default of hiding solver output, and prints
    logging information describing CVXPY’s compilation process.

  • gp (bool, optional) – If True, parses the problem as a disciplined geometric program
    instead of a disciplined convex program.

  • qcp (bool, optional) – If True, parses the problem as a disciplined quasiconvex program
    instead of a disciplined convex program.

  • requires_grad (bool, optional) –

    Makes it possible to compute gradients of a solution with respect to
    Parameters by calling problem.backward() after solving, or to
    compute perturbations to the variables given perturbations to Parameters by
    calling problem.derivative().

    Gradients are only supported for DCP and DGP problems, not
    quasiconvex problems. When computing gradients (i.e., when
    this argument is True), the problem must satisfy the DPP rules.

  • enforce_dpp (bool, optional) – When True, a DPPError will be thrown when trying to solve a non-DPP
    problem (instead of just a warning). Only relevant for problems
    involving Parameters. Defaults to False.

  • ignore_dpp (bool, optional) – When True, DPP problems will be treated as non-DPP,
    which may speed up compilation. Defaults to False.

  • method (function, optional) – A custom solve method to use.

  • kwargs (keywords, optional) – Additional solver specific arguments. See Notes below.

Notes

CVXPY interfaces with a wide range of solvers; the algorithms used by these solvers
have arguments relating to stopping criteria, and strategies to improve solution quality.

There is no one choice of arguments which is perfect for every problem. If you are not
getting satisfactory results from a solver, you can try changing its arguments. The
exact way this is done depends on the specific solver. Here are some examples:

prob.solve(solver='ECOS', abstol=1e-6)
prob.solve(solver='OSQP', max_iter=10000).
mydict = {"MSK_DPAR_INTPNT_CO_TOL_NEAR_REL":  10}
prob.solve(solver='MOSEK', mosek_params=mydict).

You should refer to CVXPY’s web documentation for details on how to pass solver
solver arguments, available at

https://www.cvxpy.org/tutorial/advanced/index.html#setting-solver-options

Returns:

The optimal value for the problem, or a string indicating
why the problem could not be solved.

Return type:

float

Raises:
  • cvxpy.error.DCPError – Raised if the problem is not DCP and gp is False.

  • cvxpy.error.DGPError – Raised if the problem is not DGP and gp is True.

  • cvxpy.error.DPPError – Raised if DPP settings are invalid.

  • cvxpy.error.SolverError – Raised if no suitable solver exists among the installed solvers,
    or if an unanticipated error is encountered.

unpack_results(solution, chain: SolvingChain, inverse_data) None[source]

Updates the problem state given the solver results.

Updates problem.status, problem.value and value of
primal and dual variables.

Parameters:
  • solution (object) – The solution returned by applying the chain to the problem
    and invoking the solver on the resulting data.

  • chain (SolvingChain) – A solving chain that was used to solve the problem.

  • inverse_data (list) – The inverse data returned by applying the chain to the problem.

Raises:

cvxpy.error.SolverError – If the solver failed

variables() List[Variable][source]

Accessor method for variables.

Returns:

A list of the variables in the problem.

Return type:

list of Variable

property constraints: List[Constraint]

A shallow copy of the problem’s constraints.

Note that constraints cannot be reassigned, appended to, or otherwise
modified after creation, except through parameters.

property objective: Minimize | Maximize

The problem’s objective.

Note that the objective cannot be reassigned after creation,
and modifying the objective after creation will result in
undefined behavior.

Type:

Minimize or Maximize

property size_metrics: SizeMetrics

Information about the problem’s size.

Type:

SizeMetrics

property solver_stats: SolverStats

Information returned by the solver.

Type:

SolverStats

property status: str

The status from the last time the problem was solved; one
of optimal, infeasible, or unbounded (with or without
suffix inaccurate).

Type:

str

property value

The value from the last time the problem was solved
(or None if not solved).

Type:

float

SizeMetrics¶

class cvxpy.problems.problem.SizeMetrics(problem: Problem)[source]

Reports various metrics regarding the problem.

num_scalar_variables

The number of scalar variables in the problem.

Type:

integer

num_scalar_data

The number of scalar constants and parameters in the problem. The number of
constants used across all matrices, vectors, in the problem.
Some constants are not apparent when the problem is constructed: for example,
The sum_squares expression is a wrapper for a quad_over_lin expression with a
constant 1 in the denominator.

Type:

integer

num_scalar_eq_constr

The number of scalar equality constraints in the problem.

Type:

integer

num_scalar_leq_constr

The number of scalar inequality constraints in the problem.

Type:

integer

max_data_dimension

The longest dimension of any data block constraint or parameter.

Type:

integer

max_big_small_squared

The maximum value of (big)(small)^2 over all data blocks of the problem, where
(big) is the larger dimension and (small) is the smaller dimension
for each data block.

Type:

integer

SolverStats¶

class cvxpy.problems.problem.SolverStats(results_dict, solver_name: str)[source]

Reports some of the miscellaneous information that is returned
by the solver after solving but that is not captured directly by
the Problem instance.

solver_name

The name of the solver.

Type:

str

solve_time

The time (in seconds) it took for the solver to solve the problem.

Type:

double

setup_time

The time (in seconds) it took for the solver to setup the problem.

Type:

double

num_iters

The number of iterations the solver had to go through to find a solution.

Type:

int

Extra statistics specific to the solver; these statistics are typically
returned directly from the solver, without modification by CVXPY.
This object may be a dict, or a custom Python object.

Type:

object

def test_solver():
    """Verify linear/quadratic solution."""
    # Set input data for the test
    I = 1.2; V = 3; m = 2; b = 0.9; k = 4
    s = lambda u: k*u
    T = 2
    dt = 0.2
    N = int(round(T/dt))
    time_points = np.linspace(0, T, N+1)

    # Test linear damping
    t = sp.Symbol('t')
    q = 2  # arbitrary constant
    u_exact = I + V*t + q*t**2   # sympy expression
    F_term = lhs_eq(t, m, b, s, u_exact, 'linear')
    print 'Fitted source term, linear case:', F_term
    F = sp.lambdify([t], F_term)
    u, t_ = solver(I, V, m, b, s, F, time_points, 'linear')
    u_e = sp.lambdify([t], u_exact, modules='numpy')
    error = abs(u_e(t_) - u).max()
    tol = 1E-13
    assert error < tol

    # Test quadratic damping: u_exact must be linear
    u_exact = I + V*t
    F_term = lhs_eq(t, m, b, s, u_exact, 'quadratic')
    print 'Fitted source term, quadratic case:', F_term
    F = sp.lambdify([t], F_term)
    u, t_ = solver(I, V, m, b, s, F, time_points, 'quadratic')
    u_e = sp.lambdify([t], u_exact, modules='numpy')
    error = abs(u_e(t_) - u).max()
    assert error < tol
 def setUp(self):
     self.testcube = solver()
     self.solved = cube()
     self.strings = ["FRLUULRFFBLF","FBFRRBLF","UULLFBLUURRDDBDRDLLFBBB",
                     "DBLURFBLURUDDDBFRLLRUFFB","BRBULFFUDDUBRBURLDUBLDRU",
                     "BFRDUFRLURFBDURBFLRUULRDBFLRUFBRLDUFRDDRFBLDUFBDRLUBF",
                     "UBRDULRUDRURBFURDBFRDLUBFRLUDBFRDUBFRLUDBFRURDFBURLBF"]

def test_all_functions():
    """Verify a linear/quadratic solution."""
    I = 1.2; V = 3; m = 2; b = 0.9
    s = lambda u: 4*u
    t = sp.Symbol('t')
    T = 2
    dt = 0.2
    N = int(round(T/dt))
    time_points = np.linspace(0, T, N+1)

    def solver_linear_damping_wrapper(
        I, V, m, b, s, F, t, damping='linear'):
        """Wrapper such that solver_linear_damping can be called as solver."""
        if callable(F):
            F = F(t)
        return solver_linear_damping(I, V, m, b, s, F, t), t

    functions = [solver, solver_linear_damping_wrapper]
    try:
        from solver_cy import solver as solver_cy
        functions.append(solver_cy)
    except ImportError:
        print 'Cython module is not compiled'
        pass

    for function in functions:
        print 'testing', function.__name__
        # Test linear damping
        q = 2  # arbitrary constant
        u_exact = I + V*t + q*t**2
        u_e = sp.lambdify(t, u_exact, modules='numpy')
        F = sp.lambdify(t, lhs_eq(t, m, b, s, u_exact, 'linear'))
        u, t_ = solver(I, V, m, b, s, F, time_points, 'linear')
        error = abs(u_e(t_) - u).max()
        nt.assert_almost_equal(error, 0, places=13)

        # Test quadratic damping
        if function != solver_linear_damping_wrapper:

            # In the quadratic damping case, u_exact must be linear
            # in order exactly recover this solution
            u_exact = I + V*t
            u_e = sp.lambdify(t, u_exact, modules='numpy')
            F = sp.lambdify(t, lhs_eq(t, m, b, s, u_exact, 'quadratic'))
            u, t_ = solver(I, V, m, b, s, F, time_points, 'quadratic')
            error = abs(u_e(t_) - u).max()
            nt.assert_almost_equal(error, 0, places=13)

def test(size):
  a = generate_a(size)
  x = generate_x(size)
  b = a.dot(x)
  xx = solver.solver(a,b)
  print(x)
  print("result:",xx)
  print(linalg.norm(x-xx))

def box_actions(results, times, N_matrix, ifprint):
    """
        Finds actions, angles and frequencies for box orbit.
        Takes a series of phase-space points from an orbit integration at times t and returns
        L = (act,ang,n_vec,toy_aa, pars) -- explained in find_actions() below.
    """
    if ifprint:
        print ("n=====nUsing triaxial harmonic toy potential")

    t = time.time()
    # Find best toy parameters
    omega = toy.findbestparams_ho(results)
    if ifprint:
        print ("Best omega " + str(omega) + " found in " + str(time.time() - t) + " seconds")

    # Now find toy actions and angles
    AA = np.array([toy.angact_ho(i, omega) for i in results])
    AA = AA[~np.isnan(AA).any(1)]
    if len(AA) == 0:
        return

    t = time.time()
    act = solver.solver(AA, N_matrix)
    if act == None:
        return

    if ifprint:
        print (
            "Action solution found for N_max = "
            + str(N_matrix)
            + ", size "
            + str(len(act[0]))
            + " symmetric matrix in "
            + str(time.time() - t)
            + " seconds"
        )

    np.savetxt("GF.Sn_box", np.vstack((act[1].T, act[0][3:])).T)

    ang = solver.angle_solver(AA, times, N_matrix, np.ones(3))
    if ifprint:
        print (
            "Angle solution found for N_max = "
            + str(N_matrix)
            + ", size "
            + str(len(ang))
            + " symmetric matrix in "
            + str(time.time() - t)
            + " seconds"
        )

    # Just some checks
    if len(ang) > len(AA):
        print ("More unknowns than equations")

    return act[0], ang, act[1], AA, omega
    def test_solving_steps(self):
       cubes = []
       for s in self.strings:
            c = solver()
            c.do_string(s)
            cubes.append(c)
       for c in cubes:
            c.solmoves = []
            c._upper_edges_FRBL()
            c._upper_edges_D()
            self.check_top_edges(c)

            c._upper_corners()
            self.check_top_corners(c)

            c.solve_middle()
            self.check_middle(c)

            c.solve_down()
            temp = solver()
            self.assertTrue(c == temp)
    def __init__(self, master):

        frame = Frame(master)
        frame.pack()

        self.rcube = solver()
        self.scramble_moves = []

        bframe = Frame(frame) #frame for cube manipulation

        #rotation buttons
        self.r = Button(bframe, text="Right", command=lambda: self.do_rotation('R'))
        self.r.grid(row=1)
        self.l = Button(bframe, text="Left", command=lambda: self.do_rotation('L'))
        self.l.grid(row=1,column=1)
        self.f = Button(bframe, text="Front", command=lambda: self.do_rotation('F'))
        self.f.grid(row=2)
        self.b = Button(bframe, text="Back", command=lambda: self.do_rotation('B'))
        self.b.grid(row=2,column=1)
        self.u = Button(bframe, text="Upper", command=lambda: self.do_rotation('U'))
        self.u.grid(row=3)
        self.d = Button(bframe, text="Down", command=lambda: self.do_rotation('D'))
        self.d.grid(row=3,column=1)

        self.newcube = Button(bframe, text="Create New Cube", command=self.create_cube)
        self.newcube.grid(row=0,column=0)

        self.scramble = Button(bframe, text="Scramble Cube",command=self.scramble_cube)
        self.scramble.grid(row=0,column=1)

        bframe.pack(side=RIGHT)

        downframe = Frame(frame)

        self.quit = Button(downframe, text="QUIT", fg="red", command=frame.quit)
        self.quit.pack(side=RIGHT)

        solveframe = Frame(downframe)

        self.solve = Button(solveframe, text="Solve Cube",command=self.solve_cube)
        self.solve.pack(side=LEFT)

        self.solinfo = Button(solveframe, text="Solution Info",command=self.sol_info)
        self.solinfo.pack(side=RIGHT)

        solveframe.pack(side=LEFT)
        downframe.pack(side=BOTTOM,pady=15,padx=15)

        self.cube_disp(frame)
def loop_actions(results, times, N_matrix, ifprint):
    """
        Finds actions, angles and frequencies for loop orbit.
        Takes a series of phase-space points from an orbit integration at times t and returns
        L = (act,ang,n_vec,toy_aa, pars) -- explained in find_actions() below.
        results must be oriented such that circulation is about the z-axis
    """
    if(ifprint):
        print("n=====nUsing isochrone toy potential")
    
    t = time.time()
    # First find the best set of toy parameters
    params = toy.findbestparams_iso(results)
    if(params[0]!=params[0]):
        params = np.array([10.,10.])
    if(ifprint):
        print("Best params "+str(params)+" found in "+str(time.time()-t)+" seconds")

    # Now find the toy angles and actions in this potential
    AA = np.array([toy.angact_iso(i,params) for i in results])
    AA = AA[~np.isnan(AA).any(1)]
    if(len(AA)==0):
        return 

    t = time.time()
    act = solver.solver(AA, N_matrix,symNx = 1)
    if act==None:
        return

    if(ifprint):
        print("Action solution found for N_max = "+str(N_matrix)+", size "+str(len(act[0]))+" symmetric matrix in "+str(time.time()-t)+" seconds")

    # Store Sn
    np.savetxt("GF.Sn_loop",np.vstack((act[1].T,act[0][3:])).T)

    # Find angles
    sign = np.array([1.,np.sign(results[0][0]*results[0][4]-results[0][1]*results[0][3]),1.])
    ang = solver.angle_solver(AA,times,N_matrix,sign,symNx = 1)
    if(ifprint):
        print("Angle solution found for N_max = "+str(N_matrix)+", size "+str(len(ang))+" symmetric matrix in "+str(time.time()-t)+" seconds")
    
    # Just some checks
    if(len(ang)>len(AA)):
        print("More unknowns than equations")

    return act[0], ang, act[1], AA, params

def test_compare_action_prepare():

    from ..actionangle import _action_prepare, _angle_prepare
    import solver
    logger.setLevel(logging.ERROR)
    AA = np.random.uniform(0., 100., size=(1000,6))
    t = np.linspace(0., 100., 1000)

    act_san,n_vectors = solver.solver(AA, N_max=6, symNx=2)
    A2,b2,n = _action_prepare(AA, N_max=6, dx=2, dy=2, dz=2)
    act_apw = np.array(solve(A2,b2))

    ang_san = solver.angle_solver(AA, t, N_max=6, symNx=2, sign=1)
    A2,b2,n = _angle_prepare(AA, t, N_max=6, dx=2, dy=2, dz=2)
    ang_apw = np.array(solve(A2,b2))

    assert np.allclose(act_apw, act_san)
    assert np.allclose(ang_apw, ang_san)
def getpost():
    """
    Stdin comes from the web page and is a set of letters.

    Call solver and send the solution (an html table) to stdout.
    """
    logging.basicConfig(filename='results.log',level=logging.DEBUG)
    cgitb.enable()
    form = cgi.FieldStorage()
    instr = form["data"].value.replace(' ','0')
    pieces = list(instr)
    logging.info(pieces)
    answer = solver(pieces)
    print "Content-type: text/html"
    print
    logging.info('response: ')
    logging.info(answer)
    print answer
def generate_bumpy_road(nbumps=12, L=200, resolution=500):
    """Generate one road profile by using a vibration ODE."""
    n = nbumps*resolution      # no of compute intervals along the road
    x = np.linspace(0, L, n+1) # points along the road
    dx = x[1] - x[0]           # step along the road
    white_noise = np.random.randn(n+1)/np.sqrt(dx)
    # Compute h(x)
    k = 1.
    m = 4.
    if dx > 2/np.sqrt(k/m):
        print 'Unstable scheme'
    def s(u):
        return k*u

    h, x = solver(I=0, V=0, m=m, b=3, s=s, F=white_noise,
                  t=x, damping='linear')
    h = h/h.max()*0.2
    return h, x
def doit(name, n,r, g,W, x,z):
    print
    print
    print "// ------- Generated from kkt_test.py ---"
    print "template <typename Scalar> int kkt_test_%s() {" % name
    print
    print "typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> Matrix;"
    print "typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Vector;"
    print
    print "// Problem"
    print "int n = %d;" % n
    print "int r = %d;" % r
    print "Matrix g(n,n);"

    print "cvxopt::ScalingMatrix<Scalar> w;"
    print "w.d.resize(2*r*n);"
    print "Vector x(n*(r+1)), y, z(2*n*r);"

    print_cxx("x", x)
    print_cxx("z", z)

    print_cxx("g", g)
    print_cxx("w.d", W['d'])

    print
    print "// Solve"
    print "KQP_KKTPreSolver<Scalar> kkt_presolver(g, Vector::Ones(r));"
    print "boost::shared_ptr<cvxopt::KKTSolver<Scalar> > kktSolver(kkt_presolver.get(w));"
    print "kktSolver->solve(x,y,z);"
    print
    
    F = solver(n,r,g)
    sF = F(W)
    sF(x, None, z)

    print
    print "// Solution"
    
    print "Eigen::VectorXd s_x(n*(r+1)), s_z(2*n*r);"
    print_cxx("s_x", x)
    print_cxx("s_z", z)

    print """

 def main(self):
     solver= sol.solver();
     i=0;
     answer=""
     while i!=-1:
         print("Please chose one of the modes");
         print("1.SA-KQ");
         print("2.SA-GC");
         print("3.MC-KQ");
         print("4.MC-GC");
         print("5.Exit");
         answer=input(">>");
         try:
             index=int(answer);
         except ValueError:
             continue;
         if(index==1):
             print("1")
             print("Puzzle size ");
             answer=input(">>");
             nr=gr.conv_str2int(answer)
             puzzle=K.K_Puzzle(nr)
             print("How many neighbours? ");
             answer=input(">>");
             nr=gr.conv_str2int(answer)
             solver.algorithm_SA(puzzle,nr)
         elif(index==2):
             print("2")
         elif(index==3):
             print("3")
             print("Puzzle size ");
             answer=input(">>");
             nr=gr.conv_str2int(answer)
             puzzle=K.K_Puzzle(nr)
             print("How many neighbours? ");
             answer=input(">>");
             nr=gr.conv_str2int(answer)
             solver.algorithm_MC(puzzle,nr)
         elif(index==4):
             print("4")
         elif(index==5):
             print("5")
             i=-1
def main():
    ai = matlabarray(zeros (10,10,dtype=int),dtype=int)
    af = copy(ai)

    ai[1,1]=2
    ai[2,2]=3
    ai[3,3]=4
    ai[4,4]=5
    ai[5,5]=1

    af[9,9]=1
    af[8,8]=2
    af[7,7]=3
    af[6,6]=4
    af[10,10]=5

    t0 = time.clock()
    mv = a.solver(ai,af,0)
    t1 = time.clock()
    print t1-t0
    print mv.shape

def getpost():
    """
    Stdin comes from the web page and is a set of sudoku numbers.

    Call solver and send the solution as a set of cell values to stdout.
    """
    logging.basicConfig(filename='results.log',level=logging.DEBUG)
    cgitb.enable()
    form = cgi.FieldStorage()
    instr = form["data"].value.replace(' ','0')
    pieces = list(instr);
    tplate = []
    indx = 0
    logging.info('input: ')
    logging.info(instr)
    for i in range(0,9):
        tplate.append([])
        for j in range(0,9):
           tplate[i].append(pieces[indx])
           indx += 1
    info_res, result = solver(tplate)
    logging.info('info_res:')
    logging.info(info_res)
    if info_res == 'failure':
        logging.info('failure')
        print "Content-type: text/html"
        print
        print instr.replace('0', ' ')
        return
    outstr = []
    for i in range(0,9):
        for j in range(0,9):
            outstr.append(result[i][j])
    print "Content-type: text/html"
    print
    response = ''.join(outstr).replace('0', ' ')
    logging.info('response: ')
    logging.info(response)
    print response
v = 2.0                         # velocity (constant)

# Vertical displacement calculation
m = 2                           # mass of the system
b = 0.2                         # friction parameter
k = 1.5                         # spring parameter
T = road_xmax/v                 # end time
t = np.linspace(0, T, n+1)      # numerical time mesh
s = lambda u: k*u               # restoring force of spring
F = lambda t: -m*d2h(v*t)       # excitation force

import sys, os
sys.path.insert(0, os.path.join(os.pardir, 'src-bumpy'))
import solver

u, t = solver.solver(I=0, V=0, m=m, b=b, s=s, F=F, t=t,
                     damping='linear')

u_amplitude = (u.max() - u.min())/2
u_scaled = R*u/u_amplitude
u_solution = Curve(v*t, 5*H + u_scaled).set_linecolor('blue').set_linewidth(1)

arc_length = 0  # arc_length along road

def draw_vehicle(x, y, x0, y0, u):
    mass_width = 3*R
    mass_height = 1.5*R
    spring_length = 3*R
    spring_start = (x, y+2*R)

    tire_center = point(x, y+R)
    tire = Composition({
 def test_solver_on_small_data(self):
     data = '../data/words_small.txt'
     [largest_word, second_largest_word, count] = solver(data)
     self.assertEquals(largest_word, (11, ['catsdogcats']))
     self.assertEquals(second_largest_word, (10, ['dogcatsdog']))
     self.assertEquals(count, 3)
from matplotlib.pyplot import *
plot(t, u)
savefig('tmp.pdf')   # save plot to PDF file
savefig('tmp.png')   # save plot to PNG file
show()
# End solver_linear_damping

import numpy as np
from numpy import sin, pi  # for nice math
from solver import solver

def F(t):
    # Sinusoidal bumpy road
    return A*sin(pi*t)

def s(u):
    return k*(0.2*u + 1.5*u**3)

A = 0.25
k = 2
t = np.linspace(0, 100, 10001)
u, t = solver(I=0.1, V=0, m=2, b=0.5, s=s, F=F, t=t,
              damping='quadratic')

# Show u(t) as a curve plot
import matplotlib.pyplot as plt
plt.plot(t, u)
plt.savefig('tmp.png')
plt.savefig('tmp.pdf')
plt.show()

from cube import cube
from solver import solver

cb = solver()
done = False
while not done:
    ms = raw_input("Scramble String: ")
    ms = ms.upper()
    done = True
    for c in ms:
        done = done and ((c in cb.sides) or (c in ["2", "3"]) or (c == "'"))
    if not done:
        print "You used an invalid character"

cb.do_string(ms)
cb.solve()
disp = cube()
disp.do_string(ms)

print "Initial cube state:"
disp.print_cube()
for step in cb.solmoves:
    raw_input("next move is: " + step)
    disp.do_string(step)
    disp.print_cube()

def pretty_print(board):
    for i in range(len(board)):
        print board[i]


edge = 4

lst_board = 'D C L P  E I A E  R N T R  S E G S'.lower().split()


board = []
for i in range(0,16,4):
    board.append(lst_board[i:i+4])
pretty_print(board)
s = solver.solver(edge)
words =  sorted(s.solve(board))
print words

score = 0
for word in words:
    if len(word) == 3 or len(word) == 4:
        score += 1
    if len(word) == 5:
        score += 2
    if len(word) == 6:
        score += 3
    if len(word) > 6:
        score += 5
print score
    

b = 0.8  # friction parameter
k = 2  # spring parameter
V = 1.5
T = road_xmax / v  # end time
t = np.linspace(0, T, 101)  # numerical time mesh
s = lambda u: k * u  # restoring force of spring
F = lambda t: -m * d2h(v * t)  # excitation force

import sys, os

sys.path.insert(0, os.path.join(os.pardir, "src-bumpy"))
import solver

print road_xmax, T, v, v * T

u, t = solver.solver(I=0, V=V, m=m, b=b, s=s, F=F, t=t, damping="linear")

"""
# if you want to see plot of solver function, turn me on
import matplotlib.pyplot as plt
plt.plot(t, u)
plt.show()
"""
u_solution = Curve(v * t, 5 * H + 0.5 * H * u)

over = Rectangle(lower_left_corner=(-1.5 * R, 2 * H), width=3 * R, height=0.75 * H)

tire = Composition(
    {
        "wheel": Circle(center=(0, 0), radius=R),
        "cross": Composition({"cross1": Line((0, -1), (0, R)), "cross2": Line((-R, 0), (R, 0))}),
def main():
  # sentences = ['distance is speed times time', 'energy is force times distance',
  #              'energy is power times time', 'power is speed times force']
  sentences = ['distance is speed times time', 'speed times time is distance',
               'force is mass times acceleration',
               'speed is acceleration times time', 'power is speed times force',
               'energy is force times distance', 'energy is power times time',
               'speed is distance divided by time',
               'acceleration is speed divided by time',
               'speed times force is power',
               'speed is power divided by force']
  # sentences = [
  #   'distance is speed times time',
  #   'speed times time is distance',
  #   'speed is distance divided time',
  #   'distance is speed2 times time',
  #              'speed2 times time is distance',
  #              'speed2 is distance divided time',
  #              ]
  tuples = generateTuples(sentences)
  # [
  # [
  #     ('f', frozenset(['m', 'a']))
  #   ],
  #   [
  #     ('p', frozenset(['s', 'f']))
  #   ]
  # ]
  (solutions, globalStats) = solver.solver(tuples, [solver.featureConsistentTemplates, solver.validModels, solver.featurePercentagesTemplates, solver.featureMajorityTemplates])

  # solMap = {}
  # for s in solutions.keys():
  #   varSet = set({s[0][0]}).union(s[0][1])
  #   k = (varSet,s[1][0].word,s[1][1].word)
  #   if not solMap.has_key(k):
  #     solMap[k] = solutions[s]
  #   elif solutions[s]>solMap[k]:
  #     solMap[k] = solutions[s]

  pprint.pprint(solutions)
  pprint.pprint(globalStats)

  f1TimesCount = 0
  f1DividedCount = 0
  f2TimesCount = 0
  f2DividedCount = 0
  f3TimesCount = 0
  f3DividedCount = 0

  for (k, c) in solutions.iteritems():
    if k[1][1].word == "times" and k[1][0].templateNumber == 0: f1TimesCount += c
    if k[1][1].word == "divided" and k[1][0].templateNumber == 0: f1DividedCount += c
    if k[1][1].word == "times" and k[1][0].templateNumber == 1: f2TimesCount += c
    if k[1][1].word == "divided" and k[1][0].templateNumber == 1: f2DividedCount += c
    if k[1][1].word == "times" and k[1][0].templateNumber == 2: f3TimesCount += c
    if k[1][1].word == "divided" and k[1][0].templateNumber == 2: f3DividedCount += c

  print f1TimesCount
  print f1DividedCount
  print f2TimesCount
  print f2DividedCount
  print f3TimesCount
  print f3DividedCount

    print
    print "=== G"
    print G
    print
    print "=== h"
    print h.T
    print

    
print "=== Problem size: n=%d and r=%d ===nn" % (n, r)
print "* np = %d" % np
print "* lambda = %g" % Lambda

print "nn   [[[Solving with optimised]]]"
T1 = time()
sol = solvers.coneqp(P, q, G, h, kktsolver=solver(n,r,g))
print "Time taken = %s" % (time() - T1)
print sol['status']
if (n * r < 10): print "Solution = %s" % sol['x'].T

printing.options['width'] = n

nzeros=0
xi = sol['x'][n*r:n*(r+1)]
maxxi=max(xi)
print sum(xi[0:n])
for i in xrange(n):
    if xi[i]/maxxi < 1e-4: nzeros += 1

print "xi = %s" % sorted(xi.T/maxxi)
print "Sparsity = %d on %d" % (nzeros, n)

 def create_cube(self):
     del self.rcube
     self.rcube = solver()
     self.output_cube()
     self.scramble_moves = []
tests = 0

all_lines = []
full_dict = []
cases = []

with open(in_file) as f:
	all_lines = f.readlines()

params = all_lines[0]
params = params.split(" ");
wordsize = int(params[0])
dictSize = int(params[1])
tests = int(params[2])

full_dict = all_lines[1:1+dictSize]
cases = all_lines[1+dictSize:]
	
word_graph = alien_dict(full_dict, wordsize)

for i in range(len(cases)):
	cases[i] = ip.parse_raw(cases[i])

result = dict()

for i in range(len(cases)):
	result[i+1] = sv.solver(word_graph, cases[i]).solve()

for key, val in result.items():
	print('Case {}: {}'.format(key, val))

Понравилась статья? Поделить с друзьями:
  • Python socket error eof
  • Python socket error class
  • Python socket connection error
  • Python smtplib sendmail error
  • Python shutil copytree error