AnyLogic
Expand
Font size

Cloud Java API

Applies to AnyLogic Cloud 2.5.1. Last modified on December 09, 2024.

To start using the API

  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
    For Private Cloud 2.3.1 and older versions: https://cloud.anylogic.com/files/api-8.5.0/clients/anylogic-cloud-client-8.5.0-old.jar
    • Inside the folder containing your AnyLogic Cloud API Java project, create a new folder and name it libs.
    • Place the .jar package you have downloaded in the libs folder.
    • Open the build.gradle file that belongs to your project.
    • 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'
      }
    • Save the changes in the build.gradle file.
    • Perform a re-import of all Gradle projects in the Java IDE you use.
  2. Obtain the API key in the AnyLogic Cloud UI.
  3. Create a new instance of the CloudClient object:
    For public version of AnyLogic Cloud:
    String apiKey = "<the API key>";
    AnyLogicCloudClient client = new AnyLogicCloudClient( apiKey );
    For Private Cloud:
    String apiKey = "<the API key>";
    String host = "<the Cloud instance URL>";
    AnyLogicCloudClient client = new AnyLogicCloudClient( apiKey, host );
  4. 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 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 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.
List <Model> getModels() Returns the list of Model objects listed in the My Models section of the AnyLogic Cloud web UI.
Model getModelById(String id) Finds and returns the Model object with a given ID.
Model getModelByName(String name) Finds and returns the Model object with a given name.
Version getModelVersionById(Model model, String versionId) Finds and returns the Version object of a given Model with a given id.
Version getModelVersionByNumber(Model model, int versionNumber) Finds and returns the Version object of a given Model with a given number (version numbering starts with 1).
Version getLatestModelVersion(Model model) Finds and returns the latest Version object of a given Model.
Version getLatestModelVersion(String modelName) Finds and returns the latest Version object of the model with a given name.
Inputs createDefaultInputs(ModelVersion version) Creates and returns an Inputs object for a given model version with default input values.
Inputs 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.
ModelRun createSimulation(Inputs inputs) Creates and returns a ModelRun object of type SIMULATION with the given Inputs (the model and version are identified by inputs).
ModelRun 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).
ModelRun 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).
ModelRun 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).
boolean fileExistsByHash(String hash) Checks whether the file with the given hash exists on the server. Returns true if this is the case, false otherwise.

hash — a string containing the file’s hash code.
String getFileHash(Path path) Calculates the hash code for the provided file.

path — a Path Java object converted from the string containing the path to the file that resides locally on the machine.
String getFileHash(InputStream inputStream) Calculates the hash code for the file presented as the Java input stream.

