Exemple #1
0
    def load_energy_system(self, name):
        # create a resourceSet that hold the contents of the esdl.ecore model and the instances we use/create
        rset = ResourceSet()

        # Assign files with the .esdl extension to the XMLResource instead of default XMI
        rset.resource_factory['esdl'] = lambda uri: XMLResource(uri)

        # Read the lastest esdl.ecore from github
        esdl_model_resource = rset.get_resource(
            HttpURI(
                'https://raw.githubusercontent.com/EnergyTransition/ESDL/master/esdl/model/esdl.ecore'
            ))

        esdl_model = esdl_model_resource.contents[0]
        # print('Namespace: {}'.format(esdl_model.nsURI))
        rset.metamodel_registry[esdl_model.nsURI] = esdl_model

        # Create a dynamic model from the loaded esdl.ecore model, which we can use to build Energy Systems
        esdl = DynamicEPackage(esdl_model)

        # fix python buildin 'from' that is also used in ProfileElement as attribute
        # use 'start' instead of 'from' when using a ProfileElement
        alias('start', esdl.ProfileElement.findEStructuralFeature('from'))

        # have a nice __repr__ for some ESDL classes when printing ESDL objects (includes all Assets and EnergyAssets)
        esdl.Item.python_class.__repr__ = lambda x: '{}: ({})'.format(
            x.name, EnergySystemHandler.attr_to_dict(x))
        esdl.Carrier.python_class.__repr__ = lambda x: '{}: ({})'.format(
            x.name, EnergySystemHandler.attr_to_dict(x))
        esdl.Geometry.python_class.__repr__ = lambda x: '{}: ({})'.format(
            x.name, EnergySystemHandler.attr_to_dict(x))
        esdl.QuantityAndUnitType.python_class.__repr__ = lambda x: '{}: ({})'.format(
            x.id, EnergySystemHandler.attr_to_dict(x))
        esdl.QuantityAndUnitReference.python_class.__repr__ = lambda x: '{}: ({})'.format(
            'QuantityAndUnitReference', EnergySystemHandler.attr_to_dict(x))
        esdl.KPI.python_class.__repr__ = lambda x: '{}: ({})'.format(
            x.name, EnergySystemHandler.attr_to_dict(x))
        esdl.ProfileElement.python_class.__repr__ = lambda x: 'ProfileElement ({})'.format(
            EnergySystemHandler.attr_to_dict(x))

        # load the ESDL file
        resource = rset.get_resource(URI(name))
        es = resource.contents[0]
        # At this point, the model instance is loaded!

        # get notifications of changes in the EnergySystem model
        #observer = PrintNotification(es)
        #observer2 = PrintNotification(es.instance[0].area)

        # also return the esdlm and rset reference, so we can create esdl classes and store them as strings
        return es, resource, esdl, rset
def MakeESDL(RegioNaam, StrategieNaam):
    # create a resourceSet that hold the contents of the esdl.ecore model and the instances we use/create
    rset = ResourceSet()
    # register the metamodel (available in the generated files)
    rset.metamodel_registry[esdl.nsURI] = esdl
    # Assign files with the .esdl extension to the XMLResource instead of default XMI
    rset.resource_factory['esdl'] = lambda uri: XMLResource(uri)  # we register the factory for '.esdl' extension and XML serialization

    # Create a new EnergySystem
    es = EnergySystem(name="Vesta Resultaten PerBebouwingsObject")
    instance = Instance(name="y2030")
    
    
    # AbstractInstanceDate = InstanceDate.date(2020)
    instance.aggrType = AggrTypeEnum.PER_COMMODITY
    es.instance.append(instance)
    es.instance[0].area = Area(name=RegioNaam)

    qau_energy_GJ_yr = QuantityAndUnitType(id=str(uuid.uuid4()), physicalQuantity="ENERGY", unit="JOULE", multiplier="GIGA", perTimeUnit="YEAR")
    qau_emission_KG = QuantityAndUnitType(id=str(uuid.uuid4()), physicalQuantity="EMISSION", unit="GRAM", multiplier="KILO")

    filename = "data/%s/PerBebouwingsObject_ESDL_%s.csv" % (StrategieNaam,RegioNaam)
    
    with open(filename, newline='') as csvfile:
        reader = csv.reader(csvfile, delimiter=';')
        
        column_names = next(reader)
