How to change constraint right hand side cplex in java - constraints

I would like to know how can I change the right hand side of a constraint after I have read a model in a file with CPLEX Java API.
Let's say I have the following code:
IloCplex cplex = new IloCplex();
cplex.setParam(IloCplex.IntParam.RootAlg,IloCplex.Algorithm.Auto);
cplex.importModel(filename);
if ( cplex.solve() ) {
// solve the model
}
and I have a constraint "c0" and I want to solve the same model changing only the right hand side of this constraint. How can I change it before I solve the model again? I tried to look for examples in the installation package, but so far I missed how to do it.
There is a function setBounds(newLB, new UB), but I can't just write in my code
c0.setBounds(new LB, new UB).
Any help would be great.

This may not be the best solution, but after some research I found that, by making:
String filename = "model.lp";
IloCplex cplex = new IloCplex();
cplex.setParam(IloCplex.IntParam.RootAlg,IloCplex.Algorithm.Auto);
cplex.importModel(filename);
IloLPMatrix lp = (IloLPMatrix)cplex.LPMatrixIterator().next();
if(cplex.solve()){
double[] x = cplex.getValues(lp);
for (int j = 0; j < x.length; ++j){
System.out.println("Nome: " + lp.getNumVar(j).getName() + " Valor: " + x[j]);
}
}
IloRange [] list = lp.getRanges();
for(int g = 0; g < list.length; ++g){
System.out.println(list[g].getLB() + " <= " + list[g].getName() + " <= " + list[g].getUB());
if(list[g].getName().equals("r1")){
list[g].setBounds(6.5, 6.5);
}
}
I could get the constraint "r1" and change its limits. It gave the correct answer for a toy problem, at least.
However, when I try to solve the model for the second time, cplex gives me:
"Warning: No solution found from 1 MIP starts."
I know that the solution of the first problem will not be a solution for the second program. From the research I made I understood, possibly wrongly, that, as the solution to the first problem is infeasible for the second, it will start from scratch because I have a MIP problem. So, would it be preferable if I just wrote the model again in file and loaded it again?

Related

Change array dimension when generating a new model CPLEX OPL

I have an optimization model that I want to implement in IBM CPLEX Optimization Studio 12.10.
I wrote the model code in OPL and the first implementation is working. What I would like to do now is to iterate the model multiple times to see how the resolution time changes depending on the dimension of the parameters.
In the .mod file I have defined three sets:
int numSet1=...;
int numSet2=...;
int numSet3=...;
range Set1 = 1..numSet1;
range Set2 = 1..numSet2;
range Set3 = 1..numSet3;
And four parameters:
float Par1[Set1]=...;
float Par2[Set1][Set2]=...;
float Par3[Set1]=...;
float Par4[Set1][Set2][Set3]=...;
In the .dat file, I have defined the initial values for these sets and parameters.
What I would like to do now is to define, in the flow control, a code that allows me to change the dimensions fo the sets, and thus, of the parameters, and save the resolution time for each resolution:
main {
var mod = thisOplModel.modelDefinition;
var dat = thisOplModel.dataElements;
for (var sizenumSet1 = 2; sizenumSet1 <= 10; sizenumSet1 += 2) {
for (var sizenumSet2 = 1; sizenumSet2 <= 5; sizenumSet2 +=1) {
for (var sizenumSet3 = 1; sizenumSet3 <=5; sizenumSet3 +=1) {
var MyCplex = new IloCplex();
var opl = new IloOplModel(mod, MyCplex);
dat.changenumSet1=sizenumSet1;
dat.changenumSet2=sizenumSet2;
dat.changenumSet3=sizenumSet3;
opl.addDataSource(dat);
opl.generate();
if (MyCplex.solve()) {
writeln("Solution: ", MyCplex.getObjValue(),
" / sizeSet1: ", sizenumSet1,
" / sizeSet2: ", sizenumSet2,
" / sizeSet3: ", sizenumSet3,
" / time: ", MyCplex.getCplexTime());
}
opl.end();
MyCplex.end();
}
}
}
}
When I launch this code what I obtain is the following list of errors:
Execution of main failed. Processing OPL model failed
Index out of bound for array Par4(1)(1):3
Scripting runtime error: (in generate) Processing OPL model failed
How can I solve this?
Thank you for your help.
In
dat.changenumSet1=sizenumSet1;
dat.changenumSet2=sizenumSet2;
dat.changenumSet3=sizenumSet3;
you are changing the wrong elements. You should be changing
dat.numSet1=sizenumSet1;
dat.numSet2=sizenumSet2;
dat.numSet3=sizenumSet3;
Moreover, it seems you are missing updates to the Par arrays. These arrays become larger in each iteration, so need to provide more data for them.

