Example #1
0
def update_CP_state(CP_name, dt_sim_time):
    #Check if EV is there
    CP_obj = gridlabd.get_object(CP_name)
    EV_name = 'EV_' + CP_name.split('_')[-1]
    EV_obj = gridlabd.get_object(EV_name)
    #New car arrived
    #import pdb; pdb.set_trace()
    #print(int(CP_obj['EV_connected']))
    if int(
            CP_obj['EV_connected']
    ) == 1:  #This should be whatever signal which pushes the new that a car arrived/disconnected
        #import pdb; pdb.set_trace()
        Kev = float(EV_obj['Kev'])
        tdep = pandas.to_datetime(EV_obj['tdep'])
        Emax = float(EV_obj['battery_capacity'])
        DeltaE = float(EV_obj['DeltaE'])
        #Write to database
        parameter_string = '(timedate, Kev, tdep, Emax, DeltaE)'
        value_tuple = (
            str(dt_sim_time),
            str(Kev),
            str(tdep),
            Emax,
            DeltaE,
        )
        myfct.set_values(EV_name + '_state_in', parameter_string, value_tuple)
        #Reset action pointer
        gridlabd.set_value(CP_name, 'EV_connected', str(0))
    elif int(CP_obj['EV_connected']) == -1:
        gridlabd.set_value(CP_name, 'EV_connected', str(0))
Example #2
0
def get_houseobjects(house_name, time):
    #Get information from physical representation
    house_obj = gridlabd.get_object(house_name)  #GUSTAVO: API implementation
    #Switch off default control
    gridlabd.set_value(house_name, 'thermostat_control', 'NONE')
    gridlabd.set_value(house_name, 'system_mode', 'OFF')

    #Read out settings
    k = float(house_obj['k'])
    T_max = float(house_obj['T_max'])
    cooling_setpoint = float(house_obj['cooling_setpoint'])
    cooling_demand = float(
        house_obj['cooling_demand'])  #cooling_demand is in kW
    T_min = float(house_obj['T_min'])
    heating_setpoint = float(house_obj['heating_setpoint'])
    heating_demand = float(
        house_obj['heating_demand'])  #heating_demand is in kW

    #Save in long-term memory (in the db) - accessible for market code
    parameter_string = '(timedate, k, T_min, heating_setpoint, T_max, cooling_setpoint)'  #timedate TIMESTAMP PRIMARY KEY,
    value_tuple = (
        time,
        k,
        T_min,
        heating_setpoint,
        T_max,
        cooling_setpoint,
    )
    myfct.set_values(house_name + '_settings', parameter_string, value_tuple)

    return
Example #3
0
 def dispatch(self, dt_sim_time, p_lem, alpha):
     #import pdb; pdb.set_trace()
     inverter = 'Bat_inverter_' + self.name.split('_')[-1]
     if (self.Q_buy_bid > 0.0) and (self.P_buy_bid > p_lem):
         gridlabd.set_value(inverter, 'P_Out', str(-self.Q_buy_bid * 1000.))
     elif (self.Q_buy_bid > 0.0) and (self.P_buy_bid == p_lem):
         print('This HVAC is marginal; no partial implementation yet: ' +
               str(alpha))
         gridlabd.set_value(inverter, 'P_Out', str(-self.Q_buy_bid * 1000.))
     elif (self.Q_sell_bid > 0.0) and (self.P_sell_bid < p_lem):
         gridlabd.set_value(inverter, 'P_Out', str(self.Q_sell_bid * 1000.))
     elif (self.Q_sell_bid > 0.0) and (self.P_sell_bid == p_lem):
         print('This HVAC is marginal; no partial implementation yet: ' +
               str(alpha))
         gridlabd.set_value(inverter, 'P_Out', str(self.Q_sell_bid * 1000.))
     else:
         gridlabd.set_value(inverter, 'P_Out', str(0.0))
     myfct.set_values(
         self.name + '_state_out',
         '(timedate, p_demand, p_supply, q_demand, q_supply)',
         (dt_sim_time, str(self.P_buy_bid), str(
             self.P_sell_bid), str(self.Q_buy_bid), str(self.Q_sell_bid)))
     self.P_sell_bid = 100000.0
     self.P_buy_bid = -100000.0
     self.Q_sell_bid = 0.0
     self.Q_buy_bid = 0.0
Example #4
0
def set_HVAC_GLD(dt_sim_time,df_house_state,df_awarded_bids):
	for ind in df_house_state.index:		
		house = df_house_state['house_name'].loc[ind]
		if df_house_state['active'].loc[ind] == 1:
			system_mode = df_house_state['system_mode'].loc[ind]
			gridlabd.set_value(house,'system_mode',system_mode) #Cool or heat
			p_bid = df_house_state['bid_p'].loc[ind]
			q_bid = df_house_state['bid_q'].loc[ind]
			#mysql_functions.set_values('awarded_bids','(appliance_name,p_bid,q_bid,timedate)',(house,float(p_bid),float(q_bid),dt_sim_time))
			df_awarded_bids = df_awarded_bids.append(pandas.DataFrame(columns=df_awarded_bids.columns,data=[[dt_sim_time,house,float(p_bid),float(q_bid),'D']]),ignore_index=True)
		else:
			system_mode = 'OFF'
			gridlabd.set_value(house,'system_mode',system_mode)
	return df_house_state,df_awarded_bids