#        print(column_names)

        for row in reader:
            area = Area(id=row[column_names.index('BU_CODE')], scope="NEIGHBOURHOOD")

            hd_total = HeatingDemand(id=str(uuid.uuid4()), name="Vraag_Warmte_totaal")
            hd_total_ip = InPort(id=str(uuid.uuid4()), name="InPort")
            hd_total_sv = SingleValue(id=str(uuid.uuid4()), value=float(row[column_names.index('Vraag_Warmte_totaal')]))
            hd_total_sv.profileQuantityAndUnit = qau_energy_GJ_yr
            hd_total_ip.profile = hd_total_sv
            hd_total.port.append(hd_total_ip)
            area.asset.append(hd_total)

            hd_MT = HeatingDemand(id=str(uuid.uuid4()), name="Vraag_MT_Warmte")
            hd_MT_ip = InPort(id=str(uuid.uuid4()), name="InPort")
            hd_MT_sv = SingleValue(id=str(uuid.uuid4()), value=float(row[column_names.index('Vraag_MT_Warmte')]))
            hd_MT_sv.profileQuantityAndUnit = qau_energy_GJ_yr
            hd_MT_ip.profile = hd_MT_sv
            hd_MT.port.append(hd_MT_ip)
            area.asset.append(hd_MT)

            hd_LT = HeatingDemand(id=str(uuid.uuid4()), name="Vraag_LT_Warmte")
            hd_LT_ip = InPort(id=str(uuid.uuid4()), name="InPort")
            hd_LT_sv = SingleValue(id=str(uuid.uuid4()), value=float(row[column_names.index('Vraag_LT_Warmte')]))
            hd_LT_sv.profileQuantityAndUnit = qau_energy_GJ_yr
            hd_LT_ip.profile = hd_LT_sv
            hd_LT.port.append(hd_LT_ip)
            area.asset.append(hd_LT)

            hd_elek = HeatingDemand(id=str(uuid.uuid4()), name="Vraag_ElektrischeWarmte")
            hd_elek_ip = InPort(id=str(uuid.uuid4()), name="InPort")
            hd_elek_sv = SingleValue(id=str(uuid.uuid4()), value=float(row[column_names.index('Vraag_ElektrischeWarmte')]))
            hd_elek_sv.profileQuantityAndUnit = qau_energy_GJ_yr
            hd_elek_ip.profile = hd_elek_sv
            hd_elek.port.append(hd_elek_ip)
            area.asset.append(hd_elek)
            
            cd = CoolingDemand(id=str(uuid.uuid4()), name="Vraag_Koude")
            cd_ip = InPort(id=str(uuid.uuid4()), name="InPort")
            cd_sv = SingleValue(id=str(uuid.uuid4()), value=float(row[column_names.index('Vraag_Koude')]))
            cd_sv.profileQuantityAndUnit = qau_energy_GJ_yr
            cd_ip.profile = cd_sv
            cd.port.append(cd_ip)
            area.asset.append(cd)

            ed = ElectricityDemand(id=str(uuid.uuid4()), name="Vraag_Elektriciteit")
            ed_ip = InPort(id=str(uuid.uuid4()), name="InPort")
            ed_sv = SingleValue(id=str(uuid.uuid4()), value=float(row[column_names.index('Vraag_Elektriciteit')]))
            ed_sv.profileQuantityAndUnit = qau_energy_GJ_yr
            ed_ip.profile = ed_sv
            ed.port.append(ed_ip)
            area.asset.append(ed)

            gd = GasDemand(id=str(uuid.uuid4()), name="Vraag_Aardgas")
            gd_ip = InPort(id=str(uuid.uuid4()), name="InPort")
            gd_sv = SingleValue(id=str(uuid.uuid4()), value=float(row[column_names.index('Vraag_Aardgas')]))
            gd_sv.profileQuantityAndUnit = qau_energy_GJ_yr
            gd_ip.profile = gd_sv
            gd.port.append(gd_ip)
            area.asset.append(gd)

            co2_gas = StringKPI(id=str(uuid.uuid4()),name='CO2_uitstoot_gas', value=row[column_names.index('CO2_uitstoot_gas')])
            co2_elek = StringKPI(id=str(uuid.uuid4()),name='CO2_uitstoot_elek', value=row[column_names.index('CO2_uitstoot_elek')])
            costs = StringKPI(id=str(uuid.uuid4()),name='Maatschappelijke_kosten', value=row[column_names.index('Maatschappelijke_kosten')])
            kpis = KPIs(id=str(uuid.uuid4()))
            kpis.kpi.append(co2_gas)
            kpis.kpi.append(co2_elek)
            kpis.kpi.append(costs)
            area.KPIs = kpis

            es.instance[0].area.area.append(area)

            # print("Energy system: {}".format(attr_to_dict(es)))

    export_name = "output/%s_%s.esdl" %(StrategieNaam,RegioNaam)

    resource = rset.create_resource(URI(export_name))
    resource.append(es)
    resource.save()
    
    return (RegioNaam, StrategieNaam)