Java 7 => Java 8 : for to foreach on a Map with calculation

I begin with Java 8 and i have a migration project. I have read a lot of documentation and tutorial to use foreach or streams but i have a little last problem. I don't find the answer, just tutorial easy example.
I'm trying to transform this loop :
for ( Map.Entry<Neuron, Double> entry: this.entries.entrySet() ) {
value += entry.getKey().getExitValue() * entry.getValue();
}
This solution doesn't match and i know why (anonymous class => final/local var)
this.entries.forEach( (neuron, weight) -> {
value += neuron.getExitValue() * weight;
});
But only with a foreach i don't know how do this simple operation.
I think it's very easy but...
I have try with stream but i have similar problems.
Double sum = entries.entrySet()
.stream()
.forEach( entry-> { ? } );
Thanks you in advance.
As #Holger said in the comments above - in this case it is better to use mapToDoble. However there is still a way to do it using forEach loop. Please note that it is an ugly, dirty trick and it is just for demonstration purposes and it shouldn't be used in production code. As we know only final or effectively final variables can be used with lambda expressions, that's why value += is an illegal expression. Java-8 added a few new classes to java.util.concurrent.atomic one of them is DoubleAdder. You can use it with lambda:
DoubleAdder adder = new DoubleAdder();
stream.forEach(e -> adder.add(e.getKey().getExitValue() * e.getValue()));
System.out.println(adder.sum());
I don't see any cases when this should be used instead of mapToDouble
I introduced a list to stall the values and then do calculation with list.
final List<BigDecimal> valuesList = new ArrayList<>();
otherList.stream().forEach(val-> valuesList.add(map.get(val)));
final BigDecimal lastValue = valuesList.stream().filter(Objects::nonNull).reduce(BigDecimal.ZERO,BigDecimal::add);

Flex: getting the height of a collection of controls

Or putting it more accurately, I want to be able to get the distance between the top of a control to the top of one of its children (and adding the height member of all the above children yields specious results!) but the process of getting the absolute coordinates, and comparing them, looks really messed up.
I use this function to calculate the height between the tops of 2 tags:
private static function GetRemainingHeight(oParent:Container, oChild:Container,
yParent:Number, yChild:Number):Number {
const ptParent:Point = oParent.localToGlobal(new Point(0, yParent));
const ptChild:Point = oChild.localToGlobal(new Point(0, yChild));
const nHeightOfEverythingAbove:Number = ptChild.y - ptParent.y;
trace(ptChild.y.toString() + '[' + yChild.toString() + '] - ' +
ptParent.y.toString() + '[' + yParent.toString() + '] = ' + nHeightOfEverythingAbove.toString() + ' > ' + oParent.height.toString());
return nHeightOfEverythingAbove;
}
Note that oParent.y == yParent and oChild.y == yChild but I did it this way for binding reasons.
The result I get is very surprising:
822[329] - 124[0] = 698 > 439
which is impossible, because the top of oChild does not disappear below oParent. The only figure I find unexpected is ptChild.y. All the other numbers look quite sane. So I'm assuming that my mistake was in subtracting two figures that are not supposed to be comparable.
Of course, if anyone has a method of calculating the difference between two points that doesn't involve localToGlobal(), that'd be fine, too.
I'm using the 3.5 SDK.
I found a partial answer by looking to http://rjria.blogspot.ca/2008/05/localtoglobal-vs-contenttoglobal-in.html (including the comments). It dithers on whether or not I should be using localToGlobal() or contentToGlobal(), but it filled in some blanks that Adobe's documentation left, which is that you get the global coordinates by feeding the function new Point(0, 0). In the end, I used this:
public static function GetRemainingHeight(oParent:DisplayObject, oChild:DisplayObject,
yParent:Number, yChild:Number):Number {
const ptParent:Point = oParent.localToGlobal(new Point(0, 0));
const ptChild:Point = oChild.localToGlobal(new Point(0, 0));
const nHeightOfEverythingAbove:Number = ptChild.y - ptParent.y;
return nHeightOfEverythingAbove;
}
See question for an explanation for the seemingly unnecessary parameters, which now seem like they might really be irrelevant.
However, I didn't need this function as often as I thought, and I'm not terribly happy w/the way it works anyway. I've learned that the way I've done it, it isn't possible to just make all those parameters to the function Bindable and expect this function to be called when changes to oChild are made. In one case I had to call this function in the handler for the updateComplete event.

