def __init__(self,
                 topnode,
                 bdnnode=None,
                 range=None,
                 pollutants=['HC'],
                 srcLimit=5,
                 bdnLimit=5,
                 filterSrc=False,
                 rawBdn=None):
        '''constructor
        inputs:
        range - user input range {'xmin', 'xmax', 'ymin', 'ymax'}, actual range is the min(user range, region envelope(e.g. jurongisland))
        topnode - uri of topnode to begin search within tree struct,
        filtersrc - true if use all children under topnode as src, false to use topnode as src directly
        bdnnode - top/colleciton node of building
        pollutants: pollutant to test
        srcLimit: limit of src number, actual number might fewer
        bdnLimit: limit of bdn number, actual number might fewer
        '''
        self.address = None
        self.pollutants = pollutants
        self.topnode = topnode
        self.bdnnode = bdnnode
        self.srcLimit = srcLimit
        self.bdnLimit = bdnLimit
        # TODO-AE remove filterSrc and topnode
        self.filterSrc = False
        self.rawBdn = rawBdn

        self.range = self.getRange(range)
        print(self.range)

        self.pythonLogger = PythonLogger('admsInputDataRetrieverNew.py')
Exemplo n.º 2
0
    def write(self):
        pythonLogger = PythonLogger('admsAplWriter.py')
        pythonLogger.postInfoToLogServer('writing to ' + self.address)
        
        #if contains this data, execute the corresponding writing function
        with open(self.address, 'w') as file:
            self.writeStr(file, HEADER)
            self.writeStr(file,SUP)
            self.writeTemp(file,MET,[self.data['Met']])
            self.writeBdn(file, self.data['Bdn'])
            self.writeStr(file,HIL)
            self.writeStr(file,FLC)
            self.writeTemp(file,GRD,self.data['Grd'])

            self.writeStr(file,PUFGAM)
            self.writeOpt(file,self.data['Opt'])
            self.writeStr(file,CHM)
            self.writeStr(file,BKGETC)


            #self.writeCoordSys(file)           # a special case, to be unified in future
            self.writeCoordSys(file, self.data['CoordiSys'])
            self.writeStr(file,MAP)
            self.writeStr(file,POLD)
            #self.writeTemp(self.data['OPT'])
            #del self.data['OPT']
            self.writeSrc(file, self.data['Src'])

          
          #  for category,value in self.data.items():  
           #     self.__getattribute__('write'+category)(file, value)
            #to be canceled in future, no copy all     
            
        pythonLogger.postInfoToLogServer('finished writing to ' + self.address)
Exemplo n.º 3
0
    # --Obtain list of building heights-- #
    # --Obtain list of building coordinates-- #

    listBuildingHeights = []
    listBuildingCoordinates = []

    for building in listOfIRIs:

        buildingHeight = sparqlBuildingHeights(building, sparqlEndPoint)["results"]["bindings"]
        height = getBuildingHeights(buildingHeight)
        listBuildingHeights.append(height)

        buildingCoordinates = sparqlBuildingCoordinates(building, sparqlEndPoint)["results"]["bindings"]
        coordinates = getBuildingCoordinates(buildingCoordinates, owlCRS, osmCRS)
        listBuildingCoordinates.append(coordinates)


    listBuildingsToTransfer = getGeoJSON(listBuildingCoordinates, listBuildingHeights, cityiri)

    return json.dumps(listBuildingsToTransfer)

if __name__ == "__main__":
    pythonLogger = PythonLogger('ADMSGeoJsonGetter.py')
    pythonLogger.postInfoToLogServer('start of ADMSGeoJsonGetter.py')
    try:
        returnResultsToJava(return_buildings())
        pythonLogger.postInfoToLogServer('end of ADMSGeoJsonGetter.py')
    except Exception as e:
        returnExceptionToJava(e)
        pythonLogger.postInfoToLogServer('end of ADMSGeoJsonGetter.py')
Exemplo n.º 4
0
from admsInputDataRetrieverNew import admsInputDataRetriever
from admsAplWriter import admsAplWriter
from collections import namedtuple
from caresjpsutil import PythonLogger
import json
import sys
import config
import cobbling




if __name__ == "__main__":
    
    pythonLogger = PythonLogger('admsMainNew.py')
    try:
        pythonLogger.postInfoToLogServer('start with ' + sys.argv[0] + '  plant = ' + sys.argv[1] + '  coordinates = ' + sys.argv[2] 
                                         + '  ADMS working dir = ' + sys.argv[3] + '  top = ' + config.bldTopnode)
        cobbling.run()
        coordinates = str(sys.argv[2]).replace("'", "\"").replace('#',',');
        coordinates = json.loads(coordinates)
    
        buildingdata = sys.argv[4].replace("\'","\"")
        buildingdata = json.loads(buildingdata)
        BDN = namedtuple('BDN', ['BldNumBuildings','BldName','BldType','BldX','BldY','BldHeight', 'BldLength', 'BldWidth', 'BldAngle'])
        BDN.BldName = buildingdata['BldName']
        BDN.BldNumBuildings = len(BDN.BldName)
        BDN.BldType = buildingdata['BldType']
        BDN.BldX = buildingdata['BldX']
        BDN.BldY = buildingdata['BldY']
        BDN.BldHeight = buildingdata['BldHeight']
