def init_refmodel(self, use_fmu, use_const, const_path):
        print("%%%---Initialising Reference Simulation---%%%")

        # Define control profile for reference
        self.control_ref = exodata.ControlFromCSV(self.control_file,
                                                  self.contr_varmap,
                                                  tz_name=self.weather.tz_name)
        index = pd.date_range(self.sim_start,
                              self.sim_end,
                              freq=str(self.meas_sampl_ref) + 'S')

        if use_const == 1:
            t_set = load_namespace(
                os.path.join(const_path, 'constraints_' + self.building)
            ).data['TAir']['Slack_GTE'].get_base_data() + 1.0
        else:
            t_set = pd.Series(20 + 273.15, index=index)
            for i in index:
                if i.hour >= 6 and i.hour <= 9:
                    t_set[i] = 20 + 273.15
                if i.hour >= 17 and i.hour <= 23:
                    t_set[i] = 20 + 273.15

        # Define control data
        self.control_ref.data = {
            "SetPoint":
            variables.Timeseries('SetPoint',
                                 t_set,
                                 units.K,
                                 tz_name=self.weather.tz_name)
        }

        if use_fmu == 0:
            self.emuref = systems.EmulationFromFMU(
                self.meas_vars_ref,
                moinfo=self.moinfo_emu_ref,
                weather_data=self.weather.data,
                control_data=self.control_ref.data,
                other_inputs=self.other_input.data,
                tz_name=self.weather.tz_name)
        else:
            self.emuref = systems.EmulationFromFMU(
                self.meas_vars_ref,
                fmupath=self.fmupath_ref,
                weather_data=self.weather.data,
                control_data=self.control_ref.data,
                other_inputs=self.other_input.data,
                tz_name=self.weather.tz_name)
import pandas as pd
#from multiprocessing import Pool
from mpcpy import units
from mpcpy import variables
from mpcpy import models_mod as models

from Simulator_HP_mod2 import SimHandler

