How to change the type of a variable using JuMP? - julia-jump

I am using Julia/JuMP to write an algorithm. I have previously defined an MILP, but now I want to relax some of the integer restrictions. How can I do this?
Here is my sample code:
using JuMP
using Gurobi
model = Model(Gurobi.Optimizer)
#variable(model, 0 <= x[i=1:2], Int)
#constraint(model, x[1] + x[2] >= 0.5)
#objective(model, Min, 3*x[1] + x[2])
# *Here I want to relax the integer restriction on x[2]*
optimize!(model)
println(value.(x))
I have found an old post with the same question (How to convert type of a variable when using JuMP), but the solution (using the function setcategory()) does not seem to work in the current version of JuMP.

You're looking for unset_integer:
https://jump.dev/JuMP.jl/stable/variables/#Integer-constraints-1
There is also relax_integrality
https://jump.dev/JuMP.jl/stable/variables/#JuMP.relax_integrality

Related

How do I repeat a random number

I've tried searching for help but I haven't found a solution yet, I'm trying to repeat math.random.
current code:
local ok = ""
for i = 0,10 do
local ok = ok..math.random(0,10)
end
print(ok)
no clue why it doesn't work, please help
Long answer
Even if the preferable answer is already given, just copying it will probably not lead to the solution you may expect or less future mistakes. So I decided to explain why your code fails and to fix it and also help better understand how DarkWiiPlayer's answer works (except for string.rep and string.gsub).
Issues
There are at least three issues in your code:
the math.random(m, n) function includes lower and the upper values
local declarations hide a same-name objects in outer scopes
math.random gives the same number sequence unless you set its seed with math.randomseed
See Detailed explanation section below for more.
Another point seems at least worth mentioning or suspicious to me, as I assume you might be puzzled by the result (it seems to me to reflect exactly the perspective of the C programmer, from which I also got to know Lua): the Lua for loop specifies start and end value, so both of these values are included.
Attempt to repair
Here I show how a version of your code that yields the same results as the answer you accepted: a sequence of 10 percent-encoded decimal digits.
-- this will change the seed value (but mind that its resolution is seconds)
math.randomseed(os.time())
-- initiate the (only) local variable we are working on later
local ok = ""
-- encode 10 random decimals (Lua's for-loop is one-based and inclusive)
for i = 1, 10 do
ok = ok ..
-- add fixed part
'%3' ..
-- concatenation operator implicitly converts number to string
math.random(0, 9) -- a random number in range [0..9]
end
print(ok)
Detailed explanation
This explanation makes heavily use of the assert function instead of adding print calls or comment what the output should be. In my opinion assert is the superior choice for illustrating expected behavior: The function guides us from one true statement - assert(true) - to the next, at the first miss - assert(false) - the program is exited.
Random ranges
The math library in Lua provides actually three random functions depending on the count of arguments you pass to it. Without arguments, the result is in the interval [0,1):
assert(math.random() >= 0)
assert(math.random() < 1)
the one-argument version returns a value between 1 and the argument:
assert(math.random(1) == 1)
assert(math.random(10) >= 1)
assert(math.random(10) <= 10)
the two-argument version explicitly specifies min and max values:
assert(math.random(2,2) == 2)
assert(math.random(0, 9) >= 0)
assert(math.random(0, 9) <= 9)
Hidden outer variable
In this example, we have two variables x of different type, the outer x is not accessible from the inner scope.
local x = ''
assert(type(x) == 'string')
do
local x = 0
assert(type(x) == 'number')
-- inner x changes type
x = x .. x
assert(x == '00')
end
assert(type(x) == 'string')
Predictable randomness
The first call to math.random() in a Lua program will return always the same number because the pseudorandom number generator (PRNG) starts at seed 1. So if you call math.randomseed(1), you'll reset the PRNG to its initial state.
r0 = math.random()
math.randomseed(1)
r1 = math.random()
assert(r0 == r1)
After calling math.randomseed(os.time()) calls to math.random() will return different sequences presuming that subsequent program starts differ at least by one second. See question Current time in milliseconds and its answers for more information about the resolutions of several Lua functions.
string.rep(".", 10):gsub(".", function() return "%3" .. math.random(0, 9) end)
That should give you what you want

Is there a way to use range with Z3ints in z3py?

I'm relatively new to Z3 and experimenting with it in python. I've coded a program which returns the order in which different actions is performed, represented with a number. Z3 returns an integer representing the second the action starts.
Now I want to look at the model and see if there is an instance of time where nothing happens. To do this I made a list with only 0's and I want to change the index at the times where each action is being executed, to 1. For instance, if an action start at the 5th second and takes 8 seconds to be executed, the index 5 to 12 would be set to 1. Doing this with all the actions and then look for 0's in the list would hopefully give me the instances where nothing happens.
The problem is: I would like to write something like this for coding the problem
list_for_check = [0]*total_time
m = s.model()
for action in actions:
for index in range(m.evaluate(action.number) , m.evaluate(action.number) + action.time_it_takes):
list_for_check[index] = 1
But I get the error:
'IntNumRef' object cannot be interpreted as an integer
I've understood that Z3 isn't returning normal ints or bools in their models, but writing
if m.evaluate(action.boolean):
works, so I'm assuming the if is overwritten in a way, but this doesn't seem to be the case with range. So my question is: Is there a way to use range with Z3 ints? Or is there another way to do this?
The problem might also be that action.time_it_takes is an integer and adding a Z3int with a "normal" int doesn't work. (Done in the second part of the range).
I've also tried using int(m.evaluate(action.number)), but it doesn't work.
Thanks in advance :)
When you call evaluate it returns an IntNumRef, which is an internal z3 representation of an integer number inside z3. You need to call as_long() method of it to convert it to a Python number. Here's an example:
from z3 import *
s = Solver()
a = Int('a')
s.add(a > 4);
s.add(a < 7);
if s.check() == sat:
m = s.model()
print("a is %s" % m.evaluate(a))
print("Iterating from a to a+5:")
av = m.evaluate(a).as_long()
for index in range(av, av + 5):
print(index)
When I run this, I get:
a is 5
Iterating from a to a+5:
5
6
7
8
9
which is exactly what you're trying to achieve.
The method as_long() is defined here. Note that there are similar conversion functions from bit-vectors and rationals as well. You can search the z3py api using the interface at: https://z3prover.github.io/api/html/namespacez3py.html