Exemplo n.º 5
0
        miscCosts, cpo, fame)
    u_prices['V_Price_Electricity_001'] /= ex_rates['V_USD_to_SGD']

    # Adjust prices to include the transport cost
    prices = transport_costs(prices, t_prices)

    # Search through the arbitrage opportunities
    return look_for_munnies(MoDS_data, prices, dates, s_prices, u_prices)

    # Define titles and labels to plot the futures prices data and plot the data
    #labels = {'FAME':{'title':'Biodiesel FAME futures prices from Chicago Mercantile Exchange', 'label':'Price (USD per tonne)'},'CPO':{'title':'Crude palm oil futures prices from Chicago Mercantile Exchange', 'label':'Price (USD per tonne)'}, 'x':{'title':'Delivery date (-)', 'label':dates['FAME']}}
    #plotting_prices(dates, prices, labels)


if __name__ == "__main__":

    pythonLogger = PythonLogger('CPO_to_FAME_MoDS2.py')
    pythonLogger.postInfoToLogServer('start of CPO_to_FAME_MoDS2.py')

    MoDS_data = str(sys.argv[1])
    miscCosts = json.loads(sys.argv[2])
    cpo = json.loads(sys.argv[3])
    fame = json.loads(sys.argv[4])
    try:
        returnResultsToJava(run(MoDS_data, miscCosts, cpo, fame))
    except Exception as e:
        import traceback
        pythonLogger.postInfoToLogServer(traceback.print_exc())
        returnExceptionToJava(e)
    finally:
        pythonLogger.postInfoToLogServer('end of CPO_to_FAME_MoDS2.py')
Exemplo n.º 6
0
import sys
import json
from config import Constants
from collections import namedtuple
from admsAplWriter import admsAplWriter
from admsInputDataRetrieverNew import admsInputDataRetriever
from caresjpsutil import PythonLogger

pythonLogger = PythonLogger('admsTest.py')


def get_bdn(buildingdata):
    bdn = namedtuple(Constants.BLD_BDN, [
        Constants.BLD_NUM, Constants.BLD_NAME, Constants.BLD_TYPE,
        Constants.BLD_X, Constants.BLD_Y, Constants.BLD_HEIGHT,
        Constants.BLD_LRNGTH, Constants.BLD_WIDTH, Constants.BLD_ANGLE
    ])
    bdn.BldName = buildingdata[Constants.BLD_NAME]
    bdn.BldNumBuildings = len(bdn.BldName)
    bdn.BldType = buildingdata[Constants.BLD_TYPE]
    bdn.BldX = buildingdata[Constants.BLD_X]
    bdn.BldY = buildingdata[Constants.BLD_Y]
    bdn.BldHeight = buildingdata[Constants.BLD_HEIGHT]
    bdn.BldLength = buildingdata[Constants.BLD_LRNGTH]
    bdn.BldWidth = buildingdata[Constants.BLD_WIDTH]
    bdn.BldAngle = buildingdata[Constants.BLD_ANGLE]

    return bdn


def get_coordinates(coordinates):
Exemplo n.º 7
0
    # return [out0[1], out1[1], out2[1], out3[1],
    #  out4[1], totGen, out0[2], out1[2], out2[2], out3[2], out4[2]]
    #  industrial cost, renewable generation, residential load 1, residential load 2, residential load 3, commerical load, industrial load]
    return [out0, out1, out2, out3, out4, totGen]


if __name__ == "__main__":
    import pandas as pd
    import sys
    from caresjpsutil import returnExceptionToJava, returnResultsToJava
    from caresjpsutil import PythonLogger
    from datetime import datetime

    now = datetime.now()
    current_time = now.strftime("%H:%M:%S")
    pythonLogger = PythonLogger('system.py')
    pythonLogger.postInfoToLogServer('start of system.py, Current Time = ' +
                                     current_time)
    folder = sys.argv[1]
    #forecast Weather
    dfWeather = pd.read_csv(folder + '/WeatherForecast.csv',
                            sep=',',
                            header=None)
    AirTemp = dfWeather[0].to_numpy()
    Radiation = dfWeather[1].to_numpy()
    # Residential Agent
    # electricity bill structure
    household_below = 1 / 50 * 0.01 * np.ones(24)
    household_above = 1 / 50 * 0.02 * np.ones(24)
    cd = 0.003
    Nr = 60  #No of Households?
Exemplo n.º 8
0
	rg.Tc_ref = Tc_ref
	rg.G_ref = G_ref
	rg.Eg_ref = Eg_ref
	rg.k = k
	
	# solar generation profile
	return Ns*rg.solar_energy(Radiation, AirTemp)/1000


