Scala : Getting Started with Mathematical optimization in scala.

Hello guys ,

Today we are gonna talk about the problem of solving the mathematical optimization. Lets take a quick example,
Have you ever been in a condition where you have inequalities and you have to find out the maximum or minimum values of the variables for which a particular equation is maximum.

For example : There are two equations basically , one equation that you need to maximize and the other equation for which acts as a constraint
Equation to be maximized : -2 * x + 5 * y
Additional Constraint : y >:= 200 – x 

Range of Values:
For X: 100<x<=200
For Y: 80<y<=170

So the value of x and y for which this equation would be maximum will be x=100 and y=170 (Checkout your mathematical skills :D)

Now we need to solve such equations programatically. Where comes in the mathematical optimization libraries.
In our case we are going to use Optimus

Now let’s get started with the programming:
Firstly you need to add the optimus dependency in your build.sbt So your buid.sbt should look like this.

name := "scala-mip"

version := "0.1"

scalaVersion := "2.12.4"

organization := "com.foobar"

// The necessary dependencies can be added here

libraryDependencies ++= Seq(
  "com.typesafe" % "config" % "1.3.1",
  //Mathematical Programming Dependencies
  "com.github.vagmcs" %% "optimus" % "2.1.0",
  "com.github.vagmcs" %% "optimus-solver-oj" % "2.1.0",
  "org.scalatest" %% "scalatest" % "3.0.0" % "test"

Now we have to make a  bounded variable i.e to define this expression:

For X: 100<x<=200
For Y: 80<y<=170

In Optimus we do it using this.

val x = MPFloatVar("x", 100, 200)
val y = MPFloatVar("y", 80, 170)

The whole code something looks like this :

    import optimus.optimization._
    implicit val problem = LQProblem(SolverLib.ojalgo)
    val x = MPFloatVar("x", 100, 200)
    val y = MPFloatVar("y", 80, 170)
    maximize(-2 * x + 5 * y)
    add(y >:= 200 - x)
    println("objective: " + objectiveValue)
    println("x = " + x.value + "y = " + y.value)


LQProblem: defines its a Linear equation Problem , there can be other problems like Quadratic  equation problem , Mixed Integer problem.
maximize(): it takes the expression that needs to me maximize there are other functions also like minimize(), subjectTo() etc.
add(): It takes a constraint expression that needs to be keep in consideration for maximizing that expression
start(): To start the computaion
release(): To release all the resources.

And it results in this output :

Hence for these value of X and Y this equation is maximum.

Currently I am working on a use case in which I am looking forward to use MIP for solving the problem. The problem is optimal Order fullfillment problem which is described here : Optimal Order Fullfillment.

If someone has any suggestions on solving this problem. Ping me ! I can also use some help 🙂

I hope you enjoyed this and find it interesting !
If you have any queries , let me know on here or on Twitter 🙂

Happy Reading 🙂

One last thing : If you are interested in community based learning , please Join us @InternityFoundation

References :
1. Optimus
2. Optimal Order fullfillment


Scala: Calculating distance between two Locations

Hey Folks,
Recently I came along a use case where I need to find out the distance between two Location co-ordinates. In today’s blog we are going to solve this problem by implementing Haversine formula in Scala.

Just FYI,

The haversine formula determines the great-circle distance between two points on a sphere given their longitudes and latitudes. Important in navigation, it is a special case of a more general formula in spherical trigonometry, the law of haversines, that relates the sides and angles of spherical triangles.

Law of Haversines:

\operatorname {hav} (c)=\operatorname {hav} (a-b)+\sin(a)\sin(b)\,\operatorname {hav} (C).

Haversine Formula :

For any two points on a sphere, the haversine of the central angle between them is given by

{\displaystyle \operatorname {hav} \left({\frac {d}{r}}\right)=\operatorname {hav} (\varphi _{2}-\varphi _{1})+\cos(\varphi _{1})\cos(\varphi _{2})\operatorname {hav} (\lambda _{2}-\lambda _{1})}


  \operatorname {hav} (\theta )=\sin ^{2}\left({\frac {\theta }{2}}\right)={\frac {1-\cos(\theta )}{2}}
  • d is the distance between the two points (along a great circle of the sphere; see spherical distance),
  • r is the radius of the sphere,
  • φ1, φ2: latitude of point 1 and latitude of point 2, in radians
  • λ1, λ2: longitude of point 1 and longitude of point 2, in radians

So , without wasting any more time , let’s get started with the code.

case class Location(lat: Double, lon: Double)

trait DistanceCalcular {
  def calculateDistanceInKilometer(userLocation: Location, warehouseLocation: Location): Int

class DistanceCalculatorImpl extends DistanceCalcular {

  private val AVERAGE_RADIUS_OF_EARTH_KM = 6371

  override def calculateDistanceInKilometer(userLocation: Location, warehouseLocation: Location): Int = {
    val latDistance = Math.toRadians( -
    val lngDistance = Math.toRadians(userLocation.lon - warehouseLocation.lon)
    val sinLat = Math.sin(latDistance / 2)
    val sinLng = Math.sin(lngDistance / 2)
    val a = sinLat * sinLat +
        * Math.cos(Math.toRadians(
        * sinLng * sinLng)
    val c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))

new DistanceCalculatorImpl().calculateDistanceInKilometer(Location(10,20),Location(40,20))


As you can see this is the scala implementation of Haversine formula and it computes the distance in pretty easy way.

You can see the compiled version of the code here on Scala Fiddle

WhatsApp Image 2017-12-01 at 1.30.31 PM


You can also verify your out put from here: National Hurricane Center


They are approximately same.

Hence in this way we can get the distance between two Locations.

If you have any queries you can contact me here or on twitter:@shiv4nsh

If you liked it, share it among peers !

Just one more thing , we are developing a community of developers and college graduates to help them so they may not face the same problem as we did. So if you liked the idea and want to be a part of this movement .

Come and join us : InternityFoundation

WhatsApp Image 2017-12-01 at 1.46.07 PM

I hope you join it 🙂
Wish you best of the weekend 🙂
Till then ! Happy hAKKAing 😀

1. Wikipedia : Haversine Formula
2. National Hurricane Center