//
// LocalSolver Model for Exercise 6.1
//

use io;

function input() 
{
  usage = "\nUsage: localsolver Exercise6.1.lsp";

  dataFile = io.openRead("Exercise6.1.dat");
  counties = dataFile.readInt();
  regions = dataFile.readInt();
  saleReps = dataFile.readInt();
  cover[i in 1..counties][j in 1..regions] = dataFile.readInt();
  doctors[i in 1..counties] = dataFile.readInt();
  average = sum[i in 1..counties] (doctors[i])/saleReps;
  close(dataFile);
}

function model()
{
  // x[j] = 1 if region j is selected and 0 otherwise
  x[j in 1..regions] <- bool();
  
  // the sum of the selected regions must equal the number of sales representatives
  constraint sum[j in 1..regions] (x[j]) == saleReps;
 
  // all counties must be covered
  for[i in 1..counties] 
    constraint sum[j in 1..regions] (cover[i][j]*x[j]) >= 1;

  // objective function is the variance of the doctors assigned to each region
  coverage[i in 1..counties] <- sum[j in 1..regions] (cover[i][j]*x[j]);
  docsPerRegion[i in 1..counties] <- (coverage[i] > 0) ? doctors[i]/coverage[i] : 0;
  assignedDocs[j in 1..regions] <- (x[j]) ? sum[i in 1..counties] (cover[i][j]*docsPerRegion[i]) : average;
  obj <- sum[j in 1..regions] (pow(assignedDocs[j]-average,2))/saleReps;
  minimize obj;
}

function output() 
{
  println("Objective function value: " + getValue(obj));
  print("Regions: ");
  for[j in 1..regions] if (getValue(x[j]) == 1) print(j + " ");
  outputFile = openWrite("Exercise6.1.out");
  for[j in 1..regions] print(outputFile, getValue(x[j]) + " ");
  close(outputFile);
}

function param() 
{
  if (lsTimeLimit == nil) lsTimeLimit = 1;
  lsVerbosity = 1;  
}