def main():
    # create a resourceSet that hold the contents of the esdl.ecore model and the instances we use/create
    rset = ResourceSet()
    # register the metamodel (available in the generated files)
    rset.metamodel_registry[esdl.nsURI] = esdl
    # Assign files with the .esdl extension to the XMLResource instead of default XMI
    rset.resource_factory['esdl'] = lambda uri: XMLResource(
        uri
    )  # we register the factory for '.esdl' extension and XML serialization

    # Create a new EnergySystem
    es = EnergySystem(name="Vesta Resultaten")
    instance = Instance(name="StartJaar")
    # AbstractInstanceDate = InstanceDate.date(2020)
    instance.aggrType = AggrTypeEnum.PER_COMMODITY
    es.instance.append(instance)
    es.instance[0].area = Area(name="RESMetropoolregioEindhoven")

    qau_energy_GJ_yr = QuantityAndUnitType(id=str(uuid.uuid4()),
                                           physicalQuantity="ENERGY",
                                           unit="JOULE",
                                           multiplier="GIGA",
                                           perTimeUnit="YEAR")
    qau_emission_KG = QuantityAndUnitType(id=str(uuid.uuid4()),
                                          physicalQuantity="EMISSION",
                                          unit="GRAM",
                                          multiplier="KILO")

    with open('data/Strategie1_isolatie_ewp/PerPlanRegio_ESDL.csv',
              newline='') as csvfile:
        reader = csv.reader(csvfile, delimiter=';')

        column_names = next(reader)
        print(column_names)

        for row in reader:
            area = Area(id=row[column_names.index('BU_CODE')],
                        scope="NEIGHBOURHOOD")

            houses = AggregatedBuilding(
                id=str(uuid.uuid4()),
                name="Woningen",
                numberOfBuildings=int(
                    row[column_names.index('Aantal_woningen')]))
            area.asset.append(houses)
            utilities = AggregatedBuilding(
                id=str(uuid.uuid4()),
                name="Utiliteiten",
                numberOfBuildings=int(
                    row[column_names.index('Aantal_utiliteiten')]))
            area.asset.append(utilities)

            hd_total = HeatingDemand(id=str(uuid.uuid4()),
                                     name="Vraag_Warmte_totaal")
            hd_total_ip = InPort(id=str(uuid.uuid4()), name="InPort")
            hd_total_sv = SingleValue(
                id=str(uuid.uuid4()),
                value=float(row[column_names.index('Vraag_Warmte_totaal')]))
            hd_total_sv.profileQuantityAndUnit = qau_energy_GJ_yr
            hd_total_ip.profile = hd_total_sv
            hd_total.port.append(hd_total_ip)
            area.asset.append(hd_total)

            hd_MT = HeatingDemand(id=str(uuid.uuid4()), name="Vraag_MT_Warmte")
            hd_MT_ip = InPort(id=str(uuid.uuid4()), name="InPort")
            hd_MT_sv = SingleValue(
                id=str(uuid.uuid4()),
                value=float(row[column_names.index('Vraag_MT_Warmte')]))
            hd_MT_sv.profileQuantityAndUnit = qau_energy_GJ_yr
            hd_MT_ip.profile = hd_MT_sv
            hd_MT.port.append(hd_MT_ip)
            area.asset.append(hd_MT)

            hd_LT = HeatingDemand(id=str(uuid.uuid4()), name="Vraag_LT_Warmte")
            hd_LT_ip = InPort(id=str(uuid.uuid4()), name="InPort")
            hd_LT_sv = SingleValue(
                id=str(uuid.uuid4()),
                value=float(row[column_names.index('Vraag_LT_Warmte')]))
            hd_LT_sv.profileQuantityAndUnit = qau_energy_GJ_yr
            hd_LT_ip.profile = hd_LT_sv
            hd_LT.port.append(hd_LT_ip)
            area.asset.append(hd_LT)

            ed = ElectricityDemand(id=str(uuid.uuid4()),
                                   name="Vraag_Elektriciteit")
            ed_ip = InPort(id=str(uuid.uuid4()), name="InPort")
            ed_sv = SingleValue(
                id=str(uuid.uuid4()),
                value=float(row[column_names.index('Vraag_Elektriciteit')]))
            ed_sv.profileQuantityAndUnit = qau_energy_GJ_yr
            ed_ip.profile = ed_sv
            ed.port.append(ed_ip)
            area.asset.append(ed)

            gd = GasDemand(id=str(uuid.uuid4()), name="Vraag_Aardgas")
            gd_ip = InPort(id=str(uuid.uuid4()), name="InPort")
            gd_sv = SingleValue(id=str(uuid.uuid4()),
                                value=float(
                                    row[column_names.index('Vraag_Aardgas')]))
            gd_sv.profileQuantityAndUnit = qau_energy_GJ_yr
            gd_ip.profile = gd_sv
            gd.port.append(gd_ip)
            area.asset.append(gd)

            co2 = StringKPI(id=str(uuid.uuid4()),
                            name='CO2_uitstoot',
                            value=row[column_names.index('CO2_uitstoot')])
            costs = StringKPI(
                id=str(uuid.uuid4()),
                name='Maatschappelijke_kosten',
                value=row[column_names.index('Maatschappelijke_kosten,')])
            kpis = KPIs(id=str(uuid.uuid4()))
            kpis.kpi.append(co2)
            kpis.kpi.append(costs)
            area.KPIs = kpis

            es.instance[0].area.area.append(area)

            # print("Energy system: {}".format(attr_to_dict(es)))

    resource = rset.create_resource(
        URI('vesta_output_warmtekeuze_per_buurt.esdl'))
    resource.append(es)
    resource.save()
