use of org.openlca.core.database.ProcessDao in project olca-app by GreenDelta.
the class XNexusEcoinventIndexExportAction method run.
@Override
public void run() {
DbSelectDialog dialog = new DbSelectDialog();
if (dialog.open() != IDialogConstants.OK_ID)
return;
File file = FileChooser.forSavingFile(M.Export, "ecoinvent_nexus_index.json");
if (file == null)
return;
App.runWithProgress("Creating Ecoinvent Nexus Index", () -> {
try {
Map<String, IndexEntry> index = new HashMap<>();
for (Entry e : dialog.entries) {
IDatabase db;
if (Database.get() != null && Database.get().getName().equals(e.database.name())) {
db = Database.get();
} else {
db = e.database.connect(DataDir.databases());
}
ProcessDao dao = new ProcessDao(db);
for (ProcessDescriptor descriptor : dao.getDescriptors()) {
Process process = dao.getForId(descriptor.id);
String id = getId(process);
IndexEntry entry = index.get(id);
if (entry == null) {
index.put(id, entry = new IndexEntry(process));
}
entry.name = getName(process);
entry.systemModel.add(e.systemModel);
}
db.close();
}
IndexEntry.writeEntries(index.values(), file);
} catch (Exception e) {
Log.error("Error creating ecoinvent nexus index", e);
}
});
}
use of org.openlca.core.database.ProcessDao in project olca-app by GreenDelta.
the class Exchanges method canRemove.
/**
* Checks if the given exchanges can be removed from the process. The exchanges
* cannot be removed and a corresponding error message is displayed when:
*
* <li>one of the given exchanges is the reference flow of the process
* <li>at least one of the exchanges is used in a product system
* <li>at least one of the exchanges is needed as default provider link
*/
static boolean canRemove(Process p, List<Exchange> exchanges) {
if (p == null || exchanges == null)
return false;
// check reference flow
if (p.quantitativeReference != null && exchanges.contains(p.quantitativeReference)) {
MsgBox.error(M.CannotDeleteRefFlow, M.CannotDeleteRefFlowMessage);
return false;
}
// collect product and waste flows
List<Exchange> techFlows = exchanges.stream().filter(e -> e.flow != null && e.flow.flowType != FlowType.ELEMENTARY_FLOW).collect(Collectors.toList());
if (techFlows.isEmpty())
return true;
// check usage in product systems
var usages = new ExchangeUseSearch(Database.get(), p).findUses(techFlows);
if (!usages.isEmpty()) {
MsgBox.error(M.CannotRemoveExchanges, M.ExchangesAreUsed);
return false;
}
// check provider links
List<Exchange> providers = techFlows.stream().filter(e -> (e.isInput && e.flow.flowType == FlowType.WASTE_FLOW) || (!e.isInput && e.flow.flowType == FlowType.PRODUCT_FLOW)).collect(Collectors.toList());
if (providers.isEmpty())
return true;
for (Exchange provider : providers) {
String query = "select f_owner from tbl_exchanges where " + "f_default_provider = " + p.id + " and " + "f_flow = " + provider.flow.id + "";
IDatabase db = Database.get();
AtomicReference<ProcessDescriptor> ref = new AtomicReference<>();
try {
NativeSql.on(db).query(query, r -> {
long owner = r.getLong(1);
ProcessDescriptor d = new ProcessDao(db).getDescriptor(owner);
if (d != null) {
ref.set(d);
return false;
}
return true;
});
} catch (Exception e) {
Logger log = LoggerFactory.getLogger(Exchanges.class);
log.error("Failed to query default providers " + query, e);
return false;
}
if (ref.get() == null)
continue;
// we found an usage as default provider, now we need to make sure
// that there is no other exchange with the same flow and direction
// that can fulfill this role (and that is not in the list of
// exchanges to be deleted).
boolean ok = p.exchanges.stream().filter(e -> e.id != provider.id && e.isInput == provider.isInput && e.flow != null && e.flow.id == provider.flow.id && !exchanges.contains(e)).findAny().isPresent();
if (ok)
continue;
MsgBox.error("Flow used as default provider", "This process is linked as default provider with flow `" + Strings.cut(Labels.name(provider.flow), 75) + "` in process `" + Strings.cut(Labels.name(ref.get()), 75) + "`.");
return false;
}
return true;
}
use of org.openlca.core.database.ProcessDao in project olca-modules by GreenDelta.
the class Library method syncProducts.
/**
* Returns the products of the library in matrix order. If this library has
* no product index or if this index is not in sync with the database, an
* empty option is returned.
*/
public Optional<TechIndex> syncProducts(IDatabase db) {
var processes = descriptors(new ProcessDao(db));
var products = descriptors(new FlowDao(db));
TechIndex index = null;
var proto = getProductIndex();
int size = proto.getProductCount();
for (int i = 0; i < size; i++) {
var entry = proto.getProduct(i);
var process = processes.get(entry.getProcess().getId());
var product = products.get(entry.getProduct().getId());
if (process == null || product == null)
return Optional.empty();
if (index == null) {
index = new TechIndex(TechFlow.of(process, product));
} else {
index.add(TechFlow.of(process, product));
}
}
return Optional.ofNullable(index);
}
use of org.openlca.core.database.ProcessDao in project olca-modules by GreenDelta.
the class ProcessWriter method map.
private void map(Exchange e, JsonObject obj) {
Json.put(obj, "@type", Exchange.class.getSimpleName());
Json.put(obj, "isAvoidedProduct", e.isAvoided);
Json.put(obj, "isInput", e.isInput);
Json.put(obj, "baseUncertainty", e.baseUncertainty);
Json.put(obj, "amount", e.amount);
Json.put(obj, "amountFormula", e.formula);
Json.put(obj, "dqEntry", e.dqEntry);
Json.put(obj, "description", e.description);
Json.put(obj, "costFormula", e.costFormula);
Json.put(obj, "costValue", e.costs);
Json.put(obj, "currency", exp.handleRef(e.currency));
Json.put(obj, "internalId", e.internalId);
Json.put(obj, "location", exp.handleRef(e.location));
Json.put(obj, "flow", exp.handleRef(e.flow));
Json.put(obj, "unit", Json.asRef(e.unit));
var property = e.flowPropertyFactor != null ? e.flowPropertyFactor.flowProperty : null;
Json.put(obj, "flowProperty", exp.handleRef(property));
Json.put(obj, "uncertainty", Uncertainties.map(e.uncertainty));
// default provider
if (e.defaultProviderId == 0L || exp.db == null)
return;
if (exp.exportProviders) {
Json.put(obj, "defaultProvider", exp.handleRef(ModelType.PROCESS, e.defaultProviderId));
} else {
var d = new ProcessDao(exp.db).getDescriptor(e.defaultProviderId);
Json.put(obj, "defaultProvider", Json.asRef(d));
}
}
use of org.openlca.core.database.ProcessDao in project olca-modules by GreenDelta.
the class AutoTagger method run.
@Override
public void run() {
// compute statistics
var stats = new HashMap<String, Integer>();
var paths = Categories.pathsOf(db);
var descriptors = new ProcessDao(db).descriptorMap();
descriptors.forEachValue(d -> {
addToStats(d.name, stats);
if (d.category != null) {
addToStats(paths.pathOf(d.category), stats);
}
return true;
});
// add auto-tags
var sql = "select id, tags from tbl_processes";
NativeSql.on(db).updateRows(sql, r -> {
var d = descriptors.get(r.getLong(1));
if (d == null)
return true;
// do nothing if there are already tags present
var tags = r.getString(2);
if (!Strings.nullOrEmpty(tags))
return true;
var candidates = new HashSet<>(words(d.name));
if (d.category != null) {
candidates.addAll(words(paths.pathOf(d.category)));
}
var tagList = candidates.stream().map(word -> Pair.of(word, stats.getOrDefault(word, 0))).filter(pair -> pair.second > 0).sorted((pair1, pair2) -> pair2.second - pair1.second).limit(maxTagCount).map(pair -> pair.first).toArray(String[]::new);
if (tagList.length == 0)
return true;
tags = String.join(",", tagList);
r.updateString(2, tags);
r.updateRow();
return true;
});
db.clearCache();
}
Aggregations