Eigen's LeastSquaresConjugateGradient solver: using Incomplete Cholesky preconditioner and specifying coefficient starting values

To solve a rectangular sparse linear system of equations I would like to use Eigen's LeastSquaresConjugateGradient. Aside from the default Jacobi and Identity preconditioner I was wondering though if it is possible to also use Incomplete Cholesky as a preconditioner within LeastSquaresConjugateGradient?
The Rcpp code I have and which uses the default Jacobi ([LeastSquareDiagonalPreconditioner) preconditioner is:
library(inline)
library(RcppEigen)
solve_sparse_lsconjgrad <- cxxfunction( signature(input_ = "list"), '
using Eigen::VectorXd;
using Eigen::MatrixXd;
using Eigen::Lower;
using Eigen::Map;
using Eigen::SparseMatrix;
using Eigen::IdentityPreconditioner;
// using Eigen::IncompleteCholesky;
using Eigen::LeastSquaresConjugateGradient;
List input(input_);
const Map<SparseMatrix<double> > m1 = input[0]; // X
const Map<VectorXd> v1 = input[1]; // y
const Map<VectorXd> x = input[2]; // initial coefficient guess
SparseMatrix<double> m2(m1.cols(), m1.cols());
m2.selfadjointView<Lower>().rankUpdate(m1.adjoint());
Eigen::LeastSquaresConjugateGradient<SparseMatrix<double> > solver;
solver.setMaxIterations(100);
solver.setTolerance(1E-20);
solver.compute(m1);
VectorXd res = solver.solveWithGuess(v1, x);
return List::create(_["res"] = res,
_["rows"] = double(solver.rows()),
_["cols"] = double(solver.cols()));
',
plugin = "RcppEigen")
Usage is
solve_sparse_lsconjgrad(list(X, y, coefficient_starting_values))
But how should I modify this to use IncompleteCholesky as a preconditioner instead? In another stack overflow question I saw that one needs to define
typedef LeastSquaresConjugateGradient<SparseMatrix<double>, IncompleteCholesky<double> > ICCG;
but I was unsure then how to use that in the code above. Any thoughts? I was also wondering if I am passing my initial coefficient estimates correctly, because I notice that if I solve my problem once and use the obtained coefficients as starting values in a new fit that I am hardly getting any speed benefits, which I thought is strange...

How to use cwise operations over specific indexes of a vector? (Eigen)

I'm trying to translate the following Matlab code to C/C++.
indl = find(dlamu1 < 0); indu = find(dlamu2 < 0);
s = min([1; -lamu1(indl)./dlamu1(indl); -lamu2(indu)./dlamu2(indu)]);
I've read on another thread that there's yet no equivalent in the Eigen library to the find() function and I'm at peace with that and have brute-forced around it.
Now, if I wanted to do the coefficient-wise division of lamu1 and dlamu1, I'd go for lamu1.cwiseQuotient(dlamu1) but how do I go about doing that but only for some of their coefficients, which indexes are specified by the coefficients of indl? I haven't found anything about this in the documentation, but maybe I'm not using the right search terms.
With the default branch you can just write lamu1(indl) with indl a std::vector<int> or a Eigen::VectorXi or whatever you like that supports random access through operator[].
There is no equivalent of find (yet) even in the default branch. Your function can however be expressed using the select method (also works with Eigen 3.3.x):
double ret1 = (dlamu1.array()<0).select(-lamu1.cwiseQuotient(dlamu1), 1.0).minCoeff();
return std::min(1.0,ret1); // not necessary, if dlamu1.array()<0 at least once
select evaluates lazily, i.e., only if the condition is true, the quotient will be calculated. On the other hand, a lot of unnecessary comparisons with 1.0 will happen with the code above.
If [d]lamu are stored in Eigen::ArrayXd instead of Eigen::VectorXd, you can write:
double ret1 = (dlamu1<0).select(-lamu1/dlamu1, 1.0).minCoeff();
If you brute-forced indl anyway, you can as ggael suggested write:
lamu1(indl).cwiseQuotient(dlamu1(indl)).minCoeff();
(this is undefined/crashes if indl.size()==0)

How to use stans integrate_ode x inputs?

Recently stan has added the integrate_ode method. Unfortunately the only documentation I can find is the stan reference manual (p.191ff). I have a model that would require some driving signal. As I understand the parameter x_r and x_i are supposed to be used for this.
For the sake of a concrete example lets assume I want to implement the example from the documentation with following change:
real[] sho(real t,
real[] y,
real[] theta,
real[] x_r,
int[] x_i) {
real dydt[2];
real input_signal; // Change from here!!!
input_signal <- how_to(t, x_r, x_i);
dydt[1] <- y[2] + input_signal; // Change to here!!!
dydt[2] <- -y[1] - theta[1] * y[2];
return dydt;
}
the input signal is supposed to be a time series that is inputted - let's say I submit input_signal_vector <- sin(t) + rnorm(T, sd=0.1) (which is supposed to be a signal at the time points in ts) and I plan to use for input_signal the closest value in time.
The only way I can imagine is one could concat ts and input_signal_vector in x_r and then a search in this array. But I can not imagine this is the intended use of these parameter. It would also be extremely inefficient.
So if someone could show how such a case is supposed to be solved I would be very grateful.

Resources