Exemple #4
0
def main():

    # create a resourceSet that hold the contents of the esdl.ecore model and the instances we use/create
    rset = ResourceSet()

    # register the metamodel (available in the generated files)
    rset.metamodel_registry[esdl.nsURI] = esdl
    rset.resource_factory['esdl'] = lambda uri: XMLResource(
        uri
    )  # we register the factory for '.esdl' extension and XML serialization

    # Create a new EnergySystem
    es = EnergySystem(name="mpoc")
    instance = Instance(name="test instance")

    # example of using an Enum
    instance.aggrType = AggrTypeEnum.PER_COMMODITY
    es.instance.append(instance)
    es.instance[0].area = Area(name="Groningen", id="PV20")

    # create a new PV parc with 10 panels
    pvparc = PVParc(name="PV parc")
    pvparc.numberOfPanels = 10

    # Use datatime to set dates and times
    now = datetime.datetime.now()
    pvparc.commissioningDate = now
    ed = ElectricityDemand(name="E demand")
    es.instance[0].area.asset.append(pvparc)
    es.instance[0].area.asset.append(ed)
    inPort = InPort(id='InPort1')
    ed.port.append(inPort)
    outPort = OutPort(id='OutPort1', connectedTo=[inPort])
    pvparc.port.append(outPort)

    # create a new windturbine
    turbine = WindTurbine(id=EnergySystemHandler.generate_uuid(),
                          name='WindTurbine 4',
                          power=2E6,
                          fullLoadHours=2000,
                          height=150.0,
                          surfaceArea=100,
                          prodType=RenewableTypeEnum.from_string('RENEWABLE'),
                          type=WindTurbineTypeEnum.from_string('WIND_ON_LAND'))
    es.instance[0].area.asset.append(turbine)

    # create new wind search area
    search_area_wind = SearchAreaWind(id=EnergySystemHandler.generate_uuid(),
                                      name="Search Area Wind",
                                      fullLoadHours=1920,
                                      area=2E8)
    es.instance[0].area.potential.append(search_area_wind)

    # create new solar search area
    search_area_solar = SearchAreaSolar(id=EnergySystemHandler.generate_uuid(),
                                        name="Search Area Solar",
                                        fullLoadHours=867,
                                        area=2E8)
    es.instance[0].area.potential.append(search_area_solar)

    # create new KPIs object
    es.instance[0].area.KPIs = KPIs(description="KPIs")

    # Create quantity and unit for CO2-emissions
    co2_unit = QuantityAndUnitType(
        physicalQuantity="EMISSION",
        multiplier="MEGA",
        # unit="GRAM",
        # perMultiplier="",
        # perUnit="",
        description="Mton (CO2-emissions)",
        # perTimeUnit="",
        id="mton",
    )

    # Create CO2-emissions KPI
    kpi_co2 = KPI(name="KPI CO2-emissions",
                  value=None,
                  quantityAndUnit=co2_unit)

    # Create quantity and unit for total costs
    costs_unit = QuantityAndUnitType(
        physicalQuantity="COST",
        multiplier="MEGA",
        # unit="GRAM",
        # perMultiplier="",
        # perUnit="",
        description="Mln euros (total costs)",
        # perTimeUnit="",
        id="meur",
    )

    # Create costs KPI
    kpi_costs = KPI(name="KPI Total costs",
                    value=None,
                    quantityAndUnit=costs_unit)

    # Add CO2-emissions and total costs KPIs to KPIs
    es.instance[0].area.KPIs.kpi.append(kpi_co2)
    es.instance[0].area.KPIs.kpi.append(kpi_costs)

    print("Energy system: {}".format(attr_to_dict(es)))
    print("OutPort connectedTo: {}".format(outPort.connectedTo))
    print("InPort connectedTo: {}".format(inPort.connectedTo))
    resource = rset.create_resource(URI('mpoc.esdl'))
    resource.append(es)
    resource.save()