inputStream — the target Java input stream.
String uploadFile(Path path) Uploads the specified file to the Cloud instance server and returns its hash code as a string.
Any operations that imply working with instance-based files in Cloud API require you to specify the API key beforehand.
file — a Path Java object converted from the string containing the path to the file that resides locally on the machine.
String uploadFile(InputStream inputStream) Uploads the specified file, Java input stream, to the Cloud instance server and returns its hash code as a string.
Any operations that imply working with instance-based files in Cloud API require you to specify the API key beforehand.
inputStream — the target Java input stream.
void downloadFile(FileResource fileResource) Downloads and saves the file, specified as fileResource, from the server to the working directory.
Any operations that imply working with instance-based files in Cloud API require you to specify the API key beforehand.
fileResource — the Java object containing the file’s hash and filename.
void downloadFile(String fileOutput, Path outputFilePath) Downloads and saves the file output identified as fileOutput, from the server to the specified directory.
Any operations that imply working with instance-based files in Cloud API require you to specify the API key beforehand.
fileOutput — the unparsed JSON string containing the value of the required file output.
path — the path to the directory you want to save the file to, presented as the Path Java object.
void downloadFile(String fileOutput, OutputStream outputStream) Downloads the file, specified as fileResource, from the server, and puts its contents into the specified Java output stream.
Any operations that imply working with instance-based files in Cloud API require you to specify the API key beforehand.
fileOutput — the unparsed JSON string containing the value of the required file output.
outputStream — the target Java output stream.

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
T getInput(String name) Returns the value (an object) of the input with a given name. See Data conversion section for possible types.
void setInput(String name, double value) Sets the value of the double input with a given name.
This function does not validate inputs in any way. Cloud performs the validation only when the experiment run starts, that is, the corresponding function of the ModelRun class is executed.
void setInput(String name, int value) Sets the value of the integer input with a given name.
This function does not validate inputs in any way. Cloud performs the validation only when the experiment run starts, that is, the corresponding function of the ModelRun class is executed.
void setInput(String name, long value) Sets the value of the long input with a given name.
This function does not validate inputs in any way. Cloud performs the validation only when the experiment run starts, that is, the corresponding function of the ModelRun class is executed.
void setInput(String name, String value) Sets the value of the input with a given name.
This function does not validate inputs in any way. Cloud performs the validation only when the experiment run starts, that is, the corresponding function of the ModelRun class is executed.
void 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).
This function does not validate inputs in any way. Cloud performs the validation only when the experiment run starts, that is, the corresponding function of the ModelRun class is executed.
void 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).
This function does not validate inputs in any way. Cloud performs the validation only when the experiment run starts, that is, the corresponding function of the ModelRun class is executed.
void 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).
This function does not validate inputs in any way. Cloud performs the validation only when the experiment run starts, that is, the corresponding function of the ModelRun class is executed.
void setStartTime(double value, TimeUnits units) Sets the start time input. The units argument must specify TimeUnits of this input.
void setStopTime(double value, TimeUnits units) Sets the stop time input. The units argument must specify TimeUnits of this input.
void setStartDate(Date date) Sets the start date input.
void setStopDate(Date date) Sets the stop date input.
void setStopMode(ModelSystemData.StopMode stopMode) Sets the stop mode input. The stop mode argument should be selected from the ModelSystemData.StopMode enumerator.
void setRandomSeed(long randomSeed) Sets the random seed input.
void 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.
void 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
String[] names() Returns the array with all output names.
String 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.
String value(String name) Returns the value of the output with a given name. The type of value depends on the output, see Data conversion.
In case of an output having the FileResource type, returns the contents of the FileResource type as a JSON object.
ModelData[] 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
List<String> getInputNames() Returns the list of names of inputs that are varied across runs.
List<String> getOutputNames() Returns the list of names of requested outputs.
String 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.
String 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().
AggregationResponse[] 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
ModelRun 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.
ModelRun 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.
Inputs stop(Inputs modelRun) Requests to stop a given modelRun run and waits for stop. Returns the same ModelRun object once the HTTP request completes.
RunStateStatus getStatus() Returns the status of the model execution as last updated by polling (does not initiate any extra communication with the server).
String getProgress() Returns the fully parsed message field of the experiment run. To find out total experiment progress, use getProgress().then( progress => progress.total).
T 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.
T 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 has not 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 a discrete 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 a discrete 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.

Using a file as an input and output

In this example, we will run a simple model that requires an input file. The model will write new values to this file. Then, we will download the file (by then it will contain new values) as output.

import com.anylogic.cloud.clients.client_8_5_0.*;
import com.anylogic.cloud.service.open_8_5_0.api.project.*;
import java.io.IOException;
import java.nio.file.Paths;
 
public static void main( String[] args ) throws IOException {
    System.out.println("Authorizing and uploading input file data.xlsx ...");
    AnyLogicCloudClient client = new AnyLogicCloudClient( "e05a6efa-ea5f-4adf-b090-ae0ca7d16c20", "https://cloud.anylogic.com");
    String inputFileHash = client.uploadFile( Paths.get( "data.xlsx" ) );
 
    System.out.println("Setting up simulation File IO API Demo ...");
    Model model = client.getModelByName("File IO API Demo");
    ModelVersion version = client.getLatestModelVersion(model);
    Inputs inputs = client.createDefaultInputs(version);
    inputs.setInput("Data", inputFileHash);
 
    System.out.println( "Running simulation...");
    SimulationRun simulation = client.createSimulation(inputs);
    SingleRunOutputs outputs = simulation.getOutputsAndRunIfAbsent();
 
    System.out.println( "Downloading data.xlsx file populated with output data...");
    String fileResource = outputs.value("Data");   
    client.downloadFile(fileResource);
 
    System.out.println( "Complete!");
}

First, we calculate the hash code from the file that is located in the file system on the machine we use to execute the experiment via the Java API, using the uploadFile() function. This is done with the help of the built-in Java Paths class, which converts the provided relative file path (a string) to the Path Java object.

Then, we specify the model (which in this case already is present in Cloud) and tell Cloud the file to use as input, using the calculated hash code.

When the experiment is completed, we first convert the resulting data to the unparsed JSON string. This string is handled by the AnyLogic Cloud API client, which accepts it as a parameter for the downloadFile() function.

How can we improve this article?