/*********************************************
* OPL 12.8.0.0 Model
* Author: AlexFleischer
* Creation Date: Jul 12, 2018 at 11:53:32 AM
*********************************************/
float lambda=1.2;
int sampleSize=10000;
float s=-2;
float e=2;
float x[i in 0..sampleSize]=s+(e-s)*i/sampleSize;
int nbSegments=100;
float x2[i in 0..nbSegments]=(s)+(e-s)*i/nbSegments;
float y2[i in 0..nbSegments]=exp(x2[i]); // Here is the function
float firstSlope=0;
float lastSlope=0;
tuple breakpoint // y=f(x)
{
key float x;
float y;
}
sorted { breakpoint } breakpoints={<x2[i],y2[i]> | i in 0..nbSegments};
float slopesBeforeBreakpoint[b in breakpoints]=
(b.x==first(breakpoints).x)
?firstSlope
:(b.y-prev(breakpoints,b).y)/(b.x-prev(breakpoints,b).x);
pwlFunction f=piecewise(b in breakpoints)
{ slopesBeforeBreakpoint[b]->b.x; lastSlope } (first(breakpoints).x, first(breakpoints).y);
assert forall(b in breakpoints) f(b.x)==b.y;
float maxError=max (i in 0..sampleSize) abs(lambda*(1-exp(x[i]))-f(x[i]));
float averageError=1/(sampleSize+1)*sum (i in 0..sampleSize) abs(exp(x[i]-f(x[i])));
execute
{
writeln("maxError = ",maxError);
writeln("averageError = ",averageError);
}
execute
{
// turn an OPL array into a python list
function getPythonListOfArray(_array)
{
var quote="\"";
var nextline="\\\n";
var res="[";
for(var i in _array)
{
var value=_array[i];
if (typeof(value)=="string") res+=quote;
res+=value;
if (typeof(value)=="string") res+=quote;
res+=",";
res+=nextline;
}
res+="]";
return res;
}
// Display a function with points with x and y arrays of x and y
function displayXY(x,y,pythonpath,pythonfile)
{
writeln("displayXY ",x," ",y," ",pythonpath," ",pythonfile);
var python=new IloOplOutputFile(pythonfile);
python.writeln("import matplotlib.pyplot as plt");
python.writeln("x = ",getPythonListOfArray(x))
python.writeln("y = ",getPythonListOfArray(y))
python.writeln("plt.plot(x, y)");
python.writeln("plt.xlabel('x - axis')");
python.writeln("plt.ylabel('y - axis')");
python.writeln("plt.title('xy graph')");
python.writeln("plt.show()");
python.close();
IloOplExec(pythonpath+" "+ pythonfile,true);
}
}
string pythonpath="C:\\Users\\IBM_ADMIN\\AppData\\Local\\Programs\\Python\\Python36\\python.exe";
string pythonfile="C:\\displayXY.py";
execute
{
displayXY(x2,y2,pythonpath,pythonfile);
}