magicanded

magicanded / algoptimizer / 0.2.16

README.md

algoptimizer - JavaScript Sandbox for JOptimizer

algoptimizer provides JavaScript sandbox which is based on RhinoJS for programming with JOptimizer.

Usage

Input

algoptimizer receives JSON object with following attributes:

ParameterDescription
inputFileJavaScript script file
variablesJSON object which contains all variables used to pass through JavaScript script via p_input parameter of main function

Output

algojse returns JSON object with following attributes:

ParameterDescription
isError'true' if error occurs, 'false' if success
errorCodeCode name of error
errorMessageMessage of error
resultsResults data
results.outputFileResults which are returned from JavaScript script. Results is JSON string which is converted from p_output parameter of main function.
results.outputFileUrlDownload URL of output file
results.inlineJSON object from p_output

JavaScript scripts

Common pattern

var g_env;
var g_input;
var g_input;

function main(p_env, p_input, p_output) {
  g_env = p_env;
  g_input = p_input;
  g_output = p_output;
  
  run();
}

function run() {
  // Processing code is here
}

Env methods

env provides API to access common Java methods:

MethodDescription
String toJson(Object obj)Convert input object to JSON string
Map objectFromJson(String json)Parse JSON string to java hash map
List listFromJson(String json)Parse JSON string to java array list
String newString(String src)Create new java string object
String newString(byte[] src, String charset)Create new java string object with charset
HashMap newHashMap()Create new java hashmap object
ArrayList newArrayList()Create new java array list object
Byte newByte(byte src)Create new java byte object
Short newShort(short src)Create new java short object
Integer newInteger(int src)Create new java integer object
Long newLong(long src)Create new java long object
Float newFloat(float src)Create new java float object
Double newDouble(double src)Create new java double object
Boolean newBoolean(boolean src)Create new java boolean object
Character newCharacter(char src)Create new java character object
List getKeys(Map src)Get all keys of a hash map
URL newURL(String protocol, String host, int port, String file)Create new java URL object
URL newURL(String protocol, String host, String file)Create new java URL object
URL newURL(String spec)Create new java URL object
URL newURL(URL context, String spec)Create new java URL object
String encodeURL(String src, String charset)Encode a URL string
String decodeURL(String src, String charset)Decode a URL string
String uniqid()Get a unique code
String suniqid()Get a small unique code
Date newDate()Create new java date object
Date newDate(long time)Create new java date object
SimpleDateFormat newDateFormat(String format)Create new java date formatter object
byte[] decodeBase64(byte[] b)Decode BASE64 byte array
byte[] encodeBase64(byte[] b)Encode BASE64 byte array
List setToList(Set src)Convert java SET object to array list object
Locale newLocale(String language)Create new java locale object
Locale newLocale(String language, String country)Create new java locale object
Locale newLocale(String language, String country, String variant)Create new java locale object
TimeZone newTimeZone(int rawOffset, String ID)Create new java timezone object
TimeZone newTimeZone(int rawOffset, String ID, int startMonth, int startDay, int startDayOfWeek, int startTime, int endMonth, int endDay, int endDayOfWeek, int endTime)Create new java timezone object
TimeZone newTimeZone(int rawOffset, String ID, int startMonth, int startDay, int startDayOfWeek, int startTime, int endMonth, int endDay, int endDayOfWeek, int endTime, int dstSavings)Create new java timezone object
TimeZone newTimeZone(int rawOffset, String ID, int startMonth, int startDay, int startDayOfWeek, int startTime, int startTimeMode, int endMonth, int endDay, int endDayOfWeek, int endTime, int endTimeMode, int dstSavings)Create new java timezone object
Calendar newCalendar()Create new java calendar object
Calendar newCalendar(Locale aLocale)Create new java calendar object
Calendar newCalendar(TimeZone zone)Create new java calendar object
Calendar newCalendar(TimeZone zone, Locale aLocale)Create new java calendar object
void writeFile(String path, byte[] contents)Write contents to file
boolean fileExist(String path)Check file exists or not
byte[] loadFile(String path)Load file contents
SJsoup newJsoup()Create new Jsoup wrapper object
String merge(String template, Map args)Merge variables in args parameter using template in 'template' parameter. Template engine used is Apache Velocity.
String merge(byte[] template, Map args)Merge variables in args parameter using template in 'template' parameter. Template engine used is Apache Velocity.
void sleep(long ms)Sleep in 'ms' milliseconds
String algo(String algo, String input)Run 'algo' algorithm with 'input' JSON string input
String algo(String algo, String inputTemplate, Map inputData)Run 'algo' algorithm with 'inputData' input hash map and 'inputTemplate' template for building input JSON string
String fileUrl(String path)Get URL of file

