AnyLogic
Expand
Font size

Cloud Java API

To start using the Java API, follow these steps:

  1. Download the client .jar package using the following link:
    https://cloud.anylogic.com/files/api-8.5.0/clients/anylogic-cloud-client-8.5.0.jar
  2. Inside the folder containing your AnyLogic Cloud API Java project, create a new folder and name it libs.
  3. Place the .jar package you have downloaded in the libs folder.
  4. Open the build.gradle file that belongs to your project.
  5. Add the following code to the file contents:
    repositories {
        mavenCentral()
        flatDir {
            dirs 'libs'
        }
    }
    dependencies {
        implementation group: 'com.anylogic.cloud.clients', name: 'anylogic-cloudclient', version: '8.5.0'
    }
  6. Save the changes in the build.gradle file.
  7. Perform a re-import of all Gradle projects in the Java IDE you use.
  8. Use the API to work with the cloud-based models.

API reference

AnyLogic Java API is synchronous (see Synchronous and asynchronous API).

The API treats names (for example, model, experiment, input, and output names) as case-insensitive.

AnyLogicCloudClient class

The AnyLogicCloudClient class is responsible for authentication and communication with the AnyLogic Cloud. Typically, there is only one object of class AnyLogicCloudClient in your Java code.

Function Description
AnyLogicCloudClient(String apiKey) A constructor that creates a synchronous AnyLogic Cloud client with the given API key and the default public cloud host name https://cloud.anylogic.com.
AnyLogicCloudClient(String apiKey, String host) A constructor that creates a synchronous AnyLogic Cloud client with the given API key and the given host name.
The client methods wait for the completion of HTTP requests (and thus block the thread) before returning the result.
getModels() Returns the list of Model objects listed in the My Models section of the AnyLogic Cloud web UI.
getModelById(String id) Finds and returns the Model object with a given ID.
getModelByName(String name) Finds and returns the Model object with a given name.
getModelVersionById(Model model, String versionId) Finds and returns the Version object of a given Model with a given id.
getModelVersionByNumber(Model model, int versionNumber) Finds and returns the Version object of a given Model with a given number (version numbering starts with 1).
getLatestModelVersion(Model model) Finds and returns the latest Version object of a given Model.
getLatestModelVersion(String modelName) Finds and returns the latest Version object of the model with a given name.
createDefaultInputs(ModelVersion version) Creates and returns an Inputs object for a given model version with default input values.
createInputsFromExperiment(ModelVersion version, String experimentName) Creates and returns the Inputs object for a given model Version object copied from the experiment with the given name.
createSimulation(Inputs inputs) Creates and returns a ModelRun object of type SIMULATION with the given Inputs (the model and version are identified by inputs).
createParameterVariation(Inputs inputs) Creates and returns a ModelRun object of type PARAMETER_VARIATION with the given Inputs (the model, its version, and range input are identified by inputs).
createMonteCarloFirstOrder(Inputs inputs) Creates and returns a ModelRun object of type MONTE_CARLO with the given Inputs (the model and version are identified by inputs).
createParameterVariationWithReplications(Inputs inputs) Creates and returns a ModelRun object of type PARAMETER_VARIATION_WITH_REPLICATIONS with the given Inputs (the model, its version, range input, and number of replications are identified by inputs).

Inputs class

An object of Inputs class is constructed in preparation of a model run (of any kind) by calling the AnyLogicCloudClient functions createDefaultInputs() or createInputsFromExperiment() and contains full information about the model, model version, and the input values. It should not be confused with the inputs field in the Version object.

Function Description
getInput(String name) Returns the value (an object) of the input with a given name. See Data conversion section for possible types.
setInput(String name, double value) Sets the value of the input with a given name.
setInput(String name, int value) Sets the value of the input with a given name.
setInput(String name, long value) Sets the value of the input with a given name.
setInput(String name, String value) Sets the value of the input with a given name.
setRangeInput(String name, int min, int max, int step) Sets a range for the integer input with a given name (in a parameter variation experiment).
setRangeInput(String name, long min, long max, long step) Sets a range for the long input with a given name (in a parameter variation experiment).
setRangeInput(String name, double min, double max, double step) Sets a range for the double input with a given name (in a parameter variation experiment).
setStartTime(double value, TimeUnits units) Sets the start time input. The units argument must specify TimeUnits of this input.
setStopTime(double value, TimeUnits units) Sets the stop time input. The units argument must specify TimeUnits of this input.
setStartDate(Date date) Sets the start date input.
setStopDate(Date date) Sets the stop date input.
setStopMode(ModelSystemData.StopMode stopMode) Sets the stop mode input. The stop mode argument should be selected from the ModelSystemData.StopMode enumerator.
setRandomSeed(long randomSeed) Sets the random seed input.
setInputsFromExperiment(Experiment experiment) Copies all input values from a given experiment to the run. Experiment can be obtained from cloud client by calling its getModelVersionExperiments() method.
setNumberOfReplications(int numberOfReplications) Sets the number of replications for the parameter variation experiment. The default value is 3.