Implementing an IObservable to compute digits of Pi

This is an academic exercise, I'm new to Reactive Extensions and trying to get my head around the technology. I set myself a goal of making an IObservable that returns successive digits of Pi (I happen to be really interested in Pi right at the moment for unrelated reasons). Reactive Extensions contains operators for making observables, the guidance they give is that you should "almost never need to create your own IObsevable". But I can't see how I can do this with the ready-made operators and methods. Let me elucidate a bit more.
I was planning to use an algorithm that would involve the expansion of a Taylor series for Arctan. To get the next digit of Pi, I'd expand a few more terms in the series.
So I need the series expansion going on asynchronously, occasionally throwing out the next computed digit to the IObserver. I obviosly don't want to restart the computation from scratch for each new digit.
Is there a way to implement this behaviour using RX's built-in operators, or am I going to have to code an IObservable from scratch? What strategy suggests itself?
For something like this, the simplest method would be to use a Subject. Subject is both an IObservable and IObserver, which sounds a bit strange but it allows you to use them like this:
class PiCalculator
{
private readonly Subject<int> resultStream = new Subject<int>();
public IObservable<int> ResultStream
{
get { return resultStream; }
}
public void Start()
{
// Whatever the algorithm actually is
for (int i = 0; i < 1000; i++)
{
resultStream.OnNext(i);
}
}
}
So inside your algorithm, you just call OnNext on the subject whenever you want to produce the next value.
Then to use it, you just need something like:
var piCalculator = new PiCalculator();
piCalculator.ResultStream.Subscribe(n => Console.WriteLine((n)));
piCalculator.Start();
Simplest way is to create an Enumerable and then convert it:
IEnumerable<int> Pi()
{
// algorithm here
for (int i = 0; i < 1000; i++)
{
yield return i;
}
}
Usage (for a cold observable, that is every new 'subscription' starts creating Pi from scratch):
var cold = Pi().ToObservable(Scheduler.ThreadPool);
cold.Take(5).Subscribe(Console.WriteLine);
If you want to make it hot (everyone shares the same underlying calculation), you can just do this:
var hot = cold.Publish().RefCount();
Which will start the calculation after the first subscriber, and stop it when they all disconnect. Here's a simple test:
hot.Subscribe(p => Console.WriteLine("hot1: " + p));
Thread.Sleep(5);
hot.Subscribe(p => Console.WriteLine("hot2: " + p));
Which should show hot1 printing only for a little while, then hot2 joining in after a short wait but printing the same numbers. If this was done with cold, the two subscriptions would each start from 0.

How to simplify adding multiple text inputs

i have an application in which i have around 100 textinputs all are numbers
i want to simplify the addition ie. any other way than saying txt1.text+txt2.text.....
that would increase my code a lot
is it possible to have (n+=txt*.text) or some thing like that
any help would be appreciated have to get the application done in two days thank you
If txt1, txt2 etc are public properties of the class representing this, you can use the following code to get the sum of the numbers in the text inputs.
var n:Number = 0;
for(i = 1; i <= total; i++)
n += Number(this["txt" + i].text);
To get a concatenated string:
var s:String = "";
for(i = 1; i <= total; i++)
s += this["txt" + i].text;
If the text inputs are properties of a different class, use the instance name of the object instead of this. For example:
instanceName["txt" + i].text;
Another solution that is more clean is to store them in an array and loop through them. But that might require changes in other parts of your code.

Resources