Exemple #5
0
def excel_to_ESDL(fname, sname_woningen, sname_bedrijven):
    book = open_workbook(fname)
    sheet = book.sheet_by_name(sname_woningen)

    top_area_type = str(sheet.cell(0, 3).value)
    if top_area_type == 'GM':
        top_area_scope = 'MUNICIPALITY'
    else:
        print('Other scopes than municipality not supported yet')
        # sys.exit(1)

    top_area_code = top_area_type + str(sheet.cell(0, 4).value)
    top_area_name = str(sheet.cell(0, 1).value)
    top_area_year = ci2s(sheet.cell(0, 2))
    sub_aggr = str(sheet.cell(0, 5).value)
    if sub_aggr == 'WK':
        sub_aggr_id_start = 'WK' + str(sheet.cell(0, 4).value)
        sub_aggr_scope = 'DISTRICT'
        sub_area_number_pos = 5
    elif sub_aggr[0:2] == 'BU':
        sub_aggr_scope = 'NEIGHBOURHOOD'
        sub_aggr_code_column = 3
        print('TODO: check buurt codes in excel')

    column1_name = str(sheet.cell(1, 1).value)
    column2_name = str(sheet.cell(1, 2).value)

    if column1_name[0:3] == 'gas':
        gas_column = 1
    if column1_name[0:4] == 'elek':
        elec_column = 1
    if column2_name[0:3] == 'gas':
        gas_column = 2
    if column2_name[0:4] == 'elek':
        elec_column = 2

    es = esdl.EnergySystem(id=str(uuid.uuid4()),
                           name=top_area_name + ' ' + top_area_year)

    carrs = esdl.Carriers(id=str(uuid.uuid4()))

    elec_car = esdl.EnergyCarrier(id='ELEC',
                                  name='Electricity',
                                  emission=180.28,
                                  energyContent=1.0,
                                  energyCarrierType='FOSSIL')
    elec_car.emissionUnit = esdl.QuantityAndUnitType(
        physicalQuantity='EMISSION',
        multiplier='KILO',
        unit='GRAM',
        perMultiplier='GIGA',
        perUnit='JOULE')
    elec_car.energyContentUnit = esdl.QuantityAndUnitType(
        physicalQuantity='ENERGY',
        multiplier='MEGA',
        unit='JOULE',
        perMultiplier='MEGA',
        perUnit='JOULE')
    carrs.carrier.append(elec_car)

    gas_car = esdl.EnergyCarrier(id='GAS',
                                 name='Natural Gas',
                                 emission=1.788225,
                                 energyContent=35.1700000,
                                 energyCarrierType='FOSSIL')
    gas_car.emissionUnit = esdl.QuantityAndUnitType(
        physicalQuantity='EMISSION',
        multiplier='KILO',
        unit='GRAM',
        perUnit='CUBIC_METRE')
    gas_car.energyContentUnit = esdl.QuantityAndUnitType(
        physicalQuantity='ENERGY',
        multiplier='MEGA',
        unit='JOULE',
        perUnit='CUBIC_METRE')
    carrs.carrier.append(gas_car)

    heat_comm = esdl.HeatCommodity(id='HEAT', name='Heat')
    carrs.carrier.append(heat_comm)

    es.energySystemInformation = esdl.EnergySystemInformation(id=str(
        uuid.uuid4()),
                                                              carriers=carrs)

    srvs = esdl.Services()

    inst = esdl.Instance(id=str(uuid.uuid4()),
                         name=top_area_name + ' ' + top_area_year)
    es.instance.append(inst)
    ar = esdl.Area(id=top_area_code, name=top_area_name, scope=top_area_scope)
    es.instance[0].area = ar

    elec_nw_op = esdl.OutPort(id=str(uuid.uuid4()),
                              name='EOut',
                              carrier=elec_car)
    elec_nw_ip = esdl.InPort(id=str(uuid.uuid4()),
                             name='EIn',
                             carrier=elec_car)
    elec_nw = esdl.ElectricityNetwork(id=str(uuid.uuid4()),
                                      name='ElectricityNetwork',
                                      port=[elec_nw_ip, elec_nw_op])
    ar.asset.append(elec_nw)

    gep_mc = esdl.SingleValue(id=str(uuid.uuid4()),
                              name='MarginalCosts',
                              value=elec_prod_mc)
    gep_ci = esdl.CostInformation(marginalCosts=gep_mc)
    gep_op = esdl.OutPort(id=str(uuid.uuid4()),
                          name='EOut',
                          connectedTo=[elec_nw_ip],
                          carrier=elec_car)
    gep = esdl.GenericProducer(id=str(uuid.uuid4()),
                               name='Unlimited Electricity Generation',
                               port=[gep_op],
                               power=gep_power,
                               costInformation=gep_ci,
                               prodType=esdl.RenewableTypeEnum.FOSSIL)
    ar.asset.append(gep)
    gec_mc = esdl.SingleValue(id=str(uuid.uuid4()),
                              name='MarginalCosts',
                              value=elec_cons_mc)
    gec_ci = esdl.CostInformation(marginalCosts=gec_mc)
    gec_ip = esdl.InPort(id=str(uuid.uuid4()),
                         name='EIn',
                         connectedTo=[elec_nw_op],
                         carrier=elec_car)
    gec = esdl.GenericConsumer(id=str(uuid.uuid4()),
                               name='Unlimited Electricity Consumption',
                               port=[gec_ip],
                               power=gec_power,
                               costInformation=gec_ci)
    ar.asset.append(gec)

    gas_nw_op = esdl.OutPort(id=str(uuid.uuid4()),
                             name='GOut',
                             carrier=gas_car)
    gas_nw_ip = esdl.InPort(id=str(uuid.uuid4()), name='GIn', carrier=gas_car)
    gas_nw = esdl.GasNetwork(id=str(uuid.uuid4()),
                             name='GasNetwork',
                             port=[gas_nw_ip, gas_nw_op])
    ar.asset.append(gas_nw)

    ggp_mc = esdl.SingleValue(id=str(uuid.uuid4()),
                              name='MarginalCosts',
                              value=gas_prod_mc)
    ggp_ci = esdl.CostInformation(marginalCosts=ggp_mc)
    ggp_op = esdl.OutPort(id=str(uuid.uuid4()),
                          name='GOut',
                          connectedTo=[gas_nw_ip],
                          carrier=gas_car)
    ggp = esdl.GenericProducer(id=str(uuid.uuid4()),
                               name='Unlimited Gas Generation',
                               port=[ggp_op],
                               power=ggp_power,
                               costInformation=ggp_ci,
                               prodType=esdl.RenewableTypeEnum.FOSSIL)
    ar.asset.append(ggp)
    # ggc_mc = esdl.SingleValue(id=str(uuid.uuid4()), name='MarginalCosts', value=gas_cons_mc)
    # ggc_ci = esdl.CostInformation(marginalCosts=ggc_mc)
    # ggc_ip = esdl.InPort(id=str(uuid.uuid4()), name='EIn', connectedTo=[gas_nw_op], carrier=elec_car)
    # ggc = esdl.GenericConsumer(id=str(uuid.uuid4()), name='Unlimited Gas Consumption', port=[ggc_ip],
    #                            power=ggc_power, costInformation=ggc_ci)
    # ar.asset.append(ggc)

    for row in range(2, sheet.nrows - 3):
        sub_area_name = str(sheet.cell(row, 0).value)
        if sub_aggr_scope == 'DISTRICT':
            sub_area_number = sub_area_name[
                sub_area_number_pos:sub_area_number_pos + 2]
            sub_area_id = str(sub_aggr_id_start + sub_area_number)
        else:
            sub_area_id = str(sheet.cell(row, sub_aggr_code_column).value)

        gas_value = sheet.cell(row, gas_column).value
        if str(gas_value) != '?' and str(gas_value) != '':
            heat_value = gas_heater_efficiency * gas_value
        else:
            heat_value = None
        elec_value = sheet.cell(row, elec_column).value
        if str(elec_value) == '?' and str(elec_value) != '':
            elec_value = None

        sub_area = esdl.Area(id=sub_area_id,
                             name=sub_area_name,
                             scope=sub_aggr_scope)

        aggr_build = esdl.AggregatedBuilding(id=str(uuid.uuid4()),
                                             name="building")

        if heat_value:
            hdprofqau = esdl.QuantityAndUnitType(physicalQuantity='ENERGY',
                                                 multiplier='TERRA',
                                                 unit='JOULE')
            hdprof = esdl.InfluxDBProfile(id=str(uuid.uuid4()),
                                          multiplier=heat_value,
                                          host=influx_host,
                                          port=influx_port,
                                          database=influx_database,
                                          filters=influx_filters,
                                          measurement=gas_measurement,
                                          field=gas_field,
                                          profileQuantityAndUnit=hdprofqau,
                                          profileType='ENERGY_IN_TJ')
            hdip = esdl.InPort(id=str(uuid.uuid4()),
                               name='InPort',
                               carrier=heat_comm,
                               profile=hdprof)
            hd = esdl.HeatingDemand(id=str(uuid.uuid4()),
                                    name='HeatingDemand_' + sub_area_id,
                                    port=[hdip])

            ghip = esdl.InPort(id=str(uuid.uuid4()),
                               name='InPort',
                               connectedTo=[gas_nw_op],
                               carrier=gas_car)
            ghop = esdl.OutPort(id=str(uuid.uuid4()),
                                name='OutPort',
                                connectedTo=[hdip],
                                carrier=heat_comm)
            gh = esdl.GasHeater(id=str(uuid.uuid4()),
                                name='GasHeater_' + sub_area_id,
                                efficiency=gas_heater_efficiency,
                                power=gas_heater_power,
                                port=[ghip, ghop])

            dbd = esdl.DrivenByDemand(id=str(uuid.uuid4()),
                                      name='DBD_GasHeater_' + sub_area_id,
                                      energyAsset=gh,
                                      outPort=ghop)
            srvs.service.append(dbd)
            aggr_build.asset.append(hd)
            aggr_build.asset.append(gh)

        if elec_value:
            edprofqau = esdl.QuantityAndUnitType(physicalQuantity='ENERGY',
                                                 multiplier='TERRA',
                                                 unit='JOULE')
            edprof = esdl.InfluxDBProfile(id=str(uuid.uuid4()),
                                          multiplier=elec_value,
                                          host=influx_host,
                                          port=influx_port,
                                          database=influx_database,
                                          filters=influx_filters,
                                          measurement=elec_measurement,
                                          field=elec_field,
                                          profileQuantityAndUnit=edprofqau,
                                          profileType='ENERGY_IN_TJ')
            edip = esdl.InPort(id=str(uuid.uuid4()),
                               name='InPort',
                               connectedTo=[elec_nw_op],
                               carrier=elec_car,
                               profile=edprof)
            ed = esdl.ElectricityDemand(id=str(uuid.uuid4()),
                                        name='ElectricityDemand_' +
                                        sub_area_id,
                                        port=[edip])

            aggr_build.asset.append(ed)

        if heat_value or elec_value:
            sub_area.asset.append(aggr_build)

        ar.area.append(sub_area)

    if sname_bedrijven:
        sheet = book.sheet_by_name(sname_bedrijven)
        aggr_build_comp = esdl.AggregatedBuilding(id=str(uuid.uuid4()),
                                                  name="building-bedrijven")

        for row in range(2, sheet.nrows - 3):
            cat = str(sheet.cell(row, 0).value)
            waarde = sheet.cell(row, 1).value

            if cat != '' and waarde != 0 and waarde != '?':  # filter non relevant data
                cat = re.sub(' ', '_', cat)
                print(cat, waarde)

                if cat.find('m3') != -1:  # category contains gasusage
                    gas_tj = waarde * gas_energy_content / mega_to_terra
                    heat_tj = gas_tj * gas_to_heat_efficiency

                    hdbprofqau = esdl.QuantityAndUnitType(
                        physicalQuantity='ENERGY',
                        multiplier='TERRA',
                        unit='JOULE')
                    hdbprof = esdl.InfluxDBProfile(
                        id=str(uuid.uuid4()),
                        multiplier=heat_tj,
                        host=influx_host,
                        port=influx_port,
                        database=influx_database,
                        filters=influx_filters,
                        measurement=gas_measurement,
                        field=gas_field_comp,
                        profileQuantityAndUnit=hdbprofqau,
                        profileType='ENERGY_IN_TJ')
                    hdbip = esdl.InPort(id=str(uuid.uuid4()),
                                        name='InPort',
                                        carrier=heat_comm,
                                        profile=hdbprof)
                    hdb = esdl.HeatingDemand(id=str(uuid.uuid4()),
                                             name='HeatingDemand_' + cat,
                                             port=[hdbip])

                    ghbip = esdl.InPort(id=str(uuid.uuid4()),
                                        name='InPort',
                                        connectedTo=[gas_nw_op],
                                        carrier=gas_car)
                    ghbop = esdl.OutPort(id=str(uuid.uuid4()),
                                         name='OutPort',
                                         connectedTo=[hdbip],
                                         carrier=heat_comm)
                    ghb = esdl.GasHeater(id=str(uuid.uuid4()),
                                         name='GasHeater_' + cat,
                                         efficiency=gas_heater_efficiency,
                                         power=gas_heater_power,
                                         port=[ghbip, ghbop])

                    aggr_build_comp.asset.append(hdb)
                    aggr_build_comp.asset.append(ghb)

                    dbd = esdl.DrivenByDemand(id=str(uuid.uuid4()),
                                              name='DBD_GasHeater_' + cat,
                                              energyAsset=ghb,
                                              outPort=ghbop)
                    srvs.service.append(dbd)

                if cat.find(
                        'kWh') != -1:  # category contains electricity usage
                    elec_tj = waarde * kwh_to_tj

                    edbprofqau = esdl.QuantityAndUnitType(
                        physicalQuantity='ENERGY',
                        multiplier='TERRA',
                        unit='JOULE')
                    edbprof = esdl.InfluxDBProfile(
                        id=str(uuid.uuid4()),
                        multiplier=elec_tj,
                        host=influx_host,
                        port=influx_port,
                        database=influx_database,
                        filters=influx_filters,
                        measurement=elec_measurement,
                        field=elec_field_comp,
                        profileQuantityAndUnit=edbprofqau,
                        profileType='ENERGY_IN_TJ')
                    edbip = esdl.InPort(id=str(uuid.uuid4()),
                                        name='InPort',
                                        connectedTo=[elec_nw_op],
                                        carrier=elec_car,
                                        profile=edbprof)
                    edb = esdl.ElectricityDemand(id=str(uuid.uuid4()),
                                                 name='ElectricityDemand_' +
                                                 cat,
                                                 port=[edbip])

                    aggr_build_comp.asset.append(edb)

        ar.asset.append(aggr_build_comp)

    es.services = srvs

    rset = ResourceSet()
    rset.resource_factory['esdl'] = lambda uri: XMLResource(uri)
    rset.metamodel_registry[esdl.nsURI] = esdl
    resource = rset.create_resource(
        URI(top_area_name + top_area_year + '.esdl'))
    resource.append(es)
    resource.save()
