use of org.openlca.core.database.ProductSystemDao in project olca-modules by GreenDelta.
the class ModelHandler method createProductSystem.
@Rpc("create/product_system")
public RpcResponse createProductSystem(RpcRequest req) {
if (req.params == null || !req.params.isJsonObject())
return Responses.invalidParams("params must be an object with valid processId", req);
var obj = req.params.getAsJsonObject();
if (!obj.has("processId") || !obj.get("processId").isJsonPrimitive())
return Responses.invalidParams("params must be an object with valid processId", req);
var processId = obj.get("processId").getAsString();
if (Strings.nullOrEmpty(processId))
return Responses.invalidParams("params must be an object with valid processId", req);
var refProcess = new ProcessDao(db).getForRefId(processId);
if (refProcess == null)
return Responses.invalidParams("No process found for ref id " + processId, req);
var system = ProductSystem.of(refProcess);
system = new ProductSystemDao(db).insert(system);
var config = new LinkingConfig().preferredType(ProcessType.UNIT_PROCESS);
if (obj.has("preferredType") && obj.get("preferredType").getAsString().equalsIgnoreCase("lci_result")) {
config.preferredType(ProcessType.LCI_RESULT);
}
config.providerLinking(ProviderLinking.PREFER_DEFAULTS);
if (obj.has("providerLinking")) {
if (obj.get("providerLinking").getAsString().equalsIgnoreCase("ignore")) {
config.providerLinking(ProviderLinking.IGNORE_DEFAULTS);
} else if (obj.get("providerLinking").getAsString().equalsIgnoreCase("only")) {
config.providerLinking(ProviderLinking.ONLY_DEFAULTS);
}
}
var builder = new ProductSystemBuilder(MatrixCache.createLazy(db), config);
builder.autoComplete(system);
system = ProductSystemBuilder.update(db, system);
var res = new JsonObject();
res.addProperty("@id", system.refId);
return Responses.ok(res, req);
}
use of org.openlca.core.database.ProductSystemDao in project olca-modules by GreenDelta.
the class ProductSystemBuilderExample method main.
public static void main(String[] args) {
String dbPath = "C:/Users/Besitzer/openLCA-data-1.4/databases/ecoinvent_2_2_unit";
IDatabase db = new Derby(new File(dbPath));
// load the reference process of the new product system
Process p = new ProcessDao(db).getForRefId("81261285-cc4a-3588-8cce-3aabb786d7aa");
// create and auto-complete the product system
var config = new LinkingConfig().providerLinking(ProviderLinking.PREFER_DEFAULTS).preferredType(ProcessType.UNIT_PROCESS);
var system = new ProductSystemBuilder(MatrixCache.createLazy(db), config).build(p);
// save the product system
new ProductSystemDao(db).insert(system);
}
use of org.openlca.core.database.ProductSystemDao in project olca-modules by GreenDelta.
the class ProductSystemImport method copy.
private void copy(ProductSystemDescriptor descriptor) {
ProductSystem srcSystem = srcDao.getForId(descriptor.id);
ProductSystem destSystem = srcSystem.copy();
destSystem.refId = srcSystem.refId;
destSystem.category = refs.switchRef(srcSystem.category);
destSystem.referenceProcess = refs.switchRef(srcSystem.referenceProcess);
switchRefExchange(srcSystem, destSystem);
destSystem.targetUnit = refs.switchRef(srcSystem.targetUnit);
switchRefFlowProp(srcSystem, destSystem);
switchParameterRedefs(destSystem);
ProductSystemDao destDao = new ProductSystemDao(dest);
ProductSystemLinks.map(source, dest, destSystem);
destSystem = destDao.insert(destSystem);
seq.put(seq.PRODUCT_SYSTEM, srcSystem.refId, destSystem.id);
}
use of org.openlca.core.database.ProductSystemDao in project olca-modules by GreenDelta.
the class Simulator method init.
private void init(IDatabase db, CalculationSetup setup) {
long rootID = setup.hasProductSystem() ? setup.productSystem().id : setup.process().id;
if (!setup.hasProductSystem()) {
root = new Node(setup, db, Collections.emptyMap());
nodeIndex.put(root.systemID, root);
return;
}
// check whether the root system has sub-system links;
// only when this is true we need to collect and order
// the sub-system relations
boolean hasSubSystems = false;
for (var link : setup.productSystem().processLinks) {
if (link.hasSubSystemProvider()) {
hasSubSystems = true;
break;
}
}
if (!hasSubSystems) {
root = new Node(setup, db, Collections.emptyMap());
nodeIndex.put(root.systemID, root);
return;
}
// systems contains the IDs of all product systems;
// with this we can quickly check if an ID is an
// ID of a product system
HashSet<Long> systems = new HashSet<>();
String sql = "select id from tbl_product_systems";
try {
NativeSql.on(db).query(sql, r -> {
systems.add(r.getLong(1));
return true;
});
} catch (Exception e) {
throw new RuntimeException("failed to collect product system IDs", e);
}
// allRels contains the sub-system relations of each product system
// in the database as: hostSystemID -> (subSystemID, hostSystemID)*
Map<Long, List<LongPair>> allRels = new HashMap<>();
sql = "select f_product_system, f_provider from tbl_process_links";
try {
NativeSql.on(db).query(sql, r -> {
long provider = r.getLong(2);
if (!systems.contains(provider))
return true;
long system = r.getLong(1);
List<LongPair> rels = allRels.computeIfAbsent(system, k -> new ArrayList<>());
rels.add(LongPair.of(provider, system));
return true;
});
} catch (Exception e) {
throw new RuntimeException("failed to collect sub-system relations", e);
}
// now collect the sub-system relations that we need to consider
HashSet<LongPair> sysRels = new HashSet<>();
Queue<Long> queue = new ArrayDeque<>();
queue.add(rootID);
HashSet<Long> handled = new HashSet<>();
handled.add(rootID);
while (!queue.isEmpty()) {
long nextID = queue.poll();
List<LongPair> rels = allRels.get(nextID);
if (rels == null)
continue;
sysRels.addAll(rels);
for (LongPair rel : rels) {
long subSystem = rel.first();
if (handled.contains(subSystem))
continue;
queue.add(subSystem);
handled.add(subSystem);
}
}
// now we can initialize the nodes in topological order
List<Long> order = TopoSort.of(sysRels);
if (order == null)
throw new RuntimeException("there are sub-system cycles in the product system");
// now, we initialize the nodes in topological order
Map<TechFlow, SimpleResult> subResults = new HashMap<>();
for (long system : order) {
CalculationSetup _setup;
if (system == rootID) {
_setup = setup;
} else {
// create node for LCI and LCC data simulation
// do *not* copy the LCIA method here
var dao = new ProductSystemDao(db);
var subSystem = dao.getForId(system);
_setup = CalculationSetup.monteCarlo(subSystem, setup.numberOfRuns()).withParameters(ParameterRedefs.join(setup, subSystem)).withCosts(setup.hasCosts()).withAllocation(setup.allocation());
}
Node node = new Node(_setup, db, subResults);
nodeIndex.put(system, node);
if (system == rootID) {
root = node;
} else {
subNodes.add(node);
// for the sub-nodes we need to initialize an empty
// result so that the respective host-systems will
// be initialized with the correct matrix shapes (
// e.g. flows that only occur in a sub-system
// need a row in the respective host-systems)
var r = SimpleResultProvider.of(node.data.techIndex).withFlowIndex(node.data.enviIndex).withTotalFlows(new double[node.data.enviIndex.size()]).toResult();
node.lastResult = r;
subResults.put(node.product, r);
}
}
// the we do not need to collect them in the simulation
for (Node node : nodeIndex.values()) {
List<LongPair> subRels = allRels.get(node.systemID);
if (subRels == null || subRels.isEmpty())
continue;
node.subSystems = new HashSet<>();
for (LongPair rel : subRels) {
Node subNode = nodeIndex.get(rel.first());
if (subNode == null)
continue;
node.subSystems.add(subNode.product);
}
}
}
use of org.openlca.core.database.ProductSystemDao in project olca-modules by GreenDelta.
the class ParameterRedefTest method testInParameterRedefSet.
@Test
public void testInParameterRedefSet() {
// create the model
ProductSystemDao dao = new ProductSystemDao(db);
ProductSystem sys = new ProductSystem();
sys.refId = UUID.randomUUID().toString();
ParameterRedefSet paramSet = new ParameterRedefSet();
sys.parameterSets.add(paramSet);
paramSet.isBaseline = true;
paramSet.name = "Baseline";
paramSet.parameters.add(redef);
dao.insert(sys);
// write and clear DB
with(zip -> new JsonExport(Tests.getDb(), zip).write(sys));
db.clear();
Assert.assertNull(dao.getForRefId(sys.refId));
Assert.assertNull(paramDao.getForRefId(globalParam.refId));
// import and check
with(zip -> new JsonImport(zip, db).run());
ProductSystem sys2 = dao.getForRefId(sys.refId);
Assert.assertEquals("R", sys2.parameterSets.get(0).parameters.get(0).name);
Parameter p = paramDao.getForRefId(globalParam.refId);
Assert.assertEquals("R", p.name);
}
Aggregations