Skip to content

Commit

Permalink
Init MD book
Browse files Browse the repository at this point in the history
  • Loading branch information
francoislerall committed Dec 2, 2024
1 parent 4bc41c6 commit e69f103
Show file tree
Hide file tree
Showing 37 changed files with 2,211 additions and 2 deletions.
56 changes: 56 additions & 0 deletions .github/workflows/mdbook.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Sample workflow for building and deploying a mdBook site to GitHub Pages
#
# To get started with mdBook see: https://rust-lang.github.io/mdBook/index.html
#
name: Deploy mdBook site to Pages

on:
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:

# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write

# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
group: "pages"
cancel-in-progress: false

jobs:
# Build job
build:
runs-on: ubuntu-latest
env:
MDBOOK_VERSION: 0.4.36
steps:
- uses: actions/checkout@v4
- name: Install mdBook
run: |
curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf -y | sh
rustup update
cargo install --version ${MDBOOK_VERSION} mdbook
- name: Setup Pages
id: pages
uses: actions/configure-pages@v5
- name: Build with mdBook
run: mdbook build
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: ./book

# Deployment job
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
needs: build
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
*.bak
mdbook.exe
mdbook
/book
29 changes: 27 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,27 @@
# openLCAJython-manual
The manual to create Jython (Python) script in openLCA
# openLCA Jython manual