def set_HVAC_GLD(dt_sim_time, df_house_state, df_awarded_bids):
    for ind in df_house_state.index:
        house = df_house_state['house_name'].loc[ind]
        #Switch on/off control for gas
        if (df_house_state['system_mode'].loc[ind]
                == 'HEAT') and (df_house_state['heating_system'].loc[ind]
                                == 'GAS'):
            thermostat_control = 'FULL'
            gridlabd.set_value(house, 'thermostat_control', thermostat_control)
        elif (df_house_state['system_mode'].loc[ind]
              == 'COOL') and (df_house_state['heating_system'].loc[ind]
                              == 'GAS'):
            thermostat_control = 'NONE'
            gridlabd.set_value(house, 'thermostat_control', thermostat_control)
        #Set system_mode for active systems
        if df_house_state['active'].loc[ind] == 1:
            #import pdb; pdb.set_trace()
            system_mode = df_house_state['system_mode'].loc[ind]
            gridlabd.set_value(house, 'system_mode',
                               system_mode)  #Cool or heat
            p_bid = df_house_state['bid_p'].loc[ind]
            q_bid = df_house_state['bid_q'].loc[ind]
            #mysql_functions.set_values('awarded_bids','(appliance_name,p_bid,q_bid,timedate)',(house,float(p_bid),float(q_bid),dt_sim_time))
            df_awarded_bids = df_awarded_bids.append(pandas.DataFrame(
                columns=df_awarded_bids.columns,
                data=[[dt_sim_time, house,
                       float(p_bid),
                       float(q_bid), 'D']]),
                                                     ignore_index=True)
        elif not ((df_house_state['system_mode'].loc[ind] == 'HEAT') and
                  (df_house_state['heating_system'].loc[ind] == 'GAS')):
            #import pdb; pdb.set_trace()
            system_mode = 'OFF'
            gridlabd.set_value(house, 'system_mode', system_mode)
    return df_house_state, df_awarded_bids
Example #6
0
def charge_EV(dt_sim_time, df_EV_state):
    df_EV_state_red = df_EV_state.loc[df_EV_state['connected'] == 1]
    df_EV_state_red = df_EV_state_red.loc[df_EV_state_red['u_t'] > 0.0]
    for EV in df_EV_state_red.index:
        EV_number = int(EV.split('_')[-1])  #int(battery.split('_')[1])
        SOC = df_EV_state['SOC_t'].loc[
            EV]  #this is SOC at the beginning of the period t
        u = -1000 * df_EV_state['u_t'].loc[EV]
        gridlabd.set_value('EV_inverter_' + EV[3:], 'P_Out', str(u))  #kW -> W

    print('GLD battery model is not used for EV, manual updating!')
    df_EV_state['SOC_t'] = df_EV_state[
        'SOC_t'] + df_EV_state['connected'] * df_EV_state['u_t'] / 12.
    df_EV_state['soc_t'] = df_EV_state['SOC_t'] / df_EV_state['SOC_max']
    return df_EV_state
Example #7
0
def initialize_EVs(house_name, time):
    #Check if EV is connected
    EV_name = 'EV' + house_name[5:]
    try:
        EV_obj = gridlabd.get_object(EV_name)
        status = True
    except:
        status = False
    if status:
        parameter_string = '(timedate, Kev, tdep, Emax, DeltaE)'
        try:
            Kev = float(EV_obj['Kev'])
        except:
            Kev = 1.0
        try:
            tdep = pandas.to_datetime(EV_obj['tdep'])
        except:
            #Assuming that departure is in the morning
            t0 = pandas.to_datetime(time)
            t0.hours = 0
            tdep = t0 + pandas.Timedelta(hours=0) + pandas.Timedelta(
                minutes=random.randint(0, 60 * 1))
            gridlabd.set_value(EV_name, 'tdep', str(tdep))
        try:
            Emax = float(EV_obj['battery_capacity'])
        except:
            Emax = 1000.0  #Set very large
        try:
            DeltaE = float(EV_obj['DeltaE'])
        except:
            DeltaE = 100.0  #100% / full charge
        if DeltaE == 0.0:
            DeltaE = 100.0

        value_tuple = (
            time,
            str(Kev),
            str(tdep),
            Emax,
            DeltaE,
        )
        myfct.set_values(EV_name + '_state_in', parameter_string, value_tuple)
