Skip to content

Commit

Permalink
feat: added functionality for LCAbyg data
Browse files Browse the repository at this point in the history
  • Loading branch information
ocni-dtu committed Mar 24, 2024
1 parent d294c3a commit 0ac8276
Show file tree
Hide file tree
Showing 13 changed files with 308 additions and 115 deletions.
4 changes: 2 additions & 2 deletions docs/code/python/usage.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
print(json.dumps(epd_dict, indent=2))

print("\nEPD as Pydantic model")
epd_pydantic = epdx.convert_ilcd(ilcd_file.read_text(), as_type="pydantic")
epd_pydantic = epdx.convert_ilcd(ilcd_file.read_text(), as_type=epdx.EPD)
print(epd_pydantic)

print("\nEPD as string")
epd_str = epdx.convert_ilcd(ilcd_file.read_text(), as_type="str")
epd_str = epdx.convert_ilcd(ilcd_file.read_text(), as_type=str)
print(epd_str)
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
name = "epdx"
description = "EPDx is a library for parsing EPD files into a common exchange format."
readme = "README.md"
requires-python = ">=3.8"
requires-python = ">=3.10"
license = { file = "LICENSE" }
authors = [
{ name = "Christian Kongsgaard", email = "christian@kongsgaard.eu" },
Expand Down
284 changes: 230 additions & 54 deletions src/epd.rs

Large diffs are not rendered by default.

45 changes: 20 additions & 25 deletions src/ilcd.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
#[allow(dead_code)]
use serde::{Deserialize};
use serde::Deserialize;
use serde::Serialize;


#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ILCD {
Expand All @@ -11,7 +10,7 @@ pub struct ILCD {
pub exchanges: Exchanges,
#[serde(alias = "LCIAResults")]
pub lcia_results: LCIAResults,
pub version: String
pub version: String,
}

#[derive(Deserialize)]
Expand All @@ -20,7 +19,6 @@ pub struct Exchanges {
pub exchange: Vec<Exchange>,
}


#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Exchange {
Expand All @@ -37,10 +35,9 @@ pub struct Exchange {

#[serde(alias = "exchange direction")]
pub exchange_direction: Option<String>,
pub other: Option<LCIAAnies>
pub other: Option<LCIAAnies>,
}


#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FlowProperty {
Expand All @@ -50,7 +47,7 @@ pub struct FlowProperty {
pub reference_flow_property: Option<bool>,
pub reference_unit: Option<String>,
#[serde(alias = "unitGroupUUID")]
pub unit_group_uuid: Option<String>
pub unit_group_uuid: Option<String>,
}

#[derive(Deserialize, Serialize)]
Expand All @@ -67,7 +64,7 @@ pub struct MaterialProperty {
pub struct ModellingAndValidation {
#[serde(alias = "LCIMethodAndAllocation")]
pub lci_method_and_allocation: LCIMethodAndAllocation,
pub compliance_declarations: ComplianceDeclarations
pub compliance_declarations: ComplianceDeclarations,
}

#[derive(Deserialize)]
Expand All @@ -88,10 +85,9 @@ pub struct ReferenceToDescription {
pub short_description: Vec<ValueLang>,
pub _type: String,
// pub ref_object_id: Option<String>,
pub version: Option<String>
pub version: Option<String>,
}


#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LCIAResults {
Expand All @@ -104,23 +100,22 @@ pub struct LCIAResults {
pub struct LCIAResult {
#[serde(alias = "referenceToLCIAMethodDataSet")]
pub reference_to_lcia_method_dataset: ReferenceToLCIAMethodDataSet,
pub other: LCIAAnies
pub other: LCIAAnies,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct LCIAAnies {
pub anies: Vec<ModuleAnie>
pub anies: Vec<ModuleAnie>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ModuleAnie {
pub module: Option<String>,
pub value: Option<AnieValue>
pub value: Option<AnieValue>,
}


#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum AnieValue {
Expand All @@ -135,7 +130,7 @@ impl From<&AnieValue> for f64 {
// Parse the string into a float
let float_value = s.parse::<f64>().unwrap();
float_value
},
}
AnieValue::ValueObject(_) => {
panic!("Cannot convert AnieValue::ValueObject to f64");
}
Expand All @@ -154,12 +149,12 @@ pub struct ValueObject {
#[derive(Deserialize, Debug)]
pub enum ModuleValue {
Value(String),
Name(ModuleMap)
Name(ModuleMap),
}

#[derive(Deserialize, Debug)]
pub struct ModuleMap {
name: String
name: String,
}

#[derive(Deserialize, Debug)]
Expand All @@ -177,34 +172,34 @@ pub struct LCIMethodAndAllocation {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Anies {
pub anies: Vec<Anie>
pub anies: Vec<Anie>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Anie {
pub name: String,
pub value: String
pub value: String,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessInformation {
pub data_set_information: DataSetInformation,
pub time: TimeData,
pub geography: Geography
pub geography: Geography,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Geography {
pub location_of_operation_supply_or_production: LocationOfOperationSupplyOrProduction
pub location_of_operation_supply_or_production: LocationOfOperationSupplyOrProduction,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LocationOfOperationSupplyOrProduction {
pub location: String
pub location: String,
}

#[derive(Deserialize)]
Expand All @@ -219,7 +214,7 @@ pub struct TimeData {
pub struct DataSetInformation {
#[serde(alias = "UUID")]
pub uuid: String,
pub name: DataSetName
pub name: DataSetName,
}

#[derive(Deserialize)]
Expand All @@ -231,5 +226,5 @@ pub struct DataSetName {
#[derive(Deserialize, Debug)]
pub struct ValueLang {
pub value: String,
pub lang: String
}
pub lang: String,
}
6 changes: 2 additions & 4 deletions src/javascript.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use wasm_bindgen::prelude::*;
use crate::epd::EPD;
use crate::parse;

use wasm_bindgen::prelude::*;

// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
Expand All @@ -20,7 +19,6 @@ pub fn convertIlcd(json: String) -> Result<EPD, JsError> {
let epd = parse::parse_ilcd(json);
match epd {
Ok(epd) => Ok(epd),
Err(error) => Err(JsError::new(error.to_string().as_str()))
Err(error) => Err(JsError::new(error.to_string().as_str())),
}
}

22 changes: 13 additions & 9 deletions src/lcabyg.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
use serde::{Deserialize, Serialize};

use crate::epd::{Conversion, EPD, ImpactCategory, Source, Standard, SubType, Unit};
use crate::epd::{Conversion, ImpactCategory, Source, Standard, SubType, Unit, EPD};
use crate::utils::get_version;


#[derive(Deserialize, Serialize)]
pub enum Nodes {
Node(Node),
}


#[derive(Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum Node {
Stage(Stage)
Stage(Stage),
}

#[derive(Serialize, Deserialize, Clone)]
Expand Down Expand Up @@ -76,7 +74,11 @@ impl From<&Vec<Stage>> for EPD {
let mut penr = ImpactCategory::new();

for stage in stages {
let stage_name = if stage.stage == "A1to3" { "A1A3" } else { &stage.stage };
let stage_name = if stage.stage == "A1to3" {
"A1A3"
} else {
&stage.stage
};

ep.add(stage_name, stage.indicators.ep);
odp.add(stage_name, stage.indicators.odp);
Expand Down Expand Up @@ -134,13 +136,15 @@ impl From<&Vec<Stage>> for EPD {
format_version: get_version(),
reference_service_life: None,
location: "".to_string(),
conversions: Some(vec![
Conversion { to: Unit::KG, value: node.mass_factor, meta_data: "".to_string() }
]),
conversions: Some(vec![Conversion {
to: Unit::KG,
value: node.mass_factor,
meta_data: "".to_string(),
}]),
perm: None,
meta_data: None,
};

epd
}
}
}
10 changes: 5 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
pub mod epd;
#[allow(dead_code)]
pub mod ilcd;
mod utils;
pub mod parse;
pub mod epd;
pub mod lcabyg;
pub mod parse;
mod utils;

#[cfg(feature = "jsbindings")]
mod javascript;
Expand All @@ -16,6 +16,6 @@ pub fn convert_ilcd(json: String) -> String {
let epd = parse::parse_ilcd(json);
match epd {
Ok(epd) => serde_json::to_string(&epd).unwrap(),
Err(_) => String::from("")
Err(_) => String::from(""),
}
}
}
4 changes: 2 additions & 2 deletions src/parse.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use serde_json::Error;
use crate::epd::EPD;
use serde_json::Error;

/// Parse a ILCD formatted EPD in an EPDx struct
///
Expand All @@ -12,6 +12,6 @@ pub fn parse_ilcd(json: String) -> Result<EPD, Error> {
let epd = serde_json::from_str(&json);
match epd {
Ok(epd) => Ok(epd),
Err(err) => Err(err)
Err(err) => Err(err),
}
}
8 changes: 4 additions & 4 deletions src/python.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use pyo3::prelude::*;
use pyo3::exceptions::PyTypeError;
use crate::parse;
use pyo3::exceptions::PyTypeError;
use pyo3::prelude::*;

#[cfg(feature = "pybindings")]
#[pyfunction]
pub fn _convert_ilcd(json: String) -> PyResult<String> {
let epd = parse::parse_ilcd(json);
match epd {
Ok(epd) => Ok(serde_json::to_string(&epd).unwrap()),
Err(error) => Err(PyTypeError::new_err(error.to_string()))
Err(error) => Err(PyTypeError::new_err(error.to_string())),
}
}

Expand All @@ -21,4 +21,4 @@ fn epdx(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(_convert_ilcd, m)?)?;

Ok(())
}
}
4 changes: 2 additions & 2 deletions src/schemars.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use schemars::{schema_for};
use schemars::schema_for;
extern crate epdx;

use epdx::epd;

fn main() {
let schema = schema_for!(epd::EPD);
println!("{}", serde_json::to_string_pretty(&schema).unwrap());
}
}
10 changes: 7 additions & 3 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ pub fn set_panic_hook() {
console_error_panic_hook::set_once();
}


pub fn get_version() -> String {
format!("{}.{}.{}", pkg_version_major!(), pkg_version_minor!(), pkg_version_patch!())
}
format!(
"{}.{}.{}",
pkg_version_major!(),
pkg_version_minor!(),
pkg_version_patch!()
)
}
5 changes: 3 additions & 2 deletions tests/test_parse_ilcd.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
#[cfg(test)]
mod tests {
use epdx::*;
use std::fs;
use std::path::Path;
use epdx::epd::{Standard, SubType};

use epdx::*;
use epdx::epd::Standard;

macro_rules! parse_ilcd_tests {
($($name:ident: $value:expr)*) => {
Expand Down

0 comments on commit 0ac8276

Please sign in to comment.