if __name__ == "__main__":
	import pandas as pd
	import sys
	from caresjpsutil import returnExceptionToJava, returnResultsToJava
	from caresjpsutil import PythonLogger

	pythonLogger = PythonLogger('solarRadiation.py')
	pythonLogger.postInfoToLogServer('start of solarRadiation.py')
	folder = sys.argv[1]
	dfWeather=pd.read_csv(folder + '/WeatherForecast.csv', sep=',', header=None)
	AirTemp = dfWeather[0].to_numpy()
	Radiation = dfWeather[1].to_numpy()
	# AirTemp = np.array([28.45, 28.3 , 28.11, 27.9 , 27.74, 27.68, 27.59,
	#  27.54, 26.59, 23.82, 26.7 , 28.23, 28.92, 29.15, 30.56, 30.45, 30.65,
	#   31.06, 30.97, 30.76, 30.03, 29.76, 29.48, 28.99])
	# Radiation = np.array([1.700e-02, 2.100e-02, 1.500e-02, 2.000e-02, 1.800e-02,
	#  1.500e-02, 2.400e-02, 3.360e-01, 2.343e+01, 1.193e+02, 4.061e+02, 5.386e+02,
	#   6.513e+02, 7.080e+02, 7.000e+02, 6.656e+02, 5.661e+02, 4.238e+02, 2.571e+02,
	#    8.630e+01, 1.071e+00, 1.900e-02, 1.800e-02, 1.700e-02])

	dfSolar=pd.read_csv(folder + '/PVGenerator.csv', sep=',', header=None)
	alpha_sc = dfSolar.iloc[0,0] #0.002132 #<http://www.theworldavatar.com/kb/sgp/singapore/singaporeelectricalnetwork/PVPanel-001.owl#V_TempCoeffSCC_PVPanel-001>
Exemplo n.º 9
0
	genH2 = res_el['n']*3.6
	Ig = np.kron(ip.res.x[ip.Nc:], np.ones(ip.mc))
	res_fc = ip.fc.N_time_steps(Ig)
	conH2 = res_fc['n']*3.6
	genEl = res_fc['P']/1000
	return [ip.res.x, ip.objfunction(ip.res.x), ip.report_load(),
	 np.dot(np.kron(np.identity(24), 1/ip.mc*np.ones(ip.mc)), genH2), np.dot(np.kron(np.identity(24),
	  1/ip.mc*np.ones(ip.mc)), conH2-genH2), np.dot(np.kron(np.identity(24), 1/ip.mc*np.ones(ip.mc)), conEl-genEl)]

if __name__ == "__main__":
	import pandas as pd
	import sys
	from caresjpsutil import returnExceptionToJava, returnResultsToJava
	from caresjpsutil import PythonLogger

	pythonLogger = PythonLogger('industrial.py')
	pythonLogger.postInfoToLogServer('start of industrial.py')
	folder = sys.argv[1]
	dfWeather=pd.read_csv(folder + '/WeatherForecast.csv', sep=',', header=None)
	AirTemp = dfWeather[0].to_numpy()
	industry_below = np.array([0.000154, 0.000154, 0.000154, 0.000154, 0.000154, 0.000154, 0.000154, 0.000154, 0.000154, 0.000154, 0.000154, 0.000154, 0.000154, 0.000154, 0.000154, 0.000154, 0.000154, 0.000154, 0.000154, 0.000154, 0.000154, 0.000154, 0.000154, 0.000154])
	industry_above = np.array([0.000308, 0.000308, 0.000308, 0.000308, 0.000308, 0.000308, 0.000308, 0.000308, 0.000308, 0.000308, 0.000308, 0.000308, 0.000308, 0.000308, 0.000308, 0.000308, 0.000308, 0.000308, 0.000308, 0.000308, 0.000308, 0.000308, 0.000308, 0.000308])
   
	#Electrolyzer
	DF_E= pd.read_csv(folder + "/ElectrolyzerConstant.csv", header=None )
	# physical constants:
	F = DF_E.iloc[2,1] #96485.34 #[A*s/mol] #Faraday's Constant
	z1 = DF_E.iloc[6,1] #2 # no. of electrons transferred per reaction #This is standard for the reaction
	# reaction information: (25 degreeC and 1 bar @ standard conditions) 
	dG0 = DF_E.iloc[8,1] #237e3 #[J/mol]
	dH = DF_E.iloc[9,1] #286e3 #[J/mol]
Exemplo n.º 10
0
    return [
        cb.res.x,
        cb.objfunction(cb.res.x),
        cb.report_load(),
        np.dot(np.kron(np.identity(24), 1 / cb.mc * np.ones(cb.mc)), RoomTemp),
        cb.res.x
    ]


if __name__ == "__main__":
    import pandas as pd
    import sys
    from caresjpsutil import returnExceptionToJava, returnResultsToJava
    from caresjpsutil import PythonLogger

    pythonLogger = PythonLogger('commercial.py')
    pythonLogger.postInfoToLogServer('start of commercial.py')
    folder = sys.argv[1]
    dfWeather = pd.read_csv(folder + '/WeatherForecast.csv',
                            sep=',',
                            header=None)
    dfConst = pd.read_csv(folder + '/constant.csv', sep=',', header=None)
    AirTemp = dfWeather[0].to_numpy()
    Radiation = dfWeather[1].to_numpy()
    C1 = dfConst.iloc[0, 0]
    C2 = dfConst.iloc[0, 1]
    C3 = dfConst.iloc[0, 2]
    K1 = dfConst.iloc[0, 3]
    K2 = dfConst.iloc[0, 4]
    K3 = dfConst.iloc[0, 5]
    K4 = dfConst.iloc[0, 6]