Example #8
0
def set_battery_GLD(dt_sim_time,df_bids_battery,df_awarded_bids):
      #Check efficiencies!!!
      #Set charging/discharging
      #Change from no to battery_name
      #Do more quickly by setting database through Gridlabd?
      for battery in df_bids_battery.index:
            batt_number = int(battery.split('_')[-1]) #int(battery.split('_')[1])
            SOC = df_bids_battery['SOC_t'].loc[battery] #this is SOC at the beginning of the period t
            active = df_bids_battery['active_t'].loc[battery] #this is activity in t
            if active == 1:
                  q_bid = df_bids_battery['q_buy'].loc[battery]
                  p_bid = df_bids_battery['p_buy'].loc[battery]
                  gridlabd.set_value('Bat_inverter_'+battery[8:],'P_Out',str(-1000*q_bid)) #kW -> W    
                  #mysql_functions.set_values('awarded_bids','(appliance_name,p_bid,q_bid,timedate)',(battery,float(p_bid),-float(q_bid)/1000,dt_sim_time))
                  df_awarded_bids = df_awarded_bids.append(pandas.DataFrame(columns=df_awarded_bids.columns,data=[[dt_sim_time,battery,float(p_bid),float(q_bid),'D']]),ignore_index=True)
            elif active == -1:
                  q_bid = df_bids_battery['q_sell'].loc[battery]
                  p_bid = df_bids_battery['p_sell'].loc[battery]
                  gridlabd.set_value('Bat_inverter_'+battery[8:],'P_Out',str(1000*q_bid)) #kW -> W
                  #Include sales as negative
                  #mysql_functions.set_values('awarded_bids','(appliance_name,p_bid,q_bid,timedate)',(battery,float(p_bid),-float(q_bid)/1000,dt_sim_time))
                  df_awarded_bids = df_awarded_bids.append(pandas.DataFrame(columns=df_awarded_bids.columns,data=[[dt_sim_time,battery,float(p_bid),float(q_bid),'S']]),ignore_index=True)
            else:
                  gridlabd.set_value('Bat_inverter_'+battery[8:],'P_Out','0.0')
      return df_bids_battery, df_awarded_bids
Example #9
0
def set_PV_GLD(dt_sim_time, df_PV_state, df_awarded_bids, partial, alpha):
    #import pdb; pdb.set_trace()
    for ind in df_PV_state.index:
        PV = df_PV_state['PV_name'].loc[ind]
        # if inverter has not been and is not switched off, only save bid and NO interaction with GLD
        if (df_PV_state['inv_ON_t'].loc[ind]
                == 1.) and (df_PV_state['inv_ON_t-1'].loc[ind] == 1.):
            # Keep inverter unchanged:
            pass
        elif (df_PV_state['inv_ON_t'].loc[ind] >
              0.0) and (df_PV_state['inv_ON_t-1'].loc[ind] < 1.):
            gridlabd.set_value(df_PV_state['inverter_name'].loc[ind],
                               'generator_status', 'ONLINE')
            gridlabd.set_value(df_PV_state['inverter_name'].loc[ind], 'P_Out',
                               str(df_PV_state['inv_ON_t'].loc[ind] *
                                   df_PV_state['q_sell'].loc[ind])
                               )  #Switch on inverter at 1.0 or alpha
        # if inverter is to be switched off
        elif (df_PV_state['inv_ON_t'].loc[ind] == 0.0):
            #gridlabd.set_value(df_PV_state['inverter_name'].loc[ind],'P_Out','0.0') #Switch inverter (partially) off
            gridlabd.set_value(df_PV_state['inverter_name'].loc[ind],
                               'generator_status',
                               'OFFLINE')  #Switch inverter (partially) off
        else:
            print('Should not happen unless for the first iteration')
    return df_PV_state, df_awarded_bids
Example #10
0
 def dispatch(self, dt_sim_time, p_lem, alpha):
     inverter = self.name
     if (self.Q_bid > 0.0) and (self.P_bid > p_lem):
         gridlabd.set_value(inverter, 'P_Out', str(-self.Q_bid * 1000.))
         mode = 1.
     elif (self.Q_bid > 0.0) and (self.P_bid == p_lem):
         print('This HVAC is marginal; no partial implementation yet: ' +
               str(alpha))
         gridlabd.set_value(inverter, 'P_Out', str(-self.Q_bid * 1000.))
         mode = 1.
     else:
         gridlabd.set_value(inverter, 'P_Out', str(0.0))
         mode = 0.
     parameter_string = '(timedate, P_bid, Q_bid, mode, DeltaE)'  #DeltaE at beginning of period
     value_tuple = (
         dt_sim_time,
         float(self.P_bid),
         float(self.Q_bid),
         float(mode),
         float(self.DeltaE),
     )
     myfct.set_values('EV_' + self.ID + '_state_out', parameter_string,
                      value_tuple)
     self.P_bid = -100000.0
     self.Q_bid = 0.0
     return
