Skip to content

Commit

Permalink
adding a units module
Browse files Browse the repository at this point in the history
when we want to produce JSON-LD packages from other
formats we often have only unit symbols like `kg`, `m3`
etc. available. But in the openLCA JSON-LD format
each unit is contained in a unit group and flow
amounts are not only given in a unit but in a unit of
a specific quantity (e.g. `m3 volume` vs.
`m3 norm volume`). So when we have a unit symbol for
an amount we need to get the references to the entities
of the corresponding classes:

* Unit
* UnitGroup
* FlowProperty

```
import olca.units as units

units.unit_ref(unit_symbol: str) -> Ref
units.group_ref(unit_symbol: str) -> Ref
units.property_ref(unit_symbol: str) -> Ref
```

we store the inits as a data file of this package. it
is a simple CSV file that can be generated via the
following Python script in openLCA

```python
import org.openlca.app.db.Database as DB
import org.openlca.io.UnitMapping as UnitMapping

import codecs
import csv

with codecs.open("C:/Users/Besitzer/Desktop/units.csv", "wb", encoding="utf-8") as f:
  w = csv.writer(f)
  w.writerow([
    "unit name",
    "unit uuid",
    "unit group name",
    "unit group uuid",
    "flow property name",
    "flow property uuid"
  ])
  mapping = UnitMapping.createDefault(DB.get())
  for uname in mapping.getUnits():
    group = mapping.getUnitGroup(uname)
    unit = group.getUnit(uname)
    prop = mapping.getFlowProperty(uname)
    w.writerow([
      uname,
      unit.refId,
      group.name,
      group.refId,
      prop.name,
      prop.refId
    ])
  • Loading branch information
msrocka committed May 20, 2019
1 parent 9566e2b commit 2643997
Show file tree
Hide file tree
Showing 7 changed files with 370 additions and 6 deletions.
12 changes: 7 additions & 5 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
.idea/
*/__pycache__/
*.egg-info/
build/
dist/
/.idea/
/*/__pycache__/
/*.egg-info/
/build/
/dist/
/env/
/.vscode/
1 change: 1 addition & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
include olca/units/units.csv
54 changes: 54 additions & 0 deletions olca/units/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import csv
import os.path as path

from typing import Optional

import olca

_unit_refs = None
_group_refs = None
_prop_refs = None


def _init():
global _unit_refs, _group_refs, _prop_refs
_unit_refs = {}
_group_refs = {}
_prop_refs = {}

fpath = path.join(path.dirname(__file__), 'units.csv')
with open(fpath, 'r', encoding='utf-8') as f:
r = csv.reader(f)
next(r)
for row in r:
unit = row[0]
_unit_refs[unit] = olca.ref(olca.Unit, row[1], unit)
_group_refs[unit] = olca.ref(olca.UnitGroup, row[3], row[2])
_prop_refs[unit] = olca.ref(olca.FlowProperty, row[5], row[4])


def unit_ref(symbol: str) -> Optional[olca.Ref]:
"""Get the unit reference (an instance of olca.Ref) for the given unit
symbol (a string like 'kg'). Returns `None` if the given unit is
unknown."""
if _unit_refs is None:
_init()
return _unit_refs.get(symbol)


def group_ref(symbol: str) -> Optional[olca.Ref]:
"""Get the unit group reference (an instance of olca.Ref) for the given
unit symbol (a string like 'kg'). Returns `None` if the given unit is
unknown."""
if _group_refs is None:
_init()
return _group_refs.get(symbol)


def property_ref(symbol: str) -> Optional[olca.Ref]:
"""Get the reference (an instance of olca.Ref) to the default flow property
(quantity) for the given unit symbol (a string like 'kg'). Returns
`None` if the given unit is unknown."""
if _prop_refs is None:
_init()
return _prop_refs.get(symbol)
274 changes: 274 additions & 0 deletions olca/units/units.csv

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
requests>=2.22.0
3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@

setup(
name='olca-ipc',
version='0.0.7',
version='0.0.8',
description='A Python package for calling openLCA functions from Python.',
long_description=long_description,
url='https://github.com/GreenDelta/olca-ipc.py',
packages=['olca'],
install_requires=['requests'],
include_package_data=True,
keywords=['openLCA', 'life cycle assessment', 'LCA'],
classifiers=[
"Development Status :: 2 - Pre-Alpha",
Expand Down
31 changes: 31 additions & 0 deletions tests/test_units.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import unittest

import olca.units as units


class TestUnits(unittest.TestCase):

def test_unit_ref(self):
ref = units.unit_ref('m2')
self.assertEqual(
'3ce61faa-5716-41c1-aef6-b5920054acc9',
ref.id),
self.assertEqual('m2', ref.name)

def test_group_ref(self):
ref = units.group_ref('m2')
self.assertEqual(
'93a60a57-a3c8-18da-a746-0800200c9a66',
ref.id),
self.assertEqual('Units of area', ref.name)

def test_prop_ref(self):
ref = units.property_ref('m2')
self.assertEqual(
'93a60a56-a3c8-19da-a746-0800200c9a66',
ref.id),
self.assertEqual('Area', ref.name)


if __name__ == '__main__':
unittest.main()

0 comments on commit 2643997

Please sign in to comment.