### Render XMILE Model as BufferedImage Source: https://context7.com/greendelta/olca-sd/llms.txt This code illustrates how to render an XMILE model into a `BufferedImage` object, capturing the stocks, flows, auxiliaries, and connectors. The generated image can then be saved to a file, for example, as a PNG. It relies on the `ModelImage` and `Xmile` classes. ```java import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import org.openlca.sd.xmile.Xmile; import org.openlca.sd.xmile.img.ModelImage; // Load model Xmile xmile = Xmile.readFrom(new File("examples/population-model.stmx")).orElseThrow(); // Create image BufferedImage image = ModelImage.createFrom(xmile).orElseThrow(); // Save as PNG ImageIO.write(image, "PNG", new File("model-diagram.png")); System.out.println("Image size: " + image.getWidth() + "x" + image.getHeight()); ``` -------------------------------- ### Manage Tensors and Arrays with Dimension and Tensor in Java Source: https://context7.com/greendelta/olca-sd/llms.txt Illustrates how to create and manipulate n-dimensional arrays using the Dimension and Tensor classes. This includes defining dimensions with named elements, creating 1D and 2D tensors, setting and retrieving values using subscripts (by name or index), and performing operations like setting all elements or getting the tensor shape. These tensors can also be integrated with the Interpreter for expression evaluation. ```java import org.openlca.sd.eqn.*; import org.openlca.sd.eqn.cells.Cell; import java.util.List; // Create dimensions Dimension products = Dimension.of("Products", "PET", "PVC", "Nylon", "HDPE"); Dimension regions = Dimension.of("Regions", "US", "EU", "ASIA"); // Create 1D tensor Tensor prices = Tensor.of(products); prices.set(Subscript.of("PET"), Cell.of(1.50)); prices.set(Subscript.of("PVC"), Cell.of(2.25)); prices.set(Subscript.of("Nylon"), Cell.of(3.00)); prices.set(Subscript.of("HDPE"), Cell.of(1.75)); // Access by name or index (1-based) Cell petPrice = prices.get(Subscript.of("PET")); // 1.50 Cell firstPrice = prices.get(Subscript.of(0)); // 1.50 (0-based internal) // Create 2D tensor Tensor salesData = Tensor.of(products, regions); salesData.set(List.of(Subscript.of("PET"), Subscript.of("US")), Cell.of(1000)); salesData.set(List.of(Subscript.of("PET"), Subscript.of("EU")), Cell.of(800)); salesData.set(List.of(Subscript.of("PVC"), Subscript.of("ASIA")), Cell.of(1500)); // Access 2D values Cell petUS = salesData.get(List.of(Subscript.of("PET"), Subscript.of("US"))); System.out.println("PET sales in US: " + petUS.asNum()); // 1000.0 // Set all elements prices.setAll(0.0); salesData.setAll(Cell.of(100)); // Get tensor shape int[] shape = salesData.shape(); // [4, 3] // Use tensors in interpreter EvalContext ctx = new EvalContext(); ctx.bind(new Var.Aux(Id.of("prices"), Cell.of(prices), "USD")); ctx.bind(new Var.Aux(Id.of("sales"), Cell.of(salesData), "units")); Interpreter interpreter = Interpreter.of(ctx); // Array access in expressions double value = interpreter.eval("prices[PET]").orElseThrow().asNum(); double sales = interpreter.eval("sales[PVC, ASIA]").orElseThrow().asNum(); // Mixed subscripts (name and integer) double mixed = interpreter.eval("sales[1, 2]").orElseThrow().asNum(); // PET, EU ``` -------------------------------- ### Run System Dynamics Simulations in Java Source: https://context7.com/greendelta/olca-sd/llms.txt Shows how to execute time-stepped simulations using the `Simulator` class with a loaded XMILE model. It details how to track specific variables and iterate through simulation states to access variable values at each time step. This enables the analysis of dynamic model behavior. ```java import java.io.File; import org.openlca.sd.eqn.Id; import org.openlca.sd.eqn.Simulator; import org.openlca.sd.xmile.Xmile; // Load model and create simulator Xmile xmile = Xmile.readFrom(new File("examples/plastic-subs.stmx")).orElseThrow(); Simulator sim = Simulator.of(xmile).orElseThrow(); // Track a specific variable Id variableId = Id.of("plastic use"); System.out.println("Results for: " + variableId); System.out.println("Iteration\tTime\tValue"); // Run simulation and iterate through states for (var result : sim) { if (result.isError()) { System.err.println("Simulation error: " + result.error()); break; } var state = result.value(); double value = state.valueOf(variableId).orElseThrow().asNum(); System.out.printf("%d\t%.2f\t%.4f%n", state.iteration(), state.time(), value); } // Access multiple variables in each state for (var result : sim) { var state = result.orElseThrow(); // Get all variables in current state for (var entry : state.vars().entrySet()) { Id id = entry.getKey(); var variable = entry.getValue(); var cell = variable.value(); System.out.printf("t=%.2f: %s = %s%n", state.time(), id.label(), cell); } } ``` -------------------------------- ### Load and Parse XMILE Models in Java Source: https://context7.com/greendelta/olca-sd/llms.txt Demonstrates how to load and parse XMILE/STMX files using the `Xmile` class. It shows how to access model metadata, simulation specifications, model elements (stocks, flows, auxiliaries), and array dimensions. This is the first step in using the olca-sd library for system dynamics modeling. ```java import java.io.File; import org.openlca.sd.xmile.Xmile; // Load from file File modelFile = new File("examples/population-model.stmx"); Xmile xmile = Xmile.readFrom(modelFile).orElseThrow(); // Access model metadata System.out.println("Model: " + xmile.header().name()); System.out.println("UUID: " + xmile.header().uuid()); System.out.println("Vendor: " + xmile.header().vendor()); // Access simulation specifications var specs = xmile.simSpecs(); System.out.println("Method: " + specs.method()); // e.g., "Euler" System.out.println("Time units: " + specs.timeUnits()); // e.g., "Years" System.out.println("Start: " + specs.start()); // e.g., 1.0 System.out.println("Stop: " + specs.stop()); // e.g., 25.0 System.out.println("dt: " + specs.dt().value()); // e.g., 0.25 // Access model elements var model = xmile.model(); System.out.println("Stocks: " + model.stocks().size()); System.out.println("Flows: " + model.flows().size()); System.out.println("Auxiliaries: " + model.auxs().size()); // Iterate over stocks for (var stock : model.stocks()) { System.out.printf("Stock '%s': equation=%s, nonNegative=%b%n", stock.name(), stock.eqn, stock.isNonNegative()); System.out.println(" Inflows: " + stock.inflows()); System.out.println(" Outflows: " + stock.outflows()); } // Access array dimensions for (var dim : xmile.dims()) { System.out.printf("Dimension '%s': size=%d, elements=%s%n", dim.name(), dim.size(), dim.elems()); } ``` -------------------------------- ### Evaluate Expressions with Interpreter in Java Source: https://context7.com/greendelta/olca-sd/llms.txt Demonstrates the usage of the Interpreter class to evaluate various mathematical, logical, and conditional expressions. It supports variables, built-in functions like SQRT and MAX, power and modulo operators, and comments within expressions. The Interpreter requires an EvalContext to bind variables and can also perform static analysis to extract variables from expressions. ```java import org.openlca.sd.eqn.EvalContext; import org.openlca.sd.eqn.Interpreter; // Create context and bind variables EvalContext ctx = new EvalContext() .bind("price", 5.0) .bind("quantity", 10) .bind("discount", 0.15); Interpreter interpreter = Interpreter.of(ctx); // Evaluate arithmetic expressions double total = interpreter.eval("price * quantity * (1 - discount)").orElseThrow().asNum(); System.out.println("Total: " + total); // Output: 42.5 // Evaluate expressions with built-in functions double result = interpreter.eval("SQRT(ABS(-16)) + MAX(3, 8, 5)").orElseThrow().asNum(); System.out.println("Result: " + result); // Output: 12.0 // Evaluate conditional expressions ctx.bind("temperature", 25); double output = interpreter.eval( "IF temperature > 30 THEN 100 ELSE IF temperature > 20 THEN 50 ELSE 0" ).orElseThrow().asNum(); System.out.println("Cooling: " + output); // Output: 50.0 // Evaluate logical expressions boolean check = interpreter.eval("(5 > 3) AND (10 <= 10)").orElseThrow().asBool(); System.out.println("Check: " + check); // Output: true // Use power operators double power1 = interpreter.eval("2^10").orElseThrow().asNum(); // 1024.0 double power2 = interpreter.eval("3**4").orElseThrow().asNum(); // 81.0 // Use modulo operators double mod1 = interpreter.eval("17 % 5").orElseThrow().asNum(); // 2.0 double mod2 = interpreter.eval("17 MOD 5").orElseThrow().asNum(); // 2.0 // Expressions with comments (ignored during evaluation) double commented = interpreter.eval( "price * quantity { calculate subtotal } * (1 - discount) { apply discount }" ).orElseThrow().asNum(); // Extract variables from expressions (static analysis) var vars = Interpreter.varsOf("a * b + SQRT(c) - MAX(d, e)").orElseThrow(); System.out.println("Variables: " + vars); // [a, b, c, d, e] ``` -------------------------------- ### Evaluate Expressions with Built-in Functions in Java Source: https://context7.com/greendelta/olca-sd/llms.txt This Java snippet shows how to use the `EvalContext` and `Interpreter` classes to evaluate mathematical, trigonometric, aggregation, statistical, and time-based expressions. The `EvalContext` manages variables and pre-registers built-in functions, enabling complex calculations within a simulation environment. ```java import org.openlca.sd.eqn.EvalContext; import org.openlca.sd.eqn.Interpreter; // Create context with built-in functions pre-registered EvalContext ctx = new EvalContext(); // Built-in constants (auto-bound in simulations) ctx.bind("INF", Double.POSITIVE_INFINITY); ctx.bind("PI", Math.PI); Interpreter interpreter = Interpreter.of(ctx); // Mathematical functions interpreter.eval("ABS(-5)"); // 5.0 interpreter.eval("SQRT(16)"); // 4.0 interpreter.eval("EXP(1)"); // 2.718... interpreter.eval("LN(2.718)"); // ~1.0 interpreter.eval("LOG10(100)"); // 2.0 interpreter.eval("INT(3.7)"); // 3.0 // Trigonometric functions interpreter.eval("SIN(PI/2)"); // 1.0 interpreter.eval("COS(0)"); // 1.0 interpreter.eval("TAN(PI/4)"); // 1.0 interpreter.eval("ARCSIN(1)"); // PI/2 interpreter.eval("ARCCOS(0)"); // PI/2 interpreter.eval("ARCTAN(1)"); // PI/4 interpreter.eval("ASIN(1)"); // PI/2 (alias) interpreter.eval("ACOS(0)"); // PI/2 (alias) interpreter.eval("ATAN(1)"); // PI/4 (alias) // Aggregation functions interpreter.eval("MAX(3, 8, 5)"); // 8.0 interpreter.eval("MIN(3, 8, 5)"); // 3.0 interpreter.eval("SUM(3, 8, 5)"); // 16.0 // Statistical functions (random) interpreter.eval("RANDOM(0, 100)"); // Random in [0, 100] interpreter.eval("NORMAL(50, 10)"); // Normal distribution (mean=50, stddev=10) interpreter.eval("POISSON(5)"); // Poisson distribution (lambda=5) interpreter.eval("EXPRND(2)"); // Exponential distribution (lambda=2) interpreter.eval("LOGNORMAL(0, 1)"); // Log-normal distribution // Time functions (available during simulation) // DT - time step size // TIME - current simulation time // STARTTIME - simulation start time // STOPTIME - simulation stop time ``` -------------------------------- ### Export Simulation Results to CSV in Java Source: https://context7.com/greendelta/olca-sd/llms.txt Shows how to use the CsvWriter utility to export simulation results to a CSV file. This process involves loading an XMILE model, creating a Simulator instance, and then running the CsvWriter with the simulator and an output file. The generated CSV includes automatic column headers for all variables, including elements from tensors, and subsequent rows represent simulation iterations. ```java import java.io.File; import org.openlca.sd.eqn.Simulator; import org.openlca.sd.util.CsvWriter; import org.openlca.sd.xmile.Xmile; // Load model and create simulator Xmile xmile = Xmile.readFrom(new File("examples/test-model.stmx")).orElseThrow(); Simulator sim = Simulator.of(xmile).orElseThrow(); // Export to CSV File outputFile = new File("simulation-results.csv"); CsvWriter.of(sim, outputFile).run().orElseThrow(); System.out.println("Results exported to: " + outputFile.getAbsolutePath()); // CSV output format: // "Iteration","Time","Population","birth_rate","death_rate",... // 0,1.0,100.0,0.05,0.02,... // 1,1.25,101.5,0.05,0.02,... // 2,1.5,103.1,0.05,0.02,... ``` -------------------------------- ### Define XMILE Variable Types in Java Source: https://context7.com/greendelta/olca-sd/llms.txt This Java code demonstrates how to define and use the three main variable types in the library: Auxiliaries, Rates/Flows, and Stocks. These types correspond to XMILE model elements and can be configured with IDs, initial values, units, and relationships to other variables. The snippet also shows how to access variable properties and create fresh copies for new simulations. ```java import org.openlca.sd.eqn.*; import org.openlca.sd.eqn.cells.Cell; import java.util.List; // Auxiliary variable - computed each time step var growthRate = new Var.Aux( Id.of("growth_rate"), Cell.of(0.05), "1/year" ); // Rate/Flow variable - rate of change var birthFlow = new Var.Rate( Id.of("births"), Cell.of(0), // Initial value, computed from equation "beings/year" ); // Stock variable - accumulates over time var population = new Var.Stock( Id.of("population"), Cell.of(1000), // Initial value "beings", // Units List.of(Id.of("births")), // Inflows List.of(Id.of("deaths")) // Outflows ); // Access variable properties System.out.println("Name: " + population.name().label()); System.out.println("Unit: " + population.unit()); System.out.println("Current value: " + population.value().asNum()); // Variables track history during simulation System.out.println("Value history: " + population.values().size() + " steps"); // Create fresh copy (without history) for new simulation run var freshPop = population.freshCopy(); ``` -------------------------------- ### Generate SVG Diagram from XMILE Model Source: https://context7.com/greendelta/olca-sd/llms.txt This snippet demonstrates how to load an XMILE model, generate an SVG document representing the model's diagram, and save it as an XML string to a file. It utilizes the `Svg` class for SVG generation and `Xmile` for model loading. ```java import java.io.File; import java.nio.file.Files; import org.openlca.sd.xmile.Xmile; import org.openlca.sd.xmile.svg.Svg; // Load model Xmile xmile = Xmile.readFrom(new File("examples/population-model.stmx")).orElseThrow(); // Generate SVG document var svgDoc = Svg.docOf(xmile); // Convert to XML string String svgXml = Svg.xmlOf(xmile).orElseThrow(); // Save to file Files.writeString(new File("model-diagram.svg").toPath(), svgXml); System.out.println("SVG diagram generated"); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.