Search in sources :

Example 66 with Variable

use of org.ojalgo.optimisation.Variable in project ojAlgo by optimatika.

the class IntegerProblems method testP20111010.

/**
 * If the relaxed problem was infeasible you got a NullPointerException instead of a result indicating
 * that the problem is infeasible.
 */
@Test
public void testP20111010() {
    final Variable[] tmpVariables = new Variable[] { Variable.makeBinary("X").weight(ONE), Variable.makeBinary("Y").weight(ONE), Variable.makeBinary("Z").weight(ONE) };
    final ExpressionsBasedModel tmpModel = new ExpressionsBasedModel(tmpVariables);
    final Expression tmpC1 = tmpModel.addExpression("C1");
    for (int i = 0; i < tmpModel.countVariables(); i++) {
        tmpC1.set(i, ONE);
    }
    tmpC1.level(ONE);
    final Expression tmpC2 = tmpModel.addExpression("C2");
    for (int i = 0; i < tmpModel.countVariables(); i++) {
        tmpC2.set(i, ONE);
    }
    tmpC2.level(TWO);
    final Expression tmpC3 = tmpModel.addExpression("C3");
    for (int i = 0; i < tmpModel.countVariables(); i++) {
        tmpC3.set(i, ONE);
    }
    tmpC3.level(THREE);
    // tmpModel.options.debug(LinearSolver.class);
    final Optimisation.Result tmpResult = tmpModel.minimise();
    TestUtils.assertEquals(State.INFEASIBLE, tmpResult.getState());
}
Also used : Variable(org.ojalgo.optimisation.Variable) Expression(org.ojalgo.optimisation.Expression) Result(org.ojalgo.optimisation.Optimisation.Result) Optimisation(org.ojalgo.optimisation.Optimisation) ExpressionsBasedModel(org.ojalgo.optimisation.ExpressionsBasedModel) Test(org.junit.jupiter.api.Test)

Example 67 with Variable

use of org.ojalgo.optimisation.Variable in project ojAlgo-finance by optimatika.

the class StrategyMixer method testStratCombQuadraticExpressionModel.

/**
 * This is test case using a reimplementation of the algorithm in {@link PortfolioMixer}.
 */