# Preconditions:
# 1. external libraries must be installed in system
# 2. "data" folder must be placed in workingdir of JPS_POWERPLANTEMISSION
# 3. costEmissionCalculation.py file placed in the same folder i.e. caresjpspowerplantemission

# Postconditions:
# Takes in data from csv files and constructs a surrogate model for each of the csv files
# which represents a specific technology


# define a function here that can interpolate the emission and cost surface, and calculate the corresponding power plant emission
# m is the power plant database, n is the emission inventory

if __name__ == "__main__":
    pythonLogger = PythonLogger('PlantEmissionCalculationTest.py')
    pythonLogger.postInfoToLogServer('start of PlantEmissionCalculationTest.py')
    
    try:
        dirPath = sys.argv[1]
        
        # load the powerplant database    
        df = pd.read_csv(dirPath + '/data/input/powerplant_database.csv', header='infer', sep=',')
             
        # choose ultrasupercritical PC from the database
        df_01 = df[df.generation_technology == 'ultrasupercritical']
        # load the emission inventory
        df_1 = pd.read_csv(dirPath +  '/data/input/baseplant/base_ultrasupercritical_PC_coal.csv', header='infer', sep=',')
         
        # choose anthracite and supercritical PC from the database
        df_m = df[df.generation_technology == 'supercritical']
Exemplo n.º 12
0
        prices["MeOH"][i] /= ex_rates['V_USD_to_CNY']
    prices["MeOH"][1] = 'Prior Settlement (USD per tonne)'

    # Adjust prices to include the transport cost
    prices = transport_costs(prices, t_prices)

    # Search through the arbitrage opportunities
    return look_for_munnies(MoDS_data, prices, dates, s_prices, u_prices)

    # Define titles and labels to plot the futures prices data and plot the data
    #labels = {'NG':{'title':'Natural gas futures prices from Chicago Mercantile Exchange', 'label':'Price (USD per mmBTU)'},'MeOH':{'title':'Methanol futures prices from Zhengzhou Commodity Exchange', 'label':'Price (USD per tonne)'}, 'x':{'title':'Delivery date (-)', 'label':dates['NG']}}
    #plotting_prices(dates, prices, labels)


if __name__ == "__main__":
    pythonLogger = PythonLogger('NG_to_MeOH_MoDS.py')
    pythonLogger.postInfoToLogServer('start of NG_to_MeOH_MoDS.py')

    MoDS_data = str(sys.argv[1])
    miscCosts = json.loads(sys.argv[2])
    hng = json.loads(sys.argv[3])
    zce = json.loads(sys.argv[4])

    try:
        returnResultsToJava(run(MoDS_data, miscCosts, hng, zce))
    except Exception as e:
        returnExceptionToJava(e)
    finally:
        pythonLogger.postInfoToLogServer('end of NG_to_MeOH_MoDS.py')

#     run("0.5527777778,-1.9678704734013681E43,-1.947340493583137E67,-1.3064212763820435E47,3063955.568812896,0.0,-1.312550425729447E46,-1.8126031951762418E54,-1.052184254037493E43",
Exemplo n.º 13
0
import sys
from caresjpsutil import PythonLogger
from config import Constants
from adms_apl_builder import AplDirector, AdmsAplPlantBuilder, AdmsAplShipBuilder
from adms_input_retriever import CliInputContext

pythonLogger = PythonLogger('adms_processor.py')


class AdmsProcessor(object):
    def __init__(self):
        self.input = None

    def get_input(self, args):
        context = CliInputContext(args)
        self.input = context.get_input()

    def save_apl(self, args):
        self.get_input(args)
        builder = None
        if args[1] == Constants.ENTITY_TYPE_PLANT:
            builder = AdmsAplPlantBuilder(self.input)
        elif args[1] == Constants.ENTITY_TYPE_SHIP:
            builder = AdmsAplShipBuilder(self.input)
        director = AplDirector()
        director.set_builder(builder)
        apl = director.get_apl()
        spec = apl.specification()
        with open(str(args[5]) + Constants.FILE_NAME_APL, 'w') as file:
            file.write(spec)
        file.close()