SJsoup methods

MethodDescription
Document parse(String html, String baseUri)Parse HTML text and create document object
Document parse(String html)Parse HTML text and create document object
Document parse(URL url, int timeoutMillis)Parse HTML page on URL and create document object
Document parseBodyFragment(String bodyHtml)Parse HTML in 'body' tag and create document object
Document parseBodyFragment(String bodyHtml, String baseUri)Parse HTML in 'body' tag and create document object
String clean(String bodyHtml, String baseUri, Whitelist whitelist)Clean HTML in 'body' tag
String clean(String bodyHtml, Whitelist whitelist)Clean HTML in 'body' tag
boolean isValid(String bodyHtml, Whitelist whitelist)Validate HTML in 'body' tag
SConnection connect(String url)Connect to URL and create connection wrapper
SConnection connect(URL url)Connect to URL and create connection wrapper

SConnection methods

MethodDescription
SConnection method(String src)Set request method
Response execute()Execute a request
SConnection cookie(String name, String value)Set cookies for request
SConnection cookies(Map cookies)Set cookies for request
SConnection data(Map src)Set request parameters
SConnection data(String... keyvals)Set request parameters
Document get()Excute GET request and create document
SConnection header(String name, String value)Set header of request
Document post()Excute POST request and create document
Map getCookies()Get cookies of response
SConnection referrer(String referrer)Set referrer of request
SConnection timeout(int millis)Set timeout of request
SConnection url(URL url)Set URL of request
SConnection url(String url)Set URL of request
SConnection userAgent(String userAgent)Set user agent of request

Sample JavaScript script: data://magicanded/public/algoptimizer-newton-unconstrained.js

var g_env;
var g_input;
var g_input;

function main(p_env, p_input, p_output) {
  g_env = p_env;
  g_input = p_input;
  g_output = p_output;
  
  run();
}

function run() {
  var v_jopt = g_env.newJOptimizer();

  var PMatrix = v_jopt.newArray2DRowRealMatrix(v_jopt.newDouble2D([ [ 1.68, 0.34, 0.38 ], [ 0.34, 3.09, -1.59 ], [ 0.38, -1.59, 1.54 ] ]));
  var qVector = v_jopt.newArrayRealVector(v_jopt.newDouble1D([ 0.018, 0.025, 0.01 ]));

  // Objective function.
  var theta = 0.01522;
  var P = PMatrix.scalarMultiply(theta);
  var q = qVector.mapMultiply(-1);
  var objectiveFunction = v_jopt.newPDQuadraticMultivariateRealFunction(P.getData(), q.toArray(), 0);
		
  var or = v_jopt.newOptimizationRequest();
  or.setF0(objectiveFunction);
  or.setInitialPoint(v_jopt.newDouble1D([ 0.04, 0.50, 0.46 ]));
  or.setTolerance(1.e-8);
		
  //optimization
  var opt = v_jopt.newNewtonUnconstrained();
  opt.setOptimizationRequest(or);
  opt.optimize(); 

  var sol = opt.getOptimizationResponse().getSolution();

  g_output.put('solution', sol);
}

Sample JavaScript script: data://magicanded/public/algoptimizer-linear-programming.js

var g_env;
var g_input;
var g_input;

function main(p_env, p_input, p_output) {
  g_env = p_env;
  g_input = p_input;
  g_output = p_output;
  
  run();
}

function run() {
  var v_jopt = g_env.newJOptimizer();
		
  //Objective function
  var c = v_jopt.newDouble1D([ -1., -1. ]);
		
  //Inequalities constraints
  var G = v_jopt.newDouble2D([[4./3., -1], [-1./2., 1.], [-2., -1.], [1./3., 1.]]);
  var h = v_jopt.newDouble1D([2., 1./2., 2., 1./2.]);
		
  //Bounds on variables
  var lb = v_jopt.newDouble1D([0 , 0]);
  var ub = v_jopt.newDouble1D([10, 10]);
		
  //optimization problem
  var or = new com.joptimizer.optimizers.LPOptimizationRequest();
  or.setC(c);
  or.setG(G);
  or.setH(h);
  or.setLb(lb);
  or.setUb(ub);
  or.setDumpProblem(true); 
		
  //optimization
  var opt = new com.joptimizer.optimizers.LPPrimalDualMethod();
		
  opt.setLPOptimizationRequest(or);
  opt.optimize();

  var sol = opt.getOptimizationResponse().getSolution();

  g_output.put('solution', sol);

}