def _create_quantity(self, o): """ :param o: objectified FlowProperty :return: """ ns = find_ns(o.nsmap, 'FlowProperty') u = str(find_common(o, 'UUID')[0]) n = str(find_common(o, 'name')[0]) c = str(find_common(o, 'generalComment')[0]) ug, ug_uri = get_reference_unit_group(o, ns=ns) ug_path = self._pathtype.join('unitgroups', ug) # need the path without extension- I know- it's all sloppy refunit, unitconv = self._create_unit(ug_path) q = LcQuantity(u, Name=n, ReferenceUnit=refunit, UnitConversion=unitconv, Comment=c) q.set_external_ref('%s/%s' % (typeDirs['FlowProperty'], u)) self.add(q) return q
def _entity_from_old_json(self, e): d = e['tags'] uid = self._key_to_id(e['entityId']) if e['entityType'] == 'quantity': unit, _ = self._create_unit(e['referenceUnit']) d['referenceUnit'] = unit entity = LcQuantity(uid, **d) elif e['entityType'] == 'flow': try: d['referenceQuantity'] = self[e['referenceQuantity']] except TypeError: pass # allow referenceQuantity to be None entity = LcFlow(uid, **d) elif e['entityType'] == 'process': entity = LcProcess(uid, **d) try: direc, flow = e['referenceExchange'].split(': ') entity['referenceExchange'] = Exchange(process=entity, flow=self[flow], direction=direc) except ValueError: pass # allow referenceExchange to be None else: raise TypeError('Unknown entity type %s' % e['entityType']) entity.set_external_ref(e['entityId']) self.add(entity)
def new_quantity(self, name=None, unit=None, comment=None): name = name or input('Enter quantity name: ') unit = unit or input('Unit by string: ') comment = comment or ifinput('Quantity Comment: ', '') q = LcQuantity.new(name, unit, Comment=comment) self._catalog[0].add(q) return q
def _quantity_from_json(self, entity_j, uid): entity_j.pop('externalId') # TODO # can't move this to entity because we need _create_unit- so we wouldn't gain anything unit, _ = self._create_unit(entity_j.pop('referenceUnit')) entity_j['referenceUnit'] = unit quantity = LcQuantity(uid, **entity_j) return quantity
def _create_quantity(self, name, unitstring): u = self._key_to_nsuuid(name) q = self[u] if q is None: q = LcQuantity(u, external_ref=name, Name=name, ReferenceUnit=self._create_unit(unitstring)[0]) self.add(q) return q
def _create_quantity(self, unitstring): """ In ecospold v1, quantities are only units, defined by string :param unitstring: :return: """ if unitstring in self._q_dict: q = self._q_dict[unitstring] else: ref_unit, _ = self._create_unit(unitstring) uid = self._key_to_id(unitstring) q = LcQuantity(uid, Name='EcoSpold Quantity %s' % unitstring, ReferenceUnit=ref_unit, Comment=self.spold_version) q.set_external_ref(unitstring) self.add(q) self._q_dict[unitstring] = q return q
def _create_quantity(self, row): """ here row is a dict from self._xl_rows :param row: :return: """ key = self._quantity_key(row) u = self._key_to_id(key) try_q = self[u] if try_q is None: unit, _ = self._create_unit(row['unit']) q = LcQuantity(u, Name=key, referenceUnit=unit, Comment='Ecoinvent LCIA implementation', Method=row['method'], Category=row['category'], Indicator=row['indicator']) q.set_external_ref(key) self.add(q) else: q = try_q return q
def _create_quantity(self, unitstring): """ In ecospold v1, quantities are only units, defined by string :param unitstring: :return: """ if unitstring in self._q_dict: q = self._q_dict[unitstring] else: ref_unit, _ = self._create_unit(unitstring) uid = self._key_to_nsuuid(unitstring) q = LcQuantity(uid, Name='EcoSpold Quantity %s' % unitstring, ReferenceUnit=ref_unit, Comment=self.spold_version) q.set_external_ref(unitstring) self.add(q) self._q_dict[unitstring] = q return q
def _create_quantity(self, unitstring): """ In ecoinvent activity overview spreadsheets, quantities are only units, defined by string. 'properties' are additionally defined with name and unit together, but because the prinicpal units don't have names (and because for the time being we are neglecting the F-Q relation), we ignore them. :param unitstring: :return: """ u = self._key_to_nsuuid(unitstring) try_q = self[u] if try_q is None: ref_unit, _ = self._create_unit(unitstring) q = LcQuantity(u, Name='Ecoinvent Spreadsheet Quantity %s' % unitstring, ReferenceUnit=ref_unit, Comment=self.version) q.set_external_ref(unitstring) self.add(q) else: q = try_q return q
def _create_quantity(self, unitstring): """ In ecoinvent activity overview spreadsheets, quantities are only units, defined by string. 'properties' are additionally defined with name and unit together, but because the prinicpal units don't have names (and because for the time being we are neglecting the F-Q relation), we ignore them. :param unitstring: :return: """ try_q = self.quantity_with_unit(unitstring) if try_q is None: ref_unit, _ = self._create_unit(unitstring) u = self._key_to_id(unitstring) q = LcQuantity(u, Name='Ecoinvent Spreadsheet Quantity %s' % unitstring, ReferenceUnit=ref_unit, Comment=self.version) q.set_external_ref(unitstring) self.add(q) else: q = try_q return q
def _create_lcia_quantity(self, o, ns): u = str(find_common(o, 'UUID')) try_q = self[u] if try_q is not None: lcia = try_q else: n = str(find_common(o, 'name')) c = str(find_common(o, 'generalComment')) m = '; '.join([str(x) for x in find_tags(o, 'methodology', ns=ns)]) ic = '; '.join( [str(x) for x in find_tags(o, 'impactCategory', ns=ns)]) ii = '; '.join( [str(x) for x in find_tags(o, 'impactIndicator', ns=ns)]) ry = str(find_tag(o, 'referenceYear', ns=ns)) dur = str(find_tag(o, 'duration', ns=ns)) rq = self._make_reference_unit(o, ns=ns) lcia = LcQuantity(u, Name=n, Comment=c, Method=m, Category=ic, Indicator=ii, ReferenceYear=ry, Duration=dur, UnitConversion=rq['UnitConversion']) lcia.set_external_ref('%s/%s' % (typeDirs['LCIAMethod'], u)) lcia.reference_entity = LcUnit('%s %s' % (rq.unit(), rq['Name']), unit_uuid=rq.uuid) self.add(lcia) return lcia
def _create_lcia_quantity(self, o, load_all_flows=False): ns = find_ns(o.nsmap, 'LCIAMethod') u = str(find_common(o, 'UUID')[0]) n = str(find_common(o, 'name')[0]) c = str(find_common(o, 'generalComment')[0]) m = '; '.join([str(x) for x in find_tag(o, 'methodology', ns=ns)]) ic = '; '.join([str(x) for x in find_tag(o, 'impactCategory', ns=ns)]) ii = '; '.join([str(x) for x in find_tag(o, 'impactIndicator', ns=ns)]) ry = str(find_tag(o, 'referenceYear', ns=ns)[0]) dur = str(find_tag(o, 'duration', ns=ns)[0]) r_uuid, r_uri = get_reference_quantity(o, ns=ns) rq = self._check_or_retrieve_child(r_uuid, r_uri) lcia = LcQuantity(u, Name=n, Comment=c, Method=m, Category=ic, Indicator=ii, ReferenceYear=ry, Duration=dur) lcia.set_external_ref('%s/%s' % (typeDirs['LCIAMethod'], u)) lcia.reference_entity = rq.reference_entity self.add(lcia) for factor in o['characterisationFactors'].getchildren(): # British spelling! brits aren't even IN the EU anymore f_uuid, f_uri, f_dir = get_flow_ref(factor, ns=ns) if self[f_uuid] is None: if not load_all_flows: # don't bother loading factors for flows that don't exist continue cf = float(find_tag(factor, 'meanValue', ns=ns)[0]) loc = str(find_tag(factor, 'location', ns=ns)[0]) if loc == '': loc = None flow = self._check_or_retrieve_child(f_uuid, f_uri) # TODO: adjust CF for different reference units!!! do this when a live one is found flow.add_characterization(lcia, value=cf, location=loc)
def _create_quantity(self, row): """ here row is a dict from self._xl_rows :param row: :return: """ key = self._quantity_key(row) u = self._key_to_nsuuid(key) try_q = self[u] if try_q is None: unit, _ = self._create_unit(row['unit']) q = LcQuantity(u, Name=key, referenceUnit=unit, Comment='Ecoinvent LCIA implementation', Method=row['method'], Category=row['category'], Indicator=row['indicator']) q.set_external_ref(key) self.add(q) else: q = try_q return q
def _create_quantity(self, o): """ :param o: objectified FlowProperty :return: """ u = str(find_common(o, 'UUID')) try_q = self[u] if try_q is not None: return try_q ns = find_ns(o.nsmap, 'FlowProperty') n = str(find_common(o, 'name')) c = str(find_common(o, 'generalComment')) ug, ug_uri = get_reference_unit_group(o, ns=ns) ug_path = self._pathtype.join( 'unitgroups', ug) # need the path without extension- I know- it's all sloppy refunit, unitconv = self._create_unit(ug_path) q = LcQuantity(u, Name=n, ReferenceUnit=refunit, UnitConversion=unitconv, Comment=c) q.set_external_ref('%s/%s' % (typeDirs['FlowProperty'], u)) self.add(q) return q
def __init__(self, ref, sheet_name='impact methods', mass_quantity=None, value_tag='CF 3.1', **kwargs): """ :param ref: :param sheet_name: 'impact methods' :param ns_uuid: :param mass_quantity: :param value_tag: 'CF 3.1' :param kwargs: quiet, upstream """ super(EcoinventLcia, self).__init__(ref, **kwargs) self._xl_rows = [] self._sheet_name = sheet_name self._value_tag = value_tag mass = mass_quantity or LcQuantity.new('Mass', self._create_unit('kg')[0]) self.add(mass) self._mass = mass
def _create_quantity(self, exchange): """ In ecospold v2, quantities are still only units, defined by string. They do get their own uuids, but only as 'properties' of the flows- flows themselves are only measured by unit. this code is cc'd from ecospold1 :param exchange: :return: """ unitstring = exchange.unitName.text unit_uuid = exchange.attrib['unitId'] try_q = self[unit_uuid] if try_q is None: ref_unit, _ = self._create_unit(unitstring) q = LcQuantity(unit_uuid, Name='EcoSpold Quantity %s' % unitstring, ReferenceUnit=ref_unit, Comment=self.spold_version) self.add(q) else: q = try_q return q
def __init__(self, source, ref=None, sheet_name='impact methods', mass_quantity=None, value_tag='CF ' + EI_LCIA_VERSION, ns_uuid=EI_LCIA_NSUUID, static=True, **kwargs): """ EI_LCIA_VERSION is presently 3.1 for the spreadsheet named 'LCIA implementation v3.1 2014_08_13.xlsx' :param source: :param ref: hard-coded 'local.ecoinvent.[EI_LCIA_VERSION].lcia'; specify at instantiation to override :param sheet_name: 'impact methods' :param mass_quantity: :param value_tag: 'CF ' + EI_LCIA_VERSION :param ns_uuid: required :param static: this archive type is always static :param kwargs: quiet, upstream """ if ref is None: ref = '.'.join(['local', 'ecoinvent', EI_LCIA_VERSION, 'lcia']) super(EcoinventLcia, self).__init__(source, ref=ref, ns_uuid=ns_uuid, static=True, **kwargs) self._xl_rows = [] self._sheet_name = sheet_name self._value_tag = value_tag mass = mass_quantity or LcQuantity.new('Mass', self._create_unit('kg')[0]) self.add(mass) self._mass = mass
if x.flow['Name'].startswith('Nitrogen oxides')) next(x for x in _petro.exchanges() if x.flow['Name'].startswith('Transport, ocean freighter, r')) if __name__ == '__main__': cat = LcCatalog(CAT_FOLDER) petro = cat.get_archive('local.uslci.olca', 'inventory').get( petro_id) # use get_archive to get entity and not ref grid = cat.get_archive('local.uslci.olca', 'inventory').get(grid_id) # shrink_petro(petro) # let's not bother shrinking this for p in (petro, grid): p._d.pop('processDocumentation') A = LcArchive(None, ref='test.entities', ns_uuid=NS_UUID) A.add_entity_and_children(petro) A.add_entity_and_children(grid) # create a dummy LCIA method q = LcQuantity.new('Emissive Coolness', 'Cool', Indicator='Coolombs') A.add(q) for k, v in cool.items(): A[k].add_characterization(q, value=v) A.check_counter() # assert len([e for e in A.entities()]) + (2 * max_count) == 54 A.write_to_file(DEST_FILE, complete=True)
def entity_from_json(self, e): """ Create an LcEntity subclass from a json-derived dict this could use some serious refactoring :param e: :return: """ if 'tags' in e: self._entity_from_old_json(e) return chars = None exchs = None e_id = e.pop('entityId') ext_ref = e.pop('externalId') uid = self._key_to_id(e_id) etype = e.pop('entityType') origin = e.pop('origin') if etype == 'quantity': # can't move this to entity because we need _create_unit- so we wouldn't gain anything unit, _ = self._create_unit(e.pop('referenceUnit')) e['referenceUnit'] = unit entity = LcQuantity(uid, **e) elif etype == 'flow': try: e.pop('referenceQuantity') except KeyError: pass if 'characterizations' in e: chars = e.pop('characterizations') entity = LcFlow(uid, **e) if chars is not None: for c in chars: v = None q = self[c['quantity']] if q is None: import json, sys print(ext_ref) json.dump(c, sys.stdout, indent=2) raise KeyError if 'value' in c: v = c['value'] if 'isReference' in c: is_ref = c['isReference'] else: is_ref = False entity.add_characterization(q, reference=is_ref, value=v) elif etype == 'process': # note-- we want to abandon referenceExchange notation, but we need to leave it in for backward compat try: rx = e.pop('referenceExchange') except KeyError: rx = None if 'exchanges' in e: exchs = e.pop('exchanges') entity = LcProcess(uid, **e) if exchs is not None: for x in exchs: v = None # is_ref = False f = self[x['flow']] d = x['direction'] if 'value' in x: v = x['value'] if 'isReference' in x: # is_ref = x['isReference'] entity.add_reference(f, d) # TODO: handle allocations -- I think this will "just work" if v is a dict entity.add_exchange(f, d, value=v) rx = None if rx is not None and rx != 'None': try: direc, flow = rx.split(': ') entity['referenceExchange'] = Exchange(process=entity, flow=self[flow], direction=direc) except AttributeError: print('rx: [%s]' % rx) except ValueError: pass else: raise TypeError('Unknown entity type %s' % e['entityType']) entity.origin = origin entity.set_external_ref(ext_ref) self.add(entity)
def new_quantity(self, name, ref_unit, **kwargs): u = self._check_key_unused(name) q = LcQuantity(u, ref_unit=LcUnit(ref_unit), Name=name, origin=self.ref, external_ref=name, **kwargs) self.add(q) return q