Example #11
0
def set_EV_GLD(dt_sim_time, df_bids_EV, df_awarded_bids):
    #Set charging/discharging
    #Change from no to battery_name
    #Do more quickly by setting database through Gridlabd?
    for EV in df_bids_EV.index:
        EV_number = int(EV.split('_')[-1])  #int(battery.split('_')[1])
        #print df_bids_EV[['connected','SOC','active','next_event']].loc[df_bids_EV['appliance_id'] == EV_number]
        #print type(df_bids_EV['next_event'].loc[df_bids_EV['appliance_id'] == EV_number].values[0])
        #print pd.isnull(df_bids_EV['next_event'].loc[df_bids_EV['appliance_id'] == EV_number].values[0])
        SOC = df_bids_EV['SOC_t'].loc[
            EV]  #this is SOC at the beginning of the period t
        active = df_bids_EV['active_t'].loc[EV]  #this is activity in t
        connected = df_bids_EV['connected'].loc[EV]
        if active == 1:
            q_bid = -1000 * df_bids_EV['q_buy'].loc[EV]
            p_bid = df_bids_EV['p_buy'].loc[EV]
            gridlabd.set_value('EV_inverter_' + EV[3:], 'P_Out',
                               str(q_bid))  #kW -> W
            #mysql_functions.set_values('awarded_bids','(appliance_name,p_bid,q_bid,timedate)',(EV,float(p_bid),-float(q_bid)/1000,dt_sim_time))
            df_awarded_bids = df_awarded_bids.append(pandas.DataFrame(
                columns=df_awarded_bids.columns,
                data=[[
                    dt_sim_time, EV,
                    float(p_bid), -float(q_bid) / 1000, 'D'
                ]]),
                                                     ignore_index=True)

        #elif active == -1:
        #     gridlabd_functions.set('EV_inverter_'+EV[3:],'P_Out',1000*df_bids_EV['q_sell'].loc[df_bids_EV['appliance_id'] == batt_number].values[0]) #kW -> W
        else:
            gridlabd.set_value('EV_inverter_' + EV[3:], 'P_Out', '0.0')

    print('GLD battery model is not used for EV, manual updating!')
    df_bids_EV['SOC_t'] = df_bids_EV[
        'SOC_t'] + df_bids_EV['active_t'] * df_bids_EV['q_buy'] / 12
    df_bids_EV['soc_t'] = df_bids_EV['SOC_t'] / df_bids_EV['SOC_max']

    return df_bids_EV, df_awarded_bids
Example #12
0
def get_settings_EVs_rnd(EVlist, interval, mysql=False):
    cols_EV = [
        'EV_name', 'house_name', 'SOC_max', 'i_max', 'v_max', 'u_max',
        'efficiency', 'charging_type', 'k', 'soc_t', 'SOC_t', 'connected',
        'next_event', 'active_t-1', 'active_t'
    ]
    df_EV = pandas.DataFrame(columns=cols_EV)
    start_time = dt_sim_time = parser.parse(
        gridlabd.get_global('clock')).replace(tzinfo=None)
    for EV in EVlist:
        house_name = 'GLD_' + EV[3:]
        EV_obj = gridlabd.get_object(EV)
        #Determine some values
        v_max = float(EV_obj['V_Max'])  #keep v_max constant for now
        SOC_max = np.random.choice(list_SOC)  #in kWh
        gridlabd.set_value(EV, 'battery_capacity', str(SOC_max * 1000))
        u_max = np.random.choice(list_u)  #in kW
        i_max = 1000 * u_max / v_max
        gridlabd.set_value(EV, 'I_Max', str(i_max))
        eff = float(EV_obj['base_efficiency'])
        charging_type = EV_obj['charging_type']
        k = float(EV_obj['k'])  #no market: always highest wllingsness to pay
        #Randomly generate SOC at midnight
        soc_t = np.random.uniform(0.2, 0.8)  #relative soc
        soc_t = soc_t + (
            1. - soc_t
        ) / 2.  #No EV connected yet - at midnight, initialize with 50% charged already
        gridlabd.set_value(EV, 'state_of_charge', str(soc_t))
        SOC_t = soc_t * SOC_max
        connected = 1
        gridlabd.set_value(EV, 'generator_status', 'ONLINE')
        next_event = start_time + pandas.Timedelta(
            hours=np.random.choice(dep_hours),
            minutes=np.random.choice(range(60)))  #Next event: disconnection
        #Save
        df_EV = df_EV.append(pandas.Series([
            EV, house_name, SOC_max, i_max, v_max, u_max, eff, charging_type,
            k, soc_t, SOC_t, connected, next_event, 0, 0
        ],
                                           index=cols_EV),
                             ignore_index=True)
    df_EV.set_index('EV_name', inplace=True)
    #Maybe drop all columns which are not used in this glm
    #import pdb; pdb.set_trace()
    return df_EV
Example #13
0
def dispatch_PV(PV, dt_sim_time):
    #import pdb; pdb.set_trace()
    #Should refer to DB and not to python object
    if PV.mode == 1:
        # No constraint
        gridlabd.set_value('PV_' + str(PV.id), 'P_Out',
                           str(PV.Q_bid))  #What if larger?
    elif PV.mode > 0:
        gridlabd.set_value('PV_' + str(PV.id), 'P_Out',
                           str(PV.Q_bid * PV.mode))
    else:
        gridlabd.set_value('PV_' + str(PV.id), 'P_Out', '0.0')