if __name__ == "__main__":

    # Naming conventions for the simulation
    community = 'ResidentialCommunityUK_rad_2elements'
    sim_id = 'MinEne'
    model_id = 'R2CW_HP'
    bldg_list = load_namespace(
        os.path.join('path_to_models',
                     'teaser_bldgs_residentialUK_10bldgs_fallback'))
    folder = 'results'
    bldg_index_start = 0
    bldg_index_end = 10

    # Overall options
    date = '11/20/2017 '
    start = date + '16:30:00'
    end = date + '19:00:00'
    meas_sampl = '300'
    horizon = 2 * 3600 / float(
        meas_sampl)  #time horizon for optimization in multiples of the sample
    mon = 'nov'

    DRstart = datetime.datetime.strptime(
Example #3
0
from mpcpy import variables
from mpcpy import models_mod as models

from Simulator_HP_mod3 import SimHandler

from pulp_funcs import *


# In[116]:


community = 'ResidentialCommunityUK_rad_2elements'
sim_id = 'MinEne'
model_id = 'R2CW_HP'
arx_model = 'ARX_lag_4_exog4'
bldg_list = load_namespace(os.path.join('path_to_folder', 'teaser_bldgs_residential'))
folder = 'path_to_folder'
bldg_index_start = 0
bldg_index_end = 30

# Overall options
date = '11/20/2017 '
start = date + '16:30:00'
end = date + '19:00:00'
meas_sampl = '300'
horizon = 3.0*3600.0/float(meas_sampl) #time horizon for optimization in multiples of the sample
mon = 'nov'

DRstart = datetime.datetime.strptime(date + '18:00:00', '%m/%d/%Y %H:%M:%S') # hour to start DR - ramp down 30 mins before
DRend = datetime.datetime.strptime(date + '18:30:00', '%m/%d/%Y %H:%M:%S') # hour to end DR - ramp 30 mins later
DR_call_start = datetime.datetime.strptime(date + '17:00:00', '%m/%d/%Y %H:%M:%S') # Round of loop to implement the call
Example #4
0
ref_profile = {}
controlseq = {}
opt_control = {}
emutemps = {}
mpctemps = {}
opt_stats = {}
flex_down = {}
flex_up = {}
power = {}

i = 0            
for bldg in bldg_list:

    building = bldg+'_'+model_id
    
    flex_cost[building] = load_namespace(os.path.join(simu_path, folder, 'flex_cost_AggrMPC')).data['flex_cost'].get_base_data()
    flex_cost[building] = flex_cost[building].resample(str(step)+'S').mean().shift(-1, freq=str(step) + 'S')
    
    ref_profile[building] = load_namespace(os.path.join("'file_path_to_folder'", folder,'ref_profile_AggrMPC')).data['ref_profile'].get_base_data()*tot_cap
    i += 1



for sim_id in sim_ids:
    opt_stats[sim_id] = {}
    controlseq[sim_id] = {}
    mpctemps[sim_id] = {}
    emutemps[sim_id] = {}
    power[sim_id] = {}
    
    for time_idx in sim_range:
Example #5
0
# The analyser

import pandas as pd
import matplotlib.pyplot as plt
import dill
import os
import numpy as np
from funcs import store_namespace
from funcs import load_namespace
import datetime

community = 'ResidentialCommunity'
sim_id = 'MinEne'
model_id = 'R2CW_HP'
bldg_list = load_namespace(
    os.path.join('path_to_models',
                 'teaser_bldgs_residentialUK_10bldgs_fallback'))
print(bldg_list)
folder = '10bldgs_centr_dyn_fin_jan'
mon = 'jan'
nodynprice = 0
step = 300
constr_folder = 'decentr_enemin_' + mon

if mon == 'jan':
    start = '1/7/2017 16:30:00'
    end = '1/7/2017 19:00:00'
    controlseq_time = '01/07/2017 16:55:00'
elif mon == 'mar':
    start = '3/1/2017 16:30:00'
    end = '3/1/2017 19:00:00'
Example #6
0
    def update_DRinfo(self, start, end, **kwargs):

        index = pd.date_range(start, end, freq=str(self.meas_sampl) + 'S')
        # Random control signal
        flex_signal = pd.Series(0, index=index)
        #price_signal = pd.Series(np.random.rand(len(index))*5,index=index)
        if 'use_ref_file' in kwargs:
            ref_signal = load_namespace(
                kwargs['profile_file']).display_data()['ref_profile']
        else:
            ref_signal = pd.Series(10000, index=index)
        #print(type(ref_signal))
        #print(ref_signal)

        flex_signal = pd.Series(0, index=index)
        if kwargs['DRevent_check'] == 1:
            print('%%%%%%%%% DR event triggered %%%%%%%%%%')
            for i in index:
                if i.hour >= kwargs['DRstart'] and i.hour < kwargs['DRend']:
                    flex_signal.loc[i] = kwargs['flex_cost']
            flex_signal.sort_index()
        '''
		for i in index:
			if i.hour >= 7 and i.hour <= 10:
				price_signal[i] = np.random.uniform(0.8,1)*40
			if i.hour >= 17 and i.hour <= 23:
				price_signal[i] = np.random.uniform(0.8,1)*40
		'''

        # Create DR event or not
        if 'DRevent_check' == 1 and use_ref_file == 0:
            print('%%%%%%%%% DR event triggered %%%%%%%%%%')
            #index = ref_signal.index.tz_convert(None)
            k = pd.Series(1, index=index)
            #flex_signal = pd.Series(0,index=index)
            #ref_signal.index = index

            if kwargs['DRevent_check'] == 1:
                for i in index:
                    if i.hour >= kwargs['DRstart'] and i.hour <= kwargs[
                            'DRend']:
                        k.loc[i] = 0.8
            print(k)
            print('Reference profile before modification:')
            print(ref_signal)
            # Sort the indices
            ref_signal.sort_index()
            k.sort_index()
            #flex_signal.sort_index()

            # Define the reference signal
            ref_signal = ref_signal * k * 30

            print('Reference profile after modification:')
            print(ref_signal)

        print('Flex cost:')
        print(flex_signal)

        #print(price_signal)
        # Define control data
        '''
		self.price.data = {"pi_e": variables.Timeseries('pi_e', price_signal,units.cents_kWh,tz_name=self.weather.tz_name)
		}
		'''
        self.flex_cost.data = {
            "flex_cost":
            variables.Timeseries('flex_cost',
                                 flex_signal,
                                 units.cents_kWh,
                                 tz_name=self.weather.tz_name)
        }
        self.ref_profile.data = {
            "ref_profile":
            variables.Timeseries('ref_profile',
                                 ref_signal,
                                 units.W,
                                 tz_name=self.weather.tz_name)
        }

        #pheat_max = pd.Series(10000,index=index)
        #self.control.collect_data(self.sim_start, self.sim_end)
        #print(self.price.display_data())
        #print(self.flex_cost.display_data())
        #print(self.ref_profile.display_data())
        #store_namespace('price_upd_'+self.building,self.price)
        store_namespace('flex_cost_upd_' + self.building, self.flex_cost)
        store_namespace('ref_profile_upd_' + self.building, self.ref_profile)
Example #7
0
    def do_plot(self):
        print(
            '%%%%%%%%%----Plot Optimized Control Signal and resulting temperature----%%%%%%'
        )
        '''
		print("----Optimization temps based on MPC model----")
		b = opt_problem.Model.display_measurements('Simulated')['TAir']
		print(b)
		
		print("----Emulated temps----")
		c = opt_problem.Model.display_measurements('Measured')['TAir']
		
		a1_plot = opt_controlseq['ConvGain2'].display_data().plot(figsize=(11.69,8.27))
		#a2_plot = opt_controlseq['Qflow2'].display_data().plot(figsize=(11.69,8.27))
		a1_fig = a1_plot.get_figure()
		a1_fig.savefig("plot_convgain.pdf")
		a1_fig.clf()
		'''

        index = pd.date_range(self.opt_start,
                              self.opt_end,
                              freq=str(self.meas_sampl) + 'S')

        sim = load_namespace('sim_val')[self.val_start:self.val_end]
        meas = load_namespace('meas_val')[self.val_start:self.val_end]

        opt_control_energy = load_namespace('opt_control_minenergy')
        opt_control_cost = load_namespace('opt_control_mincost')
        opt_control_DR = load_namespace('opt_control_DRcost')
        ref_heatinput = load_namespace('ref_heatinput')

        ref_temp = load_namespace('ref_temp')
        opt_temp = load_namespace('optemu')
        #print(opt_control['ConvGain2'].display_data())
        #print(ref_heatinput)
        opt_control_series_energy = opt_control_energy[
            'ConvGain2'].display_data()
        opt_control_series_cost = opt_control_cost['ConvGain2'].display_data()
        opt_control_series_DR = opt_control_DR['ConvGain2'].display_data()

        #print(opt_temp)

        # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        # Validation figure
        plt.figure(figsize=(11.69, 8.27))
        plot_real = plt.plot(meas.index, meas['TAir'], '-x', label="Real")
        plot_mpc = plt.plot(sim.index, sim['TAir'], '--o', label="MPC model")
        plt.legend(fontsize=14)
        plt.xlabel("Time", fontsize=18)
        plt.ylabel("Temperature [C]", fontsize=18)
        plt.title("Validation of MPC model", fontsize=22)
        plt.xticks(rotation=45)
        # We change the fontsize of minor ticks label
        plt.tick_params(axis='both', which='major', labelsize=12)
        plt.tick_params(axis='both', which='minor', labelsize=12)
        plt.savefig("validation")
        plt.clf()

        # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        # Optimization figure
        plt.figure(figsize=(11.69, 8.27))
        plt.plot(opt_control_series_energy.index,
                 opt_control_series_energy.values,
                 '-o',
                 label="MPC-EneMin")
        #plt.plot(opt_control_series_cost.index, opt_control_series_cost.values,'-+', label="MPC-CostMin")
        #plt.plot(opt_control_series_DR.index, opt_control_series_DR.values,'--o', label="MPC-DR")
        plt.plot(ref_heatinput.index,
                 ref_heatinput.values,
                 '--x',
                 label="PI-ref")
        plt.legend(fontsize=14)
        plt.xlabel("Time", fontsize=18)
        plt.ylabel("Heat Input [W]", fontsize=18)
        plt.title("Optimized Control Sequences vs. PI controller", fontsize=22)
        plt.xticks(rotation=35)
        # We change the fontsize of minor ticks label
        plt.tick_params(axis='both', which='major', labelsize=12)
        plt.tick_params(axis='both', which='minor', labelsize=12)
        plt.savefig("optimized_heatinput.pdf")
        plt.clf()

        # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        # Optimization temps
        plt.figure(figsize=(11.69, 8.27))
        plot_optimized = plt.plot(opt_temp.index,
                                  opt_temp.values,
                                  '-o',
                                  label="MPC")
        plot_ref = plt.plot(ref_temp.index,
                            ref_temp.values,
                            '-x',
                            label="PI-ref")
        plt.legend(fontsize=14)
        plt.xlabel("Time", fontsize=18)
        plt.ylabel("Temperature [C]", fontsize=18)
        plt.title("Inside Temperatures with different controls", fontsize=22)
        plt.xticks(rotation=35)
        # We change the fontsize of minor ticks label
        plt.tick_params(axis='both', which='major', labelsize=12)
        plt.tick_params(axis='both', which='minor', labelsize=12)
        plt.savefig("optimized_temps")
        plt.clf()

        #print(ref_heatinput)

        print('%%%% --- Optimised heat consumption (Wh) --- %%%%')
        print(
            sum(opt_control_energy['ConvGain2'].get_base_data().resample(
                '3600S').mean()))

        print('%%%% --- Reference (PI) heat consumption (Wh) --- %%%%')
        print(sum(ref_heatinput.resample('3600S').mean()))
import datetime
import time
import pandas as pd
#rom multiprocessing import Pool
import numpy as np
import gc

from Simulator import SimHandler
from funcs import emulate_jmod
from mpcpy import units
from mpcpy import variables

# Naming conventions for the simulation
community = 'ResidentialCommunityUK'
sim_id = 'MinCost_Centr_Res'
bldg_list = load_namespace(os.path.join('path to models'))
#print(bldg_list)
# Overall options
start = '1/7/2017 13:00:00'
end = '1/7/2017 19:00:00'
meas_sampl = '1800'
horizon = 10 #time horizon for optimization, multiple of the measurement sample
use_previous = 0
emus = 10

sim_range = pd.date_range(start, end, freq = meas_sampl+'S')
opt_start_str = start
opt_end = datetime.datetime.strptime(end, '%m/%d/%Y %H:%M:%S') + datetime.timedelta(seconds = horizon*int(meas_sampl))
opt_end_str = opt_end.strftime('%m/%d/%Y %H:%M:%S')

# Instantiate Simulator for aggregated optimisation
import matplotlib.pyplot as plt
import dill
import os
import numpy as np
from funcs import store_namespace
from funcs import load_namespace
import datetime

from matplotlib.font_manager import FontProperties

from matplotlib import rc

community = 'ResidentialCommunity'
sim_ids = ['MinEne_0-2']
model_id = 'R2CW_HP'
bldg_list = load_namespace(
    os.path.join('path to models', 'teaser_bldgs_residential'))
#
bldg_list = [bldg_list[0], bldg_list[1]]
print(bldg_list)
folder = 'results'
step = 300
nodynprice = 0
mon = 'jan'
constr_folder = 'decentr_enemin_constr_' + mon
#bldg_list = bldg_list[0:1]
if mon == 'jan':
    start = '1/7/2017 16:30:00'
    end = '1/7/2017 19:00:00'
    controlseq_time = '01/07/2017 16:55:00'
elif mon == 'mar':
    start = '3/1/2017 16:30:00'
Example #10
0
import os
import datetime
import time
import pandas as pd
#from multiprocessing import Pool
from mpcpy import units

from Simulator import SimHandler

if __name__ == "__main__":	
	
	# Naming conventions for the simulation
	community = 'ResidentialCommunityUK'
	sim_id = 'MinCost'
	model_id = 'R2CW'
	bldg_list = load_namespace(os.path.join('path to models'))
	
	# Overall options
	start = '1/7/2017 13:00:00'
	end = '1/7/2017 19:00:00'
	meas_sampl = '1800'
	horizon = 10 #time horizon for optimization in hours
	
	sim_range = pd.date_range(start, end, freq = meas_sampl+'S')
	opt_start_str = start
	opt_end = datetime.datetime.strptime(end, '%m/%d/%Y %H:%M:%S') + datetime.timedelta(seconds = horizon*int(meas_sampl))
	opt_end_str = opt_end.strftime('%m/%d/%Y %H:%M:%S')
	bldg_index_start = 0
	bldg_index_end = 10
	
	# Instantiate Simulator
Example #11
0
from scipy.linalg import expm
from numpy.linalg import inv
from sklearn.metrics import mean_squared_error, r2_score

from statsmodels.graphics.tsaplots import plot_pacf
from statsmodels.graphics.tsaplots import plot_acf

from Simulator_HP_mod3 import SimHandler

if __name__ == "__main__":  
    
    # Naming conventions for the simulation
    community = 'ResidentialCommunityUK_rad_2elements'
    sim_id = 'MinEne'
    model_id = 'R2CW_HP'
    bldg_list = load_namespace(os.path.join('file_path_to_folder', 'teaser_bldgs_residential'))
   
    bldg_index_start = 0
    bldg_index_end = 30
    
    emulate = 0 # Emulate or not?
    old_sim_param = 1 # Choose initial guesses
    
    # Overall options
    date = '1/1/2017 '
    start = '1/1/2017 00:00:00'
    end = '1/9/2017 00:00:00'
    
    train_start = start
    valid_start = '1/6/2017 00:00:00'
    train_end = valid_start
import matplotlib.pyplot as plt
import dill
import os
import numpy as np
from funcs import store_namespace
from funcs import load_namespace
import datetime

from matplotlib.font_manager import FontProperties

from matplotlib import rc

community = 'ResidentialCommunity'
sim_ids = ['MinEne_0-30']
model_id = 'R2CW_HP'
bldg_list = load_namespace(
    os.path.join('file_path_to_folder', 'teaser_bldgs_residential'))
compr_capacity_list = [float(4500.0)] * 10 + [float(3000.0)] * 20
print(bldg_list)
folder = 'results'
step = 300
nodynprice = 0
mon = 'nov'
constr_folder = 'decentr_enemin_constr_' + mon
if mon == 'jan':
    start = '1/7/2017 16:30:00'
    end = '1/7/2017 19:00:00'
    controlseq_time = '01/07/2017 16:55:00'
elif mon == 'mar':
    start = '3/1/2017 16:30:00'
    end = '3/1/2017 19:00:00'
    controlseq_time = '03/01/2017 16:55:00'
import time
import pandas as pd
#from multiprocessing import Pool
from mpcpy import units
from mpcpy import variables
from mpcpy import models_mod as models

from Simulator_HP_mod2 import SimHandler

if __name__ == "__main__":  
    
    # Naming conventions for the simulation
    community = 'ResidentialCommunityUK_rad_2elements'
    sim_id = 'MinEne'
    model_id = 'R2CW_HP'
    bldg_list = load_namespace(os.path.join('path_to_models', 'teaser_bldgs_residentialUK_10bldgs_fallback'))
    folder = 'results'
    bldg_index_start = 0
    bldg_index_end = 10
    mon = 'mar'
    
    # Overall options
    start = '3/1/2017 16:30:00'
    end = '3/1/2017 19:00:00'
    meas_sampl = '300'
    horizon = 2*3600/float(meas_sampl) #time horizon for optimization in multiples of the sample
    
    DRstart = datetime.datetime.strptime('1/7/2017 19:30:00', '%m/%d/%Y %H:%M:%S') # hour to start DR - ramp down 30 mins before
    DRend = datetime.datetime.strptime('1/7/2017 19:30:00', '%m/%d/%Y %H:%M:%S') # hour to end DR - ramp 30 mins later
    DR_call_start = datetime.datetime.strptime('1/7/2017 19:30:00', '%m/%d/%Y %H:%M:%S') # Round of loop to implement the call
    DR_ramp_start = datetime.datetime.strptime('1/7/2017 19:30:00', '%m/%d/%Y %H:%M:%S')
Example #14
0
def main():
    community = 'ResidentialCommunityUK_rad_2elements'
    sim_id = 'RBC'
    model_id = 'R2CW_HP'
    bldg_list = load_namespace(
        os.path.join('path_to_models',
                     'teaser_bldgs_residentialUK_10bldgs_fallback'))
    folder = 'results'
    bldg_index_start = 0
    bldg_index_end = 10
    mon = 'mar'

    print(bldg_list)

    # Overall options
    start = '3/1/2017 12:00:00'
    end = '3/1/2017 19:10:00'
    meas_sampl = '300'  # Daylight saving time hours 26/3 and 29/10

    index = pd.date_range(start, end, freq=meas_sampl + 'S')

    SimJmod_list = []
    SimDym_list = []
    i = 0

    index = pd.date_range(start, end, freq=meas_sampl + 'S')

    for bldg in bldg_list[bldg_index_start:bldg_index_end]:

        print('In loop:  ' + str(i))
        i = i + 1

        # Then JModelica model
        Sim = SimHandler(sim_start=start, sim_end=end, meas_sampl=meas_sampl)

        Sim.moinfo_mpc = (os.path.join(Sim.simu_path, 'Tutorial_R2CW.mo'),
                          'Tutorial_R2CW.R2CW', {})

        Sim.building = bldg + '_' + model_id

        Sim.fmupath_mpc = os.path.join(
            Sim.simu_path, 'fmus', community,
            'Tutorial_' + model_id + '_' + model_id + '.fmu')

        Sim.fmupath_emu = os.path.join(
            Sim.simu_path, 'fmus', community, community + '_' + bldg + '_' +
            bldg + '_Models_' + bldg + '_House_mpc.fmu')

        Sim.fmupath_ref = os.path.join(
            Sim.simu_path, 'fmus', community, community + '_' + bldg + '_' +
            bldg + '_Models_' + bldg + '_House_PI.fmu')

        Sim.moinfo_emu = (os.path.join(Sim.mod_path, community, bldg,
                                       bldg + '_Models',
                                       bldg + '_House_mpc.mo'),
                          community + '.' + bldg + '.' + bldg + '_Models.' +
                          bldg + '_House_mpc', {})

        Sim.moinfo_emu_ref = (os.path.join(Sim.mod_path, community, bldg,
                                           bldg + '_Models',
                                           bldg + '_House_PI.mo'),
                              community + '.' + bldg + '.' + bldg +
                              '_Models.' + bldg + '_House_PI', {})

        if i == 1:
            Sim.update_weather(start, end)
        else:
            Sim.weather = SimJmod_list[i - 2].weather

        Sim.get_other_input(start, end)
        Sim.get_constraints(start, end)

        Sim.param_file = os.path.join(Sim.simu_path, 'csvs',
                                      'Parameters_R2CW.csv')
        Sim.get_params()

        Sim.parameters.data = load_namespace(
            os.path.join(Sim.simu_path, 'sysid',
                         'sysid_HPrad_2element_' + mon + '_600S',
                         'est_params_' + bldg + '_' + model_id))
        Sim.other_input = load_namespace(
            os.path.join(Sim.simu_path, 'ibpsa_paper', 'decentr_enemin_' + mon,
                         'other_input_' + bldg + '_' + model_id))
        Sim.constraints = load_namespace(
            os.path.join(Sim.simu_path, 'ibpsa_paper', 'decentr_enemin_' + mon,
                         'constraints_' + bldg + '_' + model_id))

        store_namespace(os.path.join(folder, 'params_' + Sim.building),
                        Sim.parameters)
        store_namespace(os.path.join(folder, 'constraints_' + Sim.building),
                        Sim.constraints)
        store_namespace(os.path.join(folder, 'other_input_' + Sim.building),
                        Sim.other_input)

        # Add to list of simulations
        SimJmod_list.append(Sim)

    for Sim in SimJmod_list:

        Sim.init_refmodel(use_fmu=1,
                          use_const=1,
                          const_path=os.path.join(Sim.simu_path, 'ibpsa_paper',
                                                  'decentr_enemin_' + mon))
        store_namespace(os.path.join(folder, 'control_ref_' + Sim.building),
                        Sim.control_ref)

    for Sim in SimJmod_list:

        Sim.run_reference(start, end)