@Test
public void testStratCombQuadraticExpressionModel() {
    final BigDecimal[] tmpTarget = new BigDecimal[] { THIRD, THIRD, THIRD };
    final BigDecimal[] tmpStrat1 = new BigDecimal[] { HALF, HALF, ZERO };
    final BigDecimal[] tmpStrat2 = new BigDecimal[] { HALF, ZERO, HALF };
    final BigDecimal[] tmpStrat3 = new BigDecimal[] { ZERO, HALF, HALF };
    final BigDecimal[][] tmpStrats = new BigDecimal[][] { tmpStrat1, tmpStrat2, tmpStrat3 };
    final Variable[] tmpVars = new Variable[] { new Variable("S1"), new Variable("S2"), new Variable("S3"), Variable.makeBinary("B1"), Variable.makeBinary("B2"), Variable.makeBinary("B3") };
    for (int s = 0; s < 3; s++) {
        BigDecimal tmpVal = ZERO;
        for (int i = 0; i < 3; i++) {
            tmpVal = tmpVal.add(tmpTarget[i].multiply(tmpStrats[s][i]));
        }
        tmpVal = tmpVal.multiply(TWO).negate();
        tmpVars[s].weight(tmpVal);
        tmpVars[s].lower(ZERO);
        tmpVars[s].upper(ONE);
    }
    final ExpressionsBasedModel tmpModel = new ExpressionsBasedModel(tmpVars);
    // tmpModel.options.debug(IntegerSolver.class);
    // tmpModel.options.validate = false;
    final Expression tmpQuadObj = tmpModel.addExpression("Quadratic Objective Part");
    tmpQuadObj.weight(ONE);
    for (int row = 0; row < 3; row++) {
        for (int col = 0; col < 3; col++) {
            BigDecimal tmpVal = ZERO;
            for (int i = 0; i < 3; i++) {
                tmpVal = tmpVal.add(tmpStrats[row][i].multiply(tmpStrats[col][i]));
            }
            tmpQuadObj.set(row, col, tmpVal);
            tmpQuadObj.set(3 + row, 3 + col, tmpVal.multiply(THOUSANDTH));
        }
        final Expression tmpActive = tmpModel.addExpression(tmpVars[row].getName() + " Active");
        tmpActive.set(3 + row, ONE);
        tmpActive.set(row, NEG);
        tmpActive.lower(ZERO);
        if (DEBUG) {
            BasicLogger.debug(tmpActive.toString());
        }
    }
    final Expression tmpHundredPercent = tmpModel.addExpression("100%");
    tmpHundredPercent.level(ONE);
    tmpHundredPercent.set(0, ONE);
    tmpHundredPercent.set(1, ONE);
    tmpHundredPercent.set(2, ONE);
    if (DEBUG) {
        BasicLogger.debug(tmpHundredPercent.toString());
    }
    final Expression tmpStrategyCount = tmpModel.addExpression("Strategy Count");
    tmpStrategyCount.upper(TWO);
    tmpStrategyCount.set(3, ONE);
    tmpStrategyCount.set(4, ONE);
    tmpStrategyCount.set(5, ONE);
    if (DEBUG) {
        BasicLogger.debug(tmpStrategyCount.toString());
    }
    tmpModel.minimise();
    if (DEBUG) {
        BasicLogger.debug(tmpModel.toString());
        BasicLogger.debug(Arrays.toString(tmpVars));
    }
    int tmpUseCount = 0;
    double tmpTotalWeight = 0D;
    final Variable[] tmpSolution = new Variable[] { tmpVars[0], tmpVars[1], tmpVars[2] };
    for (final Variable tmpWeight : tmpSolution) {
        if (tmpWeight.getValue().signum() != 0) {
            tmpUseCount++;
            tmpTotalWeight += tmpWeight.getValue().doubleValue();
        }
    }
    TestUtils.assertEquals(TWO.intValue(), tmpUseCount);
    TestUtils.assertEquals(PrimitiveMath.ONE, tmpTotalWeight, 1E-14 / PrimitiveMath.THREE);
}
Also used : Variable(org.ojalgo.optimisation.Variable) Expression(org.ojalgo.optimisation.Expression) ExpressionsBasedModel(org.ojalgo.optimisation.ExpressionsBasedModel) BigDecimal(java.math.BigDecimal) Test(org.junit.jupiter.api.Test)

Example 68 with Variable

use of org.ojalgo.optimisation.Variable in project ojAlgo-finance by optimatika.

the class PortfolioMixer method mix.