The manual is created using [mdBook](https://rust-lang.github.io/mdBook/index.html) and can be browsed on its Github page: https://greendelta.github.io/openLCA2-manual/.

In order to publish your changes to the manual, make sure that the `main` branch is up to date and click on _Run workflow_ on the [Deploy mdBook site to Pages](https://github.com/GreenDelta/openLCAJython-manual/actions/workflows/mdbook.yml).

The openLCA Jython manual is compiled from the resources in this repository using [mdBook](https://github.com/rust-lang/mdBook). Thus, you need to have the `mdbook` executable installed (one simple option is to just download the `mdbook` executable from the [mdBook releases page](https://github.com/rust-lang/mdBook/releases) and put it next to the `book.toml` file at the root of this project). Then you can run the build from the command line:

```bash
cd PATH/TO/openLCAJython-manual
mdbook build
```

In order to vizualise your change while working, use the following command:

```bash
cd PATH/TO/openLCAJython-manual
mdbook serve --open
```

See also the [mdBook tutorial](https://rust-lang.github.io/mdBook/index.html) for more options to test the book locally.

## License
This project is in the worldwide public domain, released under the
[CC0 1.0 Universal Public Domain Dedication](https://creativecommons.org/publicdomain/zero/1.0/).

![Public Domain Dedication](https://licensebuttons.net/p/zero/1.0/88x31.png)
7 changes: 7 additions & 0 deletions book.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[book]
authors = ["GreenDelta GmbH"]
language = "en"
multilingual = false
src = "src"
title = "openLCA Jython Manual"
theme = "Rust"
10 changes: 10 additions & 0 deletions print-style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/* Show the details content when printing */
@media print {
details {
display: block !important;
}

summary {
display: none;
}
}
10 changes: 10 additions & 0 deletions print-style.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Show the details content when printing
function showDetailsForPrint() {
var detailsElements = document.querySelectorAll("details");
detailsElements.forEach(function(details) {
details.setAttribute("open", "");
});
}

// Run the function when the page is being printed
window.addEventListener("beforeprint", showDetailsForPrint);
150 changes: 150 additions & 0 deletions scripts/v1/example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
from org.openlca.core.database.derby import DerbyDatabase
from java.io import File
import org.openlca.core.model as model
from org.openlca.core.database import UnitGroupDao, FlowPropertyDao, CategoryDao,\
FlowDao, Daos, EntityCache
from java.util import UUID, Date
from org.openlca.core.model import FlowPropertyFactor

import scripts.v1.util as util
from org.openlca.core.matrix import ProductSystemBuilder
from org.openlca.core.math import CalculationSetup, SystemCalculator
from org.openlca.eigen import NativeLibrary
from org.openlca.eigen.solvers import DenseSolver
from org.openlca.core.matrix.cache import MatrixCache
from org.openlca.core.results import FullResultProvider

folder = 'C:/Users/Besitzer/openLCA-data-1.4/databases/example_db1'
db = DerbyDatabase(File(folder))

mass = util.find(db, model.FlowProperty, 'Mass')
if mass is None:

kg = model.Unit()
kg.name = 'kg'
kg.conversionFactor = 1.0

mass_units = model.UnitGroup()
mass_units.name = 'Units of mass'
mass_units.units.add(kg)
mass_units.referenceUnit = kg
mass_units.refId = UUID.randomUUID().toString()
dao = UnitGroupDao(db)
dao.insert(mass_units)

mass = model.FlowProperty()
mass.name = 'Mass'
mass.unitGroup = mass_units
mass.flowPropertyType = model.FlowPropertyType.PHYSICAL
fpDao = FlowPropertyDao(db)
fpDao.insert(mass)

#util.insert(db, flow)
#util.delete_all(db, model.Flow)
#util.delete_all(db, model.Category)

steel = util.create_flow(db, 'Steel', mass)
co2 = util.create_flow(db, 'CO2', mass,
flow_type=model.FlowType.ELEMENTARY_FLOW)

param = util.find(db, model.Parameter, 'param')
if param is None:
param = model.Parameter()
param.name = 'param'
param.scope = model.ParameterScope.GLOBAL
param.inputParameter = True
param.value = 42.0
util.insert(db, param)

steel_production = util.find(db, model.Process, 'Steel production')
if steel_production is None:
steel_production = model.Process()
steel_production.name = 'Steel production'
steel_output = util.create_exchange(steel, 1.0)
steel_production.exchanges.add(steel_output)
co2_output = util.create_exchange(co2, 42)
co2_output.amountFormula = '0.5 * param'
steel_production.exchanges.add(co2_output)
steel_production.quantitativeReference = steel_output
util.insert(db, steel_production)

product = util.create_flow(db, 'Product', mass)
manufacturing = util.find(db, model.Process, 'Manufacturing')
if manufacturing is None:
manufacturing = model.Process()
manufacturing.name = 'Manufacturing'
product_output = util.create_exchange(product, 1.0)
manufacturing.exchanges.add(product_output)
manufacturing.quantitativeReference = product_output
steel_input = util.create_exchange(steel, 0.5, is_input=True)
steel_input.defaultProviderId = steel_production.id
manufacturing.exchanges.add(steel_input)
util.insert(db, manufacturing)

system = util.find(db, model.ProductSystem, 'My System')
if system is None:
system = model.ProductSystem()
system.name = 'My System'

system.referenceProcess = manufacturing
qref = manufacturing.quantitativeReference
system.referenceExchange = qref
system.targetAmount = 1000
system.targetFlowPropertyFactor = qref.flowPropertyFactor
system.targetUnit = qref.unit

system.getProcesses().add(manufacturing.id)
system.getProcesses().add(steel_production.id)

link = model.ProcessLink()
link.providerId = steel_production.id
link.flowId = steel.id
link.processId = manufacturing.id
link.exchangeId = util.find_exchange(steel, manufacturing).id
system.processLinks.add(link)

util.insert(db, system)

# you could also use the auto-complete function:
# see: http://greendelta.github.io/olca-modules/olca-core/apidocs/index.html
# build = ProductSystemBuilder(...)
# ProductSystemBuilder.autoComplete(system)

NativeLibrary.loadFromDir(File('native_lib'))
solver = DenseSolver()
m_cache = MatrixCache.createEager(db)


redef = model.ParameterRedef()
redef.value = 10
redef.name = 'param'

setup = CalculationSetup(system)
setup.parameterRedefs.add(redef)

calculator = SystemCalculator(m_cache, solver)
result = calculator.calculateFull(setup)

e_cache = EntityCache.create(db)
result_provider = FullResultProvider(result, e_cache)

import csv

csv_file = open('result.csv', 'wb')
writer = csv.writer(csv_file)

for fd in result_provider.flowDescriptors:
for pd in result_provider.processDescriptors:
val = result_provider.getSingleFlowResult(pd, fd)
writer.writerow([pd.name, fd.name, val.value])
print pd.name, fd.name, val.value

import random
for i in range(1, 10):
redef.value = 42 * random.random()
result = calculator.calculateFull(setup)
print result.totalFlowResults

csv_file.close()
db.close()

111 changes: 111 additions & 0 deletions scripts/v1/patches/ei3_uncertainty_patch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
# Patch for ecoinvent 3.x uncertainty data in openLCA
The script below fixes the uncertainty data of an ecoinvent 3.x database in
openLCA as described in the
[openLCA forum](http://forum.openlca.org/viewtopic.php?f=26&t=32357). It copies
the current `gsigma` value into the basic uncertainty field and calculates the
total uncertainty from the respective Pedigree matrix entry and the basic
uncertainty. To run the script, modify the database path in the `main` method
below and ensure that the database is closed.

**Before running this script you should backup your database.**

```python
import java.lang.Math as Math
from java.io import File

from org.openlca.core.database.derby import DerbyDatabase

# see https://www.ecoinvent.org/files/dataqualityguideline_ecoinvent_3_20130506.pdf
# pp. 77
factors = [
[0.000, 0.0006, 0.002, 0.008, 0.04], # Reliability
[0.000, 0.0001, 0.0006, 0.002, 0.008], # Completeness
[0.000, 0.0002, 0.002, 0.008, 0.04], # Temporal correlation
[0.000, 2.5e-5, 0.0001, 0.0006, 0.002], # Geographical correlation
[0.000, 0.0006, 0.008, 0.04, 0.12] # Further technological correlation
]


def main():
# change the path to the database here; note that the database
# has to be closed in openLCA
db_path = 'C:/Users/Besitzer/openLCA-data-1.4/databases/ecoinvent_3_3_apos_gdfix'
db = DerbyDatabase(File(db_path))
update_exchanges(db)
db.close()


def gsd2var(gsd):
sigma = Math.log(gsd)
var = Math.pow(sigma, 2)
return var


def var2gsd(var):
sigma = Math.sqrt(var)
gsd = Math.exp(sigma)
return gsd


def total_gsd(entry, basic_gsd):
""" Calculates the total uncertainty from the given Pedigree
matrix entry and basic uncertainty """
e = entry.strip()
scores = e[1:len(e)-1].split(';')
var_sum = gsd2var(basic_gsd)
for i in range(0, len(scores)):
if i >= len(factors):
print('Invalid entry %s' % entry)
break
row = factors[i]
s = scores[i].strip()
if s == 'n.a.':
continue
try:
idx = int(s) - 1
if idx >= len(row):
print('Invalid entry %s' % entry)
break
var_sum += row[idx]
except e:
print('Invalid entry %s' % entry)
break
return var2gsd(var_sum)


def update_exchanges(db):
con = db.createConnection()
con.setAutoCommit(False)
stmt = con.createStatement()
stmt.setCursorName('E_UPDATE')
query = """ SELECT distribution_type, parameter2_value, dq_entry
FROM tbl_exchanges FOR UPDATE OF parameter2_value,
base_uncertainty """
cursor = stmt.executeQuery(query)
update_stmt = """ UPDATE tbl_exchanges SET parameter2_value = ?,
base_uncertainty = ? WHERE CURRENT OF E_UPDATE """
update = con.prepareStatement(update_stmt)
i = 0
while cursor.next():
distribution_type = cursor.getInt(1)
basic_gsd = cursor.getDouble(2)
dq_entry = cursor.getString(3)
if distribution_type != 1 or dq_entry is None:
continue
total = total_gsd(dq_entry, basic_gsd)
update.setDouble(1, total)
update.setDouble(2, basic_gsd)
update.executeUpdate()
i += 1
cursor.close()
stmt.close()
update.close()
con.commit()
con.close()
print('%i exchanges updated' % i)


if __name__ == '__main__':
main()

```
Loading

0 comments on commit e69f103

Please sign in to comment.