Example #14
0
def compute_bill(gridlabd, **kwargs):

    global csvwriter
    verbose = gridlabd.get_global("verbose") == "TRUE"
    global csvfile

    # get data
    classname = kwargs['classname']
    id = kwargs['id']
    data = kwargs['data']
    bill_name = f"{classname}:{id}"
    bill = gridlabd.get_object(bill_name)
    bill_name = bill["name"]
    baseline = to_float(bill["baseline_demand"])
    tariff = gridlabd.get_object(bill["tariff"])
    meter = gridlabd.get_object(bill["meter"])
    energy = to_float(meter["measured_real_energy"]) / 1000  # units in kW

    # get duration
    clock = to_datetime(gridlabd.get_global('clock'), '%Y-%m-%d %H:%M:%S %Z')

    if not "lastreading" in data.keys():
        duration = timedelta(0)
    else:
        duration = clock - data["lastreading"]
    data["lastreading"] = clock
    billing_days = (duration.total_seconds() / 86400)  # seconds in a day

    # compute energy usage
    if not "lastenergy" in data.keys():
        usage = 0.0
    else:
        usage = energy - data["lastenergy"]
    data["lastenergy"] = energy

    # calculate bill
    tariff_name = tariff["name"]
    meter_name = meter["name"]
    if verbose:
        gridlabd.output(
            f"Bill '{bill_name}' for meter '{meter_name}' on tariff '{tariff_name}' at time '{clock}':"
        )
        gridlabd.output(f"  Billing days..... %5.0f    days" % (billing_days))
        gridlabd.output(f"  Meter reading.... %7.1f  kWh" % (energy))
    if baseline == 0.0:
        if verbose:
            gridlabd.output(f"  Energy usage..... %7.1f  kWh" % (usage))
        charges = usage * to_float(tariff["energy_charge_base"])
    else:
        tier1 = min(usage, baseline * billing_days)
        tier2 = min(usage - tier1, baseline * billing_days * 4)
        tier3 = usage - tier1 - tier2
        if verbose:
            gridlabd.output(f"  Tier 1 usage..... %7.1f  kWh" % (tier1))
            if tier2 > 0:
                gridlabd.output(f"  Tier 2 usage..... %7.1f  kWh" % (tier2))
            if tier3 > 0:
                gridlabd.output(f"  Tier 3 usage..... %7.1f  kWh" % (tier3))
        charges = tier1 * to_float(
            tariff["energy_charge_base"]) + tier2 * to_float(
                tariff["energy_charge_100"]) + tier3 * to_float(
                    tariff["energy_charge_400"])

    # apply discount, if any
    discount = to_float(tariff["discount"])
    if discount > 0:
        charges -= usage * discount

    # apply daily minimum
    minimum = to_float(tariff["minimum_daily_charge"])
    if charges < minimum * billing_days:
        charges = minimum * billing_days
    if verbose:
        gridlabd.output(f"  Energy charges... %8.2f US$" % (charges))

    # output billing record only if charges are non-zero
    if charges > 0:
        csvwriter.writerow([
            clock.strftime('%Y-%m-%d'), meter_name, tariff_name,
            int(billing_days),
            round(usage, 1), 0,
            round(charges, 2)
        ])
        csvfile.flush()

    # update billing data
    gridlabd.set_value(bill_name, "total_bill",
                       str(to_float(bill["total_bill"]) + charges))
    gridlabd.set_value(bill_name, "billing_days", str(billing_days))
    gridlabd.set_value(bill_name, "energy_charges",
                       str(to_float(bill["energy_charges"]) + charges))
    gridlabd.set_value(bill_name, "total_charges",
                       str(to_float(bill["total_charges"]) + charges))
Example #15
0
def setup(obj, t):  # called to set up a new thermostat in a house
    thermostats[obj] = thermostat(obj)
    gridlabd.set_value(obj, "thermostat_control", 'NONE')
    # disable the internal thermostat
    return 0  # setup ok
Example #16
0
def simulate_EVs(house_name, dt_sim_time):
    EV_name = 'EV' + house_name[5:]
    EV_obj = gridlabd.get_object(EV_name)
    online_t = EV_obj['generator_status']
    CP_inv_name = 'EV_inverter' + house_name[5:]

    if dt_sim_time.hour >= 0 and dt_sim_time.hour <= 19:
        if online_t == 'OFFLINE':
            arrival = numpy.random.choice([True, False],
                                          p=[10 / 60., 1. - 10 / 60.])
            if arrival:
                #Actual physical parameters
                gridlabd.set_value(EV_name, 'generator_status', 'ONLINE')
                soc = numpy.random.uniform(0.2, 0.8)
                gridlabd.set_value(EV_name, 'state_of_charge',
                                   str(soc))  #Unknow in TESS

                #Settings through User App
                Kev = numpy.random.uniform(0.5, 1.5)
                gridlabd.set_value(EV_name, 'Kev', str(Kev))
                tdep = dt_sim_time + pandas.Timedelta(
                    hours=7) + pandas.Timedelta(
                        minutes=random.randint(0, 60 * 1))
                gridlabd.set_value(EV_name, 'tdep', str(tdep))
                DeltaE = max(
                    numpy.random.choice(numpy.arange(5., 30., 5.),
                                        p=[1 / 5.] * 5), (1. - soc) * 100.)
                gridlabd.set_value(EV_name, 'DeltaE', str(DeltaE))
                gridlabd.set_value(CP_inv_name, 'EV_connected', str(1))

    if online_t == 'ONLINE':
        #EV_obj = gridlabd.get_object(EV_name) #get new departure time
        if pandas.to_datetime(EV_obj['tdep']) < dt_sim_time:
            gridlabd.set_value(EV_name, 'generator_status', 'OFFLINE')
            gridlabd.set_value(CP_inv_name, 'EV_connected', str(-1))