public List<BigDecimal> mix(final int aNumber) {
    final int tmpNumberOfAssets = myTarget.getWeights().size();
    final int tmpNumberOfComponents = myComponents.size();
    final Variable[] tmpVariables = new Variable[2 * tmpNumberOfComponents];
    for (int c = 0; c < tmpNumberOfComponents; c++) {
        final Variable tmpVariable = new Variable(C + c);
        BigDecimal tmpVal = ZERO;
        for (int i = 0; i < tmpNumberOfAssets; i++) {
            tmpVal = tmpVal.add(myTarget.getWeights().get(i).multiply(myComponents.get(c).getWeights().get(i)));
        }
        tmpVal = tmpVal.multiply(TWO).negate();
        tmpVariable.weight(tmpVal);
        tmpVariable.lower(ZERO);
        tmpVariable.upper(ONE);
        tmpVariables[c] = tmpVariable;
        tmpVariables[tmpNumberOfComponents + c] = Variable.makeBinary(B + c);
    }
    final ExpressionsBasedModel tmpModel = new ExpressionsBasedModel(tmpVariables);
    final Expression tmpQuadObj = tmpModel.addExpression(QUADRATIC_OBJECTIVE_PART);
    tmpQuadObj.weight(ONE);
    for (int row = 0; row < tmpNumberOfComponents; row++) {
        for (int col = 0; col < tmpNumberOfComponents; col++) {
            BigDecimal tmpVal = ZERO;
            for (int i = 0; i < tmpNumberOfAssets; i++) {
                tmpVal = tmpVal.add(myComponents.get(row).getWeights().get(i).multiply(myComponents.get(col).getWeights().get(i)));
            }
            tmpQuadObj.set(row, col, tmpVal);
            tmpQuadObj.set(tmpNumberOfComponents + row, tmpNumberOfComponents + col, tmpVal.multiply(THOUSANDTH));
        }
        final Expression tmpActive = tmpModel.addExpression(tmpVariables[row].getName() + ACTIVE);
        tmpActive.set(row, NEG);
        tmpActive.set(tmpNumberOfComponents + row, ONE);
        tmpActive.lower(ZERO);
    // BasicLogger.logDebug(tmpActive.toString());
    // BasicLogger.logDebug(tmpActive.getName(), tmpActive.getLinear().getFactors());
    }
    // BasicLogger.logDebug(QUADRATIC_OBJECTIVE_PART, tmpQuadObj.getQuadratic().getFactors());
    final Expression tmpHundredPercent = tmpModel.addExpression("100%");
    tmpHundredPercent.level(ONE);
    for (int c = 0; c < tmpNumberOfComponents; c++) {
        tmpHundredPercent.set(c, ONE);
    }
    // BasicLogger.logDebug(tmpHundredPercent.toString());
    // BasicLogger.logDebug(tmpHundredPercent.getName(), tmpHundredPercent.getLinear().getFactors());
    final Expression tmpStrategyCount = tmpModel.addExpression(STRATEGY_COUNT);
    tmpStrategyCount.upper(TypeUtils.toBigDecimal(aNumber));
    for (int c = 0; c < tmpNumberOfComponents; c++) {
        tmpStrategyCount.set(tmpNumberOfComponents + c, ONE);
    }
    for (final Entry<int[], LowerUpper> tmpEntry : myAssetConstraints.entrySet()) {
        // For now I assume there is only 1 index
        final int tmpIndex = tmpEntry.getKey()[0];
        final BigDecimal tmpLower = tmpEntry.getValue().lower;
        final BigDecimal tmpUpper = tmpEntry.getValue().upper;
        final Expression tmpExpr = tmpModel.addExpression("AC" + Arrays.toString(tmpEntry.getKey()));
        for (int c = 0; c < tmpNumberOfComponents; c++) {
            tmpExpr.set(c, myComponents.get(c).getWeights().get(tmpIndex));
        }
        if (tmpLower != null) {
            tmpExpr.lower(tmpLower);
        }
        if (tmpUpper != null) {
            tmpExpr.upper(tmpUpper);
        }
    }
    for (final Entry<int[], LowerUpper> tmpEntry : myComponentConstraints.entrySet()) {
        // For now I assume there is only 1 index
        final int tmpIndex = tmpEntry.getKey()[0];
        final BigDecimal tmpLower = tmpEntry.getValue().lower;
        final BigDecimal tmpUpper = tmpEntry.getValue().upper;
        final Expression tmpExpr = tmpModel.addExpression("CC" + Arrays.toString(tmpEntry.getKey()));
        tmpExpr.set(tmpIndex, BigMath.ONE);
        for (int c = 0; c < tmpNumberOfComponents; c++) {
        }
        if (tmpLower != null) {
            tmpExpr.lower(tmpLower);
        }
        if (tmpUpper != null) {
            tmpExpr.upper(tmpUpper);
        }
    }
    tmpModel.minimise();
    final ArrayList<BigDecimal> retVal = new ArrayList<>(tmpNumberOfComponents);
    for (int v = 0; v < tmpNumberOfComponents; v++) {
        retVal.add(tmpVariables[v].getValue());
    }
    return retVal;
}
Also used : Variable(org.ojalgo.optimisation.Variable) Expression(org.ojalgo.optimisation.Expression) ArrayList(java.util.ArrayList) ExpressionsBasedModel(org.ojalgo.optimisation.ExpressionsBasedModel) BigDecimal(java.math.BigDecimal)

