Can't derive dual values from a LP using CPLEX - linear-programming

I am trying to code a Bender's decomposition algorithm using CPLEX. To ensure that I code it correctly, I follow the numerical example from "Decomposition techniques in mathematical programming" by A.J. Conejo et al., p.247.
However, my problem can be stated without access to the mentionned material or knowledge of the context.
I need to solve the following LP and derive dual values for "fixing_x" constraint.
import cplex
x_master_value = 100.
c_toy_slave = cplex.Cplex()
types = c_toy_slave.variables.type
y = c_toy_slave.variables.add(names=["y"+str(i) for i in range(3)], lb=[0]*3, types=[types.continuous]*3)
x = c_toy_slave.variables.add(names=["x"], lb=[0], types=[types.continuous])
w = c_toy_slave.variables.add(names=["w"], lb=[0], types=[types.continuous])
cst1 = c_toy_slave.linear_constraints.add([[["y0", "y1", "x", "w"], [-1, -3, 2, -1]]],
names=["cst1"], rhs=[2], senses=['L'])
cst2 = c_toy_slave.linear_constraints.add([[["y0", "y1", "x", "w"], [1, 3, -1, -1]]],
names=["cst2"], rhs=[3], senses=['L'])
cst3 = c_toy_slave.linear_constraints.add([[["y2", "x"], [1, -3]]],
names=["cst3"], rhs=[7/2], senses=['L'])
cst4 = c_toy_slave.linear_constraints.add([[["x"], [1]]],
names=["fixing_x"], rhs=[x_master_value], senses=['E'])
c_toy_slave.objective.set_linear([("y0", -1.5), ("y1", -2), ("y2", -2), ("w", 40)])
c_toy_slave.objective.set_sense(c_toy_slave.objective.sense.minimize)
c_toy_slave.solve()
print("lambda = ", c_toy_slave.solution.get_dual_values("fixing_x"))
But CPLEX says it cannot use the get_dual_values method and prompt this message :
CPLEX Error 1017: Not available for mixed-integer problems.
I don't know how to solve that since the input I give is not a MIP but a genuine LP.

It turned out that removing the types=[type.continuous] optional argument solved my problem (i.e., the optimization problem is then properly recognized as an LP). If we look at the documentation for Cplex.variables.add, it says:
If types is specified, the problem type will be a MIP, even if all
variables are specified to be continuous.
So, this is the expected behavior.

Related

Reconciling exponential function results in C++ (Rcpp) and R

