Introduction
With the openLCA API, you can automate workflows, read and write data, run calculations, analyse results, or even build your own user interface on top of openLCA. To enable this, openLCA exposes an inter-process communication (IPC) protocol that works with any programming language (including Python, JavaScript, .NET, Go, or Java1) and can be served either directly by the desktop application or by a server running only the openLCA back-end.
This documentation covers the available API methods in detail with many
examples. You can modify and try the interactive JavaScript examples right
inside this manual. Simply start the IPC server in openLCA (see below) and click
the Run button beneath an example. Your browser may prompt you for permission
to access the local openLCA server, but everything runs locally on your
machine, no data is sent to external servers.
// list the impact assessment methods of the active database
const methods = await call("data/get/descriptors", { "@type": "ImpactMethod" });
console.log(`found ${methods.length} impact assessment methods:`);
for (const method of methods) {
console.log(`- ${method.name}`);
}
The example uses the small helper function call for sending requests to the
IPC server, see running the JavaScript
examples below.
Starting an IPC server
In the openLCA desktop application, you can start an IPC server for the
currently active database from the tools menu: Tools > Developer tools > IPC Server. This brings up the following dialog where you can start and stop the
server:
For headless stand-alone servers, please see the appendix stand-alone servers.
Available protocols and client libraries
Typically, you will use a client library such as olca-ipc.py to call the API. Under the hood, openLCA supports three protocols built on the same service back-end and the openLCA Schema as data format:
-
JSON-RPC over HTTP (default IPC server) – lightweight and easy to use anywhere, including directly in a browser.
-
gRPC – great when you already use gRPC or want generated client code from the service definitions.
-
REST (via openLCA web-services) – JSON over HTTP, well suited for web applications.
The table below lists some available client libraries and demo projects by language and protocol:
| Language | Type | Protocol | |
|---|---|---|---|
| olca-ipc.py | Python | Client library | JSON-RPC, REST |
| olca-ipc.ts | JavaScript/TypeScript | Client library | JSON-RPC, REST |
| ProtoLCA-Demo | C# | Demo | gRPC |
| protolca-js-example | JavaScript/Node | Client library | gRPC |
| olcarpc.py | Python | Client library | gRPC |
Running the JavaScript examples
The JavaScript examples in this documentation can be edited and executed
directly in the browser with the Run button below an example (or with
Ctrl+Enter in the example). For this, an IPC server needs to run on port
8080 (in openLCA: Tools > Developer tools > IPC Server).
Some examples use the following helper function call for the JSON-RPC calls.
It is available in the runnable examples of this documentation; when you use
such an example outside of this documentation, you need to add this function:
async function call(method, params) {
const resp = await fetch("http://localhost:8080", {
method: "POST",
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
});
const r = await resp.json();
if (r.error) {
throw new Error(r.error.message);
}
return r.result;
}
-
Because openLCA runs on the JVM, languages like Java, Kotlin, Scala, or Clojure can use the headless openLCA Java API directly as standard libraries instead of going through an IPC server (this is also how openLCA’s built-in Python (powered by Jython) editor accesses openLCA). ↩
Working with data
All API methods exchange data using the openLCA Schema (parameter and return types throughout this documentation link directly to its reference). Two core schema concepts shape how you work with data in the API:
-
Root vs. nested entities: Stand-alone data sets such as processes or flows are root entities. Other objects, such as a process’s inputs and outputs, only exist inside a root entity.
-
Lightweight references (Ref): Root entities are never embedded inside each other. Instead, they link via a
Refobject that carries only the target’s@type,@id, and optional metadata (such asname). For example, an Exchange holds aRefto itsFlowrather than the full flow data set.Refobjects are also returned as lightweight descriptors, for instance in search results, when loading the full data set is unnecessary.
Most CRUD methods work identically across all root entity types and take the target entity’s type, ID, or name as parameters. In JSON-RPC, these are passed as fields in a parameter object; in REST, they are part of the URL path (see the REST API reference for the path segments of all types)
| Parameter | JSON-RPC | REST path segment |
|---|---|---|
| type | "@type": root entity type, e.g. "Process" | {type}, e.g. processes |
| ID | "@id": ID of the data set | {id} |
| name | name: name of the data set | {name} (URL-encoded) |
Get descriptors
Returns a list of lightweight descriptors (Ref) for all data sets of a given
type. This is useful for browsing the contents of a database without loading
full objects. Each descriptor includes only basic metadata (such as @id,
name, and category) and can be passed directly as a reference in other API
calls, such as specifying a target process in a calculation setup.
| JSON-RPC | REST | Parameters | Returns |
|---|---|---|---|
data/get/descriptors | GET data/{type} | @type | List[Ref] |
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
// You can change the type here, e.g. to Flow; but note that
// this will try to print all flows of the database below (!).
// So better test this with types like UnitGroup, ImpactMethod,
// ImpactCategory, ...
const descriptors = await call("data/get/descriptors", {
"@type": "FlowProperty"
});
console.log(descriptors);
Python IPC
import olca_ipc as ipc
import olca_schema as o
client = ipc.Client()
refs = client.get_descriptors(o.FlowProperty)
for ref in refs:
print(ref.name)
# Area
# Area*time
# Duration
# Energy
Get a full data set by ID
This method returns the full data set of a given type and ID.
| JSON-RPC | REST | Parameters | Returns |
|---|---|---|---|
data/get | GET data/{type}/{id} | @type, @id | E > RootEntity |
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
// This should return the flow property "Mass" when you are connected to a
// database with openLCA reference data. Try to change the type to Process with
// an ID from your database for example.
const v = await call("data/get", {
"@type": "FlowProperty",
"@id": "93a60a56-a3c8-11da-a746-0800200b9a66"
});
console.log(v);
Python IPC
import olca_ipc as ipc
import olca_schema as o
client = ipc.Client()
process = client.get(o.Process, "eacc4872-6f4e-4ff1-946e-c1bddeda24be")
print(process)
# Process(
# id='eacc4872-6f4e-4ff1-946e-c1bddeda24be',
# exchanges=[Exchange(amount=1.0, flow=Ref(id='b254bbdf- ...
Curl
endpoint="http://localhost:8080"
process_id="eacc4872-6f4e-4ff1-946e-c1bddeda24be"
curl "$endpoint/data/process/$process_id"
# { "@type":"Process",
# "@id":"eacc4872-6f4e-4ff1-946e-c1bddeda24be",
# "name":"blast furnace gas, Recycled Content cut-off
Get a full data set by name
Returns the complete entity for a given root type and name. Because names in an openLCA database are not required to be unique, this method simply returns the first matching data set it finds.
| JSON-RPC | REST | Parameters | Returns |
|---|---|---|---|
data/get | GET data/{type}/name/{name} | @type, name | E > RootEntity |
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
// This will try to fetch the flow property Mass from your database.
const v = await call("data/get", {
"@type": "FlowProperty",
"name": "Mass",
});
console.log(v);
Python IPC
import olca_ipc as ipc
import olca_schema as o
client = ipc.Client()
mass = client.get(o.FlowProperty, name="Mass")
print(mass)
# FlowProperty(
# name='Mass',
# id='93a60a56-a3c8-11da-a746-0800200b9a66',
# unit_group=Ref(id='93a60a57-a4c8-11da-a746-0800200c9a66', ...
Get a single descriptor
Returns the descriptor (Ref) of a root entity for a given type and ID (or name).
| JSON-RPC | REST | Parameters | Returns |
|---|---|---|---|
data/get/descriptor | GET data/{type}/{id}/info | @type, @id | Ref |
data/get/descriptor | – | @type, name | Ref |
Examples
Python IPC
import olca_ipc as ipc
import olca_schema as o
client = ipc.Client()
mass_ref = client.get_descriptor(o.FlowProperty, name="Mass")
print(mass_ref)
# Ref(
# id='93a60a56-a3c8-11da-a746-0800200b9a66',
# category='Technical flow properties',
# name='Mass',
# ...
Get all data sets of a given type
Returns every complete entity of a given root type from the database. Depending on the protocol or server configuration, this method may be disabled and it is only practical for small collections (such as unit groups). Querying all processes or flows in a large database can overload the server; in most cases, you should fetch descriptors instead.
| JSON-RPC | REST | Parameters | Returns |
|---|---|---|---|
data/get/all | GET data/{type}/all | @type | List[E > RootEntity] |
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
// safe for small collections like UnitGroup; avoid Process or Flow in large
// databases
const v = await call("data/get/all", {
"@type": "UnitGroup"
});
console.log(v);
Python IPC
import olca_ipc as ipc
import olca_schema as o
client = ipc.Client()
for group in client.get_all(o.UnitGroup):
print(group.name)
# Units of area
# Units of energy
# Units of length
# Units of mass
# ...
Get the parameters of a data set
Returns the local parameters defined for the specified root entity:
-
Processes and impact categories: Returns a list of
Parameterobjects. -
Product systems: Returns a list of
ParameterRedefobjects (parameter redefinitions).
| JSON-RPC | REST | Parameters | Returns |
|---|---|---|---|
data/get/parameters | GET data/{type}/{id}/parameters | @type, @id | List[Parameter] or List[ParameterRedef] |
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
// You need to change the ID of the product system for which you want to get the
// possible parameters. You can also change the type to Process or
// ImpactCategory to get defined parameters of these types.
const v = await call("data/get/parameters", {
"@type": "ProductSystem",
"@id": "eb00c506-35d1-4046-8018-f70573d67e60",
});
console.log(v);
Python IPC
import olca_ipc as ipc
import olca_schema as o
client = ipc.Client()
params = client.get_parameters(
o.ProductSystem, "0db1eda6-a34e-4c82-b06b-19f27c92495a"
)
for p in params:
print(f"{p.name}: {p.value}")
# param1: 42
# param2: 21
# ...
Get the usage of a data set
Returns references to the data sets that use a specified data set. For example, for a flow, these are the processes that have the flow as an input or output, the impact categories with characterization factors for that flow, etc. For a process, these are the product systems that contain the process, and so on. If the data set is not used anywhere, an empty list is returned. This is the same search that openLCA runs before a data set is deleted.
| JSON-RPC | REST | Parameters | Returns |
|---|---|---|---|
data/get/usage | – | @type, @id | List[Ref] |
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
// Modify the type or ID and maybe do not take the ID of a flow that is used in
// thousands of processes...
const v = await call("data/get/usage", {
"@type": "Flow",
"@id": "e87f039d-d9ce-4242-ac18-c9284cc80f3d",
});
console.log(v);
Python IPC
import olca_ipc as ipc
import olca_schema as o
client = ipc.Client()
refs = client.get_usage(o.Flow, "7f6bb533-2d3c-43a6-ac60-6eef299d7c52")
for ref in refs:
print(f"{ref.ref_type}: {ref.name}")
# RefType.Process: steel production
# RefType.Process: car assembly
# RefType.ImpactCategory: Climate change
# ...
Get providers of technosphere flows
Returns the available process–flow provider pairs for technosphere flows (products and waste flows) that can be linked inside a product system:
-
Products: Providers are processes that generate the product as an output (linkable to product inputs of other processes).
-
Waste flows: Providers are waste treatment processes that accept the waste as an input (linkable to waste outputs of other processes).
| JSON-RPC | REST | Parameters | Returns |
|---|---|---|---|
data/get/providers | GET data/providers | List[TechFlow] |
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
// lists all possible providers of the database ... it can take a bit until this
// completes and it may returns a huge list depending on your database
const v = await call("data/get/providers");
console.log(v);
Python IPC
import olca_ipc as ipc
client = ipc.Client()
for p in client.get_providers()[:5]:
print(p)
# TechFlow(
# provider=Ref(id='71dab7ae-4d58-4f73-8449-5967c296bcde', ...
# flow=Ref(id='7f6bb533-2d3c-43a6-ac60-6eef299d7c52', ...
Get providers for a flow
Returns the provider processes (Ref) for a specific product or waste flow
(passed as a flow reference or ID):
-
Product flow: Returns processes that produce the product as an output.
-
Waste flow: Returns waste treatment processes that accept the waste as an input.
The returned providers can be linked to matching product inputs or waste outputs in a product system.
| JSON-RPC | REST | Parameters | Returns |
|---|---|---|---|
data/get/providers | GET data/providers/{id} | @id of the flow | List[TechFlow] |
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
// Change the ID of the flow for which you want to get the possible providers.
const v = await call("data/get/providers", {
"@type": "Flow",
"@id": "761145b7-3abe-48a5-a426-da5da6c36674",
});
console.log(v);
Python IPC
import olca_ipc as ipc
import olca_schema as o
client = ipc.Client()
providers = client.get_providers(
flow=o.Ref(id="7f6bb533-2d3c-43a6-ac60-6eef299d7c52")
)
for p in providers:
print(p)
# TechFlow(
# provider=Ref(id='71dab7ae-4d58-4f73-8449-5967c296bcde', ...
# flow=Ref(id='7f6bb533-2d3c-43a6-ac60-6eef299d7c52', ...
Insert or update a data set
Inserts or updates a provided data set in the database. This method is not available when a server runs in read-only mode.
| JSON-RPC | REST | Parameters | Returns |
|---|---|---|---|
data/put | PUT data/{type} | the data set, E > RootEntity | Ref |
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
// This will insert the given source data set into the database, if it already
// exists there, it will update it. (In openLCA, press F5 in the navigation to
// see it after the method call.)
const v = await call("data/put", {
"@type": "Source",
"@id": "91bbc461-4ce1-4f83-b95d-de0909575174",
"name": "Inter-process communication with openLCA",
// ...
});
console.log(v);
Python IPC
import olca_ipc as ipc
import olca_schema as o
client = ipc.Client()
ref = client.put(o.Source(name="Inter-process communication with openLCA"))
print(ref)
# Ref(
# id="16cba9b2-2987-4735-9f3e-96fedf8449dd",
# name="Inter-process communication with openLCA",
# ...
Create a product system
This method creates a product system for a given process. It recursively links the processes of that system according to the given linking configuration. The process must have a quantitative reference. The method returns a reference to the new product system, which is stored in the database.
| JSON-RPC | REST | Parameters | Returns |
|---|---|---|---|
data/create/system | POST data/create-system | process: Ref[Process], config: LinkingConfig (optional) | Ref[ProductSystem] |
The linking configuration defines how the processes are linked:
providerLinking: whether default providers of exchanges should be ignored (IGNORE_DEFAULTS), preferred (PREFER_DEFAULTS), or exclusively used (ONLY_DEFAULTS).preferUnitProcesses: if there are multiple possible providers of a product, unit processes are preferred over system processes when this istrue.cutoff: an optional cutoff value; product inputs or waste outputs with a demand below this value, relative to one unit of the reference product of the system, are not linked further.
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
// This example tries to find a process with this name and builds a product
// system from it. Note that it can take a bit until this method completes.
const processName = "grape production | grape | Cutoff, U";
const processes = await call("data/get/descriptors", { "@type": "Process" });
const process = processes.find((d) => d.name === processName);
if (!process) {
throw new Error(`Could not find process: ${processName}`);
}
const system = await call("data/create/system", {
process: { "@type": "Process", "@id": process["@id"] },
config: {
preferUnitProcesses: true,
providerLinking: "PREFER_DEFAULTS",
},
});
console.log(`created product system ${system.name}, id=${system["@id"]}`);
Python IPC
import sys
import olca_ipc as ipc
import olca_schema as o
client = ipc.Client()
# this example tries to find a process with this name
# and builds a product system from it
process_name = "grape production | grape | Cutoff, U"
process_ref = client.find(o.Process, process_name)
if process_ref is None:
print(f"Could not find process: {process_name}")
sys.exit(1)
config = o.LinkingConfig(
prefer_unit_processes=True,
provider_linking=o.ProviderLinking.PREFER_DEFAULTS,
)
system_ref = client.create_product_system(process_ref, config)
if system_ref is None:
print("Failed to create the product system")
sys.exit(1)
print(f"created product system {system_ref.name}, id={system_ref.id}")
Delete a data set
Deletes the specified root entity from the database. This method is unavailable when the server runs in read-only mode.
Warning: This method does not check whether the entity is still referenced elsewhere. Deleting a data set that is in use can corrupt the database. Always check its usages first.
| JSON-RPC | REST | Parameters | Returns |
|---|---|---|---|
data/delete | DELETE data/{type}/{id} | @type, @id | Ref |
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
// This would delete the source that we created in the put-example ... so
// nothing bad should happen
const v = await call("data/delete", {
"@type": "Source",
"@id": "91bbc461-4ce1-4f83-b95d-de0909575174",
});
console.log(v);
Python IPC
import olca_ipc as ipc
import olca_schema as o
client = ipc.Client()
ref = client.delete(
o.Ref(ref_type=o.RefType.Source, id="16cba9b2-2987-4735-9f3e-96fedf8449dd")
)
print(ref)
# Ref(
# id="16cba9b2-2987-4735-9f3e-96fedf8449dd",
# name="Inter-process communication with openLCA",
# ...
Calculation and results
When starting a calculation, it is first scheduled in a calculation queue. This
is because multiple calculations could be started at the same time and
calculations may need to wait for other calculations first to be finished. Thus,
a calculation directly returns a
ResultState
object with a unique identifier. With this identifier, the state of the
calculation can be retrieved from the server. It is then also the ID of the
corresponding result when the calculation is finished. When a result is not
needed anymore, the dispose method should be called so that the allocated
resources of the result can be released.
The idea of the result interface is not to provide some ready-to-use charts and tables but to provide all possible building blocks with which such higher level result views can be created (charts, tables, upstream trees, Sankey diagrams). Thus, the result interface has many methods that often look quite similar but they have their purpose for efficiently creating higher level result views.
Result elements
Depending on the calculation setup and the calculated model, results can be retrieved for different elements, these are:
- Technosphere flows,
tech-flows: the product and waste flows of the product system with their corresponding providers. - Intervention flows,
envi-flows: typically elementary flows but also unconnected product or waste inputs or outputs of the processes in the system. These flows cross the boundary to the environment of the system and form the inventory result of the system. In case of a regionalized calculation, an intervention flow is a pair of flow and location. - Impact categories,
impact-categories: the impact categories of the impact assessment method selected in the calculation setup. - Costs: life cycle costs, if the calculation setup includes costs.
Technosphere flows are always present. All other result elements are only available if the calculated model provides these elements and/or if the corresponding options are set in the calculation setup.
Result types
The following chapters are organized by result type. Each chapter describes the methods of a result type for the different result elements. The table below gives an overview of which result types are available for which elements:
| Result type | Technosphere flows | Intervention flows | Impact categories | Costs |
|---|---|---|---|---|
| Result elements | ✓ | ✓ | ✓ | |
| Total results | ✓ | ✓ | ✓ | |
| Technosphere requirements | ✓ | |||
| Direct contributions | ✓ | ✓ | ✓ | |
| Intensities | ✓ | ✓ | ✓ | |
| Total process results | ✓ | ✓ | ✓ | |
| Impact factors | ✓ | ✓ | ||
| Upstream trees | ✓ | ✓ | ✓ | |
| Grouped results | ✓ | ✓ | ✓ | |
| Tag results | ✓ | ✓ | ✓ |
Method names and parameters
Each result method has a name, like flow-contributions-of, from which the
method names of the different protocols and client libraries are derived:
| Protocol | Method name | Example |
|---|---|---|
| JSON-RPC | result/<name> | result/flow-contributions-of |
| REST | GET result/{result-id}/<name>/{params} | GET result/{result-id}/flow-contributions-of/{envi-flow} |
| Python IPC | Result.get_<name> in snake case | result.get_flow_contributions_of(envi_flow) |
| olca-ipc.ts | Result.get<Name> in camel case | result.getFlowContributionsOf(enviFlow) |
All methods take the ID of the result as parameter; the client libraries pass it automatically. Depending on the method, the result element for which a result should be returned is passed as additional parameter. Via JSON-RPC, the parameters are passed as an object with the following fields; via REST, they are passed as path segments in the order in which they are listed in the method tables:
| Parameter | JSON-RPC | REST path segment |
|---|---|---|
| result ID | "@id": "<result-id>" | {result-id} |
| technosphere flow | techFlow: { provider: { "@id": ... }, flow: { "@id": ... } } | {tech-flow}: <provider-id>::<flow-id> |
| intervention flow | enviFlow: { flow: { "@id": ... }, location: { "@id": ... } } | {envi-flow}: <flow-id> or <flow-id>::<location-id> |
| impact category | impactCategory: { "@id": ... } | {impact-category}: <impact-category-id> |
The location of an intervention flow is only required in regionalized results. There are a few exceptions from these rules:
calculateandsimulateare methods of the client:POST result/calculateandPOST result/simulatewith the calculation setup as request body,Client.calculateandClient.simulatein Python.stateisget_statein Python.disposeandsimulate/nextarePOSTrequests in REST anddisposeandsimulate_nextin Python.- The normalized and weighted results are
total-impacts/normalizedandtotal-impacts/weightedin JSON-RPC and REST butget_normalized_impactsandget_weighted_impactsin Python (getNormalizedImpactsandgetWeightedImpactsin olca-ipc.ts). - The upstream tree methods are
POSTrequests in REST with the path in the request body (see upstream trees). sankeyis aPOSTrequest in REST with the Sankey request as body; in JSON-RPC, the Sankey request is passed in the fieldconfig. In Python, the method isResult.get_sankey_graph.- The totality factors, the grouped results, and the tag results are only
available via JSON-RPC. The total cost values of all processes
(
total-cost-values) are only available via REST.
A complete list of the REST endpoints is given in the REST API reference.
The JavaScript examples call the JSON-RPC methods with the call
helper.
Mathematical relations
Where possible, a short formula for calculating a respective result is provided in the following documentation of the respective functions. These formulas are based on standard matrix algebra for LCA computations. However, this does not mean that a respective result is calculated by exactly using this formula. The following symbols are used:
| Symbol | Meaning |
|---|---|
| \(A\) | technology matrix, \(n \times n\), indexed by the technosphere flows |
| \(B\) | intervention matrix, \(m \times n\) |
| \(C\) | matrix with characterisation factors, \(l \times m\) |
| \(q\) | vector with the net-costs of the processes |
| \(f\) | final demand vector |
| \(s\) | scaling vector, \(A s = f\) |
| \(t\) | total requirements of the technosphere flows |
| \(tf\) | totality factors |
| \(g = B s\) | inventory result |
| \(h = C g\) | impact assessment result |
| \(M = B A^{-1}\) | intensity matrix of the intervention flows |
| \(N = C M\) | intensity matrix of the impact categories |
Calculate results
This method schedules a new calculation for a given setup. It directly returns
a state object that contains the result ID (field @id). With this ID
the result state can be queried.
| Method | Parameters | Returns |
|---|---|---|
calculate | CalculationSetup | ResultState |
This is a method of the client and not of a result: via REST, it is
POST result/calculate with the calculation setup as request body; in Python,
it is Client.calculate.
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const v = await call("result/calculate", {
target: {
"@type": "ProductSystem",
"@id": "0db1eda6-a34e-4c82-b06b-19f27c92495a"
},
impactMethod: {
"@id": "b4571628-4b7b-3e4f-81b1-9a8cca6cb3f8",
},
nwSet: {
"@id": "867fe119-0b5c-38a0-a3e6-1d845ffaedd5",
},
withCosts: true,
amount: 1.0
});
console.log(v);
// {
// "@id": "e316a369-bf5b-4c25-a61f-3492cfca9535",
// isReady: false,
// isScheduled: true,
// time: 1671187585187
// }
Python IPC
import olca_ipc as ipc
import olca_schema as o
# create a calculation setup
setup = o.CalculationSetup(
target=o.Ref(
ref_type=o.RefType.ProductSystem,
id="0db1eda6-a34e-4c82-b06b-19f27c92495a",
),
impact_method=o.Ref(id="b4571628-4b7b-3e4f-81b1-9a8cca6cb3f8"),
nw_set=o.Ref(id="867fe119-0b5c-38a0-a3e6-1d845ffaedd5"),
)
# run a calculation
client = ipc.Client()
result: ipc.Result = client.calculate(setup)
Get state
This method returns the result state of a calculation. When a calculation is started, it is
scheduled in a calculation queue first. The calculation directly returns a result state with
a unique ID (field @id) of the result. Only when the state of a result is ready, calculation
results can be retrieved.
| Method | Parameters | Returns |
|---|---|---|
state | ResultState |
In Python, the method is Result.get_state. There is also the method
Result.wait_until_ready which polls the state until the result is ready.
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const v = await call("result/state", {
"@id": "e316a369-bf5b-4c25-a61f-3492cfca9535",
});
console.log(v);
// {
// "@id": "e316a369-bf5b-4c25-a61f-3492cfca9535",
// isReady: true,
// isScheduled: false,
// time: 1671187586993
// }
Python IPC
state = result.get_state()
if state.error:
print(f"calculation failed: {state.error}")
exit(-1)
# actively waiting for a result
import time
while not result.get_state().is_ready:
time.sleep(1)
print("waiting ...")
# or better do this:
state = result.wait_until_ready()
print(f"result id: {state.id}")
Dispose result
This method should be always called when a result is not needed anymore. It disposes the result and releases allocated resources of that result.
| Method | Parameters | Returns |
|---|---|---|
dispose | ResultState |
Via REST, it is a POST request: POST result/{result-id}/dispose.
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const v = await call("result/dispose", {
"@id": "e316a369-bf5b-4c25-a61f-3492cfca9535",
});
console.log(v);
// {
// "@id": "e316a369-bf5b-4c25-a61f-3492cfca9535"
// }
Python IPC
# it is important to dispose a result when it is not needed anymore
result.dispose()
Monte Carlo Simulations
Running a Monte Carlo Simulation is similar to a normal calculation. You first
call the simulate method with a calculation setup. This schedules a first
simulation run. When the calculation is ready, the result can be queried like
any other result. For each subsequent iteration you call the next method on
that result which schedules a new iteration, that again returns a result that
can be queried, and so on. Old iteration results are disposed automatically when
a new iteration is started but you should dispose the last result when it is not
needed anymore.
| Method | Parameters | Returns |
|---|---|---|
simulate | CalculationSetup | ResultState |
simulate/next | ResultState |
Like calculate, simulate is a method of the client: via REST, it is
POST result/simulate with the calculation setup as request body; in Python, it
is Client.simulate. simulate/next is called on the result:
POST result/{result-id}/simulate/next via REST and Result.simulate_next
in Python.
Python IPC
import random as rand
import statistics as stats
import olca_ipc as ipc
import olca_schema as o
client = ipc.Client()
# schedule a first iteration
print("run iteration 1")
result = client.simulate(
o.CalculationSetup(
target=o.Ref(
ref_type=o.RefType.ProductSystem,
id="7d1cbce0-b5b3-47ba-95b5-014ab3c7f569",
),
impact_method=o.Ref(id="99b9d86b-ec6f-4610-ba9f-68ebfe5691dd"),
)
)
result.wait_until_ready()
# get the result for some indicator from the first iteration
indicator = rand.choice(result.get_impact_categories())
val = lambda: result.get_total_impact_value_of(indicator).amount
xs: list[float] = [val()]
# collect the values from 99 more iterations
for i in range(0, 99):
print(f"run iteration {i+2}")
result.simulate_next()
result.wait_until_ready()
xs.append(val())
result.dispose()
# plot the results in a simple histogram
bucket_count = 15
quantiles = stats.quantiles(xs, n=bucket_count + 1, method="inclusive")
buckets = [0] * bucket_count
for x in xs:
bucket = 0
for i in range(1, bucket_count):
if x <= quantiles[i]:
bucket += 1
buckets[bucket] += 1
for i in buckets:
print(f"|{'#' * i}")
# ...
# run iteration 98
# run iteration 99
# run iteration 100
#
# |#######
# |######
# |######
# |######
# |######
# |#######
# |######
# |######
# |######
# |######
# |#######
# |######
# |######
# |######
# |#############
Result elements
These methods return the elements of a result for which result values can be retrieved: the technosphere flows, the intervention flows, and the impact categories. The elements returned by these methods can be directly used as parameters in other result methods (see method names and parameters).
| Method | Returns |
|---|---|
tech-flows | List[TechFlow] |
envi-flows | List[EnviFlow] |
impact-categories | List[Ref[ImpactCategory]] |
Technosphere flows
The method tech-flows returns the \(n\) technosphere flows of a result.
These are the flows by which the processes of the calculated system are linked.
Each technosphere flow is a pair of a product or waste flow and a provider where
the provider is typically a process but can also be a product system (a
sub-system) or even another result. The technology matrix \(A\) is
symmetrically indexed by these technosphere flows:
$$ A \in \mathbb{R}^{n \times n} $$
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const v = await call("result/tech-flows", {
"@id": "77ccaffa-9d79-4f38-8da5-4413469b8a7b",
});
console.log(v);
// [
// {
// provider: {
// "@type": "Process",
// "@id": "7c619276-7b15-472a-b261-0110d461755a",
// name: "market for natural gas, high pressure",
// processType: "LCI_RESULT",
// flowType: "PRODUCT_FLOW"
// },
// flow: {
// "@type": "Flow",
// "@id": "a9007f10-7e39-4d50-8f4a-d6d03ce3d673",
// name: "natural gas, high pressure",
Python IPC
tech_flows = result.get_tech_flows()
print(
pd.DataFrame(
[
(tf.provider.name, tf.flow.name, tf.flow.ref_unit)
for tf in tech_flows
],
columns=["Provider", "Flow", "Unit"],
).head()
)
# Provider Flow Unit
# 0 Fresh wheat, corn, rice, and oth... Fresh wheat, corn, ric... USD
# 1 Synthetic dyes and pigments... Synthetic dyes an... USD
# 2 Cardboard containers... Cardboard ... USD
# 3 Synthetic rubber and artificial ... Synthetic rubber and a... USD
# 4 Packaged poultry... Packag... USD
Intervention flows
The method envi-flows returns the \(m\) intervention flows of a result.
These are the flows that cross the boundary with the environment of the
calculated system (this is why the short name is EnviFlow in the API). In
regionalized calculations these flows can be pairs of flows and locations, the
same flow can occur in different locations (with possibly different
characterisation factors). The rows of the intervention matrix are indexed by
these \(m\) intervention flows (and the columns by the \(n\) technosphere
flows):
$$ B \in \mathbb{R}^{m \times n} $$
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const v = await call("result/envi-flows", {
"@id": "66dcc7d0-ce47-46bf-b77a-ada4b4c95169",
});
console.log(v);
// [
// {
// flow: {
// "@type": "Flow",
// "@id": "60ea7a31-8f27-46af-bfe5-66417f00088b",
// name: "Barite",
// category: "Elementary flows/Emission to water/ocean",
// flowType: "ELEMENTARY_FLOW",
// refUnit: "kg"
// },
// isInput: false
// },
// {
// flow: {
// "@type": "Flow",
Python IPC
envi_flows = result.get_envi_flows()
print(
pd.DataFrame(
[
(ef.is_input, ef.flow.name, ef.flow.category, ef.flow.ref_unit)
for ef in envi_flows
],
columns=["Is input?", "Flow", "Category", "Unit"],
).head()
)
# Is input? Flow Category Unit
# 0 False 1,4-dioxane Elementary Flows/air/unspecified kg
# 1 False oryzalin Elementary Flows/soil/groundwater kg
# 2 False Sethoxydim Elementary Flows/soil/groundwater kg
# 3 False Chlorpyrifos Elementary Flows/air/low population density kg
# 4 False lead Elementary Flows/air/unspecified kg
Impact categories
The method impact-categories returns the \(l\) impact categories of a
result. The rows of the characterisation matrix \(C\) are indexed by these
impact categories and the columns by the \(m\) intervention flows of the
system. \(C\) contains the respective characterisation factors of the
intervention flows.
$$ C \in \mathbb{R}^{l \times m} $$
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const v = await call("result/impact-categories", {
"@id": "4780f66c-0b77-49ca-9226-c7ce4447ea2d",
});
console.log(v);
// [
// {
// "@type": "ImpactCategory",
// "@id": "2dddb0a4-2f97-3fef-a4e6-708f0b4c2554",
// name: "Human toxicity, cancer - inorganics",
// category: "EF 3.0 Method (adapted)",
// refUnit: "CTUh"
// },
// {
// "@type": "ImpactCategory",
// "@id": "248a3f3f-933e-3c45-a799-fad9f956e03c",
// name: "Photochemical ozone formation",
// category: "EF 3.0 Method (adapted)",
// refUnit: "kg NMVOC eq"
// },
Python IPC
impact_categories = result.get_impact_categories()
print(
pd.DataFrame(
[(i.name, i.ref_unit) for i in impact_categories],
columns=["Impact category", "Unit"],
)
)
# Impact category Unit
# 0 OZON kg CFC11-eq
# 1 EUTR kg N eq
# 2 SMOG kg O3 eq
# 3 HNC CTUh
# 4 ETOX CTUe
# 5 HC CTUh
# 6 HRSP kg PM2.5 eq
# 7 GCC kg CO2 eq
# 8 HTOX CTUh
# 9 ACID kg SO2-eq
Total results
These methods return the overall results of the calculated product system related to its final demand: the inventory result, the impact assessment result (also normalized and weighted), and the total life cycle costs.
| Method | Parameters | Returns | Formula |
|---|---|---|---|
total-flows | List[EnviFlowValue] | \(g\) | |
total-flow-value-of | enviFlow | EnviFlowValue | \(g_i\) |
total-impacts | List[ImpactValue] | \(h\) | |
total-impact-value-of | impactCategory | ImpactValue | \(h_k\) |
total-impacts/normalized¹ | List[ImpactValue] | \(diag(nv)^{-1} h\) | |
total-impacts/weighted¹ | List[ImpactValue] | \(diag(w) diag(nv)^{-1} h\) | |
total-costs | CostValue | \(q^T s\) |
¹ Python: get_normalized_impacts and get_weighted_impacts; olca-ipc.ts:
getNormalizedImpacts and getWeightedImpacts
Inventory result
The inventory result \(g\) of the calculated product system is the amount \(g_i\) of each intervention flow \(i\) that crosses the boundary to the environment related to the final demand of the product system. It can be calculated by multiplying the intervention matrix \(B\) with the scaling vector \(s\):
$$ g = B s $$
The method total-flows returns the complete inventory result and
total-flow-value-of the result \(g_i\) of a single flow \(i\).
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const v = await call("result/total-flows", {
"@id": "66dcc7d0-ce47-46bf-b77a-ada4b4c95169",
});
console.log(v);
// [
// { enviFlow: { flow: [Object], isInput: false }, amount: 5.316452367058923e-12 },
// { enviFlow: { flow: [Object], isInput: false }, amount: 0.0000020503441278781976 },
// { enviFlow: { flow: [Object], isInput: false }, amount: 2.2757672132330865e-10 },
// { enviFlow: { flow: [Object], isInput: false }, amount: 5.003477809709274e-7 },
// { enviFlow: { flow: [Object], isInput: true }, amount: 0.0013196599415652454 },
Impact assessment result
The impact assessment result \(h\) of the calculated product system can be calculated by multiplying the characterisation matrix \(C\) with the inventory result \(g\):
$$ h = C g $$
The method total-impacts returns the complete impact assessment result and
total-impact-value-of the result \(h_k\) of a single impact category
\(k\).
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const v = await call("result/total-impacts", {
"@id": "86b36d3b-1dba-4804-bd61-dc5bcaf7c86c",
});
console.log(v);
// [
// {
// impactCategory: {
// "@type": "ImpactCategory",
// "@id": "3bc1c67f-d3e3-3891-9fea-4512107d88ef",
// name: "Climate change",
// category: "EF 3.0 Method (adapted)",
// refUnit: "kg CO2 eq"
// },
// amount: 0.6387478227404646
// },
// ...
Normalized results
If a normalization and weighting set was selected in the calculation setup, the normalized impact assessment result can be retrieved. Mathematically, it is the impact assessment result \(h\) divided by the respective normalization values \(nv\):
$$ diag(nv)^{-1} h $$
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const v = await call("result/total-impacts/normalized", {
"@id": "15432ac4-7752-4066-a62d-31270f6a0dbd",
});
console.log(v);
// [
// {
// impactCategory: {
// "@type": "ImpactCategory",
// "@id": "248a3f3f-933e-3c45-a799-fad9f956e03c",
// name: "Photochemical ozone formation",
// category: "EF 3.0 Method (adapted)",
// refUnit: "kg NMVOC eq"
// },
// amount: 0.0010466725460636012
// },
Python IPC
import olca_ipc as ipc
import olca_schema as o
client = ipc.Client()
# get the impact assessment method
method = client.get(o.ImpactMethod, "bf665139-3159-45ef-9b00-f439251d2b5b")
# select the first normalisation & weighting set for the example;
# make sure the method has nw-sets
nwset = method.nw_sets[0]
# run a calculation
result = client.calculate(o.CalculationSetup(
target=o.Ref(
id="7d1cbce0-b5b3-47ba-95b5-014ab3c7f569",
ref_type=o.RefType.ProductSystem,
),
impact_method=method.to_ref(),
nw_set=nwset.to_ref(),
))
result.wait_until_ready()
# print the normalized results
for nr in result.get_normalized_impacts():
print(f"{nr.impact_category.name} :: {nr.amount}")
result.dispose()
Weighted results
If a normalization and weighting set was selected in the calculation setup, the weighted impact assessment result can be retrieved. Mathematically, it is the impact assessment result \(h\) divided by the respective normalization values \(nv\) and multiplied with the respective weighting factors \(w\):
$$ diag(w) \ diag(nv)^{-1} h $$
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const v = await call("result/total-impacts/weighted", {
"@id": "546a1d13-3cae-4c9b-82d0-a18204b0c6eb",
});
console.log(v);
// [
// {
// impactCategory: {
// "@type": "ImpactCategory",
// "@id": "3bc1c67f-d3e3-3891-9fea-4512107d88ef",
// name: "Climate change",
// category: "EF 3.0 Method (adapted)",
// refUnit: "kg CO2 eq"
// },
// amount: 2.038186234380937
// },
// ...
Python IPC
import olca_ipc as ipc
import olca_schema as o
client = ipc.Client()
# get the impact assessment method
method = client.get(o.ImpactMethod, "bf665139-3159-45ef-9b00-f439251d2b5b")
# select the first normalisation & weighting set for the example;
# make sure the method has nw-sets
nwset = method.nw_sets[0]
# run a calculation
result = client.calculate(o.CalculationSetup(
target=o.Ref(
id="7d1cbce0-b5b3-47ba-95b5-014ab3c7f569",
ref_type=o.RefType.ProductSystem,
),
impact_method=method.to_ref(),
nw_set=nwset.to_ref(),
))
result.wait_until_ready()
# print the weighted results
for wr in result.get_weighted_impacts():
print(f"{wr.impact_category.name} :: {wr.amount} {nwset.weighted_score_unit}")
result.dispose()
Costs
If costs were included in the calculation setup, the method total-costs
returns the total life cycle costing (LCC) result of the calculated product
system. It is the vector \(q\) with the net-costs of the processes multiplied
with the scaling vector \(s\). The returned value contains the reference
currency of the database.
$$ q^T s $$
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const o = await import("https://cdn.jsdelivr.net/npm/olca-ipc@2.6.2/+esm");
const client = o.IpcClient.on(8080);
const result = await client.calculate(o.CalculationSetup.of({
target: o.Ref.of({
refType: o.RefType.ProductSystem,
id: "99ad5640-b73c-4387-b03c-ee0a9c6a7d6b",
}),
withCosts: true,
}));
await result.untilReady();
const totals = await result.getTotalCosts();
const code = totals.currency?.refUnit;
console.log(`total costs: ${totals.amount} ${code}`);
// total costs: 60 USD
result.dispose();
Technosphere requirements
These methods return results for the technosphere flows of the calculated product system: the final demand, the scaling factors, the total requirements, the totality factors, and the scaled or unscaled inputs and outputs of the technosphere flows of a single process.
| Method | Parameters | Returns | Formula |
|---|---|---|---|
demand | TechFlowValue | \(f\) | |
scaling-factors | List[TechFlowValue] | \(s\) | |
total-requirements | List[TechFlowValue] | \(t\) | |
total-requirements-of | techFlow | TechFlowValue | \(t_j\) |
totality-factors¹ | List[TechFlowValue] | \(tf\) | |
totality-factor-of¹ | techFlow | TechFlowValue | \(tf_j\) |
scaled-tech-flows-of | techFlow | List[TechFlowValue] | \(s_j A[:, j]\) |
unscaled-tech-flows-of | techFlow | List[TechFlowValue] | \(A[:, j]\) |
¹ only available via JSON-RPC
Final demand
In openLCA, a product system is calculated for a single demand value for a technosphere flow: a product output or waste input of the system. It is the quantitative reference of the system. In the general case, a system can have multiple demand values organized in a final demand vector \(f\) which is indexed in the same way as the technology matrix (note that a multi-demand system can be transformed into a single demand system by simply adding an additional process column to the technology matrix). In the result calculation, the technology matrix \(A\) is scaled by a scaling vector \(s\) to fulfill the final demand:
$$ f = \sum_j{A[:, j] \ s_j} = A s $$
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const v = await call("result/demand", {
"@id": "841c7110-4106-49d3-8447-38acc0805ca5",
});
console.log(v);
// {
// amount: 1,
// techFlow: {
// provider: {
// "@type": "Process",
// "@id": "4446fcf6-7b87-4eb6-9529-775f3fe0c016",
// ...
Scaling factors
The scaling vector \(s\) contains for each process \(j\) a factor \(s_j\) by which the process needs to be scaled to fulfill the demand of the product system. Mathematically, it can be calculated by solving the following equation for \(s\) where \(A\) is the technology matrix and \(f\) the final demand vector of the system:
$$ A s = f $$
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const v = await call("result/scaling-factors", {
"@id": "fa78990c-3f88-455a-9f8f-bd9e536bac28",
});
console.log(v);
// [
// {
// techFlow: { provider: [Object], flow: [Object] },
// amount: 0.0016129032258064518
// },
// { techFlow: ...
Total requirements
The total requirements of the technosphere flows are the amounts that are needed to fulfill the demand of the calculated product system. Mathematically, this is the diagonal of the technology matrix \(A\) scaled by the scaling vector \(s\):
$$ t = diag(s) \ diag(A) $$
The method total-requirements returns the total requirements of all
technosphere flows and total-requirements-of the total requirements
\(t_j = s_j \ A[j, j]\) of a single technosphere flow \(j\).
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const v = await call("result/total-requirements", {
"@id": "fa78990c-3f88-455a-9f8f-bd9e536bac28",
});
console.log(v);
// [
// { techFlow: { provider: [Object], flow: [Object] }, amount: 1 },
// { techFlow: { provider: [Object], flow: [Object] }, amount: 1 },
// { techFlow: {
// provider: [Object],
// flow: [Object] },
// amount: 15.151515151515152 }, ..
Totality factors
The concept of totality factors is a bit complicated, but they are very useful for visualizations like Sankey diagrams. In short, they scale an intensity result to a total process result. An intensity result is related to one unit of product output (waste input) of a technosphere flow \(j\) including the direct, upstream, and downstream contributions. Multiplying such an intensity with the totality factor \(tf_j\) gives the total result related to the total requirements of product (waste) \(j\). Directly multiplying the intensity with the total requirements would double count possible loops.
Mathematically, the totality factor of a technosphere flow \(j\) is calculated by multiplying the total requirements \(t_j\) of that flow by a loop factor \(\lambda_j\):
$$ tf_j = \lambda_j \ t_j $$
Where the loop factor is calculated via:
$$ \lambda_j = \frac{1}{A[j, j] \ A^{-1}[j, j]} $$
As the calculation of a totality factor \(tf_j\) requires to solve the
complete system for one unit of technosphere flow \(j\), it is almost always a
better idea to only query the totality factors that are really needed via
totality-factor-of instead of totality-factors.
Scaled technosphere flows
The method scaled-tech-flows-of returns the scaled inputs and outputs of the
linked product and waste flows of a process \(j\) related to the final demand
of the product system. Mathematically, it is the scaled column \(j\) of the
technology matrix \(A\):
$$ s_j \ A[:,j] $$
The returned values are negative for inputs and positive for outputs of the respective flows. Also, the returned values contain the total requirements of the technosphere flow \(j\) to which the other requirements are related.
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const v = await call("result/scaled-tech-flows-of", {
"@id": "77ccaffa-9d79-4f38-8da5-4413469b8a7b",
techFlow: {
provider: {
"@type": "Process",
"@id": "ff6b1c80-03b2-4433-adaf-66c51063b078",
},
flow: {
"@type": "Flow",
"@id": "759b89bd-3aa6-42ad-b767-5bb9ef5d331d",
}
}
});
console.log(v);
// [
// {
// techFlow: { provider: [Object], flow: [Object] },
// amount: 0.0029162004774116275
// },
// { techFlow: ...
Unscaled technosphere flows
The method unscaled-tech-flows-of returns the inputs and outputs of the linked
product and waste flows of a process \(j\) related to the quantitative
reference of that process, without applying a scaling factor. Mathematically, it
is just the column \(j\) of the technology matrix \(A\):
$$ A[:, j] $$
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const v = await call("result/unscaled-tech-flows-of", {
"@id": "66dcc7d0-ce47-46bf-b77a-ada4b4c95169",
"techFlow": {
provider: {
"@type": "Process",
"@id": "ff6b1c80-03b2-4433-adaf-66c51063b078",
},
flow: {
"@type": "Flow",
"@id": "759b89bd-3aa6-42ad-b767-5bb9ef5d331d",
}
}
});
console.log(v);
// [
// { techFlow: { provider: [Object], flow: [Object] }, amount: 3.6 },
// { techFlow: { ...
Direct contributions
Direct contributions are the results that are directly related to the processes of the calculated product system, without their upstream or downstream contributions. For each result element, these results form a matrix with the result elements as rows and the processes (technosphere flows) \(j\) as columns, scaled by the scaling vector \(s\). There are methods for getting a row (the contributions of all processes to a single result element), a column (the direct result of a single process), or a single value of this matrix.
| Method | Parameters | Returns | Formula |
|---|---|---|---|
flow-contributions-of | enviFlow | List[TechFlowValue] | \(G[i, :]\) |
direct-interventions-of | techFlow | List[EnviFlowValue] | \(G[:, j]\) |
direct-intervention-of | enviFlow, techFlow | EnviFlowValue | \(G[i, j]\) |
impact-contributions-of | impactCategory | List[TechFlowValue] | \(H[k, :]\) |
direct-impacts-of | techFlow | List[ImpactValue] | \(H[:, j]\) |
direct-impact-of | impactCategory, techFlow | ImpactValue | \(H[k, j]\) |
cost-contributions | List[TechFlowValue] | \(q^T diag(s)\) | |
direct-costs-of | techFlow | number | \(q_j s_j\) |
Intervention flows
The direct contributions of the processes to the inventory result are given by the scaled intervention matrix \(G\):
$$ G = B \ diag(s) $$
flow-contributions-ofreturns the row \(G[i, :]\): the direct contribution of each process \(j\) in the system to the inventory result of a flow \(i\).direct-interventions-ofreturns the column \(G[:, j]\): the direct intervention flows of a process \(j\) related to the final demand of the product system.direct-intervention-ofreturns the single value \(G[i, j]\).
Try it
You can edit and execute the examples below. Just make sure an openLCA IPC
server is running on port 8080.
Contributions to a flow:
const v = await call("result/flow-contributions-of", {
"@id": "66dcc7d0-ce47-46bf-b77a-ada4b4c95169",
enviFlow: {
flow: {
"@type": "Flow",
"@id": "5f7aad3d-566c-4d0d-ad59-e765f971aa0f",
name: "Methane, fossil",
},
}
});
console.log(v);
// [
// {
// techFlow: { provider: [Object], flow: [Object] },
// amount: 1.5185665316633185e-8
// },
// {
// techFlow: { provider: [Object], flow: [Object] },
// amount: 0.0018045126002407595
// }, ...
Direct interventions of a process:
const v = await call("result/direct-interventions-of", {
"@id": "66dcc7d0-ce47-46bf-b77a-ada4b4c95169",
techFlow: {
provider: {
"@type": "Process",
"@id": "ff6b1c80-03b2-4433-adaf-66c51063b078",
},
flow: {
"@type": "Flow",
"@id": "759b89bd-3aa6-42ad-b767-5bb9ef5d331d",
}
}
});
console.log(v);
// [
// { enviFlow: { flow: [Object], isInput: false },
// amount: 2.4884640352310415e-19 },
// { enviFlow: { flow: [Object], isInput: false },
// amount: 1.0147225898077544e-12 }, ...
Impact categories
The direct contributions of the processes to the impact assessment result are given by the direct impact matrix \(H\):
$$ H = C \ B \ diag(s) $$
impact-contributions-ofreturns the row \(H[k, :]\): the direct contribution of each process \(j\) in the system to the impact assessment result of an impact category \(k\).direct-impacts-ofreturns the column \(H[:, j]\): the direct impacts of a process \(j\) related to the final demand of the product system.direct-impact-ofreturns the single value \(H[k, j]\).
Try it
You can edit and execute the examples below. Just make sure an openLCA IPC
server is running on port 8080.
Contributions to an impact category:
const v = await call("result/impact-contributions-of", {
"@id": "86b36d3b-1dba-4804-bd61-dc5bcaf7c86c",
impactCategory: {
"@id": "dbdd01d5-2be4-3ba4-8127-de89f065fda1",
},
});
console.log(v);
// [
// {
// techFlow: { provider: [Object], flow: [Object] },
// amount: 0.00008582892489209728
// },
// { techFlow: { provider: [Object], flow: [Object] },
// amount: 2.023594297933216 },
// ...
Direct impacts of a process:
const v = await call("result/direct-impacts-of", {
"@id": "86b36d3b-1dba-4804-bd61-dc5bcaf7c86c",
techFlow: {
provider: { "@id": "37eb4bf5-9fbc-4caf-a24a-0e0b71b997dd" },
flow: { "@id": "817c3650-4fed-4ef2-b9b6-404a198834e6" }
}
});
console.log(v);
// [
// {
// impactCategory: {
// "@type": "ImpactCategory",
// "@id": "3bc1c67f-d3e3-3891-9fea-4512107d88ef",
// name: "Climate change",
// category: "EF 3.0 Method (adapted)",
// refUnit: "kg CO2 eq"
// },
// amount: 0.0008854099635082675
// },
// ...
Costs
For costs, there is only a single result row: the net-costs \(q\) of the processes scaled by the scaling vector \(s\):
$$ q^T diag(s) $$
cost-contributionsreturns the direct contribution of each process \(j\) in the system to the total cost result.direct-costs-ofreturns the direct costs \(q_j s_j\) of a process \(j\). Via JSON-RPC, the value is returned as plain number.
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const o = await import("https://cdn.jsdelivr.net/npm/olca-ipc@2.6.2/+esm");
const client = o.IpcClient.on(8080);
const result = await client.calculate(o.CalculationSetup.of({
target: o.Ref.of({
refType: o.RefType.ProductSystem,
id: "99ad5640-b73c-4387-b03c-ee0a9c6a7d6b",
}),
withCosts: true,
}));
await result.untilReady();
// the currency code is taken from the total result
const code = (await result.getTotalCosts()).currency?.refUnit;
const contributions = await result.getCostContributions();
for (const c of contributions) {
console.log(`${c.techFlow?.provider?.name}: ${c.amount} ${code}`);
}
// Q: 15 USD
// P: 45 USD
result.dispose();
Intensities
Intensities are the total results related to one unit of product output or waste input of a technosphere flow \(j\) in the supply chain. They include the direct, upstream, and downstream contributions related to one unit of this flow. For each result element, the intensities form a matrix with the result elements as rows and the technosphere flows as columns. There are methods for getting a column (all intensities of a technosphere flow) or a single value of this matrix.
To get the total result related to the total requirements of a technosphere flow, an intensity needs to be multiplied with the totality factor of that flow. This is done by the methods for the total process results.
| Method | Parameters | Returns | Formula |
|---|---|---|---|
flow-intensities-of | techFlow | List[EnviFlowValue] | \(M[:, j]\) |
flow-intensity-of | enviFlow, techFlow | EnviFlowValue | \(M[i, j]\) |
impact-intensities-of | techFlow | List[ImpactValue] | \(N[:, j]\) |
impact-intensity-of | impactCategory, techFlow | ImpactValue | \(N[k, j]\) |
cost-intensities-of | techFlow | number | \(q^T A^{-1}[:, j]\) |
Intervention flows
The intensities of the intervention flows are given by the intensity matrix \(M\):
$$ M = B \ A^{-1} $$
The method flow-intensities-of returns the column \(M[:, j]\), the
intervention flows related to one unit of the technosphere flow \(j\), and
flow-intensity-of the intensity \(M[i, j]\) of a single flow \(i\).
Impact categories
The intensities of the impact categories are given by the impact intensity matrix \(N\):
$$ N = C \ B \ A^{-1} = C \ M $$
The method impact-intensities-of returns the column \(N[:, j]\), the impacts
related to one unit of the technosphere flow \(j\), and impact-intensity-of
the intensity \(N[k, j]\) of a single impact category \(k\).
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const v = await call("result/impact-intensities-of", {
"@id": "86b36d3b-1dba-4804-bd61-dc5bcaf7c86c",
techFlow: {
provider: { "@id": "37eb4bf5-9fbc-4caf-a24a-0e0b71b997dd" },
flow: { "@id": "817c3650-4fed-4ef2-b9b6-404a198834e6" }
}
});
console.log(v);
// [
// {
// impactCategory: {
// "@type": "ImpactCategory",
// "@id": "3bc1c67f-d3e3-3891-9fea-4512107d88ef",
// name: "Climate change",
// category: "EF 3.0 Method (adapted)",
// refUnit: "kg CO2 eq"
// },
// amount: 1.3687522905554603
// },
// ...
Costs
The method cost-intensities-of returns the life cycle costs related to one
unit of the technosphere flow \(j\). Via JSON-RPC, the value is returned as
plain number:
$$ q^T A^{-1}[:, j] $$
Total process results
The total result of a process (technosphere flow) \(j\) is the result related to the total requirements \(t_j\) of that flow in the calculated product system. It includes the direct, upstream, and downstream contributions related to \(t_j\). Mathematically, it is the intensity of the flow scaled by its totality factor \(tf_j\).
| Method | Parameters | Returns | Formula |
|---|---|---|---|
total-interventions-of | techFlow | List[EnviFlowValue] | \(M[:, j] \ tf_j\) |
total-intervention-of | enviFlow, techFlow | EnviFlowValue | \(M[i, j] \ tf_j\) |
total-impacts-of | techFlow | List[ImpactValue] | \(N[:, j] \ tf_j\) |
total-impact-of | impactCategory, techFlow | ImpactValue | \(N[k, j] \ tf_j\) |
total-costs-of | techFlow | number | \(q^T A^{-1}[:, j] \ tf_j\) |
total-cost-values¹ | List[TechFlowValue] | \(q^T A^{-1} diag(tf)\) |
¹ only available via REST
Intervention flows
The method total-interventions-of returns the total intervention flows of a
technosphere flow \(j\): the column \(j\) of the intensity matrix \(M\)
scaled by the totality factor \(tf_j\). The method total-intervention-of
returns this value for a single flow \(i\).
Impact categories
The method total-impacts-of returns the total impacts of a technosphere flow
\(j\): the column \(j\) of the impact intensity matrix \(N\) scaled by the
totality factor \(tf_j\). The method total-impact-of returns this value for
a single impact category \(k\).
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const v = await call("result/total-impacts-of", {
"@id": "86b36d3b-1dba-4804-bd61-dc5bcaf7c86c",
techFlow: {
provider: { "@id": "37eb4bf5-9fbc-4caf-a24a-0e0b71b997dd" },
flow: { "@id": "817c3650-4fed-4ef2-b9b6-404a198834e6" }
}
});
console.log(v);
// [
// {
// impactCategory: {
// "@type": "ImpactCategory",
// "@id": "3bc1c67f-d3e3-3891-9fea-4512107d88ef",
// name: "Climate change",
// category: "EF 3.0 Method (adapted)",
// refUnit: "kg CO2 eq"
// },
// amount: 0.020981112466506135
// },
// ...
Costs
The method total-costs-of returns the total life cycle costs of a technosphere
flow \(j\). Via JSON-RPC, the value is returned as plain number. Via REST,
the method total-cost-values returns the total life cycle costs of all
technosphere flows.
Impact factors
These methods return the characterisation factors of an impact category and the contributions of the intervention flows to the result of an impact category.
| Method | Parameters | Returns | Formula |
|---|---|---|---|
impact-factors-of | impactCategory | List[EnviFlowValue] | \(C[k, :]\) |
impact-factor-of | impactCategory, enviFlow | EnviFlowValue | \(C[k, i]\) |
flow-impacts-of | impactCategory | List[EnviFlowValue] | \(C[k, :] diag(g)\) |
flow-impact-of | impactCategory, enviFlow | EnviFlowValue | \(C[k, i] \ g_i\) |
Impact factors
The method impact-factors-of returns the characterisation factors of an
impact category \(k\) for the intervention flows of the result. Mathematically,
it is the row \(C[k, :]\) of the characterisation matrix \(C\). The method
impact-factor-of returns the characterisation factor \(C[k, i]\) of a single
flow \(i\).
Flow impacts
The method flow-impacts-of returns the contribution of each intervention flow
\(i\) to the result of an impact category \(k\). Mathematically, it is the
row \(k\) of the characterisation matrix \(C\) multiplied with the inventory
result \(g\):
$$ C[k, :] \ diag(g) $$
The method flow-impact-of returns the impact \(C[k, i] \ g_i\) of a single
flow \(i\).
Upstream trees
An upstream tree shows the contributions of the processes in the supply chain to the result of a result element. The root of the tree is the reference process (the final demand) of the calculated product system and the child nodes of a node are the providers of the product inputs (or waste outputs) of that node. The result of each node is the total result of that node including its upstream contributions.
The methods below return the child nodes of a given path in such an upstream tree. The path is a sequence of technosphere flows that describe the path to the parent node of the returned nodes. If the path is empty, the root of the tree is returned. Note that such an upstream tree can be infinitely deep when the calculated system has cycles.
| Method | Parameters | Returns |
|---|---|---|
upstream-interventions-of | enviFlow, path | List[UpstreamNode] |
upstream-impacts-of | impactCategory, path | List[UpstreamNode] |
upstream-costs-of | path | List[UpstreamNode] |
With the client libraries, the path is passed as list of
technosphere flows.
Via JSON-RPC, the path is passed as string in the field path; via REST, these
methods are POST requests with the path in the field path of the request
body. In the path string, each technosphere flow is encoded as
<provider-id>::<flow-id> and multiple technosphere flows are separated by /:
<provider-id>::<flow-id>/<provider-id>::<flow-id>/...
Intervention flows
The method upstream-interventions-of returns the upstream tree nodes of an
intervention flow.
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const o = await import("https://cdn.jsdelivr.net/npm/olca-ipc@2.6.2/+esm");
// connect to a local server running on port 8080
const client = o.IpcClient.on(8080);
const setup = o.CalculationSetup.of({
target: o.Ref.of({
id: "d3a9a9b2-ec3e-4811-8617-ae853573b50b",
refType: o.RefType.ProductSystem,
}),
});
const result = await client.calculate(setup);
await result.untilReady();
// select the first best inventory flow and expand a tree for it
const flow = (await result.getEnviFlows())[0];
console.log(`upstream tree for ${flow.flow?.name} (${flow.flow?.category})`);
await expand(result, flow, []);
// as always, dispose the result
result.dispose();
async function expand(r, flow, path) {
const level = path.length;
const indent = " ".repeat(level);
const unit = flow.flow?.refUnit;
const nodes = await r.getUpstreamInterventionsOf(flow, path);
for (const node of nodes) {
if (node.result === 0) {
continue;
}
const name = node.techFlow?.provider?.name;
const value = node.result?.toExponential(2);
console.log(`${indent}- ${value} ${unit} :: ${name}`);
// we stop the expansion after 3 levels; you can set other cut-offs like
// result contributions etc.
if (level < 3) {
const next = path.slice();
next.push(node.techFlow);
await expand(r, flow, next);
}
}
}
/*
upstream tree for COD, Chemical Oxygen Demand (Elementary flows/Emission to water/ground water)
- 1.73e-9 t :: ...
- 1.73e-9 t :: ...
- 7.21e-10 t :: ...
- 3.45e-10 t :: ...
- 2.04e-10 t :: ...
- ...
- 5.77e-10 t :: ...
- 4.40e-10 t :: ...
- 7.53e-11 t :: ...
- 3.21e-11 t :: ...
- ...
*/
Python IPC
import olca_ipc as ipc
import olca_schema as o
def main():
# calculate a result
client = ipc.Client(8080)
setup = o.CalculationSetup(
target=o.Ref(
id="d3a9a9b2-ec3e-4811-8617-ae853573b50b",
ref_type=o.RefType.ProductSystem,
)
)
result = client.calculate(setup)
result.wait_until_ready()
# select the first best inventory flow and expand a tree for it
flow = result.get_envi_flows()[0]
print(f"upstream tree for {flow.flow.name} ({flow.flow.category})")
expand(result, flow, [])
# as always, dispose the result
result.dispose()
def expand(r: ipc.IpcResult, flow: o.EnviFlow, path: list[o.TechFlow]):
level = len(path)
indent = " " * level
unit = flow.flow.ref_unit
nodes = r.get_upstream_interventions_of(flow, path)
for node in nodes:
if node.result == 0 or not node.tech_flow:
continue
name = node.tech_flow.provider.name
value = node.result
print(f"{indent}- {value:.2E} {unit} :: {name}")
# we stop the expansion after 3 levels; you can set other cut-offs like
# result contributions etc.
if level < 3:
expand(r, flow, path + [node.tech_flow])
pass
if __name__ == "__main__":
main()
Impact categories
The method upstream-impacts-of returns the upstream tree nodes of an impact
category.
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const o = await import("https://cdn.jsdelivr.net/npm/olca-ipc@2.6.2/+esm");
// connect to a local server running on port 8080
const client = o.IpcClient.on(8080);
const setup = o.CalculationSetup.of({
target: o.Ref.of({
id: "d3a9a9b2-ec3e-4811-8617-ae853573b50b",
refType: o.RefType.ProductSystem,
}),
impactMethod: o.Ref.of({
id: "07370e48-dde9-4248-9a9b-7255f701da89",
})
});
const result = await client.calculate(setup);
await result.untilReady();
// select the first best impact category and expand a tree for it
const indicator = (await result.getImpactCategories())[0];
console.log(`upstream tree for ${indicator.name}`);
await expand(result, indicator, []);
// as always, dispose the result
result.dispose();
async function expand(r, indicator, path) {
const level = path.length;
const indent = " ".repeat(level);
const unit = indicator.refUnit;
const nodes = await r.getUpstreamImpactsOf(indicator, path);
for (const node of nodes) {
if (node.result === 0) {
continue;
}
const name = node.techFlow?.provider?.name;
const value = node.result?.toExponential(2);
console.log(`${indent}- ${value} ${unit} :: ${name}`);
// we stop the expansion after 3 levels; you can set other cut-offs like
// result contributions etc.
if (level < 3) {
const next = path.slice();
next.push(node.techFlow);
await expand(r, indicator, next);
}
}
}
/*
upstream tree for Photochemical ozone formation
- 2.66e-2 kg NMVOC eq ...
- 2.66e-2 kg NMVOC eq ...
- 1.13e-2 kg NMVOC eq ...
- 4.69e-3 kg NMVOC eq ...
- 4.53e-3 kg NMVOC eq ...
- 1.41e-3 kg NMVOC eq ...
- 8.72e-3 kg NMVOC eq ...
- 4.18e-3 kg NMVOC eq ...
- 4.18e-3 kg NMVOC eq ...
- 1.01e-4 kg NMVOC eq ...
*/
Python IPC
The Python example below uses the utree module of the olca-ipc.py API which
makes working with upstream trees a bit more convenient:
import olca_schema as o
import olca_ipc as ipc
import olca_ipc.utree as utree
# maximum number of levels and child nodes that should be expanded
MAX_EXPAND_LEVELS = 3
MAX_EXPAND_NODES = 5
def main():
# calculate a result
client = ipc.Client()
setup = o.CalculationSetup(
target=o.Ref(
ref_type=o.RefType.Process,
id="2d1b0c1f-dd8f-3aea-bc50-bbd10acbd86d",
),
impact_method=o.Ref(id="99b9d86b-ec6f-4610-ba9f-68ebfe5691dd"),
)
result = client.calculate(setup)
result.wait_until_ready()
# select the first impact category for the tree
ref = result.get_impact_categories()[0]
print(f"\nTree for {ref.name}, results in {ref.ref_unit}:")
# create the upstream tree and expand it
root = utree.of(result, ref)
expand(root, 0)
# always dispose the result
result.dispose()
def expand(node: utree.Node, level: int):
"""This function recursively expands an upstream tree.
The maximum number of levels and maximum number of child nodes are defined
with the constants above. Note that an upstream tree can be
"""
indent = " " * level
print(f"{indent} - {node.provider.name} : {node.result}")
if level < MAX_EXPAND_LEVELS:
for c in node.childs[0:MAX_EXPAND_NODES]:
expand(c, level + 1)
if __name__ == "__main__":
main()
Costs
The method upstream-costs-of returns the upstream tree nodes of the life cycle
costs.
Grouped results
These methods return the results of the analysis groups of the calculated product system. An analysis group is a set of processes of the system for which the results are aggregated.
| Method | Parameters | Returns |
|---|---|---|
grouped-flow-results-of | enviFlow | List[GroupValue] |
grouped-impact-results-of | impactCategory | List[GroupValue] |
grouped-cost-results | List[GroupValue] |
These methods are only available via JSON-RPC.
Intervention flows
The method grouped-flow-results-of returns the grouped results of an
intervention flow.
Impact categories
The method grouped-impact-results-of returns the grouped results of an impact
category.
Costs
The method grouped-cost-results returns the grouped results of the life cycle
costs.
Tag results
These methods return the results aggregated by the tags of the processes in the calculated product system.
| Method | Parameters | Returns |
|---|---|---|
tag-results-of-flow | enviFlow | List[TagValue] |
tag-results-of-impact | impactCategory | List[TagValue] |
tag-results-of-costs | List[TagValue] |
These methods are only available via JSON-RPC.
Intervention flows
The method tag-results-of-flow returns the tag results of an intervention
flow.
Impact categories
The method tag-results-of-impact returns the tag results of an impact
category.
Costs
The method tag-results-of-costs returns the tag results of the life cycle
costs.
Sankey Graphs
This method returns a graph data structure with which Sankey diagrams can be constructed.
| Method | Parameters | Returns |
|---|---|---|
sankey | config: SankeyRequest | SankeyGraph |
Via REST, it is a POST request with the Sankey request as body:
POST result/{result-id}/sankey. In Python, the method is
Result.get_sankey_graph.
Try it
You can edit and execute the example below. Just make sure an openLCA IPC
server is running on port 8080:
const o = await import("https://cdn.jsdelivr.net/npm/olca-ipc@2.6.2/+esm");
const client = o.RestClient.on("http://localhost:8080");
// calculate the result
const result = await client.calculate(o.CalculationSetup.of({
target: o.Ref.of({
refType: o.RefType.ProductSystem,
id: "7d1cbce0-b5b3-47ba-95b5-014ab3c7f569",
}),
impactMethod: o.Ref.of({ id: "99b9d86b-ec6f-4610-ba9f-68ebfe5691dd" }),
}));
await result.untilReady();
const g = await result.getSankeyGraph(o.SankeyRequest.of({
impactCategory: o.Ref.of({ id: "b8658d7c-9c6e-4361-acbf-3bd6d9fef8c9" }),
maxNodes: 10,
}));
console.log(
`loaded a graph with ${g.nodes?.length} nodes and ${g.edges?.length} edges`,
);
result.dispose();
Python IPC
import olca_ipc.rest as ipc
import olca_schema as o
# in this example we use the REST client
client = ipc.RestClient("http://localhost:8080")
# calculate a result for the default quantitative reference of a product system
result = client.calculate(
o.CalculationSetup(
target=o.Ref(
ref_type=o.RefType.ProductSystem,
id="7d1cbce0-b5b3-47ba-95b5-014ab3c7f569",
),
impact_method=o.Ref(id="99b9d86b-ec6f-4610-ba9f-68ebfe5691dd"),
)
)
result.wait_until_ready()
# get the Sankey graph for an impact category
g = result.get_sankey_graph(
o.SankeyRequest(
impact_category=o.Ref(id="b8658d7c-9c6e-4361-acbf-3bd6d9fef8c9"),
max_nodes=10,
)
)
print(f"loaded a graph with {len(g.nodes)} nodes and {len(g.edges)} edges")
# prints something like: loaded a graph with 10 nodes and 14 edges
# finally, dispose the result
result.dispose()
Stand-alone servers
As shown in the section before, it is easy to start an IPC server in openLCA
from the user interface but it is of course also possible to run these servers
as stand-alone servers. The JSON-RPC and gRPC servers are part of the openLCA
modules, the
gdt-server provides an
implementation of the Rest API of the openLCA IPC protocol. All these servers
provide a common command line interface with which a server can be configured
and started. The parameters of the configuration are listed below. All
parameters are optional. By default a server uses the default openLCA workspace
folder as used by the desktop application (~/openLCA-data-1.4) and connects to
the database with the name database in that folder:
-data <path to data folder>
The path to the data folder that contains the database and possible
libraries. The folder structure need to follow the openLCA workspace
structure, means the sub-folder `databases` of that folder contains the
database and the sub-folder `libraries` possible data libraries to which
the database is linked. If this parameter is not provided, the default
openLCA workspace (currently `~/openLCA-data-1.4`) is taken as data folder.
-db <database>
The name of the database in the data folder (only the name, not a full
file path, must be provided); defaults to 'database'.
-port <port>
The port of the server; defaults to 8080.
-native <path to native library folder>
The path to the folder from which the native libraries should be
loaded; defaults to the data folder.
-threads <number of calculation threads>
The number of parallel threads that can be used for calculations. Make sure
that the server has enough resources if you provide a larger number than 1
here; defaults to 1.
-timeout <minutes after which results are disposed>
The time in minutes after which results are cleaned up if they were not
disposed by the user. A value of <=0 means that no timeout should be
applied; defaults to 0.
--readonly <true | false>?
If this flag is set, the server will run in readonly mode and modifying the
database will not be possible.
-static <path to folder with static files>
A path to a folder with static files that should be hosted by the server.
This only has an effect if the server supports hosting of static files.
Startup scripts in openLCA
In the bin folder of the openLCA application, there are two scripts for
starting a headless IPC server (without user interface involved):
ipc-server: for JSON-RPC based IPC serversgrpc-server: for gRPC based IPC servers
These scripts just take the name of a database in the default openLCA workspace
as argument and will start a server at port 8080. For example, for Windows
starting a headless IPC server for the database ecoinvent39 looks like this:
cd openLCA\bin
.\ipc-server.cmd ecoinvent39
A running server can be quit with Ctr+c. Note that you cannot connect to a
database that is opened via the openLCA desktop application with a headless
server. You can of course modify these scripts to your needs or re-package a
server application under the respective license conditions.
Running with Docker
An IPC server can be of course also packaged as a Docker container and the gdt-server is especially useful for this. There are basically two types of gdt-server images: images with packaged LCA models (model images) and images without a model (service images).
Model images
A model image is an easy way to distribute and share one or more computable LCA
models. Such models are often parameterized and can be calculated for a given
set of parameter values on demand. Model images are typically shared as tar
archives which can be loaded into a local image repository via the load
command:
docker load -i gdt-server-{identifier}.tar
With docker image ls you should see the image then. A model image typically
does not need any configuration (timeouts, number of threads etc.), you just
run it and map the 8080 port of openLCA service in the container (note that
-d runs the container in detached mode, --rm will delete it when it is
stopped):
docker run -p 3000:8080 -d --rm gdt-server-{identifier}
In the example above, it maps the port 8080 in the container to the port
3000, the URL http://localhost:3000/api/version should then respond with the
API version of the gdt-server.
Service images
A service image contains a gdt-server and can be configured via start parameters of a container. The components of such a service image are freely available in the Github container registry and can be composed via this Dockerfile, e.g.:
cd <workdir>
curl https://raw.githubusercontent.com/GreenDelta/gdt-server/main/Dockerfile \
> Dockerfile \
&& docker build -t gdt-server .
A container can be started from such an image in the following way:
docker run \
-p 3000:8080 \
-v $HOME/openLCA-data-1.4:/app/data \
--rm -d gdt-server \
-db example --readonly
As above, it first maps the internal port to the port 3000 of the host. Also,
a data folder needs to be mounted under the /app/data folder of the container.
In this example, it maps the default openLCA workspace to that folder. More
configuration parameters can be passed to the server via the start command of
the container.
REST API reference
This page lists all endpoints of the REST API of the openLCA IPC protocol, as
provided by the gdt-server (see
stand-alone servers and the routes in its
Server.java).
The paths are relative to the base URL of the server, e.g.
http://localhost:8080/. Request and response bodies are JSON documents
following the openLCA Schema.
The following placeholders are used in the paths:
| Placeholder | Value |
|---|---|
{type} | the type of a data set, see the table below |
{id} | the ID of a data set |
{name} | the URL-encoded name of a data set |
{result-id} | the ID of a result |
{tech-flow} | a technosphere flow: <provider-id>::<flow-id> |
{envi-flow} | an intervention flow: <flow-id> or <flow-id>::<location-id> |
{impact-category} | the ID of an impact category |
The {type} path segments of the data set types are:
| Type | {type} | Type | {type} |
|---|---|---|---|
Actor | actors | Parameter | parameters |
Currency | currencies | Process | processes |
DQSystem | dq-systems | ProductSystem | product-systems |
Epd | epds | Project | projects |
Flow | flows | Result | results |
FlowProperty | flow-properties | SocialIndicator | social-indicators |
ImpactCategory | impact-categories | Source | sources |
ImpactMethod | impact-methods | UnitGroup | unit-groups |
Location | locations | Category | categories |
The server also accepts the singular forms of these path segments (e.g.
process instead of processes) as well as method(s) for impact methods and
model(s) for product systems.
Server
| Request | Returns |
|---|---|
GET api/version | the API version of the server |
Working with data
| Request | Body | Returns | Documentation |
|---|---|---|---|
GET data/{type} | List[Ref] | Get descriptors | |
GET data/{type}/all | List[{type}] | Get all | |
GET data/{type}/{id} | {type} | Get by ID | |
GET data/{type}/name/{name} | {type} | Get by name | |
GET data/{type}/{id}/info | Ref | Get descriptor | |
GET data/{type}/{id}/parameters | List[Parameter] or List[ParameterRedef] | Get parameters | |
GET data/providers | List[TechFlow] | Get providers | |
GET data/providers/{id} | List[TechFlow] | Get providers for flow | |
PUT data/{type} | the data set | Ref | Insert or update |
POST data/create-system | {process: Ref, config: LinkingConfig} | Ref | Create a product system |
DELETE data/{type}/{id} | Ref | Delete a data set |
Calculations
| Request | Body | Returns | Documentation |
|---|---|---|---|
POST result/calculate | CalculationSetup | ResultState | Calculate |
POST result/simulate | CalculationSetup | ResultState | Monte Carlo simulations |
GET result/{result-id}/state | ResultState | Get state | |
POST result/{result-id}/simulate/next | ResultState | Monte Carlo simulations | |
POST result/{result-id}/dispose | ResultState | Dispose result | |
DELETE result/{result-id} | ResultState | Dispose result |
Results
All result requests start with result/{result-id}/, which is omitted in the
table below. Except of the upstream trees and the Sankey graph, all result
requests are GET requests without a request body.
| Request | Returns | Documentation |
|---|---|---|
tech-flows | List[TechFlow] | Result elements |
envi-flows | List[EnviFlow] | Result elements |
impact-categories | List[Ref] | Result elements |
total-flows | List[EnviFlowValue] | Total results |
total-flow-value-of/{envi-flow} | EnviFlowValue | Total results |
total-impacts | List[ImpactValue] | Total results |
total-impact-value-of/{impact-category} | ImpactValue | Total results |
total-impacts/normalized | List[ImpactValue] | Total results |
total-impacts/weighted | List[ImpactValue] | Total results |
total-costs | CostValue | Total results |
demand | TechFlowValue | Technosphere requirements |
scaling-factors | List[TechFlowValue] | Technosphere requirements |
total-requirements | List[TechFlowValue] | Technosphere requirements |
total-requirements-of/{tech-flow} | TechFlowValue | Technosphere requirements |
scaled-tech-flows-of/{tech-flow} | List[TechFlowValue] | Technosphere requirements |
unscaled-tech-flows-of/{tech-flow} | List[TechFlowValue] | Technosphere requirements |
flow-contributions-of/{envi-flow} | List[TechFlowValue] | Direct contributions |
direct-interventions-of/{tech-flow} | List[EnviFlowValue] | Direct contributions |
direct-intervention-of/{envi-flow}/{tech-flow} | EnviFlowValue | Direct contributions |
impact-contributions-of/{impact-category} | List[TechFlowValue] | Direct contributions |
direct-impacts-of/{tech-flow} | List[ImpactValue] | Direct contributions |
direct-impact-of/{impact-category}/{tech-flow} | ImpactValue | Direct contributions |
cost-contributions | List[TechFlowValue] | Direct contributions |
direct-costs-of/{tech-flow} | number | Direct contributions |
flow-intensities-of/{tech-flow} | List[EnviFlowValue] | Intensities |
flow-intensity-of/{envi-flow}/{tech-flow} | EnviFlowValue | Intensities |
impact-intensities-of/{tech-flow} | List[ImpactValue] | Intensities |
impact-intensity-of/{impact-category}/{tech-flow} | ImpactValue | Intensities |
cost-intensities-of/{tech-flow} | number | Intensities |
total-interventions-of/{tech-flow} | List[EnviFlowValue] | Total process results |
total-intervention-of/{envi-flow}/{tech-flow} | EnviFlowValue | Total process results |
total-impacts-of/{tech-flow} | List[ImpactValue] | Total process results |
total-impact-of/{impact-category}/{tech-flow} | ImpactValue | Total process results |
total-costs-of/{tech-flow} | number | Total process results |
total-cost-values | List[TechFlowValue] | Total process results |
impact-factors-of/{impact-category} | List[EnviFlowValue] | Impact factors |
impact-factor-of/{impact-category}/{envi-flow} | EnviFlowValue | Impact factors |
flow-impacts-of/{impact-category} | List[EnviFlowValue] | Impact factors |
flow-impact-of/{impact-category}/{envi-flow} | EnviFlowValue | Impact factors |
POST upstream-interventions-of/{envi-flow} | List[UpstreamNode] | Upstream trees |
POST upstream-impacts-of/{impact-category} | List[UpstreamNode] | Upstream trees |
POST upstream-costs-of | List[UpstreamNode] | Upstream trees |
POST sankey | SankeyGraph | Sankey graphs |
The upstream tree requests take the path in the upstream tree as body
{"path": "<path>"}, see upstream trees.
The Sankey request takes a
SankeyRequest
as body.
Deprecated routes
For backwards compatibility with older API versions, the server still provides the following routes. They should not be used anymore:
| Deprecated route | Replacement |
|---|---|
POST results/calculate | POST result/calculate |
GET results/{id}/state | GET result/{result-id}/state |
GET results/{id}/total-impacts | GET result/{result-id}/total-impacts |
POST results/{id}/dispose | POST result/{result-id}/dispose |
DELETE results/{id} | DELETE result/{result-id} |
Not available via REST
The following methods of the JSON-RPC protocol have no REST endpoint:
data/get/usage(Get usage)data/put/source-fileresult/totality-factorsandresult/totality-factor-of(Technosphere requirements)- the grouped results (Grouped results)
- the tag results (Tag results)
export/json-ldruntime/shutdown
Python IPC - From scratch
In this section we will go through a complete example using the openLCA IPC interface from the olca-ipc.py Python package. As we will create everything from scratch, we first create an empty database and start an IPC server for that database:
In the Python code, we first import the required packages that we will use in
our example. The olca-schema package is a dependency of the olca-ipc
package and contains the data type definitions of the openLCA model and some
utility methods. We will use Pandas for formatting our data output and NumPy,
which is a dependency of Pandas, for checking the calculation. Also, we will
add type annotations in our code. The packages can be installed via pip
(olca-ipc requires Python 3.12 or newer):
pip install olca-ipc pandas
With a clone of this documentation, you can also run the example directly with uv, which installs the required packages automatically:
uv run src/appendix/examples/pyipc_from_scratch.py
import olca_ipc as ipc
import olca_schema as o
import pandas as pd
import numpy as np
from typing import Callable
A historic example
Our example was taken from Heijungs 19941 and extended a bit. First, we define the technosphere of our system which are 4 processes connected by 4 products:
technosphere = pd.DataFrame(
data=[
[1.0, -50.0, -1.0, 0.0],
[-0.01, 1.0, -1.0, 0.0],
[0.0, 0.0, 1.0, -1.0],
[0.0, 0.0, 0.0, 100],
],
columns=[
"electricity production",
"aluminium production",
"aluminium foil production",
"sandwitch package production",
],
index=[
"electricity [MJ]",
"aluminium [kg]",
"aluminium foil [kg]",
"sandwitch package [Item(s)]",
],
)
print(technosphere)
When we print this data frame, we get the following table:
| electricity production | aluminium production | aluminium foil production | sandwitch package production | |
|---|---|---|---|---|
| electricity [MJ] | 1.00 | -50.0 | -1.0 | 0.0 |
| aluminium [kg] | -0.01 | 1.0 | -1.0 | 0.0 |
| aluminium foil [kg] | 0.00 | 0.0 | 1.0 | -1.0 |
| sandwitch package [Item(s)] | 0.00 | 0.0 | 0.0 | 100.0 |
In the rows, we have our products, in the columns the processes. Inputs have negative and outputs positive values. Thus, for 100 sandwitch packages, we would need 1 kg of aluminium foil (this is how sandwitches were packed in the 90s)2.
Next, we define the interventions of these processes with the environment:
interventions = pd.DataFrame(
data=[
[0.0, -5.0, 0.0, 0.0],
[-0.5, 0.0, 0.0, 0.0],
[3.0, 0.0, 0.0, 0.0],
[2.0, 10.0, 0.0, 1.0],
],
columns=technosphere.columns,
index=[
"bauxite [kg]",
"crude oil [kg]",
"CO2 [kg]",
"solid waste [kg]",
],
)
print(interventions)
| electricity production | aluminium production | aluminium foil production | sandwitch package production | |
|---|---|---|---|---|
| bauxite [kg] | 0.0 | -5.0 | 0.0 | 0.0 |
| crude oil [kg] | -0.5 | 0.0 | 0.0 | 0.0 |
| CO2 [kg] | 3.0 | 0.0 | 0.0 | 0.0 |
| solid waste [kg] | 2.0 | 10.0 | 0.0 | 1.0 |
In the paper, the inventory is calculated for 10 sandwitch packages as the final demand \(f\) of the system, which we can quickly do with NumPy now:
f = [
0.0,
0.0,
0.0,
10,
]
s = np.linalg.solve(technosphere.to_numpy(), f)
g = interventions.to_numpy() @ s
print(pd.DataFrame(g, index=interventions.index))
This gives the expected result:
| bauxite [kg] | -1.01 |
| crude oil [kg] | -5.10 |
| CO2 [kg] | 30.60 |
| solid waste [kg] | 22.52 |
Inventory calculations
Now we do the same in openLCA via the IPC interface. First, we create an IPC client that holds our connection data:
client = ipc.Client(8080)
As we have nothing in our database, we first need to create the units and flow properties (quantity kinds) in which the flows of the examples are measured:
mass_units = o.new_unit_group("Mass units", "kg")
energy_units = o.new_unit_group("Energy units", "MJ")
counting_units = o.new_unit_group("Counting units", "Item(s)")
mass = o.new_flow_property("Mass", mass_units)
energy = o.new_flow_property("Energy", energy_units)
count = o.new_flow_property("Number of items", counting_units)
client.put_all(
mass_units,
energy_units,
counting_units,
mass,
energy,
count,
)
While IPC server is running, you can also continue to use the openLCA user interface, just do not close the dialog of the server. When you refresh the navigation, you will see the newly created unit groups and flow properties:
However, typically you will not create units and flow properties but use the
reference data from openLCA. For example, we can get the flow property Mass
by its name:
print(client.get(o.FlowProperty, name="Mass").to_json())
This will print the JSON serialization of that flow property which is the internal communication format of the IPC interface (and also the standard openLCA data exchange format in general):
{
"@type": "FlowProperty",
"@id": "b24a123b-f5a1-40fb-a481-afeeb50f6159",
"lastChange": "2023-01-26T13:36:37.954Z",
"name": "Mass",
"unitGroup": {
"@type": "UnitGroup",
"@id": "3e912f50-9490-473c-89fc-1393ed2eea03",
"name": "Mass units"
},
"version": "01.00.000"
}
Next, we create the flows of the example. In the snippet below, it iterates over the rows of the data frames and creates a product or elementary flow for each row, extracting the unit from the row label and mapping the corresponding flow property:
def create_flow(
row_label: str, fn: Callable[[str, o.FlowProperty], o.Flow]
) -> o.Flow:
parts = row_label.split("[")
name = parts[0].strip()
unit = parts[1][0:-1].strip()
match unit:
case "kg":
prop = mass
case "MJ":
prop = energy
case "Item(s)":
prop = count
flow = fn(name, prop)
client.put(flow)
return flow
tech_flows = [create_flow(label, o.new_product) for label in technosphere.index]
envi_flows = [
create_flow(label, o.new_elementary_flow) for label in interventions.index
]
Then we iterate over the columns of the data frames and create the corrsponding processes with their inputs and outputs of the flows we just created. One the diagonal of the technosphere matrix, the reference products of the respective processes are located and we set the these exchanges as the quantitative reference of the corresponding process:
def create_process(index: int, name: str) -> o.Process:
process = o.new_process(name)
def exchange(flow: o.Flow, value: float) -> o.Exchange | None:
if value == 0:
return None
if value < 0:
return o.new_input(process, flow, abs(value))
else:
return o.new_output(process, flow, value)
for (i, tech_flow) in enumerate(tech_flows):
value = technosphere.iat[i, index]
e = exchange(tech_flow, value)
if e and i == index:
e.is_quantitative_reference = True
for (i, envi_flow) in enumerate(envi_flows):
value = interventions.iat[i, index]
exchange(envi_flow, value)
client.put(process)
return process
processes = [
create_process(index, name)
for (index, name) in enumerate(technosphere.columns)
]
When you refresh the navigation in openLCA again, you should now see these new processes and flows:
Now we can calculate the inventory of this system. We create a calculation setup
for the sandwitch packaging process as calculation target. We do not need to set
the unit in the setup as it would take the unit of the quantitative reference of
the process by default, but we need to set the amount as we want the result for
10 sandwitches but the process has 100 as quantitative reference. The
calculation immediately returns a result object but this is maybe not ready yet,
so we wait for the calculation to be finished via the wait_until_ready
method:
setup = o.CalculationSetup(
target=o.Ref(ref_type=o.RefType.Process, id=processes[3].id),
unit=count.unit_group.ref_unit, # "Item(s)"
amount=10,
)
result = client.calculate(setup)
result.wait_until_ready()
When the result is ready, we can query the inventory from it:
inventory = result.get_total_flows()
print(
pd.DataFrame(
data=[
(
i.envi_flow.flow.name,
i.envi_flow.is_input,
i.amount,
i.envi_flow.flow.ref_unit,
)
for i in inventory
],
columns=["Flow", "Is input?", "Amount", "Unit"],
)
)
This prints the following expected values:
Flow Is input? Amount Unit
0 CO2 False 30.60 kg
1 crude oil True 5.10 kg
2 solid waste False 22.52 kg
3 bauxite True 1.01 kg
Finally, when we do not need the result anymore, we need to dispose it so that allocated resources can be freed on the openLCA side:
result.dispose()
Full workbook
Below is the full example. Note that you can run it as a note-book, cell by cell, in VS Code:
# %%
# ANCHOR: imports
import olca_ipc as ipc
import olca_schema as o
import pandas as pd
import numpy as np
from typing import Callable
# ANCHOR_END: imports
# %%
# ANCHOR: techsphere
technosphere = pd.DataFrame(
data=[
[1.0, -50.0, -1.0, 0.0],
[-0.01, 1.0, -1.0, 0.0],
[0.0, 0.0, 1.0, -1.0],
[0.0, 0.0, 0.0, 100],
],
columns=[
"electricity production",
"aluminium production",
"aluminium foil production",
"sandwitch package production",
],
index=[
"electricity [MJ]",
"aluminium [kg]",
"aluminium foil [kg]",
"sandwitch package [Item(s)]",
],
)
print(technosphere)
# ANCHOR_END: techsphere
# %%
# ANCHOR: envisphere
interventions = pd.DataFrame(
data=[
[0.0, -5.0, 0.0, 0.0],
[-0.5, 0.0, 0.0, 0.0],
[3.0, 0.0, 0.0, 0.0],
[2.0, 10.0, 0.0, 1.0],
],
columns=technosphere.columns,
index=[
"bauxite [kg]",
"crude oil [kg]",
"CO2 [kg]",
"solid waste [kg]",
],
)
print(interventions)
# ANCHOR_END: envisphere
# %%
# ANCHOR: numsol
f = [
0.0,
0.0,
0.0,
10,
]
s = np.linalg.solve(technosphere.to_numpy(), f)
g = interventions.to_numpy() @ s
print(pd.DataFrame(g, index=interventions.index))
# ANCHOR_END: numsol
# %%
# ANCHOR: mkclient
client = ipc.Client(8080)
# ANCHOR_END: mkclient
# %%
# ANCHOR: units
mass_units = o.new_unit_group("Mass units", "kg")
energy_units = o.new_unit_group("Energy units", "MJ")
counting_units = o.new_unit_group("Counting units", "Item(s)")
mass = o.new_flow_property("Mass", mass_units)
energy = o.new_flow_property("Energy", energy_units)
count = o.new_flow_property("Number of items", counting_units)
client.put_all(
mass_units,
energy_units,
counting_units,
mass,
energy,
count,
)
# ANCHOR_END: units
# %%
# ANCHOR: mass
print(client.get(o.FlowProperty, name="Mass").to_json())
# ANCHOR_END: mass
# %%
# ANCHOR: flows
def create_flow(
row_label: str, fn: Callable[[str, o.FlowProperty], o.Flow]
) -> o.Flow:
parts = row_label.split("[")
name = parts[0].strip()
unit = parts[1][0:-1].strip()
match unit:
case "kg":
prop = mass
case "MJ":
prop = energy
case "Item(s)":
prop = count
flow = fn(name, prop)
client.put(flow)
return flow
tech_flows = [create_flow(label, o.new_product) for label in technosphere.index]
envi_flows = [
create_flow(label, o.new_elementary_flow) for label in interventions.index
]
# ANCHOR_END: flows
# %%
# ANCHOR: processes
def create_process(index: int, name: str) -> o.Process:
process = o.new_process(name)
def exchange(flow: o.Flow, value: float) -> o.Exchange | None:
if value == 0:
return None
if value < 0:
return o.new_input(process, flow, abs(value))
else:
return o.new_output(process, flow, value)
for (i, tech_flow) in enumerate(tech_flows):
value = technosphere.iat[i, index]
e = exchange(tech_flow, value)
if e and i == index:
e.is_quantitative_reference = True
for (i, envi_flow) in enumerate(envi_flows):
value = interventions.iat[i, index]
exchange(envi_flow, value)
client.put(process)
return process
processes = [
create_process(index, name)
for (index, name) in enumerate(technosphere.columns)
]
# ANCHOR_END: processes
# %%
# ANCHOR: calc
setup = o.CalculationSetup(
target=o.Ref(ref_type=o.RefType.Process, id=processes[3].id),
unit=count.unit_group.ref_unit, # "Item(s)"
amount=10,
)
result = client.calculate(setup)
result.wait_until_ready()
# ANCHOR_END: calc
# %%
# ANCHOR: inventory
inventory = result.get_total_flows()
print(
pd.DataFrame(
data=[
(
i.envi_flow.flow.name,
i.envi_flow.is_input,
i.amount,
i.envi_flow.flow.ref_unit,
)
for i in inventory
],
columns=["Flow", "Is input?", "Amount", "Unit"],
)
)
# ANCHOR_END: inventory
# %%
# ANCHOR: free-inventory
result.dispose()
# ANCHOR_END: free-inventory
# %%
-
Reinout Heijungs: A generic method for the identification of options for cleaner products. Ecological Economics, Volume 10, Issue 1, 1994, Pages 69-81, ISSN 0921-8009, https://doi.org/10.1016/0921-8009(94)90038-8. ↩
-
it is of course just an illustrative example and not real data ↩
Calculation parameters
This example shows the calculation of an LCA model with different parameter values. We will use the olca-ipc.py package and the REST API in this example. The package requires Python 3.12 or newer and can be installed via pip:
pip install olca-ipc
With a clone of this documentation, you can also run the example directly with uv, which installs the required packages automatically:
uv run src/appendix/examples/parameters.py
We connect to a REST API in this example and assume that it is running at
http://localhost:3000, e.g. a gdt-server Docker container as described in
stand-alone servers:
import olca_schema as o
import olca_ipc.rest as rest
import json
client = rest.RestClient("http://localhost:3000")
To check that we can access the server, we can also just call this URL in a
browser: http://localhost:3000/api/version, which should then return the
API version of that server.
Next, we check which models (product systems) are available and select the first model for our calculations:
models = client.get_descriptors(o.ProductSystem)
for model in models:
print(f"{model.name} :: {model.id}")
model = models[0]
This should print something like this depending on the available models:
battery model without EoL :: 59327d11-9a0d-477b-9cc0-060ca74b6327
battery model with EoL :: eb31db8a-8102-453d-a549-be989e83c592
Again, we could just query an URL for this, for the example:
http://localhost:3000/data/product-systems
We do the same for the available impact assessment methods (
http://localhost:3000/data/methods):
methods = client.get_descriptors(o.ImpactMethod)
for method in methods:
print(f"{method.name} :: {method.id}")
method = methods[0]
This should print something like this:
EF 3.0 Method (adapted) :: b4571628-4b7b-3e4f-81b1-9a8cca6cb3f8
...
With the reference to a product system and LCIA method, we can create a calculation setup:
setup = o.CalculationSetup(
target=model,
impact_method=method,
)
print(json.dumps(setup.to_dict(), indent=2))
The objects of the openLCA Schema can be easily translated to JSON as done in the snippet above. This is the payload that is posted to the server in a calculation request:
{
"impactMethod": {
"@type": "ImpactMethod",
"@id": "b4571628-4b7b-3e4f-81b1-9a8cca6cb3f8",
"category": "openLCA LCIA methods 2_1_2",
"name": "EF 3.0 Method (adapted)"
},
"target": {
"@type": "ProductSystem",
"@id": "59327d11-9a0d-477b-9cc0-060ca74b6327",
"name": "battery model without EoL"
}
}
We can calculate the setup like this:
result = client.calculate(setup)
result.wait_until_ready()
impacts = result.get_total_impacts()
for i in impacts:
assert i.impact_category
print(f"{i.impact_category.name} {i.amount} {i.impact_category.ref_unit}")
result.dispose()
As shown above, we should dispose a result when we do not need it anymore. The snippet prints something like:
...
Climate change 0.7891638059816873 kg CO2 eq
...
For parameterized models, the default parameter values are applied in a calculation but we can change them in each calculation. We can query the parameters of a model like this:
parameters = client.get_parameters(o.ProductSystem, model.id)
for param in parameters:
print(f"parameter: {param.name} = {param.value}")
param = parameters[0]
For our example, we just have a single parameter, number_of_recharges with
a default value of 1.0:
parameter: number_of_recharges = 1.0
The corresponding URL is:
http://localhost:3000/data/product-systems/59327d11-9a0d-477b-9cc0-060ca74b6327/parameters
Finally, we run a set of calculations over a parameter range:
for x in range(0, 55, 5):
setup = o.CalculationSetup(
target=model,
impact_method=method,
parameters=[
o.ParameterRedef(name=param.name, value=x, context=param.context)
],
)
result = client.calculate(setup)
assert result
result.wait_until_ready()
impacts = result.get_total_impacts()
for i in impacts:
if i.impact_category.name == "Climate change":
print(f"{param.name}: {x} => {i.amount : .3f} kg CO2 eq")
result.dispose()
For the example, it prints something like this:
number_of_recharges: 0 => 0.788 kg CO2 eq
number_of_recharges: 5 => 0.792 kg CO2 eq
number_of_recharges: 10 => 0.796 kg CO2 eq
number_of_recharges: 15 => 0.800 kg CO2 eq
number_of_recharges: 20 => 0.803 kg CO2 eq
number_of_recharges: 25 => 0.807 kg CO2 eq
number_of_recharges: 30 => 0.811 kg CO2 eq
number_of_recharges: 35 => 0.814 kg CO2 eq
number_of_recharges: 40 => 0.818 kg CO2 eq
number_of_recharges: 45 => 0.822 kg CO2 eq
number_of_recharges: 50 => 0.826 kg CO2 eq