Inputs of distribution type (for Monte Carlo 2nd order experiments) are coming in future releases of AnyLogic Cloud API.

SingleRunOutputs class

An object of this class is returned after a call of getOutputs() or getOutputsAndRunIfAbsent() of a ModelRun constructed for a single run simulation experiment.

Function Description
names() Returns the array with all output names.
findNameIncluding(String namePart) Searches for an output name that has namePart as a substring and returns it. If there is no such name or more than one such name is found, throws an exception. This function is useful because full names of the outputs may be complex, see Outputs data object.
value(String name) Returns the value of the output with a given name. The type of value depends on the output, see Data conversion.
getRawOutputs() Returns an array of all output items, each item has fields name, type, units, and value. For possible values of type and units field, see the Output types and Units sections correspondingly. The value field contains an object constructed as described in Data conversion.
Example
This is an example of raw outputs:
[
    {
        name: "Queue size stats",
        type: "STATISTICS_CONTINUOUS",
        units: null,
        value: {
            count: 1255584,
            max: 7,
            mean: 0.9988466028875719,
            min: 0,
            totalTime: 999999.2699032243,
            type: "CONTINUOUS",
            variance: 0.0027334062484944965
        }
    },
    {
        name: "Total time in system|Total time in system",
        type: "HISTOGRAM_DATA",
        units: null,
        value: {
            hits: (20) [800912, 159870, 29594, 5804, 3399, 1073, 257, 56, 12, 9, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            hitsOutHigh: 0,
            hitsOutLow: 0,
            intervalWidth: 1.6,
            lowerBound: 1.6,
            statistics:{
            count: 1000987,
                max: 18.533258249757637,
                mean: 2.5012383408878067,
                min: 1.6001570096705109,
                type: "DISCRETE",
                variance: 1.2835661096259896
            }
        }
    },
    {
        name: "Utilization|Server utilization",
        type: "DOUBLE",
        units: null,
        value: 0.31275860811685163,
    },
    {
        name: "Mean queue size|Mean queue size",
        type: "DOUBLE",
        units: null,
        value: 0.9988466025848514
    }
]

MultiRunOutputs class

An object of this class is returned after a call of getOutputs() or getOutputsAndRunIfAbsent() of a ModelRun constructed for a parameter variation or other multi run experiment. It simplifies navigation within the complex outputs structure. Keep in mind that you need to explicitly specify the required outputs when calling getOutputs() functions.

Function Description
getInputNames() Returns the list of names of inputs that are varied across runs.
getOutputNames() Returns the list of names of requested outputs.
getValuesOfInput(String name) Returns the values of the input with a given name across all runs in some fixed sequence.
You can only query values of the varied inputs. The fixed inputs are not stored in MultiRunOutputs.
getValuesOfOutput(String name) Returns the values of the output with a given name across all runs in some fixed sequence. This function can be used together with getValuesOfInput().
getRawData() Returns a table (a two-dimensional array) with values of all variable inputs and all outputs with a header row. For example, here is the raw data of a parameter variation experiment with one variable parameter Mean service time and one scalar output Utilization|Server utilization:
[
    ["Mean service time", "Utilization|Server utilization"],
    [1.8, 0.5621987153519676],
    [1.9, 0.5939408971748594],
    [2, 0.6253419155200399]
]

ModelRun class

The ModelRun class is responsible for communication with and control of a model run (without animation) executed in Cloud. It can be considered as a front-end mirror of a back-end experiment run.

Objects of ModelRun subclasses are created and returned by calling the functions createSimulation(), createParameterVariation(), createMonteCarloFirstOrder(), or createParameterVariationWithReplications() of the AnyLogicCloudClient. A ModelRun object contains full information about the model, version, inputs, and experiment type.

SimulationRun subclass

The SimulationRun subclass is used to communicate with with and control a simulation experiment (without animation) executed in Cloud. Objects of the SimulationRun subclass are created and returned by calling the createSimulation() function of the AnyLogicCloudClient.

ParameterVariationRun subclass

The ParameterVariationRun subclass is used to communicate with and control a parameter variation experiment (without animation) executed in Cloud. Objects of the ParameterVariationRun class are created and returned by calling the createParameterVariation() and createParameterVariationWithReplications() functions of the AnyLogicCloudClient.

MonteCarloFirstOrderRun subclass

The MonteCarloFirstOrderRun subclass is used to communicate with and control a Monte Carlo 1st Order experiment (without animation) executed in Cloud. Objects of the MonteCarloFirstOrderRun class are created and returned by calling the createMonteCarloFirstOrder() function of the AnyLogicCloudClient.

The following methods are common for all ModelRun objects:

Function Description
run() Starts the model run and waits for the run completion. Polling is used to determine the run state. The thread is blocked until the run is completed or terminated. Returns the list of outputs.
waitForCompletion(long pollingPeriod) Waits for the experiment to complete and returns the same ModelRun object. The pollingPeriod parameter is optional, the default value is 5000ms.
stop(Inputs modelRun) Requests to stop a given modelRun run and waits for stop. Returns the same ModelRun object once the HTTP request completes.
getStatus() Returns the status of the model execution as last updated by polling (does not initiate any extra communication with the server). Possible values are the same as described in the Experiment Run State section.
getProgress() Returns the fully parsed message field of the Experiment Run State object. To find out total experiment progress, use getProgress().then( progress => progress.total).
getOutputs(List<String> requiredOutputNames) If the run has already been completed, returns the run outputs (either SingleRunOutputs or MultiRunOutputs object), otherwise throws an exception. requiredOutputNames is the list of output names that are to be returned. If requiredOutputNames is omitted, the behavior is different for single and multi-run experiments: for a single run, all outputs are returned, for a multi run — only outputs of scalar types are returned.
getOutputsAndRunIfAbsent(List<String> requiredOutputNames, long pollingPeriod) If the run has already been completed, returns the run outputs (either SingleRunOutputs or MultiRunOutputs object), otherwise requests to run the experiment, waits for completion by polling, and then returns the outputs. requiredOutputNames has the same meaning as in getOutputs(). The pollingPeriod parameter is optional, the default value is 5000ms.

Examples

Simulation run without animation (minimalistic)

This is done with the API function ModelRun.getOutputsAndRunIfAbsent().

String API_KEY = "e05a6efa-ea5f-4adf-b090-ae0ca7d16c20";
String DOUBLE_INPUT = "Server capacity";
String DOUBLE_OUTPUT = "Utilization|Server utilization";
AnyLogicCloudClient client = new AnyLogicCloudClient(API_KEY);
Model model = client.getModelByName("Service System Demo");
ModelVersion version = client.getLatestModelVersion(model);

Inputs inputs = client.createDefaultInputs(version);
inputs.setInput(DOUBLE_INPUT, 20);
SimulationRun simulation = client.createSimulation(inputs);
SingleRunOutputs outputs = simulation.getOutputsAndRunIfAbsent(); // will exit upon run completion

System.out.println(outputs.value(DOUBLE_OUTPUT));

First, we define multiple values that will be used for input.

  1. The AnyLogicCloudClient class is constructed, given the API key.
  2. The server is asked to find the model with the given model name (Service System Demo).
  3. The server is asked to find the latest version of the model.
  4. When (and if) such model and version is found, we create the Inputs object with the default input values.
  5. We use the setInput function to change the value of the “Server capacity” parameter to 20.0. Other inputs will keep their default values.
  6. We ask the AnyLogicCloudClient to create a simulation object with the inputs. This is done on the client side, there is no communication with the server.
  7. The getOutputsAndRunIfAbsent() function is called, which checks the simulation status:
    • If such simulation has been completed, it gets the outputs
    • If such simulation hasn’t been run yet, it runs the simulation and waits for the outputs. The SingleRunOutputs object is returned
  8. Finally, the output value for the “Average performance” field is displayed in the Java console using the API of SingleRunOutputs.

If an error occurs during any step, the error message will be displayed in the Java console.

To get the value of a particular output, we need to specify its name exactly as it is constructed when the model is uploaded to Cloud (for more information refer to the Output data object section. The case, however, does not matter: you can use either lower case or upper case.

Querying simulation results of a completed run

The key function used here is ModelRun.getOutputs().

package com.anylogic.cloud.java_api_example;

  import com.anylogic.cloud.clients.client_8_5_0.*;
  import com.anylogic.cloud.service.open_8_5_0.api.project.*;

  public class Example {
      private static final String API_KEY = "4b7494a6-8c4e-4fb2-b4a8-9d829dcbb7a6";
      private static final String MODEL_ID = "a56057c6-b937-4539-8bdc-ab4e5f8fe86a";
      private static final String DOUBLE_INPUT = "Server capacity";
      private static final String DOUBLE_OUTPUT = "Average performance";

      public static void main(String[] args) {
          singleSimulationRun();
      }

      private static void singleSimulationRunGetResultsOfCompletedRun() {
          System.out.println("Getting results of already completed run with Server capacity = 20.0");
          AnyLogicCloudClient client = new AnyLogicCloudClient(API_KEY);
          Model model = client.getModelById(MODEL_ID);
          ModelVersion version = client.getLatestModelVersion(model);
          Inputs inputs = client.createDefaultInputs(version);
          inputs.setInput(DOUBLE_INPUT, 20.0);
          SimulationRun simulation = client.createSimulation(inputs);
          SingleRunOutputs outputs = simulation.getOutputs(); 
          System.out.println(outputs.value(DOUBLE_OUTPUT));
      }
  }

The Example class contains multiple values that will be used for input.

We use the setInput() function to change the value of the “Server capacity” parameter to 20.0. Having constructed the inputs and the simulation objects, we call simulation.getOutputs(). If the outputs exist, they are returned. If there are no outputs, an error occurs.

Running parameter variation

In this example, we will run a parameter variation experiment. One of the input parameters will be varied in range. To demonstrate one more feature of the AnyLogic Cloud API, we will take the input values from an existing simulation experiment defined in the standard AnyLogic Cloud web interface and change a parameter value from a scalar to a range.

package com.anylogic.cloud.java_api_example;

import com.anylogic.cloud.clients.client_8_5_0.*;
import com.anylogic.cloud.service.open_8_5_0.api.project.*;

import java.util.Arrays;

public class Example {
    private static final String API_KEY = "4b7494a6-8c4e-4fb2-b4a8-9d829dcbb7a6";
    private static final String MODEL_ID = "a56057c6-b937-4539-8bdc-ab4e5f8fe86a";
    private static final String DOUBLE_INPUT = "Server capacity";
    private static final String DOUBLE_OUTPUT = "Average performance";

    public static void main(String[] args) {
        parameterVariationRun();
    }

    private static void parameterVariationRun() {
        System.out.println( "A parameter variation run with Double input varied from 20.0 to 180.0 with step 20.0" );
        AnyLogicCloudClient client = new AnyLogicCloudClient(API_KEY);
        Model model = client.getModelById(MODEL_ID);
        ModelVersion version = client.getLatestModelVersion(model);
        Inputs inputs = client.createDefaultInputs(version);
        inputs.setRangeInput(DOUBLE_INPUT, 20.0, 180.0, 20.0);
        ParameterVariationRun variation = client.createParameterVariation(inputs);
        MultiRunOutputs outputs = variation.getOutputsAndRunIfAbsent(Arrays.asList(DOUBLE_OUTPUT)); // will exit upon run completion
        System.out.println(outputs.getValuesOfOutput(DOUBLE_OUTPUT));
    }
}

The Example class contains multiple values that will be used for input.

Here, we use the Inputs.setRangeInput() function to change the value of the "Server capacity" input to a range type, from 20.0 to 180.0 with step 20.0. Therefore, nine simulation runs are to be performed.

Then we need to create a ModelRun object of the parameter variation type, which is done by the AnyLogicCloudClient.createParameterVariation() function.

The run of parameter variation is invoked by calling the getOutputsAndRunIfAbsent() function just like in our previous examples, but there is one important difference. Full outputs of a multiple run experiment may be a very large piece of data, so the API user has to explicitly specify which outputs need to be delivered. This is done by listing the output names in the array passed to getOutputsAndRunIfAbsent() or getOutputs() as a parameter. In this example, we are interested in the "Average performance" output. If the parameter is omitted for a multi run experiment, only scalar outputs will be returned, if any.

Outputs of a multi run experiment are returned as a MultiRunOutputs object, which has a number of functions simplifying navigation.

Running parameter variation with replications

In this example, we will run a parameter variation experiment with the explicitly set number of replications. One of the input parameters will be varied in range. We will also use the input values from an existing simulation experiment defined in the standard AnyLogic Cloud web interface.

package com.anylogic.cloud.java_api_example;

import com.anylogic.cloud.clients.client_8_5_0.*;
import com.anylogic.cloud.service.open_8_5_0.api.project.*;

import java.util.Arrays;

public class Example {
    private static final String API_KEY = "4b7494a6-8c4e-4fb2-b4a8-9d829dcbb7a6";
    private static final String MODEL_ID = "a56057c6-b937-4539-8bdc-ab4e5f8fe86a";
    private static final String DOUBLE_INPUT = "Server capacity";
    private static final String DOUBLE_OUTPUT = "Average performance";

    public static void main(String[] args) {
        parameterVariationWithReplicationsRun();
    }

    private static void parameterVariationWithReplicationsRun() {
        System.out.println( "A parameter variation with replications run with Double input varied from 20.0 to 180.0 with step 20.0, 4 replications" );
        AnyLogicCloudClient client = new AnyLogicCloudClient(API_KEY, HOST);
        Model model = client.getModelById(MODEL_ID);
        ModelVersion version = client.getLatestModelVersion(model);
        Inputs inputs = client.createDefaultInputs(version);
        inputs.setRangeInput(DOUBLE_INPUT, 20.0, 180.0, 20.0);
        inputs.setNumberOfReplications(4);
        ParameterVariationRun variation = client.createParameterVariationWithReplications(inputs);
        MultiRunOutputs outputs = variation.getOutputsAndRunIfAbsent(Arrays.asList(DOUBLE_OUTPUT)); // will exit upon run completion
        System.out.println(outputs.getValuesOfOutput(DOUBLE_OUTPUT));
    }
}

The Example class contains multiple values that will be used for input.

Here, we use the Inputs.setNumberofReplications() function to specify the number of replications to be run.

Then we create a ModelRun object for the needed experiment type, which is done by the AnyLogicCloudClient.createParameterVariationWithReplications() function.

The experiment run is triggered by calling the getOutputsAndRunIfAbsent() function just like in our previous examples, but there is one important difference. Full outputs of a multiple run experiment may be a very large piece of data, so the API user has to explicitly specify which outputs need to be delivered. This is done by listing the output names in the array passed to getOutputsAndRunIfAbsent() or getOutputs() as a parameter. In this example, we are interested in the "Average performance" output. If the parameter is omitted for a multi run experiment, only scalar outputs will be returned, if any.

Outputs of a multi-run experiment are returned as a MultiRunOutputs object, which has a number of functions simplifying navigation.

Running Monte Carlo 1st order

In this example, we will run a Monte Carlo 1st order experiment with the explicitly set number of replications. When executed via the API, the Monte Carlo experiment runs the simulation a specified number of times, obtains the collections of values, and then returns them.

One of the input parameters will be varied in range. We will also use the input values from an existing simulation experiment defined in the standard AnyLogic Cloud web interface.

package com.anylogic.cloud.java_api_example;

import com.anylogic.cloud.clients.client_8_5_0.*;
import com.anylogic.cloud.service.open_8_5_0.api.project.*;

import java.util.Arrays;

public class Example {
    private static final String API_KEY = "4b7494a6-8c4e-4fb2-b4a8-9d829dcbb7a6";
    private static final String MODEL_ID = "a56057c6-b937-4539-8bdc-ab4e5f8fe86a";
    private static final String DOUBLE_INPUT = "Server capacity";
    private static final String DOUBLE_OUTPUT = "Average performance";

    public static void main(String[] args) {
        monteCarloFirstOrderRun();
    }

    private static void monteCarloFirstOrderRun() {
        System.out.println( "A Monte-Carlo 1st order run with 4 replications" );
        AnyLogicCloudClient client = new AnyLogicCloudClient(API_KEY, HOST);
        Model model = client.getModelById(MODEL_ID);
        ModelVersion version = client.getLatestModelVersion(model);
        Inputs inputs = client.createDefaultInputs(version);
        inputs.setNumberOfReplications(4);
        MonteCarloFirstOrderRun monteCarlo = client.createMonteCarloFirstOrder(inputs);
        MultiRunOutputs outputs = monteCarlo.getOutputsAndRunIfAbsent(Arrays.asList(DOUBLE_OUTPUT)); // will exit upon run completion
        System.out.println(outputs.getValuesOfOutput(DOUBLE_OUTPUT));
    }
}

The Example class contains multiple values that will be used for input.

The Inputs.setNumberofReplications() function specifies the number of replications to be run.

Then we create a ModelRun object for the needed experiment type, which is done by the AnyLogicCloudClient.createMonteCarloFirstOrder() function.

The experiment run is triggered by calling the getOutputsAndRunIfAbsent() function just like in our previous examples, but there is one important difference. Full outputs of a multiple run experiment may be a very large piece of data, so the API user has to explicitly specify which outputs need to be delivered. This is done by listing the output names in the array passed to getOutputsAndRunIfAbsent() or getOutputs() as a parameter. In this example, we are interested in the "Average performance" output. If the parameter is omitted for a multi run experiment, only scalar outputs will be returned, if any.

Outputs of a multi-run experiment are returned as a MultiRunOutputs object, which has a number of functions simplifying navigation.

How can we improve this article?