I am working on speeding up software from my dissertation by utilizing Rcpp and RcppEigen. I have been very impressed with Rcpp and RcppEigen as the speed of my software has increased by upwards of 100 times. This is quite exciting to me because my R code had been parallelized using snow/doSNOW and the foreach package, so the actual speed gain is probably somewhere around 400x. However, the last time I attempeted to run my program in entirety to assess overall speed gains after translating some gradient/hessian calculations into Cpp, I see that the new Hessian matrix calculated using my C++ code differs from the old, much slower version which was calculated strictly in R. I had been very careful to check my results line by line, slowly increasing the complexity of my calculations while assuring the results were identical in R and C++. I realize now that I was only checking the first 11 or so digits.
The code for optimization has been very robust in R, but was dreadfully slow. All of the calculations in C++ have been checked and were virtually identical to previous versions in R (this was checked to 11 digits via specifying options(digits = 11) at the beginning of each session). However, deviations in long vectors or matrices representing particular quantities begin at 15 or so digits past the decimal point in some cells/elements. These differences become problematic when using matrix multiplication and summing over risk sets, as a small difference can lead to a large error (is it an error?) in the overall precision of the final estimate.
After looking back over my code and finding the first point of deviation in results between R and C++, I observed that this first occurs after taking the exponential of a matrix or vector in my Rcpp code. This led me to work out the examples below, which I hope illustrates the issue I am seeing. Has anyone observed this before, and is there a way to utilize the R exponential function within C++ or change the routine used within C++?
## A small example to illustrate issues with Rcppsugar exponentiate function
library(RcppEigen)
library(inline)
RcppsugarexpC <-
"
using Eigen::MatrixXd;
typedef Eigen::Map<Eigen::MatrixXd> MapMatd;
MapMatd A(as<MapMatd>(AA));
MatrixXd B = exp(A.array());
return wrap(B);
"
RcppexpC <-
"
using Eigen::MatrixXd;
using Eigen::VectorXd;
typedef Eigen::Map<Eigen::MatrixXd> MapMatd;
MapMatd A(as<MapMatd>(AA));
MatrixXd B = A.array().exp().matrix();
return wrap(B);
"
Rcppsugarexp <- cxxfunction(signature(AA = "NumericMatrix"), RcppsugarexpC, plugin = "RcppEigen")
Rcppexp <- cxxfunction(signature(AA = "NumericMatrix"), RcppexpC, plugin = "RcppEigen")
mat <- matrix(seq(-5.25, 10.25, by = 1), ncol = 4, nrow = 4)
RcppsugarC <- Rcppsugarexp(mat)
RcppexpC <- Rcppexp(mat)
exp <- exp(mat)
I then tested whether these exponentiated matrices were actually equal beyond the print standard (default is 7) that R uses via:
exp == RcppexpC ## inequalities in 3 cells
exp == RcppsugarC ## inequalities in 3 cells
RcppsugarC == RcppexpC ## these are equal!
sprintf("%.22f", exp)
Please forgive me if this is a dense question - my computer science skills are not as strong as they should be, but I am eager to learn how to do better. I appreciate any and all help or advice that can be given me. Special thanks to the creators of Rcpp, and all of the wonderful moderators/contributors at this site - your previous answers have saved me from posting questions on here well over a hundred times!
Edit:
It turns out that I didn't know what I was doing. I wanted to apply Rcppsugar to the MatrixXd or VectorXd, which I was attempting by using the .array() method, however calling exp(A.array()) or A.exp() computes what is referred to as the matrix exponential, rather than computing exp(A_ij) element by element. My friend pointed this out to me when he worked out a simple example using std::exp() on each element in a nested for loop and found that this result was identical to what was reported in R. I thus needed to use the .unaryExpr functionality of eigen, which meant changing the compiler settings to -std=c++0x. I was able to do this by specifying the following in R:
settings$env$PKG_CXXFLAGS='-std=c++0x'
I then made a file called Rcpptesting.cpp which is below:
#include <RcppEigen.h>
// [[Rcpp::depends(RcppEigen)]]
using Eigen::Map; // 'maps' rather than copies
using Eigen::MatrixXd; // variable size matrix, double precision
using Eigen::VectorXd; // variable size vector, double precision
// [[Rcpp::export]]
MatrixXd expCorrect(Map<MatrixXd> M) {
MatrixXd M2 = M.unaryExpr([](double e){return(std::exp(e));});
return M2;
}
After this, I was able to call this function in with sourceCpp() in R as follows: (note that I used the option verbose = TRUE and rebuild = TRUE because this seems to give me info regarding what the settings are - I was trying to make sure that -std=c++0x was actually being used)
sourceCpp("~/testingRcpp.cpp", verbose = TRUE, rebuild = TRUE)
Then the following R code worked like a charm:
mat <- matrix(seq(-5.25, 10.25, by = 1), ncol = 4, nrow = 4)
exp(mat) == expCorrect(mat)
Pretty cool!

Understanding this python code

This code was on an exam and it asked what it's output was going to be.
I got it wrong unfortunately and put it was all 1's.
I'm a little confused with what this program is doing specifically with the if/else statement.
I'm a C programmer, so if possible could someone please translate the if/else statement into C code so I can understand what is going on. Thank you!
EDIT: to clarify, I'm not sure what the condition means "if x in d"
def somefunction(L):
d = {}
for x in L:
if x in d:
d[x] = d[x] + 1
else:
d[x] = 1
return d
L = [6, 10, -2, 2, 6, 4, -2, 6]
print somefunction(L)
output: {10: 1, 2: 1, 4: 1, -2: 2, 6: 3}
in in Python performs a containment check. It looks at the right-hand operand to see if it contains the left-hand operand.
>>> 2 in [1, 2, 4]
True
>>> 3 in [1, 2, 4]
False
I'd encourage you NOT to translate everything into C. Python is considerably different and trying to keep things in a C frame of mind will make things harder to understand.
One thing that is great is that Python is interpreted, so you can type "python" and then enter commands to see what they do. You can exam all the variables as things are manipulated. For example, you can do:
L = [6, 10, -2, 2, 6, 4, -2, 6]
for x in L:
print x
To see what the "in" does. Likewise for the rest of the code. Also, there are great online tutorials on Python, Google "Dive into Python", for example.
See Basically in this code what you are doing is you are making a count of no of times the element is repeated in the list..you are using dictionary as a means to take the count..
First of all in the if-else block you are checking whether the element is present or not..if its present then you are incrementing the count using the element as key..else you are creating a new key,key being the element and default value being 1...
Thus you iterate all over the list and check the count of each element in the list..
d[i]=j
#i is key,j is value.
And at last you print your findings by printing the dictionary..!!

