CSsharp Example:
using System;
using System.Collections.Generic;
using System.Collections;
using Maximal.OptiMax;
namespace ShortPath
{
class MplShortPath
{
private string _resultString;
private double _totalDistance;
private double[] _path;
public MplShortPath()
{
_resultString = "";
_totalDistance = 0.0;
_path = null;
}
private ResultType loadModel(Model model, string startCity, string endCity, string[] cityNames, ArrayList routeDistData)
{
const double flow = 1.0;
try
{
model.IndexSets.Add("node", cityNames);
model.IndexSets.Add("FromNode[node]", cityNames);
model.IndexSets.Add("ToNode[node]", cityNames);
model.DataVectors.Add("Distance[FromNode,ToNode]", routeDistData);
model.DataStrings.Add("StartCity", startCity);
model.DataStrings.Add("EndCity", endCity);
model.VariableVectors.Add("Path[FromNode, ToNode] WHERE (Distance > 0)");
model.Objectives.Add("SUM(FromNode,ToNode: Distance*Path)");
ConstraintVector conFlowBal = model.ConstraintVectors.Add("FlowBalance[node]",
"SUM(FromNode: Path[FromNode, ToNode:=node]) = SUM(ToNode: Path[FromNode:=node, ToNode])");
conFlowBal[startCity].RHSValue = -flow;
conFlowBal[endCity].RHSValue = flow;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return model.LastResult;
}
public bool SolveModel(string solverName, string startCity, string endCity, string[] cityNames, ArrayList routeDistData)
{
OptiMax mpl = new OptiMax();
Model model = mpl.Models.Add("ShortPath");
Solver solver = mpl.Solvers.Add(solverName);
if (solver == null)
{
_resultString = "Solver " + solverName + " was not found.";
return false;
}
ResultType result = loadModel(model, startCity, endCity, cityNames, routeDistData);
if (result != ResultType.Success)
{
_resultString = model.Error.ToString();
return false;
}
model.UseExceptions = false;
result = model.Solve(solver);
if (result != ResultType.Success)
{
_resultString = "Solver " + solver.Name + ": " + model.ResultString + "\n" + model.Solution.ResultString;
return false;
}
_resultString = model.Solution.ResultString;
getSolutionValues(model);
return true;
}
private int getSolutionValues(Model model)
{
VariableVector varPath = model.VariableVectors["Path"];
List<double> solPath = new List<double>();
foreach (Variable var in varPath)
{
solPath.Add(var.Activity);
}
_path = solPath.ToArray();
_totalDistance = model.Solution.ObjectValue;
return solPath.Count;
}
public string ResultString
{
get { return _resultString; }
}
public double[] Path
{
get { return _path; }
}
public double TotalDistance
{
get { return _totalDistance; }
}
public string DataDir
{
get
{
return GetDataDir();
}
}
public static string GetDataDir()
{
OptiMax tempMpl = new OptiMax();
string dataDir = tempMpl.ModelDirectory;
tempMpl = null;
return dataDir;
}
}
}