Home Contact us

OptimJ code samples

Concepts found in modeling languages (models, decision variables, constraints...) are directly expressible in OptimJ™. Here we will develop two well-known examples: the diet problem and the portfolio problem.

Diet: a linear programming problem

The goal of the diet problem is to find the cheapest combination of foods that will satisfy all the daily nutritional requirements of a person. The problem is formulated as a linear program.

Following is the entire code for the model. Comments are given below.

Source code

package examples;

public model DietModel extends DietModelParams solver cplex
{

/**
* All model parameters are passed via the constructor.
*/

public DietModel (
String[] VTMN, // name of the vitamin i
String[] FOOD, // name of the food i
double[String] cost, // cost of the food i
float[String] f_min, // minimum amount of food i desired per day
float[String] f_max, // maximum amount of food i desired
float[String] n_min, // minimum amount of vitamins i required
float[String] n_max, // maximum amount of vitamins i required
float[String][String] amt)// amount of nutriment j in food i
{
// keep a local reference to the data
super(VTMN, FOOD, cost, f_min, f_max, n_min, n_max, amt);
}

// decision variables
final var double[String] Buy[String j : FOOD]
   in f_min[j] .. f_max[j];

// objective function
minimize
sum {String j : FOOD} { cost[j] * Buy[j] };

// constraints
constraints {
forall(String i : VTMN) {
n_min[i] <= sum {String j : FOOD} {amt[i][j] * Buy[j]};
sum {String j : FOOD} {amt[i][j] * Buy[j]} <= n_max[i];
}
}
}
DietModel.optimj .

If you're familiar with Java, you will notice a few additional constructions : model cplex, var, constraints... If you're familiar with modeling languages, you will notice a few additional programming artefacts such as package, public, extends...

Comments

public model DietModel extends DietModelParams solver cplex

A model is a Java class extended with optimization specific concepts. Like any other Java class, it has modifiers for controlling access and visibility, it can extend classes and implement interfaces.

DietModelParams is a superclass used to define parameters as fields of the model. A solver context is introduced by the model declaration with the keyword solver. Reusing the same model for a different solver is simply a matter of changing the solver declaration.


   public DietModel(...)

This is the model constructor. As OptimJ is an extension of Java, this is nothing else than a standard class constructor. In particular, model parameters can be retrieved from any data sources using standard Java APIs, such as:


The full source code for these examples is provided with the OptimJsamples. You can browse them by downloading the free evaluationversion of OptimJ.




   super(VTMN, FOOD, cost, f_min, f_max, n_min, n_max, amt);

This is a superclass constructor invocation that initializes the fields with the values of the parameters and checks consistency of the input data using the standard Java assertion mechanism.


   final var double[String] Buy[String j : FOOD]
     in
f_min[j] .. f_max[j];

var double is the type of decision variables whose solutions are of type double. Every Java data type, including user-defined types, has a var equivalent.

This code declares an associative array of var double, ie. an array of decision variables. The j-th variable is bound by f_min[j] and f_max[j].

The major difference between an imperative language such asJava and an optimization modeling language is the notion of what is a variable:

  • Imperative variables refer to memory locations that can be assigned a value.
  • Decision variables are placeholders for the solutions of a problem.

If you're familiar with other algebraic modeling languages, you may find these type declarations unnecessarily verbose. This may be true for simple textbook examples, but decades of experience in software engineering prove that they provide invaluable help in guaranteeing correctness of code. They also promote code readability and reusability. The same applies to optimization models.

   Buy[String j : FOOD] in f_min[j] .. f_max[j];

Additionally, OptimJ provides familiar and concise notation for

  • declaring arrays of decision variables
  • specifying bounds of decision variables

minimize

This introduces the objective function. It is followed by a standard Java expression.

sum

Aggregate operators such as sum, product , etc., allow expressions to range over arbitrary collections of data.

constraints{...}

A constraint is any Java boolean expression involving decision variables. They have the same syntax as ordinary Java expressions. Constraints can be written within a constraints block.

forall

Collections of constraints can be expressed with the forall construct, based on the comprehension notation.

Download more examples and an evaluation licence.

Portfolio optimization: a quadratic programming problem

In this example, we show how the portfolio selection problem is formulated as a convex quadratic programming problem.

The Portfolio model calculates the optimal capital weightings for a basket of investments that gives the highest return for the least risk.

Source code

public model Portfolio extends PortfolioParam solver cplex
{
/**
* This constructor takes as parameters the parameters of the model.
*/

Portfolio(
final Investment[] investments, // expected returns
final double [Investment] [Investment] covariance, // covariance matrix
final double riskAversion // risk-aversion parameter
)
{
// call to super and keep local reference to the data
super(returns, covariance, riskAversion);
}

// Investment level
final var double [Investment] allocation[investments] in 0 .. 1;


maximize // quadratic objective
sum{Investment i : investments}{i.expectedReturns()*allocation[i]} -
(riskAversion/2)*sum{Investment i : investments, Investment j : investments}
{covariance[i][j]*allocation[i]*allocation[j]};


constraints{
sum {Investment i : investments}{allocation[i]} == 1;
}
}
Investment.optimj
Portfolio.optimj
RunPortfolio.optimj

Example code comments:

Investment i : investments

This generator introduces a new local variable i that ranges over all values of investments

covariance[i][j]*allocation[i]*allocation[j]

Any Java expression can be used as a constraint or an objective function. OptimJ type-checking will complain if this is not a valid expression according to the solver. In this sample code the objective function is quadratic.
This quadratic problem can be solved using ILOG CPLEX as it is a quadratic optimizer.

Download more examples and an evaluation licence.

Customer quotes

With OptimJ you get the expressiveness of OPL™ with the integrability and flexibility of Ilog Concert™ -- the best of both worlds.

 Luc Mercier,
 Phd student,
 Brown University.
See more quotes

Newsletter

To request a free subscription to our bi-monthly newsletter, enter your e-mail address below:
To prevent spam, please answer this little quiz:
2+2 =

Whitepapers


"The economics of OptimJ a business case."

Optimization projects that took weeks are now measured in days. Thisbusiness-oriented whitepaper explains why.




"Object-OrientedModeling with OptimJ."

OptimJ enables Object-Oriented Modeling, a radically new way to expressyour optimization models. This technically-oriented whitepaperdemonstrates this concept on an example.