Batchmode Examples#
This section includes source code for all of the Gurobi batch mode examples.
The same source code can be found in the examples
directory of the
Gurobi distribution.
/* Copyright 2024, Gurobi Optimization, LLC */
/* This example reads a MIP model from a file, solves it in batch mode,
* and prints the JSON solution string. */
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#if defined (WIN32) || defined (WIN64)
#include <Windows.h>
#define sleep(n) Sleep(1000*n)
#else
#include <unistd.h>
#endif
#include "gurobi_c.h"
/* setup gurobi environment */
int setupbatchconnection(GRBenv **envP)
{
int error = 0;
GRBenv *env = NULL;
/* setup a batch environment */
error = GRBemptyenv(envP);
if (error) goto QUIT;
env = *envP;
error = GRBsetintparam(env, "CSBatchMode", 1);
if (error) goto QUIT;
error = GRBsetstrparam(env, "LogFile", "batchmode.log");
if (error) goto QUIT;
error = GRBsetstrparam(env, "CSManager", "http://localhost:61080");
if (error) goto QUIT;
error = GRBsetstrparam(env, "UserName", "gurobi");
if (error) goto QUIT;
error = GRBsetstrparam(env, "ServerPassword", "pass");
if (error) goto QUIT;
error = GRBstartenv(env);
if (error) goto QUIT;
QUIT:
if (error) {
printf("Failed to setup environment, error code %d\n", error);
} else {
printf("Successfully created environment\n");
}
return error;
}
/* display batch-error code if any */
void batcherrorinfo(GRBbatch *batch)
{
int error = 0;
int errorCode;
char *errorMsg;
char *BatchID;
if (!batch) goto QUIT;
/* query the last error code */
error = GRBgetbatchintattr(batch, "BatchErrorCode", &errorCode);
if (error || !errorCode) goto QUIT;
/* query the last error message */
error = GRBgetbatchstrattr(batch, "BatchErrorMessage", &errorMsg);
if (error) goto QUIT;
error = GRBgetbatchstrattr(batch, "BatchID", &BatchID);
if (error) goto QUIT;
printf("Batch ID %s Error Code %d (%s)\n", BatchID, errorCode, errorMsg);
QUIT:
return;
}
/* create a batch request for given problem file */
int newbatchrequest(const char *filename,
char *BatchID)
{
int error = 0;
GRBenv *env = NULL;
GRBenv *menv = NULL;
GRBmodel *model = NULL;
char tag[128];
int cols, j;
/* setup a batch connection */
error = setupbatchconnection(&env);
if (error) goto QUIT;
/* read a model */
error = GRBreadmodel(env, filename, &model);
if (error) goto QUIT;
/* set some params */
menv = GRBgetenv(model);
error = GRBsetdblparam(menv, "MIPGap", 0.01);
if (error) goto QUIT;
/* for extra detailed information on JSON solution string */
error = GRBsetintparam(menv, "JSONSolDetail", 1);
if (error) goto QUIT;
/* setup some tags, we need tags to be able to query results later on */
error = GRBgetintattr(model, "NumVars", &cols);
if (error) goto QUIT;
if (cols > 10) cols = 10;
for (j = 0; j < cols; j++) {
sprintf(tag, "MyUniqueVariableID%d",j);
error = GRBsetstrattrelement(model, "VTag", j, tag);
}
/* submit batch request to the Manager */
error = GRBoptimizebatch(model, BatchID);
if (error) goto QUIT;
QUIT:
if (error) {
printf("Failed to submit a new batch request, error code %d\n", error);
} else {
printf("Successfully submitted new batch request %s\n", BatchID);
}
GRBfreemodel(model);
GRBfreeenv(env);
return error;
}
/* wait for final bstatus */
int waitforfinalstatus(const char *BatchID)
{
int error = 0;
GRBenv *env = NULL;
GRBbatch *batch = NULL;
time_t start, current;
int bstatus;
/* setup a batch connection */
error = setupbatchconnection(&env);
if (error) goto QUIT;
/* create batch-object */
error = GRBgetbatch(env, BatchID, &batch);
if (error) goto QUIT;
/* query bstatus, and wait for completed */
error = GRBgetbatchintattr(batch, "BatchStatus", &bstatus);
if (error) goto QUIT;
start = time(NULL);
while (bstatus == GRB_BATCH_SUBMITTED) {
/* abort if taking too long */
current = time(NULL);
if (current - start >= 3600) {
/* request to abort the batch */
error = GRBabortbatch(batch);
if (error) goto QUIT;
}
/* do not bombard the server */
sleep(1u);
/* update local attributes */
error = GRBupdatebatch(batch);
if (error) goto QUIT;
/* query bstatus */
error = GRBgetbatchintattr(batch, "BatchStatus", &bstatus);
if (error) goto QUIT;
/* deal with failed bstatus */
if (bstatus == GRB_BATCH_FAILED) {
/* retry the batch request */
error = GRBretrybatch(batch);
if (error) goto QUIT;
bstatus = GRB_BATCH_SUBMITTED;
}
}
QUIT:
if (error) {
printf("Failed to wait for final bstatus, error code %d\n", error);
} else {
printf("Final Batch Status %d\n", bstatus);
}
batcherrorinfo(batch);
/* release local resources */
GRBfreebatch(batch);
GRBfreeenv(env);
return error;
}
/* final report on batch request */
int finalreport(const char *BatchID)
{
int error = 0;
GRBenv *env = NULL;
GRBbatch *batch = NULL;
char *jsonsol = NULL;
int bstatus;
/* setup a batch connection */
error = setupbatchconnection(&env);
if (error) goto QUIT;
/* create batch object */
error = GRBgetbatch(env, BatchID, &batch);
if (error) goto QUIT;
/* query bstatus, and wait for completed */
error = GRBgetbatchintattr(batch, "BatchStatus", &bstatus);
if (error) goto QUIT;
/* display depending on batch bstatus */
switch (bstatus) {
case GRB_BATCH_CREATED:
printf("Batch is 'CREATED'\n");
printf("maybe batch-creation process was killed?\n");
break;
case GRB_BATCH_SUBMITTED:
printf("Batch is 'SUBMITTED'\n");
printf("Some other user re-submitted this Batch object?\n");
break;
case GRB_BATCH_ABORTED:
printf("Batch is 'ABORTED'\n");
break;
case GRB_BATCH_FAILED:
printf("Batch is 'FAILED'\n");
break;
case GRB_BATCH_COMPLETED:
/* print JSON solution into string */
error = GRBgetbatchjsonsolution(batch, &jsonsol);
if (error) goto QUIT;
printf("JSON solution: %s\n", jsonsol);
/* save solution into a file */
error = GRBwritebatchjsonsolution(batch, "batch-sol.json.gz");
if (error) goto QUIT;
break;
default:
printf("This should not happen, probably points to a"
" user-memory corruption problem\n");
exit(EXIT_FAILURE);
break;
}
QUIT:
if (error) {
printf("Failed to perform final report, error code %d\n", error);
} else {
printf("Reporting done\n");
}
batcherrorinfo(batch);
if (jsonsol)
GRBfree(jsonsol);
GRBfreebatch(batch);
GRBfreeenv(env);
return error;
}
/* remove batch ID from manager */
int discardbatch(const char *BatchID)
{
int error = 0;
GRBenv *env = NULL;
GRBbatch *batch = NULL;
/* setup a batch connection */
error = setupbatchconnection(&env);
if (error) goto QUIT;
/* create batch object */
error = GRBgetbatch(env, BatchID, &batch);
if (error) goto QUIT;
/* discard the batch object in the manager */
error = GRBdiscardbatch(batch);
if (error) goto QUIT;
QUIT:
batcherrorinfo(batch);
GRBfreebatch(batch);
GRBfreeenv(env);
return error;
}
int
main(int argc,
char **argv)
{
int error = 0;
char BatchID[GRB_MAX_STRLEN+1];
/* ensure enough parameters */
if (argc < 2) {
fprintf(stderr, "Usage: %s filename\n", argv[0]);
goto QUIT;
}
/* create a new batch request */
error = newbatchrequest(argv[1], BatchID);
if (error) goto QUIT;
/* wait for final bstatus */
error = waitforfinalstatus(BatchID);
if (error) goto QUIT;
/* query final bstatus, and if completed, print JSON solution */
error = finalreport(BatchID);
if (error) goto QUIT;
/* eliminate batch from the manager */
error = discardbatch(BatchID);
if (error) goto QUIT;
QUIT:
return error;
}
/* Copyright 2024, Gurobi Optimization, LLC */
// This example reads a MIP model from a file, solves it in batch mode,
// and prints the JSON solution string.
//
// You will need a Compute Server license for this example to work.
#include <ctime>
#if defined (WIN32) || defined (WIN64) || defined(_WIN32) || defined (_WIN64)
#include <Windows.h>
#define sleep(n) Sleep(1000*n)
#else
#include <unistd.h>
#endif
#include "gurobi_c++.h"
using namespace std;
// Set-up the environment for batch mode optimization.
//
// The function configures and start an environment to be used for batch
// optimization.
void
setupbatchenv(GRBEnv* env)
{
env->set(GRB_StringParam_LogFile, "batchmode.log");
env->set(GRB_StringParam_CSManager, "http://localhost:61080");
env->set(GRB_StringParam_UserName, "gurobi");
env->set(GRB_StringParam_ServerPassword, "pass");
env->set(GRB_IntParam_CSBatchMode, 1);
// No network communication happened up to this point. This will happen
// now that we call the start() method.
env->start();
}
// Print batch job error information, if any
void
printbatcherrorinfo(GRBBatch &batch)
{
if (batch.get(GRB_IntAttr_BatchErrorCode) == 0)
return;
cerr << "Batch ID " << batch.get(GRB_StringAttr_BatchID)
<< ": Error code " << batch.get(GRB_IntAttr_BatchErrorCode)
<< " (" << batch.get(GRB_StringAttr_BatchErrorMessage)
<< ")" << endl;
}
// Create a batch request for given problem file
string
newbatchrequest(char* filename)
{
GRBEnv* env = NULL;
GRBModel* model = NULL;
GRBVar* v = NULL;
string batchID;
try {
// Start environment, create Model object from file
env = new GRBEnv(true);
setupbatchenv(env);
model = new GRBModel(*env, filename);
// Set some parameters; switch on detailed JSON information
model->set(GRB_DoubleParam_MIPGap, 0.01);
model->set(GRB_IntParam_JSONSolDetail, 1);
// Define tags for some variables in order to access their values later
int numvars = model->get(GRB_IntAttr_NumVars);
v = model->getVars();
if (numvars > 10) numvars = 10;
for (int j = 0; j < numvars; j++) {
char vtag[64];
sprintf(vtag, "Variable %d", j);
v[j].set(GRB_StringAttr_VTag, string(vtag));
}
// submit batch request
batchID = model->optimizeBatch();
} catch (...) {
// Free local resources
delete[] v;
delete model;
delete env;
// Let the exception propagate
throw;
}
// Free local resources
delete[] v;
delete model;
delete env;
return batchID;
}
// Wait for the final status of the batch.
// Initially the status of a batch is "submitted"; the status will change
// once the batch has been processed (by a compute server).
void
waitforfinalstatus(string batchID)
{
// Wait no longer than one hour
time_t maxwaittime = 3600;
GRBEnv* env = NULL;
GRBBatch* batch = NULL;
try {
// Setup and start environment, create local Batch handle object
env = new GRBEnv(true);
setupbatchenv(env);
batch = new GRBBatch(*env, batchID);
time_t starttime = time(NULL);
int BatchStatus = batch->get(GRB_IntAttr_BatchStatus);
while (BatchStatus == GRB_BATCH_SUBMITTED) {
// Abort this batch if it is taking too long
time_t curtime = time(NULL);
if (curtime - starttime > maxwaittime) {
batch->abort();
break;
}
// Wait for two seconds
sleep(2);
// Update the resident attribute cache of the Batch object with the
// latest values from the cluster manager.
batch->update();
BatchStatus = batch->get(GRB_IntAttr_BatchStatus);
// If the batch failed, we try again
if (BatchStatus == GRB_BATCH_FAILED)
batch->retry();
}
} catch (...) {
// Print information about error status of the job that
// processed the batch
printbatcherrorinfo(*batch);
// Free local resources
delete batch;
delete env;
// let the exception propagate
throw;
}
// Free local resources
delete batch;
delete env;
}
void
printfinalreport(string batchID)
{
GRBEnv* env = NULL;
GRBBatch* batch = NULL;
try {
// Setup and starts environment, create local Batch handle object
env = new GRBEnv(true);
setupbatchenv(env);
batch = new GRBBatch(*env, batchID);
int BatchStatus = batch->get(GRB_IntAttr_BatchStatus);
if (BatchStatus == GRB_BATCH_CREATED)
cout << "Batch status is 'CREATED'" << endl;
else if (BatchStatus == GRB_BATCH_SUBMITTED)
cout << "Batch is 'SUBMITTED" << endl;
else if (BatchStatus == GRB_BATCH_ABORTED)
cout << "Batch is 'ABORTED'" << endl;
else if (BatchStatus == GRB_BATCH_FAILED)
cout << "Batch is 'FAILED'" << endl;
else if (BatchStatus == GRB_BATCH_COMPLETED) {
cout << "Batch is 'COMPLETED'" << endl;
// Pretty printing the general solution information
cout << "JSON solution:" << batch->getJSONSolution() << endl;
// Write the full JSON solution string to a file
batch->writeJSONSolution("batch-sol.json.gz");
} else {
// Should not happen
cout << "Batch has unknown BatchStatus" << endl;
}
} catch (...) {
// Free local resources
delete batch;
delete env;
// let the exception propagate
throw;
}
// Free local resources
delete batch;
delete env;
}
// Instruct cluster manager to remove all data relating to this BatchID
void
batchdiscard(string batchID)
{
GRBEnv* env = NULL;
GRBBatch* batch = NULL;
try {
// Setup and start environment, create local Batch handle object
env = new GRBEnv(true);
setupbatchenv(env);
batch = new GRBBatch(*env, batchID);
// Remove batch request from manager
batch->discard();
} catch (...) {
// Free local resources even
delete batch;
delete env;
// let the exception propagate
throw;
}
// Free local resources
delete batch;
delete env;
}
// Solve a given model using batch optimization
int
main(int argc,
char** argv)
{
// Ensure we have an input file
if (argc != 2) {
cout << "Usage: " << argv[0] << " filename" << endl;
return 0;
}
try {
// Submit new batch request
string batchID = newbatchrequest(argv[1]);
// Wait for final status
waitforfinalstatus(batchID);
// Report final status info
printfinalreport(batchID);
// Remove batch request from manager
batchdiscard(batchID);
cout << "Batch optimization OK" << endl;
} catch (GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch (...) {
cout << "Exception during optimization" << endl;
}
return 0;
}
/* Copyright 2024, Gurobi Optimization, LLC */
/* This example reads a MIP model from a file, solves it in batch mode,
and prints the JSON solution string.
You will need a Compute Server license for this example to work. */
using System;
using Gurobi;
class batchmode_cs
{
/// <summary>Set-up the environment for batch mode optimization.
/// </summary>
/// <remarks>
/// The function creates an empty environment, sets all neccessary
/// parameters, and returns the ready-to-be-started Env object to
/// caller.
/// </remarks>
static void setupbatchenv(ref GRBEnv env)
{
env.CSBatchMode = 1;
env.CSManager = "http://localhost:61080";
env.LogFile = "batchmode.log";
env.ServerPassword = "pass";
env.UserName = "gurobi";
// No network communication happened up to this point. This will happen
// now that we call start().
env.Start();
}
///<summary>Print batch job error information, if any</summary>
static void printbatcherrorinfo(ref GRBBatch batch)
{
if (batch.BatchErrorCode == 0)
return;
Console.WriteLine("Batch ID: " + batch.BatchID + ", Error code: " +
batch.BatchErrorCode + "(" +
batch.BatchErrorMessage + ")");
}
///<summary>Create a batch request for given problem file</summary>
static string newbatchrequest(string filename)
{
string batchID= "";
// Create an empty environment
GRBEnv env = new GRBEnv(true);
// set environment and build model
setupbatchenv(ref env);
GRBModel model = new GRBModel(env, filename);
try {
// Set some parameters
model.Set(GRB.DoubleParam.MIPGap, 0.01);
model.Set(GRB.IntParam.JSONSolDetail, 1);
// Define tags for some variables to access their values later
int count = 0;
foreach (GRBVar v in model.GetVars()) {
v.VTag = "Variable" + count;
count += 1;
if (count >= 10) break;
}
// Submit batch request
batchID = model.OptimizeBatch();
} finally {
// Dispose of model and env
model.Dispose();
env.Dispose();
}
return batchID;
}
///<summary>Wait for the final status of the batch. Initially the
/// status of a batch is <see cref="GRB.BatchStatus.SUBMITTED"/>;
/// the status will change once the batch has been processed
/// (by a compute server).</summary>
static void waitforfinalstatus(string batchID)
{
// Wait no longer than one hour
double maxwaittime = 3600;
DateTime start = DateTime.Now;
// Setup and start environment, create local Batch handle object
GRBEnv env = new GRBEnv(true);
setupbatchenv(ref env);
GRBBatch batch = new GRBBatch(env, batchID);
try {
while (batch.BatchStatus == GRB.BatchStatus.SUBMITTED) {
// Abort this batch if it is taking too long
TimeSpan interval = DateTime.Now - start;
if (interval.TotalSeconds > maxwaittime) {
batch.Abort();
break;
}
// Wait for two seconds
System.Threading.Thread.Sleep(2000);
// Update the resident attribute cache of the Batch object
// with the latest values from the cluster manager.
batch.Update();
// If the batch failed, we retry it
if (batch.BatchStatus == GRB.BatchStatus.FAILED) {
batch.Retry();
System.Threading.Thread.Sleep(2000);
batch.Update();
}
}
} finally {
// Print information about error status of the job
// that processed the batch
printbatcherrorinfo(ref batch);
batch.Dispose();
env.Dispose();
}
}
///<summary>Final Report for Batch Request</summary>
static void printfinalreport(string batchID)
{
// Setup and start environment, create local Batch handle object
GRBEnv env = new GRBEnv(true);
setupbatchenv(ref env);
GRBBatch batch = new GRBBatch(env, batchID);
switch(batch.BatchStatus) {
case GRB.BatchStatus.CREATED:
Console.WriteLine("Batch status is 'CREATED'\n");
break;
case GRB.BatchStatus.SUBMITTED:
Console.WriteLine("Batch is 'SUBMITTED\n");
break;
case GRB.BatchStatus.ABORTED:
Console.WriteLine("Batch is 'ABORTED'\n");
break;
case GRB.BatchStatus.FAILED:
Console.WriteLine("Batch is 'FAILED'\n");
break;
case GRB.BatchStatus.COMPLETED:
Console.WriteLine("Batch is 'COMPLETED'\n");
// Get JSON solution as string
Console.WriteLine("JSON solution:" + batch.GetJSONSolution());
// Write the full JSON solution string to a file
batch.WriteJSONSolution("batch-sol.json.gz");
break;
default:
// Should not happen
Console.WriteLine("Unknown BatchStatus" + batch.BatchStatus);
Environment.Exit(1);
break;
}
// Cleanup
batch.Dispose();
env.Dispose();
}
///<summary>Instruct the cluster manager to discard all data relating
/// to this BatchID</summary>
static void batchdiscard(string batchID)
{
// Setup and start environment, create local Batch handle object
GRBEnv env = new GRBEnv(true);
setupbatchenv(ref env);
GRBBatch batch = new GRBBatch(env, batchID);
// Remove batch request from manager
batch.Discard();
// Cleanup
batch.Dispose();
env.Dispose();
}
///<summary>Solve a given model using batch optimization</summary>
static void Main(string[] args)
{
if (args.Length < 1) {
Console.Out.WriteLine("Usage: batchmode_cs filename");
return;
}
try {
// Submit new batch request
string batchID = newbatchrequest(args[0]);
// Wait for final status
waitforfinalstatus(batchID);
// Report final status info
printfinalreport(batchID);
// Remove batch request from manager
batchdiscard(batchID);
Console.WriteLine("Batch optimization OK");
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " +
e.Message);
}
}
}
/* Copyright 2024, Gurobi Optimization, LLC */
/* This example reads a model from a file, solves it in batch mode
* and prints the JSON solution string. */
import com.gurobi.gurobi.*;
public class Batchmode {
// Set-up a batch-mode environment
private static GRBEnv setupbatchconnection() throws GRBException {
GRBEnv env = new GRBEnv(true);
env.set(GRB.IntParam.CSBatchMode, 1);
env.set(GRB.StringParam.LogFile, "batchmode.log");
env.set(GRB.StringParam.CSManager, "http://localhost:61080");
env.set(GRB.StringParam.UserName, "gurobi");
env.set(GRB.StringParam.ServerPassword, "pass");
env.start();
return env;
}
// Display batch-error if any
private static void batcherrorinfo(GRBBatch batch) throws GRBException {
// Get last error code
int error = batch.get(GRB.IntAttr.BatchErrorCode);
if (error == 0) return;
// Query last error message
String errMsg = batch.get(GRB.StringAttr.BatchErrorMessage);
// Query batchID
String batchID = batch.get(GRB.StringAttr.BatchID);
System.out.println("Batch ID " + batchID + "Error Code " +
error + "(" + errMsg + ")");
}
// Create a batch request from the given problem file
private static String newbatchrequest(String filename) throws GRBException {
// Setup a batch connection
GRBEnv env = setupbatchconnection();
// Read a model
GRBModel model = new GRBModel(env, filename);
// Set some parameters
model.set(GRB.DoubleParam.MIPGap, 0.01);
model.set(GRB.IntParam.JSONSolDetail, 1);
// Set-up some tags, we need tags to be able to query results
int count = 0;
for (GRBVar v: model.getVars()) {
v.set(GRB.StringAttr.VTag, "UniqueVariableIdentifier" + count);
count += 1;
if (count >= 10) break;
}
// Batch-mode optimization
String batchid = model.optimizeBatch();
// no need to keep the model around
model.dispose();
// no need to keep environment
env.dispose();
return batchid;
}
// Wait for final status
private static void waitforfinalstatus(String batchid) throws Exception {
// Setup a batch connection
GRBEnv env = setupbatchconnection();
// Create Batch-object
GRBBatch batch = new GRBBatch(env, batchid);
try {
// Query status, and wait for completed
int status = batch.get(GRB.IntAttr.BatchStatus);
long timestart = System.currentTimeMillis();
while(status == GRB.BatchStatus.SUBMITTED) {
// Abort if taking too long
long curtime = System.currentTimeMillis();
if (curtime - timestart > 3600 * 1000) {
// Request to abort the batch
batch.abort();
break;
}
// Do not bombard the server
Thread.sleep(2000);
// Update local attributes
batch.update();
// Query current status
status = batch.get(GRB.IntAttr.BatchStatus);
// Deal with failed status
if (status == GRB.BatchStatus.FAILED ||
status == GRB.BatchStatus.ABORTED ) {
// Retry the batch job
batch.retry();
}
}
} catch (Exception e) {
// Display batch-error if any
batcherrorinfo(batch);
throw e;
} finally {
// Dispose resources
batch.dispose();
env.dispose();
}
}
// Final report on batch request
private static void finalreport(String batchid) throws GRBException {
// Setup a batch connection
GRBEnv env = setupbatchconnection();
// Create batch object
GRBBatch batch = new GRBBatch(env, batchid);
try {
int status = batch.get(GRB.IntAttr.BatchStatus);
// Display depending on batch status
switch(status) {
case GRB.BatchStatus.CREATED:
System.out.println("Batch is 'CREATED'");
System.out.println("maybe batch-creation process was killed?");
break;
case GRB.BatchStatus.SUBMITTED:
System.out.println("Batch is 'SUBMITTED'");
System.out.println("Some other user re-submitted this Batch object?");
break;
case GRB.BatchStatus.ABORTED:
System.out.println("Batch is 'ABORTED'");
break;
case GRB.BatchStatus.FAILED:
System.out.println("Batch is 'FAILED'");
break;
case GRB.BatchStatus.COMPLETED:
// print JSON solution into string
System.out.println("JSON solution:" + batch.getJSONSolution());
// save solution into a file
batch.writeJSONSolution("batch-sol.json.gz");
break;
default:
System.out.println("This should not happen, probably points to a user-memory corruption problem");
System.exit(1);
break;
}
} catch (GRBException e) {
// Display batch-error if any
batcherrorinfo(batch);
throw e;
} finally {
// Dispose resources
batch.dispose();
env.dispose();
}
}
// Discard batch data from the Cluster Manager
private static void discardbatch(String batchid) throws GRBException {
// Setup a batch connection
GRBEnv env = setupbatchconnection();
// Create batch object
GRBBatch batch = new GRBBatch(env, batchid);
try {
// Request to erase input and output data related to this batch
batch.discard();
} catch (GRBException e) {
// Display batch-error if any
batcherrorinfo(batch);
throw e;
} finally {
// Dispose resources
batch.dispose();
env.dispose();
}
}
// Main public function
public static void main(String[] args) {
// Ensure enough parameters
if (args.length < 1) {
System.out.println("Usage: java Batch filename");
System.exit(1);
}
try {
// Create a new batch request
String batchid = newbatchrequest(args[0]);
// Wait for final status
waitforfinalstatus(batchid);
// Query final status, and if completed, print JSON solution
finalreport(batchid);
// once the user is done, discard all remote information
discardbatch(batchid);
// Signal success
System.out.println("OK");
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". "
+ e.getMessage());
} catch (Exception e) {
System.out.println("Error");
}
}
}
#!/usr/bin/env python3.11
# Copyright 2024, Gurobi Optimization, LLC
# This example reads a MIP model from a file, solves it in batch mode,
# and prints the JSON solution string.
#
# You will need a Compute Server license for this example to work.
import sys
import time
import json
import gurobipy as gp
from gurobipy import GRB
# Set up the environment for batch mode optimization.
#
# The function creates an empty environment, sets all necessary parameters,
# and returns the ready-to-be-started Env object to caller. It is the
# caller's responsibility to dispose of this environment when it's no
# longer needed.
def setupbatchenv():
env = gp.Env(empty=True)
env.setParam("LogFile", "batchmode.log")
env.setParam("CSManager", "http://localhost:61080")
env.setParam("UserName", "gurobi")
env.setParam("ServerPassword", "pass")
env.setParam("CSBatchMode", 1)
# No network communication happened up to this point. This will happen
# once the caller invokes the start() method of the returned Env object.
return env
# Print batch job error information, if any
def printbatcherrorinfo(batch):
if batch is None or batch.BatchErrorCode == 0:
return
print(
f"Batch ID {batch.BatchID}: Error code {batch.BatchErrorCode} ({batch.BatchErrorMessage})"
)
# Create a batch request for given problem file
def newbatchrequest(filename):
# Start environment, create Model object from file
#
# By using the context handlers for env and model, it is ensured that
# model.dispose() and env.dispose() are called automatically
with setupbatchenv().start() as env, gp.read(filename, env=env) as model:
# Set some parameters
model.Params.MIPGap = 0.01
model.Params.JSONSolDetail = 1
# Define tags for some variables in order to access their values later
for count, v in enumerate(model.getVars()):
v.VTag = f"Variable{count}"
if count >= 10:
break
# Submit batch request
batchID = model.optimizeBatch()
return batchID
# Wait for the final status of the batch.
# Initially the status of a batch is "submitted"; the status will change
# once the batch has been processed (by a compute server).
def waitforfinalstatus(batchID):
# Wait no longer than one hour
maxwaittime = 3600
# Setup and start environment, create local Batch handle object
with setupbatchenv().start() as env, gp.Batch(batchID, env) as batch:
starttime = time.time()
while batch.BatchStatus == GRB.BATCH_SUBMITTED:
# Abort this batch if it is taking too long
curtime = time.time()
if curtime - starttime > maxwaittime:
batch.abort()
break
# Wait for two seconds
time.sleep(2)
# Update the resident attribute cache of the Batch object with the
# latest values from the cluster manager.
batch.update()
# If the batch failed, we retry it
if batch.BatchStatus == GRB.BATCH_FAILED:
batch.retry()
# Print information about error status of the job that processed the batch
printbatcherrorinfo(batch)
def printfinalreport(batchID):
# Setup and start environment, create local Batch handle object
with setupbatchenv().start() as env, gp.Batch(batchID, env) as batch:
if batch.BatchStatus == GRB.BATCH_CREATED:
print("Batch status is 'CREATED'")
elif batch.BatchStatus == GRB.BATCH_SUBMITTED:
print("Batch is 'SUBMITTED")
elif batch.BatchStatus == GRB.BATCH_ABORTED:
print("Batch is 'ABORTED'")
elif batch.BatchStatus == GRB.BATCH_FAILED:
print("Batch is 'FAILED'")
elif batch.BatchStatus == GRB.BATCH_COMPLETED:
print("Batch is 'COMPLETED'")
print("JSON solution:")
# Get JSON solution as string, create dict from it
sol = json.loads(batch.getJSONSolution())
# Pretty printing the general solution information
print(json.dumps(sol["SolutionInfo"], indent=4))
# Write the full JSON solution string to a file
batch.writeJSONSolution("batch-sol.json.gz")
else:
# Should not happen
print("Batch has unknown BatchStatus")
printbatcherrorinfo(batch)
# Instruct the cluster manager to discard all data relating to this BatchID
def batchdiscard(batchID):
# Setup and start environment, create local Batch handle object
with setupbatchenv().start() as env, gp.Batch(batchID, env) as batch:
# Remove batch request from manager
batch.discard()
# Solve a given model using batch optimization
if __name__ == "__main__":
# Ensure we have an input file
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} filename")
sys.exit(0)
# Submit new batch request
batchID = newbatchrequest(sys.argv[1])
# Wait for final status
waitforfinalstatus(batchID)
# Report final status info
printfinalreport(batchID)
# Remove batch request from manager
batchdiscard(batchID)
print("Batch optimization OK")
' Copyright 2024, Gurobi Optimization, LLC
'
' This example reads a MIP model from a file, solves it in batch mode,
' and prints the JSON solution string.
'
' You will need a Compute Server license for this example to work. */
Imports System
Imports Gurobi
Class batchmode_vb
' Set-up the environment for batch mode optimization.
'
' The function creates an empty environment, sets all neccessary
' parameters, and returns the ready-to-be-started Env object to caller.
' It is the caller's responsibility to dispose of this environment when
' it's no longer needed.
Private Shared Function setupbatchenv() As GRBEnv
Dim env As GRBEnv = New GRBEnv(True)
env.CSBatchMode = 1
env.CSManager = "http://localhost:61080"
env.LogFile = "batchmode.log"
env.ServerPassword = "pass"
env.UserName = "gurobi"
' No network communication happened up to this point. This will happen
' once the caller invokes the start() method of the returned Env
' Object.
Return env
End Function
' Print batch job error information, if any
Private Shared Sub printbatcherrorinfo(ByRef batch As GRBBatch)
If batch.BatchErrorCode = 0 Then Return
Console.WriteLine("Batch ID: " & batch.BatchID & ", Error code: " + batch.BatchErrorCode & "(" + batch.BatchErrorMessage & ")")
End Sub
' Create a batch request for given problem file
Private Shared Function newbatchrequest(ByVal filename As String) As String
Dim batchID As String = ""
' Start environment, create Model object from file
Dim env As GRBEnv = setupbatchenv()
env.Start()
Dim model As GRBModel = New GRBModel(env, filename)
Try
' Set some parameters
model.[Set](GRB.DoubleParam.MIPGap, 0.01)
model.[Set](GRB.IntParam.JSONSolDetail, 1)
' Define tags for some variables in order to access their values later
Dim count As Integer = 0
For Each v As GRBVar In model.GetVars()
v.VTag = "Variable" & count
count += 1
If count >= 10 Then Exit For
Next
' submit batch request
batchID = model.OptimizeBatch()
Finally
model.Dispose()
env.Dispose()
End Try
Return batchID
End Function
' Wait for the final status of the batch.
' Initially the status of a batch is "submitted"; the status will change
' once the batch has been processed (by a compute server).
Private Shared Sub waitforfinalstatus(ByVal batchID As String)
' Wait no longer than one hour
Dim maxwaittime As Double = 3600
Dim start As DateTime = DateTime.Now
' Setup and start environment, create local Batch handle object
Dim env As GRBEnv = setupbatchenv()
env.Start()
Dim batch As GRBBatch = New GRBBatch(env, batchID)
Try
While batch.BatchStatus = GRB.BatchStatus.SUBMITTED
' Abort this batch if it is taking too long
Dim interval As TimeSpan = DateTime.Now - start
If interval.TotalSeconds > maxwaittime Then
batch.Abort()
Exit While
End If
' Wait for two seconds
System.Threading.Thread.Sleep(2000)
' Update the resident attribute cache of the Batch object with the
' latest values from the cluster manager.
batch.Update()
' If the batch failed, we retry it
If batch.BatchStatus = GRB.BatchStatus.FAILED Then
batch.Retry()
System.Threading.Thread.Sleep(2000)
batch.Update()
End If
End While
Finally
' Print information about error status of the job that
' processed the batch
printbatcherrorinfo(batch)
batch.Dispose()
env.Dispose()
End Try
End Sub
Private Shared Sub printfinalreport(ByVal batchID As String)
' Setup and start environment, create local Batch handle object
Dim env As GRBEnv = setupbatchenv()
env.Start()
Dim batch As GRBBatch = New GRBBatch(env, batchID)
Select Case batch.BatchStatus
Case GRB.BatchStatus.CREATED
Console.WriteLine("Batch status is 'CREATED'" & vbLf)
Case GRB.BatchStatus.SUBMITTED
Console.WriteLine("Batch is 'SUBMITTED" & vbLf)
Case GRB.BatchStatus.ABORTED
Console.WriteLine("Batch is 'ABORTED'" & vbLf)
Case GRB.BatchStatus.FAILED
Console.WriteLine("Batch is 'FAILED'" & vbLf)
Case GRB.BatchStatus.COMPLETED
Console.WriteLine("Batch is 'COMPLETED'" & vbLf)
' Pretty printing the general solution information
Console.WriteLine("JSON solution:" & batch.GetJSONSolution())
' Write the full JSON solution string to a file
batch.WriteJSONSolution("batch-sol.json.gz")
Case Else
' Should not happen
Console.WriteLine("Unknown BatchStatus" & batch.BatchStatus)
Environment.[Exit](1)
End Select
batch.Dispose()
env.Dispose()
End Sub
' Instruct cluster manager to discard all data relating to this BatchID
Private Shared Sub batchdiscard(ByVal batchID As String)
' Setup and start environment, create local Batch handle object
Dim env As GRBEnv = setupbatchenv()
env.Start()
Dim batch As GRBBatch = New GRBBatch(env, batchID)
' Remove batch request from manager
batch.Discard()
batch.Dispose()
env.Dispose()
End Sub
' Solve a given model using batch optimization
Shared Sub Main(ByVal args As String())
' Ensure we have an input file
If args.Length < 1 Then
Console.Out.WriteLine("Usage: batchmode_vb filename")
Return
End If
Try
' Submit new batch request
Dim batchID As String = newbatchrequest(args(0))
' Wait for final status
waitforfinalstatus(batchID)
' Report final status info
printfinalreport(batchID)
' Remove batch request from manager
batchdiscard(batchID)
Console.WriteLine("Batch optimization OK")
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " + e.Message)
End Try
End Sub
End Class