Search in sources :

Example 6 with ProductSystemDao

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);
}
Also used : ProcessDao(org.openlca.core.database.ProcessDao) LinkingConfig(org.openlca.core.matrix.linking.LinkingConfig) ProductSystemBuilder(org.openlca.core.matrix.ProductSystemBuilder) JsonObject(com.google.gson.JsonObject) ProductSystemDao(org.openlca.core.database.ProductSystemDao) Rpc(org.openlca.ipc.Rpc)

Example 7 with ProductSystemDao

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);
}
Also used : IDatabase(org.openlca.core.database.IDatabase) Derby(org.openlca.core.database.Derby) ProcessDao(org.openlca.core.database.ProcessDao) LinkingConfig(org.openlca.core.matrix.linking.LinkingConfig) ProductSystemBuilder(org.openlca.core.matrix.ProductSystemBuilder) Process(org.openlca.core.model.Process) File(java.io.File) ProductSystemDao(org.openlca.core.database.ProductSystemDao)

Example 8 with ProductSystemDao

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);
}
Also used : ProductSystem(org.openlca.core.model.ProductSystem) ProductSystemDao(org.openlca.core.database.ProductSystemDao)

Example 9 with ProductSystemDao

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);
        }
    }
}
Also used : HashMap(java.util.HashMap) TechFlow(org.openlca.core.matrix.index.TechFlow) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet) ProductSystemDao(org.openlca.core.database.ProductSystemDao) CalculationSetup(org.openlca.core.model.CalculationSetup) LongPair(org.openlca.core.matrix.index.LongPair) SimpleResult(org.openlca.core.results.SimpleResult) ArrayDeque(java.util.ArrayDeque)

Example 10 with ProductSystemDao

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);
}
Also used : JsonImport(org.openlca.jsonld.input.JsonImport) ProductSystem(org.openlca.core.model.ProductSystem) Parameter(org.openlca.core.model.Parameter) JsonExport(org.openlca.jsonld.output.JsonExport) ProductSystemDao(org.openlca.core.database.ProductSystemDao) ParameterRedefSet(org.openlca.core.model.ParameterRedefSet) AbstractZipTest(org.openlca.jsonld.AbstractZipTest) Test(org.junit.Test)

Aggregations

ProductSystemDao (org.openlca.core.database.ProductSystemDao)14 ProcessDao (org.openlca.core.database.ProcessDao)6 ProductSystem (org.openlca.core.model.ProductSystem)6 Test (org.junit.Test)3 FlowDao (org.openlca.core.database.FlowDao)3 HashMap (java.util.HashMap)2 CategoryDao (org.openlca.core.database.CategoryDao)2 FlowPropertyDao (org.openlca.core.database.FlowPropertyDao)2 IDatabase (org.openlca.core.database.IDatabase)2 UnitGroupDao (org.openlca.core.database.UnitGroupDao)2 ProductSystemBuilder (org.openlca.core.matrix.ProductSystemBuilder)2 LinkingConfig (org.openlca.core.matrix.linking.LinkingConfig)2 ProcessLink (org.openlca.core.model.ProcessLink)2 RootDescriptor (org.openlca.core.model.descriptors.RootDescriptor)2 JsonObject (com.google.gson.JsonObject)1 TLongIntHashMap (gnu.trove.map.hash.TLongIntHashMap)1 File (java.io.File)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 ArrayDeque (java.util.ArrayDeque)1 ArrayList (java.util.ArrayList)1