def MakeESDL(RegioNaam, flipcsv, actions):
    rset = ResourceSet()
    rset.metamodel_registry[esdl.nsURI] = esdl
    rset.resource_factory['esdl'] = lambda uri: XMLResource(
        uri
    )  # we register the factory for '.esdl' extension and XML serialization

    es_name = RegioNaam

    # Create a new EnergySystem
    es = EnergySystem(id=str(uuid.uuid4()), name=es_name)
    instance = Instance(id=str(uuid.uuid4()), name='y2030')

    # AbstractInstanceDate = InstanceDate.date(2020)
    RawDate = '2030'
    instance.date = InstanceDate(date=EDate.from_string(RawDate + "-01-01"))
    instance.aggrType = AggrTypeEnum.PER_COMMODITY
    es.instance.append(instance)
    es.instance[0].area = Area(id=RegioNaam, name=RegioNaam)

    esi = EnergySystemInformation(id=str(uuid.uuid4()))
    qau = QuantityAndUnits(id=str(uuid.uuid4()))
    es.energySystemInformation = esi
    esi.quantityAndUnits = qau

    s1a = Measures(id=str(uuid.uuid4()))

    if not os.path.exists(flipcsv):
        print("========= WARNING: {} does not exist! Skipping...".format(
            flipcsv))
    else:
        with open(flipcsv, newline='') as csvfile:
            csvfile = (line.lower() for line in csvfile)
            reader = csv.reader(csvfile, delimiter=';')

            column_names = next(reader)
            print(column_names)

            for row in reader:
                bu_code = row[column_names.index('bu_code')]
                bu_code.replace('\'', '')  # remove quotes from bu_code
                area = Area(id=bu_code, scope="NEIGHBOURHOOD")

                ce_buurtoptie = row[column_names.index('uitkomst_gecheckt')]

                # measure = Measure(id=str(uuid.uuid4()),name=ce_buurtoptie)

                if not ce_buurtoptie == '':
                    measures = Measures(id=str(uuid.uuid4()))
                    # measures.measure.append(ce_buurtoptie)

                    # ce_buurtoptie = row[column_names.index('uitkomst_gecheckt')]
                    # measure = Measure(id=str(uuid.uuid4()),name=ce_buurtoptie)
                    if ce_buurtoptie == 'all-electric':
                        measures.measure.append(
                            MeasureReference(id=str(uuid.uuid4()),
                                             reference='S1a_B_LuchtWP'))
                        # measures.measure.append(MeasureReference(id=str(uuid.uuid4()),reference='s1b'))
                    if ce_buurtoptie == 'warmtenet':
                        measures.measure.append(
                            MeasureReference(id=str(uuid.uuid4()),
                                             reference='S2a_B_Restwarmte'))
                        # measures.measure.append(MeasureReference(id=str(uuid.uuid4()),reference='s2b'))
                        # measures.measure.append(MeasureReference(id=str(uuid.uuid4()),reference='s3a'))
                        # measures.measure.append(MeasureReference(id=str(uuid.uuid4()),reference='s3b'))
                        # measures.measure.append(MeasureReference(id=str(uuid.uuid4()),reference='s3c'))
                        # measures.measure.append(MeasureReference(id=str(uuid.uuid4()),reference='s3d'))
                        measures.measure.append(
                            MeasureReference(id=str(uuid.uuid4()),
                                             reference='S3e_B_TEO'))
                    if ce_buurtoptie == 'groengas':
                        measures.measure.append(
                            MeasureReference(id=str(uuid.uuid4()),
                                             reference='S4a_GG_B_hWP'))
                        # measure.append(MeasureReference(id=str(uuid.uuid4()),reference='s4b'))

                    ed_app_sv.profileQuantityAndUnit = MeasureReference(
                        reference=s1a)
                    ed_app_ip.profile.append(ed_app_sv)

                    area.measures = measures
                es.instance[0].area.area.append(area)

# <measures xsi:type="esdl:Measures">
#   <measure xsi:type="esdl:Measure" id="S1a_B_LuchtWP" name="S1a_B_LuchtWP"/>
#   <measure xsi:type="esdl:Measure" id="S3a_B_LT30_30" name="S3a_B_LT30_30"/>
#   <measure xsi:type="esdl:Measure" id="S0_Referentie" name="S0_Referentie"/>
# </measures>

    if 'save_to_disk' in actions:
        export_name = "FlipInput/%s.esdl" % (RegioNaam)
        resource = rset.create_resource(URI(export_name))
        resource.append(es)
        resource.save()