class admsInputDataRetriever(object):
    BDN = namedtuple('BDN', [
        'BldNumBuildings', 'BldName', 'BldType', 'BldX', 'BldY', 'BldHeight',
        'BldLength', 'BldWidth', 'BldAngle'
    ])
    OPT = namedtuple('OPT', [
        'OptNumOutputs', 'OptPolName', 'OptInclude', 'OptShortOrLong',
        'OptSamplingTime', 'OptSamplingTimeUnits', 'OptCondition',
        'OptNumPercentiles', 'OptNumExceedences', 'OptPercentiles',
        'OptExceedences', 'OptUnits', 'OptGroupsOrSource', 'OptAllSources',
        'OptNumGroups', 'OptIncludedGroups', 'OptIncludedSource',
        'OptCreateComprehensiveFile'
    ])

    def __init__(self,
                 topnode,
                 bdnnode=None,
                 range=None,
                 pollutants=['HC'],
                 srcLimit=5,
                 bdnLimit=5,
                 filterSrc=False,
                 rawBdn=None):
        '''constructor
        inputs:
        range - user input range {'xmin', 'xmax', 'ymin', 'ymax'}, actual range is the min(user range, region envelope(e.g. jurongisland))
        topnode - uri of topnode to begin search within tree struct,
        filtersrc - true if use all children under topnode as src, false to use topnode as src directly
        bdnnode - top/colleciton node of building
        pollutants: pollutant to test
        srcLimit: limit of src number, actual number might fewer
        bdnLimit: limit of bdn number, actual number might fewer
        '''
        self.address = None
        self.pollutants = pollutants
        self.topnode = topnode
        self.bdnnode = bdnnode
        self.srcLimit = srcLimit
        self.bdnLimit = bdnLimit
        # TODO-AE remove filterSrc and topnode
        self.filterSrc = False
        self.rawBdn = rawBdn

        self.range = self.getRange(range)
        print(self.range)

        self.pythonLogger = PythonLogger('admsInputDataRetrieverNew.py')

    def getRange(self, userrange):
        return ((float(userrange['xmin']), float(userrange['xmax'])),
                (float(userrange['ymin']), float(userrange['ymax'])))

    def getSrcData(self):
        '''get all sourced data : 
        returns: data object 
        '''
        self.pythonLogger.postInfoToLogServer('start getSrcData(), topnode=' +
                                              self.topnode)

        filtered = (self.topnode, )

        s = set()  #make a set of substance to query later
        result = []
        for uri in filtered:
            print("connecting: {:s}".format(uri))
            self.connectDB(uri, connectType='parse')
            qdata = self.query("""
                PREFIX sys: <http://www.theworldavatar.com/ontology/ontocape/upper_level/system.owl#>
                PREFIX space_and_time_extended: <http://www.theworldavatar.com/ontology/ontocape/supporting_concepts/space_and_time/space_and_time_extended.owl#>
                PREFIX plant:<http://www.theworldavatar.com/ontology/ontocape/chemical_process_system/CPS_realization/plant.owl#>
                PREFIX topology:<http://www.theworldavatar.com/ontology/meta_model/topology/topology.owl#>
                PREFIX behavior: <http://www.theworldavatar.com/ontology/ontocape/chemical_process_system/CPS_behavior/behavior.owl#>
                PREFIX chemical_process_system:<http://www.theworldavatar.com/ontology/ontocape/chemical_process_system/chemical_process_system.owl#>
                PREFIX phase_system:<http://www.theworldavatar.com/ontology/ontocape/material/phase_system/phase_system.owl#>
                PREFIX material: <http://www.theworldavatar.com/ontology/ontocape/material/material.owl#>
                PREFIX substance:<http://www.theworldavatar.com/ontology/ontocape/material/substance/substance.owl#>

                SELECT ?o ?height ?diameter ?content ?x ?y ?velocity ?massflow ?temp ?moleweight ?heatcapa ?density
                WHERE {{
                ?o plant:hasHeight ?he.
                ?he sys:numericalValue ?height .

                 ?o sys:hasSubsystem ?chm.
                ?chm plant:hasInsideDiameter ?de . #?dev  sys:hasValue ?de.
                ?de sys:numericalValue ?diameter.

                ?phase phase_system:has_temperature  ?tempE.
                ?tempE sys:hasValue ?vte.
                ?vte sys:numericalValue ?temp .

                ?o space_and_time_extended:hasGISCoordinateSystem ?coe .
                ?coe space_and_time_extended:hasProjectedCoordinate_x ?xe.
                 ?xe sys:hasValue ?xv.
                  ?xv sys:numericalValue ?x.

                   ?coe space_and_time_extended:hasProjectedCoordinate_y ?ye.
                 ?ye sys:hasValue ?yv.
                  ?yv sys:numericalValue ?y.

                  ?stream topology:leaves ?o.
                  ?stream chemical_process_system:refersToGeneralizedAmount ?ga.
                  ?ga sys:hasSubsystem ?ma.
                  
                  ?ma sys:hasProperty ?ve.
                  ?ve a behavior:Velocity .
                  ?ve sys:hasValue ?vv.
                  ?vv sys:numericalValue ?velocity.
                  
                  ?ma sys:hasProperty ?me.
                  ?me a behavior:ConvectiveMassFlowrate .
                  ?me sys:hasValue ?mv.
                  ?mv sys:numericalValue ?massflow.
    
                 ?mw a substance:MolecularWeight.
                 ?mw sys:hasValue ?mwv.
                 ?mwv  sys:numericalValue ?moleweight.
    
                 ?cp a phase_system:ThermodynamicStateProperty.
                                     ?cp sys:hasValue ?cpv.
                 ?cpv  sys:numericalValue ?heatcapa.
    
                 ?den a phase_system:Density.
                  ?den sys:hasValue ?denv.
                 ?denv  sys:numericalValue ?density.
    
                }}
                LIMIT 1 
            """)

            aresult, = [row.asdict() for row in qdata]

            qdataC = self.query("""
                    PREFIX sys: <http://www.theworldavatar.com/ontology/ontocape/upper_level/system.owl#>
			PREFIX substance:<http://www.theworldavatar.com/ontology/ontocape/material/substance/substance.owl#>

            SELECT DISTINCT  ?content
            WHERE {{
            ?mix a substance:Mixture.
            ?mix sys:containsDirectly  ?content. 
            }}
            """)

            contents = [row['content'].toPython() for row in qdataC]

            s = s.union(contents)
            aresult['content'] = contents

            qdataERate = self.query("""
                    PREFIX sys: <http://www.theworldavatar.com/ontology/ontocape/upper_level/system.owl#>
           PREFIX substance:<http://www.theworldavatar.com/ontology/ontocape/material/substance/substance.owl#>
           PREFIX behavior:<http://www.theworldavatar.com/ontology/ontocape/chemical_process_system/CPS_behavior/behavior.owl#>

            SELECT DISTINCT  ?er ?v
            WHERE {{
            ?mix a substance:Mixture.
            ?mix sys:hasProperty  ?er.
            ?er  a behavior:ConvectiveMassFlowrate.
                         ?er sys:hasValue ?erv.
             ?erv sys:numericalValue ?v
            }}
            """)

            emissionrates = {
                row['er'].toPython(): row['v'].toPython()
                for row in qdataERate
            }
            #todo: sort emissionrates to order of substances

            sorteder = []
            for content in contents:
                name = content.split('#')[1]
                for ername, v in emissionrates.items():
                    if name in ername:
                        sorteder.append(v)

            print(sorteder)
            aresult['emissionrates'] = sorteder

            result.append(aresult)

        print("FILTERED :")
        print(result)
        '''   
        #use this if need query substance separately
        #query substance for substance related data
        cMap = {}

        
        #hard coding for now before I get a better solusion
        self.connectDB("http://www.theworldavatar.com/ontology/ontocape/material/substance/substance.owl", connectType = 'parse')

        template = """
            PREFIX sys: <http://www.theworldavatar.com/ontology/ontocape/upper_level/system.owl#>
            PREFIX space_and_time_extended: <http://www.theworldavatar.com/ontology/ontocape/supporting_concepts/space_and_time/space_and_time_extended.owl#>
            PREFIX sub:<http://www.theworldavatar.com/ontology/ontocape/material/substance/substance.owl#>
            PREFIX behavior: <http://www.theworldavatar.com/ontology/ontocape/chemical_process_system/CPS_behavior/behavior.owl#>
            PREFIX phase_system:<http://www.theworldavatar.com/ontology/ontocape/material/phase_system/phase_system.owl#>
            SELECT DISTINCT  ?o ?hc ?d ?mw
            WHERE {{
            <{0}> behavior:hasHeatCapacityRatio  ?hce.   #heatcapacity ratio
            ?hce sys:hasValue ?hcv . 
            ?hcv sys:numericalValue ?hc.
           
            <{0}> phase_system:has_density ?de .        #density
           ?de sys:hasValue ?dv . 
            ?dv sys:numericalValue ?d.
           
             <{0}> sys:hasProperty ?mwe.                #molecular weight
             ?mwe a sub:MolecularWeight .
             ?mwe sys:hasValue ?mwv . 
            ?mwv sys:numericalValue ?mw.
            }}
            LIMIT 1
       """

        for sub in s:
            print (sub)
            print (template.format(sub))
            cMap[sub], = self.query(template.format(sub))

               
     
        
        #todo:construct an array of contents, and corresponding content data
        

            subData = {}
            subData['mw'] = [cMap[content]['mw'] for content in src['content'] ]
            subData['d'] = [cMap[content]['d'] for content in src['content'] ]
            subData['hc'] = [cMap[content]['hc'] for content in src['content'] ]
            pollutantnames = [self.polIRI2Name(content) for content in src['content'] ]
            print(subData)
            print('!!!!!!!!!!!')
            print(src['y'].datatype)
            print(src['y'].value)
            print(type(src['y'].value))

            print(src['y'].toPython)
            print(float(src['y']))

        '''
        packed = []
        for src in result:
            SrcNumPollutants = len(src['content'])
            pollutantnames = [
                self.polIRI2Name(content) for content in src['content']
            ]

            newSrc = admsSrc(SrcName=src['o'].toPython(),
                             SrcHeight=src['height'].toPython(),
                             SrcDiameter=src['diameter'].toPython(),
                             SrcVertVeloc=src['velocity'].toPython(),
                             SrcPolEmissionRate=src['emissionrates'],
                             SrcPollutants=pollutantnames,
                             SrcTemperature=src['temp'].toPython(),
                             SrcX1=src['x'].toPython(),
                             SrcY1=src['y'].toPython(),
                             SrcMolWeight=src['moleweight'].toPython(),
                             SrcDensity=src['density'].toPython(),
                             SrcSpecHeatCap=src['heatcapa'].toPython(),
                             SrcNumPollutants=SrcNumPollutants,
                             SrcMassFlux=src['massflow'].toPython())
            packed.append(newSrc)

        return packed

    def filterBdnEnvelope(self):
        '''
        Get all buildings within range by comparing range with envelope
        return list of building url
        '''
        xRange, yRange = self.range
        qb = self.query('''
            PREFIX sys: <http://www.theworldavatar.com/ontology/ontocape/upper_level/system.owl#>
            PREFIX citygml: <http://www.theworldavatar.com/ontology/ontocitygml/OntoCityGML.owl#>
            PREFIX space_and_time_extended: <http://www.theworldavatar.com/ontology/ontocape/supporting_concepts/space_and_time/space_and_time_extended.owl#>
            PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

              SELECT distinct ?bdn 
              WHERE{{
              ?cityM a citygml:CityModelType.
              ?cityM citygml:boundedBy ?envelope .
              ?envelope a citygml:EnvelopeType.            # get all envelopes
              ?envelope citygml:upperCornerPoint ?upoint.  # get bounds of envelope
              ?upoint space_and_time_extended:hasGISCoordinateSystem ?uco.  
              ?uco   space_and_time_extended:hasProjectedCoordinate_x ?uxe.    
              ?uxe sys:hasValue ?uxv.
              ?uxv sys:numericalValue ?ux.
              ?uco   space_and_time_extended:hasProjectedCoordinate_y ?uye.
              ?uye sys:hasValue ?uyv.
              ?uyv sys:numericalValue ?uy.
              ?envelope citygml:lowerCornerPoint ?lpoint.
              ?lpoint space_and_time_extended:hasGISCoordinateSystem ?lco.  
              ?lco   space_and_time_extended:hasProjectedCoordinate_x ?lxe.    
              ?lxe sys:hasValue ?lxv.
              ?lxv sys:numericalValue ?lx.
              ?lco   space_and_time_extended:hasProjectedCoordinate_y ?lye.
              ?lye sys:hasValue ?lyv.
              ?lyv sys:numericalValue ?ly.
              ?cityM citygml:cityObjectMember ?bdn .  #get bdn belongs to filterd envelope
                Filter(xsd:double(?ly) > "{1}"^^xsd:double  && xsd:double(?uy) < "{2}"^^xsd:double && xsd:double(?lx) > "{3}"^^xsd:double && xsd:double(?ux) < "{4}"^^xsd:double) #filter envelope within range
                        }} 
            LIMIT {0}   #limit of building num
            '''.format(self.bdnLimit, *yRange, *xRange))

        ########todo: in future delete stud data
        return tuple(row['bdn'] for row in qb)

    def coreBdn2Src(self):
        self.pythonLogger.postInfoToLogServer(
            'calculate main building for each src')
        #compare src coords to each bdn
        y_midpoint = (self.range[1][0] + self.range[1][1]) / 2
        x_midpoint = (self.range[0][0] + self.range[0][1]) / 2
        for src in self.rawSrc:
            closed, dClosed, first = None, sys.maxsize, True
            #print('find closed bdn for src: '+src.SrcName+" with x: "+str(src.SrcX1) +" y: "+str(src.SrcY1))

            self.pythonLogger.postInfoToLogServer('find closed bdn for src: ' +
                                                  src.SrcName + " with x: " +
                                                  str(src.SrcX1) + " y: " +
                                                  str(src.SrcY1) +
                                                  ", no of buildings=" +
                                                  str(len(self.rawBdn.BldX)))
            for i in range(len(self.rawBdn.BldX)):

                #print('bdn x: ' +str( self.rawBdn.BldX[i]))
                print(type(self.rawBdn.BldX[i]))
                print(type(src.SrcX1))

                #dx, dy = self.rawBdn.BldX[i] - src.SrcX1, self.rawBdn.BldY[i] - src.SrcY1
                dx, dy = self.rawBdn.BldX[i] - x_midpoint, self.rawBdn.BldY[
                    i] - y_midpoint

                d = dx * dx + dy * dy
                if first:
                    dClosed = d
                    closed = self.rawBdn.BldName[i]
                    first = False
                #print('d:{0} dclosed:{1}'.format(d, dClosed))
                if d - dClosed < 0:
                    closed = self.rawBdn.BldName[i]
                    dClosed = d
                    print('new smallest distance: ' + str(dClosed))
            if closed is not None:
                src.setMainBuilding(closed)

            else:  #err handling, something is wrong if no closed building is found, just throw it
                raise Exception(
                    'Dear lord, no closed buildinf found for src: ' +
                    src.SrcName)

    def getOpt(self, PolNames, SrcNames):
        numPol = len(PolNames)
        return self.OPT(numPol, PolNames, [1] * numPol, [0] * numPol,
                        [1] * numPol, [3] * numPol, [0] * numPol, [0] * numPol,
                        [0] * numPol, [0] * 80, [0] * 80, ['ug/m3'] * numPol,
                        1, 0, 1, "Grouptank001", SrcNames, 0)

    def polIRI2Name(self, polIRI):
        substances = {
            #'http://www.theworldavatar.com/ontology/ontocape/material/substance/substance.owl#chlorine':'Cl2',
            'http://www.theworldavatar.com/ontology/ontocape/material/substance/chemical_species.owl#Nitrogen__dioxide':
            'NO2',
            'http://www.theworldavatar.com/ontology/ontocape/material/substance/chemical_species.owl#Carbon__monoxide':
            'CO',
            'http://www.theworldavatar.com/ontology/ontocape/material/substance/chemical_species.owl#Carbon__dioxide':
            'CO2',
            'http://www.theworldavatar.com/ontology/ontocape/material/substance/pseudocomponent.owl#Unburned_Hydrocarbon':
            'HC',
            'http://www.theworldavatar.com/ontology/ontocape/material/substance/pseudocomponent.owl#Nitrogen__oxides':
            'NOx'
        }

        if polIRI in substances.keys():
            print('Found: ' + substances[polIRI])
            return substances[polIRI]
        else:
            print(polIRI + 'Not found !!!!')
            #raise Exception('This substance is not defined!!!!')
            return None

    def getWeather(self):
        '''
        get weather data,
        for now we trigger a python script to write the .met file directly
        '''
        #finish writing met
        metpath = "C://JPS_DATA/workingdir/JPS/ADMS/test.met"
        self.pythonLogger.postInfoToLogServer('path for adms met file=' +
                                              metpath)
        return metpath

    def get(self):
        '''main function, get all related info for adms
        returns: complete data for adms
        '''
        #get all src data
        self.rawSrc = self.getSrcData()
        ##todo: think about this case: when nothing is found ,where should we handle it?
        ##then nothing should be written, and catch this exception and mute it in main function
        if self.rawSrc is None:
            raise Exception("No src in found to requiries")

        print('raw building: ')
        print(self.rawBdn)
        rawOpt = self.getOpt(self.pollutants, [s.SrcName for s in self.rawSrc])
        self.coreBdn2Src()

        #for debuging, in future,define this for data type, i dont think it auto rpint for objet
        for src in self.rawSrc:
            print(src)

        met = self.getWeather()
        xran, yran = self.range
        grd = xran[0], yran[0], xran[1], yran[1]

        #return {'Src': self.rawSrc, 'Bdn': self.rawBdn, 'Opt': rawOpt, 'Met': met, 'Grd':grd}
        return {'Src': self.rawSrc, 'Opt': rawOpt, 'Met': met, 'Grd': grd}

    def queryEndpoint(self, str):
        def literal2TLit(sparqlres):

            if 'results' not in sparqlres:
                return
            for row in sparqlres['results']['bindings']:
                for name, value in row.items():
                    if value['type'] == 'literal' and 'datatype' in value:
                        value['type'] = 'typed-literal'

        print('requesting @ ' + self.address + " with query:")
        #print(str)
        resp = requests.get(self.address,
                            params={'query': str},
                            timeout=1500,
                            headers={'user-agent': 'my-app/0.0.1'})
        print('raw resp:')

        print(resp.json())
        result = resp.json()
        literal2TLit(result)
        print('literal to typed-literal')
        print(result)
        qres = jsresult.JSONResult(result)  #json decoded
        print('after parse:')
        print(qres)
        return qres

    def queryLocalGraph(self, str):
        qres = self.g.query(str)
        return qres

    def Uri2Local(uri):
        '''replace a uri to local address
        inputs:
        uri - uri to be changed
        returns: string - local address
        '''
        return uri.replace("http://www.jparksimulator.com",
                           config.root).replace(
                               "http://www.theworldavatar.com", config.root)

    def remote2local(self, func):
        '''decorator to change connection function to local connection by replacing given iri to local address
        '''
        def functionWrapper(self, address):
            address = self.Uri2Local(address)
            func(self, address)

        return functionWrapper

    def connectDB(self, address, connectType='endpoint'):
        '''connect to db anyhow (we use rdflib graph parse now)
        '''
        def connectDBActual(address):
            '''
            Actual method to connect to db
            '''
            #obsolete: use rdflib locally
            self.address = address
            if connectType is 'parse':
                self.g = rdflib.Graph()  #comment out in future
                self.g.parse(address)  #comment out in future

        self.qmethodMap = {
            'parse': self.queryLocalGraph,
            'endpoint': self.queryEndpoint
        }

        if not sameGraph(address, self.address):
            print('parsing graph: ' + address)
            if connectType not in self.qmethodMap:
                raise exception('db connection method not defined')
            #self.connectType = connectType
            self.query = self.qmethodMap[connectType]
            connectDBActual(address)
