use of org.apache.commons.math3.optim.linear.LinearConstraint in project vsp-playgrounds by matsim-vsp.
the class TimeAllocationProblem method getConstraints.
LinearConstraintSet getConstraints() {
// For notational consistency with formula write-up.
final int _N = this.realizedActivities.size();
final double[] a = new double[_N];
final double[] b = new double[_N];
for (int q = 0; q < _N; q++) {
final TripTime tripTravelTime = this.realizedActivities.get(q).nextTripTravelTime;
a[q] = tripTravelTime.dTT_dDptTime;
b[q] = tripTravelTime.ttOffset_s;
}
final List<LinearConstraint> constraints = new ArrayList<>();
// The first departure must not occur before midnight.
{
final RealVector coeffs = new ArrayRealVector(_N);
coeffs.setEntry(0, 1.0);
constraints.add(new LinearConstraint(coeffs, GEQ, 0.0));
}
// Departure from an activity must not happen before arrival.
for (int q = 0; q < _N - 1; q++) {
final RealVector coeffs = new ArrayRealVector(_N);
coeffs.setEntry(q, -(1.0 + a[q]));
coeffs.setEntry(q + 1, 1.0);
constraints.add(new LinearConstraint(coeffs, GEQ, MINACTDUR_S + b[q]));
}
// lower bound on departure time due to time discretization
for (int q = 0; q < _N; q++) {
final RealVector coeffs = new ArrayRealVector(_N);
coeffs.setEntry(q, 1.0);
constraints.add(new LinearConstraint(coeffs, GEQ, this.realizedActivities.get(q).nextTripTravelTime.minDptTime_s - this.slack_s));
}
// upper bound on departure time due to time discretization
for (int q = 0; q < _N; q++) {
final RealVector coeffs = new ArrayRealVector(_N);
coeffs.setEntry(q, 1.0);
constraints.add(new LinearConstraint(coeffs, LEQ, this.realizedActivities.get(q).nextTripTravelTime.maxDptTime_s + this.slack_s));
}
return new LinearConstraintSet(constraints);
}
use of org.apache.commons.math3.optim.linear.LinearConstraint in project ipss-plugin by InterPSS-Project.
the class ApacheLPSolver method printInputData.
@Override
public void printInputData(String fileName) {
if (objFunc == null) {
this.build(cstContainer);
}
FileWriter fstream = null;
try {
fstream = new FileWriter(fileName);
BufferedWriter out = new BufferedWriter(fstream);
RealVector f = objFunc.getCoefficients();
out.write("Objective funtion: ");
out.append("\n");
out.append("( ");
out.append("{ ");
for (int i = 0; i < f.getDimension(); i++) {
out.append(Double.toString(f.getEntry(i)));
out.append(", ");
}
out.append("}, ");
out.append(Double.toString(objFunc.getConstantTerm()));
out.append(");\n ");
Iterator<LinearConstraint> it = constraintCollection.iterator();
out.append("Linear constraints: ");
out.append("\n");
while (it.hasNext()) {
out.append("( ");
out.append("{ ");
LinearConstraint con = it.next();
RealVector vec = con.getCoefficients();
for (int i = 0; i < vec.getDimension(); i++) {
out.append(Double.toString(vec.getEntry(i)));
out.append(", ");
}
out.append("}, ");
out.append(con.getRelationship().toString());
out.append(" , ");
out.append(Double.toString(con.getValue()));
out.append(");\n ");
}
out.close();
OPFLogger.getLogger().info("Input data saved to: " + fileName);
} catch (IOException e) {
OPFLogger.getLogger().severe(e.toString());
}
}
use of org.apache.commons.math3.optim.linear.LinearConstraint in project ipss-plugin by InterPSS-Project.
the class ApacheLpsolveSolverInputBuilder method buildInput.
public void buildInput() {
for (OpfConstraint conIn : cstContainer) {
IntArrayList idx = conIn.getColNo();
DoubleArrayList val = conIn.getVal();
// output constraint to constraint collection
OpenMapRealVector vec = new OpenMapRealVector(numOfVar);
LinearConstraint con = null;
OpfConstraintType type = conIn.getCstType();
try {
if (type.equals(OpfConstraintType.EQUALITY)) {
double rh = conIn.getLowerLimit();
for (int j = 0; j < idx.size(); j++) {
int colIdx = idx.elements()[j];
double posVal = val.elements()[j];
vec.setEntry(colIdx, posVal);
}
con = new LinearConstraint(vec, Relationship.EQ, rh);
} else if (type.equals(OpfConstraintType.LARGER_THAN)) {
double[] valRow = val.elements();
double rh = conIn.getLowerLimit();
double[] valRow_r = valRow;
for (int ii = 0; ii < idx.size(); ii++) {
valRow_r[ii] = valRow[ii] * (-1);
int colIdx = idx.elements()[ii];
double posVal = valRow_r[ii];
vec.setEntry(colIdx, posVal);
}
con = new LinearConstraint(vec, Relationship.LEQ, -rh);
} else if (type.equals(OpfConstraintType.LESS_THAN)) {
double[] valRow = val.elements();
double rh = conIn.getUpperLimit();
for (int j = 0; j < idx.size(); j++) {
int colIdx = idx.elements()[j];
double posVal = valRow[j];
vec.setEntry(colIdx, posVal);
}
con = new LinearConstraint(vec, Relationship.LEQ, rh);
}
constCol.add(con);
} catch (Exception e) {
OPFLogger.getLogger().severe(e.toString() + " at constraint: " + conIn.getDesc());
// e.printStackTrace();
}
}
}
use of org.apache.commons.math3.optim.linear.LinearConstraint in project neqsim by equinor.
the class LinearProgrammingChemicalEquilibrium method generateInitialEstimates.
// Method added by Neeraj
/*
* public double[] generateInitialEstimates(SystemInterface system, double[] bVector, double
* inertMoles, int phase){ int i,j; double[] n = new double[components.length]; Matrix atemp,
* btemp; Matrix mutemp = new
* Matrix(chemRefPot,1).times(1.0/(R*system.getPhase(phase).getTemperature())). copy(); Matrix
* ntemp; atemp = new Matrix(7,7); btemp = new Matrix(1,7); //for (i=0;i<4;i++) for
* (i=0;i<5;i++) { for (j=0;j<7;j++) atemp.set(i,j,Amatrix[i][j]); btemp.set(0,i,bVector[i]);
*
* } atemp.set(5,4,1); atemp.set(6,5,1); //atemp.set(4,4,1); //atemp.set(5,5,1);
* //atemp.set(6,1,1); //atemp.print(5,1); //btemp.print(5,5); //mutemp.print(5,5); ntemp =
* atemp.solve(btemp.transpose()); ntemp.print(5,5); for (i=0;i<7;i++) n[i] = ntemp.get(i,0);
* int rank = atemp.rank(); return n;
*
*
* }
*/
// Method updated to use Apache Commons Math 3 by Marlene 07.12.18
/**
* <p>
* generateInitialEstimates.
* </p>
*
* @param system a {@link neqsim.thermo.system.SystemInterface} object
* @param bVector an array of {@link double} objects
* @param inertMoles a double
* @param phase a int
* @return an array of {@link double} objects
*/
public double[] generateInitialEstimates(SystemInterface system, double[] bVector, double inertMoles, int phase) {
int i, j;
double rhs = 0.0;
Matrix mutemp = new Matrix(chemRefPot, 1).times(1.0 / (R * system.getPhase(phase).getTemperature())).copy();
double[] v = new double[components.length + 1];
for (i = 0; i < components.length; i++) {
v[i + 1] = mutemp.get(0, i);
}
LinearObjectiveFunction f = new LinearObjectiveFunction(v, 0.0);
List<LinearConstraint> cons = new ArrayList<LinearConstraint>();
for (j = 0; j < bVector.length; j++) {
for (i = 0; i < components.length; i++) {
v[i + 1] = Amatrix[j][i];
}
rhs = bVector[j];
cons.add(new LinearConstraint(v, Relationship.EQ, rhs));
}
NonNegativeConstraint nonneg = new NonNegativeConstraint(true);
LinearConstraintSet consSet = new LinearConstraintSet(cons);
SimplexSolver solver = new SimplexSolver();
PointValuePair optimal = null;
try {
optimal = solver.optimize(new MaxIter(1000), f, consSet, GoalType.MINIMIZE, nonneg);
} catch (NoFeasibleSolutionException exp) {
System.out.println("no feasible solution");
return null;
} catch (Exception exp) {
System.out.println("linear optimization failed");
return null;
}
int compNumb = system.getPhase(phase).getNumberOfComponents();
double[] lp_solution = new double[compNumb];
double[] temp = optimal.getPoint();
for (i = 0; i < compNumb - (compNumb - components.length); i++) {
lp_solution[i] = temp[i + 1];
}
return lp_solution;
}
use of org.apache.commons.math3.optim.linear.LinearConstraint in project java by gunnarfloetteroed.
the class FrankWolfe method run.
public void run(final double[] initialPoint) {
int it = 0;
this.point = new double[initialPoint.length];
System.arraycopy(initialPoint, 0, this.point, 0, initialPoint.length);
// Arrays.fill(this.point, 1.0 / this.dim);
this.value = this.objectiveFunction.value(this.point);
double residual = 0.0;
do {
it++;
/*-
* Construct linear objective function.
*
* Q(x) = Q(x0) + grad * (x - x0)
* = grad * x + [Q(x0) - grad * x0]
*
*/
final double[] grad = this.gradientFunction.value(this.point);
final LinearObjectiveFunction linearObjFctApprox = new LinearObjectiveFunction(grad, this.value - innerProd(grad, this.point));
/*
* Construct constraints.
*/
final List<LinearConstraint> constraints = new ArrayList<LinearConstraint>(initialPoint.length + 1);
// non-negative
for (int i = 0; i < initialPoint.length; i++) {
final double[] coeffs = new double[initialPoint.length];
coeffs[i] = 1.0;
constraints.add(new LinearConstraint(coeffs, Relationship.GEQ, 0.0));
}
// sum is one
final double[] coeffs = new double[initialPoint.length];
Arrays.fill(coeffs, 1.0);
constraints.add(new LinearConstraint(coeffs, Relationship.EQ, 1.0));
/*
* Solve the problem.
*/
final PointValuePair result = (new SimplexSolver()).optimize(linearObjFctApprox, new LinearConstraintSet(constraints));
/*
* Update solution point.
*/
if (lineSearch == null) {
final double innoWeight = 1.0 / it;
final double[] newPoint = this.sum(result.getPoint(), innoWeight, this.point, 1.0 - innoWeight);
final double[] dir = this.sum(newPoint, 1.0, this.point, -1.0);
// Logger.getLogger(this.getClass().getName()).info(
// "dir=" + (new Vector(dir)));
// residual = this.maxAbs(dir);
this.point = newPoint;
this.value = this.objectiveFunction.value(this.point);
} else {
final double[] dir = this.sum(result.getPoint(), 1.0, this.point, -1.0);
double eta = this.lineSearch.stepLength(this.point, dir);
// Logger.getLogger(this.getClass().getName()).info(
// "eta(orig)=" + eta);
eta = Math.max(0, Math.min(1.0, eta));
// Logger.getLogger(this.getClass().getName()).info(
// "dir=" + (new Vector(dir)));
// Logger.getLogger(this.getClass().getName()).info(
// "eta(constr)=" + eta);
// residual = Math.abs(eta) * Math.sqrt(innerProd(dir, dir)); //
// Math.abs(eta) * this.maxAbs(dir);
this.point = this.sum(this.point, 1.0, dir, eta);
this.value = this.objectiveFunction.value(this.point);
}
residual = Math.abs(linearObjFctApprox.value(this.point) - this.value);
Logger.getLogger(this.getClass().getName()).info("it " + it + ": val = " + this.value + ", residual=" + residual);
} while ((residual > this.eps) && (it < this.maxIts));
}
Aggregations