Example #17
0
def update_EV(dt_sim_time, df_EV_state):
    print('Update EV')
    df_EV_state['active_t-1'] = df_EV_state['active_t']
    df_EV_state['active_t'] = 0
    df_events = pandas.read_csv('EV_events_pop.csv',
                                index_col=[0],
                                parse_dates=df_EV_state.index.tolist())
    for EV in df_EV_state.index:
        EV_number = int(EV.split('_')[-1])
        next_event, next_u, next_soc, next_socmax = df_events[[
            EV, EV + '_u', EV + '_SOC', EV + '_SOCmax'
        ]].iloc[0]
        next_event = next_event.to_pydatetime()
        #Event change
        if next_event <= dt_sim_time:  #event change in the last period -> change in status of battery
            #prev_event, prev_soc = df_events[[EV,EV+'_SOC']].iloc[0]
            df_events[[EV, EV + '_u', EV + '_SOC',
                       EV + '_SOCmax']] = df_events[[
                           EV, EV + '_u', EV + '_SOC', EV + '_SOCmax'
                       ]].shift(-1)

            #Randomly choose for fast-charging
            if EV_speed == 'fast':
                energy_refuel = (1. - next_soc) * next_socmax
                list_EVs = [(24., 22.), (50., 32.), (50., 60.), (120., 90.)]
                EV_type = np.random.choice(len(list_EVs), 1)[0]
                next_u, next_socmax = list_EVs[EV_type]
                next_soc = max(next_socmax - energy_refuel, 0.0) / next_socmax

            #next_event, next_soc = df_events[[EV,EV+'_SOC']].iloc[0]
            if not np.isnan(next_soc):
                #Set EV
                gridlabd.set_value(EV, 'generator_status', 'ONLINE')
                gridlabd.set_value(EV, 'state_of_charge', str(next_soc))
                gridlabd.set_value(EV, 'battery_capacity',
                                   str(next_socmax * 1000))
                i_max = 1000 * next_u / df_EV_state['v_max'].loc[EV]
                gridlabd.set_value(EV, 'I_Max', str(i_max))
                gridlabd.set_value(EV, 'P_Max', str(next_u * 1000))
                gridlabd.set_value(EV, 'E_Max', str(next_u * 1000 * 1))
                EV_inv = 'EV_inverter' + EV[2:]
                gridlabd.set_value(EV_inv, 'rated_power',
                                   str(1.2 * next_u * 1000))
                gridlabd.set_value(EV_inv, 'rated_battery_power',
                                   str(1.2 * next_u * 1000))
                #import pdb; pdb.set_trace()

                #Set df_EV_state
                df_EV_state.at[EV, 'SOC_max'] = next_socmax
                df_EV_state.at[EV, 'i_max'] = i_max
                df_EV_state.at[EV, 'u_max'] = next_u
                df_EV_state.at[
                    EV,
                    'connected'] = 1  #Does this one not work such that delay in connection?
                df_EV_state.at[EV, 'soc_t'] = next_soc
                df_EV_state.at[EV, 'SOC_t'] = next_soc * next_socmax
                df_EV_state.at[EV, 'next_event'] = next_event
            else:  #if next event associated with non-NaN SOC - now connected and pot. charging
                #Set EV (only switch off)
                gridlabd.set_value(EV, 'generator_status', 'OFFLINE')
                gridlabd.set_value(EV, 'state_of_charge', str(0.0))
                #Set df_EV_state
                df_EV_state.at[EV, 'SOC_max'] = 0.0
                df_EV_state.at[EV, 'i_max'] = 0.0
                df_EV_state.at[EV, 'u_max'] = 0.0
                df_EV_state.at[
                    EV,
                    'connected'] = 0  #Does this one not work such that delay in connection?
                df_EV_state.at[EV, 'soc_t'] = 0.0
                df_EV_state.at[EV, 'SOC_t'] = 0.0
                df_EV_state.at[EV, 'next_event'] = next_event
        #After last event (no upcoming events)
        elif pandas.isnull(next_event):
            #Set EV (only switch off)
            gridlabd.set_value(EV, 'generator_status', 'OFFLINE')
            #Set df_EV_state
            df_EV_state.at[EV, 'SOC_max'] = 0.0
            df_EV_state.at[EV, 'i_max'] = 0.0
            df_EV_state.at[EV, 'u_max'] = 0.0
            df_EV_state.at[
                EV,
                'connected'] = 0  #Does this one not work such that delay in connection?
            df_EV_state.at[EV, 'soc_t'] = 0.0
            df_EV_state.at[EV, 'SOC_t'] = 0.0
            df_EV_state.at[EV, 'next_event'] = next_event
        #During charging event: Update EV state (SOC)
        elif pandas.isnull(next_socmax):
            # Updating through GridlabD model
            EV_obj = gridlabd.get_object(EV)
            soc_t = float(EV_obj['state_of_charge'])
            df_EV_state.at[EV, 'soc_t'] = soc_t
            SOC_t = soc_t * float(
                EV_obj['battery_capacity']
            ) / 1000  #In Wh #Losses updated by GridlabD ?
            df_EV_state.at[EV, 'SOC_t'] = SOC_t

            # Updating using df
            #print('GLD battery model is not used, manual updating!')
            #gridlabd.set_value(EV,'state_of_charge',str(df_EV_state['soc_t'].loc[EV])) #in p.u.
        else:
            pass

    df_events.to_csv('EV_events_pop.csv')
    return df_EV_state