Example 69 with Variable

use of org.ojalgo.optimisation.Variable in project ojAlgo-finance by optimatika.

the class OptimisedPortfolio method makeModel.

final ExpressionsBasedModel makeModel(final Map<int[], LowerUpper> constraints) {
    final int tmpLength = myVariables.length;
    final Variable[] tmpVariables = new Variable[tmpLength];
    for (int i = 0; i < tmpVariables.length; i++) {
        tmpVariables[i] = myVariables[i].copy();
        if (!this.isShortingAllowed() && ((myVariables[i].getLowerLimit() == null) || (myVariables[i].getLowerLimit().signum() == -1))) {
            tmpVariables[i].lower(ZERO);
        }
    }
    final ExpressionsBasedModel retVal = new ExpressionsBasedModel(myOptimisationOptions);
    retVal.addVariables(tmpVariables);
    final Expression myOptimisationVariance = retVal.addExpression(VARIANCE);
    final BasicMatrix tmpCovariances = this.getCovariances();
    for (int j = 0; j < tmpLength; j++) {
        for (int i = 0; i < tmpLength; i++) {
            myOptimisationVariance.set(i, j, tmpCovariances.get(i, j));
        }
    }
    final Expression tmpBalanceExpression = retVal.addExpression(BALANCE);
    for (int i = 0; i < tmpLength; i++) {
        tmpBalanceExpression.set(i, ONE);
    }
    tmpBalanceExpression.level(ONE);
    for (final Map.Entry<int[], LowerUpper> tmpEntry : constraints.entrySet()) {
        final int[] tmpKey = tmpEntry.getKey();
        final LowerUpper tmpValue = tmpEntry.getValue();
        final Expression tmpExpression = retVal.addExpression(Arrays.toString(tmpKey));
        for (int i = 0; i < tmpKey.length; i++) {
            tmpExpression.set(tmpKey[i], ONE);
        }
        tmpExpression.lower(tmpValue.lower).upper(tmpValue.upper);
    }
    return retVal;
}
Also used : BasicMatrix(org.ojalgo.matrix.BasicMatrix) Variable(org.ojalgo.optimisation.Variable) Expression(org.ojalgo.optimisation.Expression) ExpressionsBasedModel(org.ojalgo.optimisation.ExpressionsBasedModel) Map(java.util.Map)

Aggregations

Variable (org.ojalgo.optimisation.Variable)69 ExpressionsBasedModel (org.ojalgo.optimisation.ExpressionsBasedModel)59 Expression (org.ojalgo.optimisation.Expression)44 Test (org.junit.jupiter.api.Test)39 Result (org.ojalgo.optimisation.Optimisation.Result)37 BigDecimal (java.math.BigDecimal)26 Optimisation (org.ojalgo.optimisation.Optimisation)24 ArrayList (java.util.ArrayList)9 BasicMatrix (org.ojalgo.matrix.BasicMatrix)9 NumberContext (org.ojalgo.type.context.NumberContext)9 BigArray (org.ojalgo.array.BigArray)6 PrimitiveMatrix (org.ojalgo.matrix.PrimitiveMatrix)6 List (java.util.List)5 Map (java.util.Map)5 Collectors (java.util.stream.Collectors)5 RationalMatrix (org.ojalgo.matrix.RationalMatrix)5 HashMap (java.util.HashMap)4 LinkedHashMap (java.util.LinkedHashMap)4 BasicLogger (org.ojalgo.netio.BasicLogger)4 IntIndex (org.ojalgo.access.Structure1D.IntIndex)3