Exemplo n.º 15
0
    ]


if __name__ == "__main__":
    #automatically assigned
    household_below = 1 / 50 * 0.01 * np.ones(24)
    household_above = 1 / 50 * 0.02 * np.ones(24)
    #read bcap from csv
    cd = 0.003
    Nr = 60

    import pandas as pd
    import sys
    from caresjpsutil import returnExceptionToJava, returnResultsToJava
    from caresjpsutil import PythonLogger
    pythonLogger = PythonLogger('residential.py')
    pythonLogger.postInfoToLogServer('start of residential.py')
    folder = sys.argv[1]
    low = pd.read_csv(folder + '/Pmin.csv', header=None)
    high = pd.read_csv(folder + '/Pmax.csv', header=None)
    unwill = pd.read_csv(folder + '/unwill.csv', header=None)
    bcap = pd.read_csv(folder + '/bcap.csv', header=None)
    appl1 = pd.read_csv(folder + '/ApplianceScheduleLoad1.csv',
                        sep=',',
                        header=None)
    f = open(folder + "/residence.csv", 'ab')
    for r in range(0, 3):
        bcap1 = bcap.iloc[r, 0]
        seq = appl1.iloc[r]
        sche1 = np.array([seq[i:i + 11] for i in range(0, len(seq), 11)])
        flex1 = np.array(sche1, dtype=bool)