Example #18
0
def get_settings_EVs(EVlist, interval, mysql=False):
    cols_EV = [
        'EV_name', 'house_name', 'SOC_max', 'i_max', 'v_max', 'u_max',
        'efficiency', 'charging_type', 'k', 'soc_t', 'SOC_t', 'connected',
        'next_event', 'active_t-1', 'active_t'
    ]
    df_EV = pandas.DataFrame(columns=cols_EV)
    #Read in charging events
    #df_events = pandas.read_csv('EV_events_2016_july_Austin.csv',index_col=[0],parse_dates=True) #'EV_events_2015_july.csv'
    df_events = pandas.read_csv(EV_data, index_col=[0], parse_dates=True)
    first_time = pandas.Timestamp.today()
    first_time = first_time.replace(year=first_time.year +
                                    4)  #to ensure working with RT data
    for EV in EVlist:
        df_events[EV] = pandas.to_datetime(df_events[EV])
        if df_events[EV].min() < first_time:
            first_time = df_events[EV].min()
    first_time = first_time.replace(hour=0, minute=0, second=0)
    start_time = pandas.to_datetime(start_time_str)
    delta = start_time - first_time
    for EV in EVlist:
        df_events[EV] = df_events[EV] + delta
        EV_obj = gridlabd.get_object(EV)
        #gridlabd.set_value(EV,'use_internal_battery_model','FALSE')
        house_name = 'GLD_' + EV[3:]
        #Use GridLABD default values
        v_max = float(EV_obj['V_Max'])  #keep v_max constant for now
        eff = float(EV_obj['base_efficiency'])
        #Fills TABLE market_appliances
        #SOC_min = float(EV_obj['reserve_state_of_charge']) #in % - 20%
        #SOC_max = float(EV_obj['battery_capacity'])/1000 #Wh in Gridlabd -> kWh
        #str_i_max = EV_obj['I_Max']
        #i_max = str_i_max.split('+')[1]
        #u_max = float(EV_obj['V_Max'])*float(i_max)/1000 #W -> kW #better inverter?
        charging_type = EV_obj['charging_type']
        k = float(EV_obj['k'])  #no market: always highest wllingsness to pay
        #Gets next event
        cols = [EV, EV + '_u', EV + '_SOC', EV + '_SOCmax']
        df_events_EV = df_events[cols]
        discard_events = True
        while discard_events:
            if (df_events_EV[EV].iloc[0] < pandas.to_datetime(start_time_str)
                ) and (df_events_EV[EV].iloc[1] <
                       pandas.to_datetime(start_time_str)):
                df_events_EV = df_events_EV.iloc[2:]
            elif (df_events_EV[EV].iloc[0] < pandas.to_datetime(start_time_str)
                  ) and (df_events_EV[EV].iloc[1] >
                         pandas.to_datetime(start_time_str)):
                #Get information from EV events table
                soc_t = df_events_EV[EV + '_SOC'].iloc[0]  #relative soc
                u_max = df_events_EV[EV + '_u'].iloc[0]  #in kW
                SOC_max = df_events_EV[EV + '_SOCmax'].iloc[0]  #in kWh
                #For start of the simulation
                soc_t = soc_t + (
                    1. - soc_t
                ) / 2.  #No EV connected yet - at midnight, initialize with 50% charged already
                SOC_t = soc_t * SOC_max
                gridlabd.set_value(EV, 'state_of_charge', str(soc_t))
                gridlabd.set_value(EV, 'battery_capacity', str(SOC_max * 1000))
                i_max = 1000 * u_max / v_max
                gridlabd.set_value(EV, 'I_Max', str(i_max))
                gridlabd.set_value(EV, 'generator_status', 'ONLINE')
                next_event = df_events_EV[EV].iloc[
                    1]  #Next event: disconnection
                df_events_EV = df_events_EV.iloc[
                    1:]  #Only discard connection event
                connected = 1
                discard_events = False
            elif (df_events_EV[EV].iloc[0] > pandas.to_datetime(start_time_str)
                  ) and (df_events_EV[EV].iloc[1] >
                         pandas.to_datetime(start_time_str)):
                soc_t = 0.0
                u_max = 0.0
                SOC_max = 0.0
                soc_t = 0.0
                SOC_t = 0.0
                i_max = 0.0
                next_event = df_events_EV[EV].iloc[0]  #Next event: connection
                connected = 0
                gridlabd.set_value(EV, 'generator_status', 'OFFLINE')
                discard_events = False
            else:
                print(
                    'Unclear or no EV events at that charging station during that time'
                )
                soc_t = 0.0
                i_max = 0.0
                next_event = pandas.to_datetime(
                    end_time_str)  #Next event: none / end_time
                connected = 0
                gridlabd.set_value(EV, 'generator_status', 'OFFLINE')
                discard_events = False
        df_EV = df_EV.append(pandas.Series([
            EV, house_name, SOC_max, i_max, v_max, u_max, eff, charging_type,
            k, soc_t, SOC_t, connected, next_event, 0, 0
        ],
                                           index=cols_EV),
                             ignore_index=True)
        df_events_EV.index = df_events_EV.index - df_events_EV.index[
            0]  #reset index to range()
        df_events[cols] = df_events_EV[cols]
        df_events.to_csv('EV_events_pop.csv')
    df_EV.set_index('EV_name', inplace=True)
    #Maybe drop all columns which are not used in this glm
    return df_EV