Mathematica - Functions with Lists

I got this error in Mathematica today:
Set::shape: "Lists {0,0,0,0,0,0,0,0,0,0} and {0,0,0,0,0,0,0,0,0,0,{1}} are not the same shape" >>
And after 3 of those :
General::stop : Further output of Set::shape will be suppressed during this calculation. >>
I am confused as to why I cannot append a "1" to my list of zeros. Is this because I cannot edit the list that is passed into the function? If so, how could I edit that list and somehow return or print it?
Here is my full code:
notFunctioningFunction[list_] := (For[i = 1, i < 10, i++, list = Append[list, {1}]];
Print[list])
list = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
notFunctioningFunction[list]
The reason why I am appending a "{1}" is because in my function, I am solving an equation, and getting the value of the variable which outputs {1}. Here is my code for that :
varName / . Solve[ function1 == function2 ]
Obviously I am a beginner with Mathematica so please be patient :)
Thanks,
Bucco
Append needs to take one list and one element. Like so:
Append[{1,2,3,4},5]
If you have two lists, you can use Join. Like so:
Join[{1,2,3,4},{5}]
Both of these will yield the same result: {1,2,3,4,5}.
Dear Mathematica beginner.
First, when you use something like
{a,b} = {c,d,e};
in Mathematica, between two lists, the program has a difficulty because this is a construct used to assign values to variables, and it requires (among other things) the two lists to be equal.
If what you want is just to add a "1" to an existing and named list, one at a time, the best construct is:
AppendTo[list, 1];
(this construct will modify the variable 'list')
or
list = Join[list, {1}];
Second: about the error messages, they are printed 3 times by default in an evaluation, then muted so that a long list of identical error messages does not clutter your display.
Third, if what you need is adding 10 1s to a list, there is no need to construct that in a loop. You can do that in one pass:
list = Join[list, Table[1, {10}]]
or, more cryptic for beginners
list = Join[list, Array[1&, 10]]

Assigning list elements to variables

The output from Mathematica with the following operation FactorInteger[28851680048402838857] is as follows:
{{3897424303, 1}, {7402755719, 1}}
My question is: how could I go about extracting the two prime numbers (without the exponents) and assign them to an arbitrary variable?
I basically want to retrieve two primes, whatever they may be, and assign them some variables.
Ex: x0 = 3897424303 and x1 = 7402755719
Thanks!
The output is a list and you can use list manipulating functions like Part ([[ ]]) to pick the pieces you want, e.g.,
{x0, x1} = FactorInteger[28851680048402838857][[All, 1]]
or, without Part:
{{x0,dummy}, {x1,dummy}} = FactorInteger[28851680048402838857];
Implicit in your question is the issue of handing parts of the expression that is returned as output from functions such as FactorInteger. Allow me to suggest alternatives.
1. Keep all of the values in a {list} and access each element with Part:
x = First /# FactorInteger[7813426]
{2, 31, 126023}
x[[1]]
x[[3]]
2
126023
2. Store factors as values of the function x, mimicking indexation of an array:
(This code uses MapIndexed, Function.)
Clear[x]
MapIndexed[
(x[First##2] = First##1) &,
FactorInteger[7813426]
];
x[1]
x[3]
2
126023
You can see all the values using ? or ?? (see Information):
?x
Global`x
x[1]=2
x[2]=31
x[3]=126023

How to feed a list valued variable in the Outer command in mathematica

Consider the following piece of mathematica code:
a := {1, 2, 3};
f[n_, a_] := Sum[a[[j]], {j, 1, n}];
Outer[f, {3}, (a)]
The intention is to simply to evaluate f[3,a]. But I get the following error messages:
During evaluation of In[16]:= Part::partd: Part specification 1[[1]] is longer
than depth of object. >>
During evaluation of In[16]:= Part::partd: Part specification 1[[2]] is longer
than depth of object. >>
During evaluation of In[16]:= Part::partd: Part specification 1[[3]] is longer
than depth of object. >>
During evaluation of In[16]:= General::stop: Further output of Part::partd will
be suppressed during this calculation. >>
Out[16]= {{1[[1]] + 1[[2]] + 1[[3]], 2[[1]] + 2[[2]] + 2[[3]],
3[[1]] + 3[[2]] + 3[[3]]}}
So apparently Outer takes the list variable input a apart and treat its components separately.
My question is, how can I bundle the components in a together in the Outer environment? Many thanks!
You can do this:
Outer[f, {3}, {a}, 1, 1]
(* {{6}} *)
Depending on the real problem you are solving, there may be more superior ways (w.r.t. Outer), using Map or similar.