Example #19
0
def update_EV_rnd(dt_sim_time, df_EV_state):
    print('Update EV')
    df_EV_state['active_t-1'] = df_EV_state['active_t']
    df_EV_state['active_t'] = 0

    today = pandas.Timestamp(dt_sim_time.year, dt_sim_time.month,
                             dt_sim_time.day)
    for EV in df_EV_state.index:
        EV_number = int(EV.split('_')[-1])
        next_event = df_EV_state['next_event'].loc[EV]
        #Event change
        if next_event <= dt_sim_time:  #event change in the last period -> change in status of battery

            #Randomly choose for fast-charging
            if EV_speed == 'fast':
                energy_refuel = (1. - next_soc) * next_socmax
                list_EVs = [(24., 22.), (50., 32.), (50., 60.), (120., 90.)]
                EV_type = np.random.choice(len(list_EVs), 1)[0]
                next_u, next_socmax = list_EVs[EV_type]
                next_soc = max(next_socmax - energy_refuel, 0.0) / next_socmax

            #just arrived
            if df_EV_state['connected'].loc[EV] == 0:
                #Set EV
                next_u = df_EV_state['u_max'].loc[EV]
                gridlabd.set_value(EV, 'generator_status', 'ONLINE')
                soc_t = np.random.uniform(0.2, 0.8)
                gridlabd.set_value(EV, 'state_of_charge', str(soc_t))
                gridlabd.set_value(EV, 'battery_capacity',
                                   str(df_EV_state['SOC_max'].loc[EV] * 1000))
                i_max = 1000 * next_u / df_EV_state['v_max'].loc[EV]
                gridlabd.set_value(EV, 'I_Max', str(i_max))
                gridlabd.set_value(EV, 'P_Max', str(next_u * 1000))
                gridlabd.set_value(EV, 'E_Max', str(next_u * 1000 * 1))
                EV_inv = 'EV_inverter' + EV[2:]
                gridlabd.set_value(EV_inv, 'rated_power',
                                   str(1.2 * next_u * 1000))
                gridlabd.set_value(EV_inv, 'rated_battery_power',
                                   str(1.2 * next_u * 1000))
                #import pdb; pdb.set_trace()

                #Set df_EV_state
                df_EV_state.at[
                    EV,
                    'connected'] = 1  #Does this one not work such that delay in connection?
                df_EV_state.at[EV, 'soc_t'] = soc_t
                df_EV_state.at[
                    EV, 'SOC_t'] = soc_t * df_EV_state['SOC_max'].loc[EV]

                #Departure time tomorrow
                df_EV_state.at[EV, 'next_event'] = today + pandas.Timedelta(
                    days=1,
                    hours=np.random.choice(dep_hours),
                    minutes=np.random.choice(
                        range(60)))  #Next event: disconnection

            else:  #if next event associated with non-NaN SOC - now connected and pot. charging
                #Set EV (only switch off)
                gridlabd.set_value(EV, 'generator_status', 'OFFLINE')
                gridlabd.set_value(EV, 'state_of_charge', str(0.0))
                #Set df_EV_state
                df_EV_state.at[
                    EV,
                    'connected'] = 0  #Does this one not work such that delay in connection?
                df_EV_state.at[EV, 'soc_t'] = 0.0
                df_EV_state.at[EV, 'SOC_t'] = 0.0
                #Arrival time today
                df_EV_state.at[EV, 'next_event'] = today + pandas.Timedelta(
                    hours=np.random.choice(arr_hours),
                    minutes=np.random.choice(
                        range(60)))  #Next event: disconnection

        #During charging event: Update EV state (SOC)
        elif df_EV_state['connected'].loc[EV] == 1:
            # Updating through GridlabD model
            # EV_obj = gridlabd.get_object(EV)
            # soc_t = float(EV_obj['state_of_charge'])
            # df_EV_state.at[EV,'soc_t'] = soc_t
            # SOC_t = soc_t*float(EV_obj['battery_capacity'])/1000 #In Wh #Losses updated by GridlabD ?
            # df_EV_state.at[EV,'SOC_t'] = SOC_t

            # Updating using df
            #print('GLD battery model is not used for EVs, manual updating!')
            gridlabd.set_value(EV, 'state_of_charge',
                               str(df_EV_state['soc_t'].loc[EV]))  #in p.u.
        else:
            pass

    return df_EV_state