Example #1
0
def update_house(dt_sim_time, df_market_hvac):
    #rec_obj = gridlabd.get_object('rec_T')
    for i in df_market_hvac.index:  #directly from mysql
        #house_obj = gridlabd.get_object(df_market_hvac['house_name'].loc[i])
        #df_market_hvac.at[i,'air_temperature'] = float(house_obj['air_temperature'])
        df_market_hvac.at[i, 'air_temperature'] = float(
            gridlabd.get_value(df_market_hvac['house_name'].loc[i],
                               'air_temperature')[:-5])
        #Update bidding q to latest demand values
        #if house_obj['system_mode'] == 'HEAT':
        if df_market_hvac.at[
                i, 'active'] == 1:  #Only update if it was active before
            if gridlabd.get_value(df_market_hvac['house_name'].loc[i],
                                  'system_mode') == 'HEAT':
                df_market_hvac.at[i, 'P_heat'] = float(
                    gridlabd.get_value(df_market_hvac['house_name'].loc[i],
                                       'hvac_load')[:-3])
            #elif house_obj['system_mode'] == 'COOL':
            elif gridlabd.get_value(df_market_hvac['house_name'].loc[i],
                                    'system_mode') == 'COOL':
                #df_market_hvac.at[i,'P_cool'] = float(house_obj['hvac_load'])
                #print(gridlabd.get_value(df_market_hvac['house_name'].loc[i],'hvac_load'))
                df_market_hvac.at[i, 'P_cool'] = float(
                    gridlabd.get_value(df_market_hvac['house_name'].loc[i],
                                       'hvac_load')[:-3])
    return df_market_hvac
def update_house(dt_sim_time, df_market_hvac):
    #rec_obj = gridlabd.get_object('rec_T')
    for i in df_market_hvac.index:  #directly from mysql
        #house_obj = gridlabd.get_object(df_market_hvac['house_name'].loc[i])
        #df_market_hvac.at[i,'air_temperature'] = float(house_obj['air_temperature'])

        # This measures the temperature - but it's actually the temperature from -5min bec it's not synchronized yet !!!
        #df_market_hvac.at[i,'air_temperature_measured'] = float(gridlabd.get_value(df_market_hvac['house_name'].loc[i],'air_temperature')[:-5])
        df_market_hvac.at[i, 'air_temperature'] = float(
            gridlabd.get_value(df_market_hvac['house_name'].loc[i],
                               'air_temperature')[:-5])

        #Update bidding q to latest demand values
        #if house_obj['system_mode'] == 'HEAT':
        if df_market_hvac.at[
                i, 'active'] == 1:  #Only update if it was active before
            if gridlabd.get_value(df_market_hvac['house_name'].loc[i],
                                  'system_mode') == 'HEAT':
                if not df_market_hvac.at[i, 'heating_system'] == 'GAS':
                    df_market_hvac.at[i, 'P_heat'] = float(
                        gridlabd.get_value(df_market_hvac['house_name'].loc[i],
                                           'hvac_load')[:-3])
                # else:
                # 	import pdb; pdb.set_trace()
            #elif house_obj['system_mode'] == 'COOL':
            elif gridlabd.get_value(df_market_hvac['house_name'].loc[i],
                                    'system_mode') == 'COOL':
                #df_market_hvac.at[i,'P_cool'] = float(house_obj['hvac_load'])
                #print(gridlabd.get_value(df_market_hvac['house_name'].loc[i],'hvac_load'))
                df_market_hvac.at[i, 'P_cool'] = float(
                    gridlabd.get_value(df_market_hvac['house_name'].loc[i],
                                       'hvac_load')[:-3])

    # This makes a forecast of the actual temperature in t (i.e. g(theta_t-1) = est_theta_t )

    T_out = float(gridlabd.get_object('tmy_file')['temperature'])
    #ind_off = df_market_hvac.loc[(df_market_hvac['active'] == 0)].index
    df_market_hvac['air_temperature'] = df_market_hvac[
        'beta'] * df_market_hvac['air_temperature'] + (
            1. - df_market_hvac['beta']) * T_out
    ind_cool = df_market_hvac.loc[(df_market_hvac['active'] == 1) & (
        df_market_hvac['system_mode'] == 'COOL')].index
    df_market_hvac['air_temperature'].loc[
        ind_cool] = df_market_hvac['air_temperature'].loc[ind_cool] - (
            df_market_hvac['P_cool'] * df_market_hvac['gamma_cool'] *
            share_t).loc[ind_cool]
    ind_heat = df_market_hvac.loc[(df_market_hvac['active'] == 1) & (
        df_market_hvac['system_mode'] == 'HEAT')].index
    df_market_hvac['air_temperature'].loc[
        ind_heat] = df_market_hvac['air_temperature'].loc[ind_heat] + (
            df_market_hvac['P_heat'] * df_market_hvac['gamma_heat'] *
            share_t).loc[ind_heat]
    return df_market_hvac
def on_term(t):
    last = None
    for obj in gridlabd.get("objects"):
        oclass = gridlabd.get_value(obj, "class")
        prop = gridlabd.property(obj, "py_object")
        if oclass == "test":
            prop = gridlabd.property(obj, "py_object")
        elif oclass == "check":
            prop = gridlabd.property(obj, obj)
        else:
            continue
        prop.rlock()
        value = prop.get_value()
        initv = prop.get_initial()
        text = str(prop)
        info = repr(prop)
        unit = prop.get_unit()
        prop.unlock()
        if obj in test.keys():
            value = test[obj]
            prop.wlock()
            if type(value) is dict:
                goal = value
                check = value
                init = True
            elif type(test[obj]) is list:
                goal = value[0]
                check = value[1]
                init = False
            else:
                goal = value
                check = value
                init = False
            prop.set_value(goal)
            if init:
                result = prop.get_initial()
            else:
                result = prop.get_value()
            if obj in convert.keys():
                check = convert[obj](check)
            if result != check:
                raise Exception(f"set failed ('{result}' != '{check}')")
            prop.unlock()

            for u, v in units.items():
                if prop.get_name() == u:
                    x = prop.convert_unit(v[1])
                    if x != v[0]:
                        raise Exception(
                            f"unit conversion failed ({x} != {u[0]}")
        if prop == last:
            raise Exception("property eq comparison failed unexpectedly")
        if prop != prop:
            raise Exception("property ne comparison failed unexpectedly")
        ok = None
        try:
            prop < last
            prop > last
            prop <= last
            prop >= last
            ok = False
        except:
            ok = True
            pass
        if ok == None:
            raise Exception("property lt/le/gt/ge test inconclusive")
        elif ok == False:
            raise Exception("property lt/le/gt/ge succeeded unexpectedly")
        last = prop
Example #4
0
def on_sync(t):
    """GridLAB-D synchronization event handler

    Parameter:
        t (int): target timestamp

    Return:
        int: timestamp of next desired sync event call
    """
    global property_list
    global limit_list

    # get the current timestamp in human readable form
    dt = datetime.datetime.fromtimestamp(t)
    gridlabd.debug(f"*** onsync({dt}) ***")

    # determine whether a violation has occurred
    violation_active = int(gridlabd.get_global("powerflow::violation_active"))
    if violation_active:
        gridlabd.debug(f"{dt}: violation detected (violation_active={violation_active})")

    # start by assuming there's nothing left to do with the property being considered
    done = None

    # if there's still a property to consider
    if property_list:

        # get the object name of the property to consider (the first one in the list of keys
        objname = list(property_list.keys())[0]
        gridlabd.debug(f"{dt}: updating {objname}")
        if objname not in limit_list:
            limit_list[objname] = {}

        # get the properties being considered for this object
        proplist = property_list[objname]

        # if the property list is non-empty
        if proplist:

            # for each property in the object's property list
            for propname, specs in proplist.items():
                if propname not in limit_list[objname]:
                    limit_list[objname][propname] = {}

                # get the property name and the property's original value
                prop = specs[0]
                base = specs[1]
                limit = specs[2]

                # if the original value is zero
                if base.real == 0.0:

                    # consider property by fixed increment specified by delta and reactive_ratio
                    value = prop.get_value() - complex(delta,delta*reactive_ratio)

                # original value is non-zero
                else:

                    # consider property by relative increments specified by delta
                    value = prop.get_value() - base/base.real*delta

                # if a violation has occurred
                if violation_active:
                    gridlabd.debug(f"{dt}: resetting {objname}.{propname} to base {base}")

                    # reset the property to its original value
                    prop.set_value(base)

                    # record the load limit
                    if not objname in limit_list.keys() or not propname in limit_list[objname].keys():
                        load_limit = base - value
                        limit_list[objname][propname] = {
                            "timestamp" : str(datetime.datetime.fromtimestamp(t)), 
                            "real" : load_limit.real, 
                            "reactive" : load_limit.imag}
                    limit_list[objname][propname]["violation"] = gridlabd.get_value(objname,"violation_detected")

                    # flag that processing is done
                    done = objname

                # if the maximum solar limit is reached
                elif power_limit and value.real < power_limit and limit == "POWER":
                    gridlabd.debug(f"{dt}: power limit reach for {objname}.{propname} = {value}")

                    # reset the property to its original value
                    prop.set_value(base)

                    # record the load limit
                    if not objname in limit_list.keys() or not propname in limit_list[objname].keys():
                        load_limit = base - value
                        limit_list[objname][propname] = {
                            "timestamp" : str(datetime.datetime.fromtimestamp(t)), 
                            "real" : load_limit.real, 
                            "reactive" : load_limit.imag}
                    limit_list[objname][propname]["violation"] = "POWERLIMIT"

                    # flag that processing is done
                    done = objname

                # if the maximum solar limit is reached
                elif voltage_limit and base.real != 0.0 and abs((value.real-base.real)/base.real) > voltage_limit and limit == "VOLTAGE":
                    gridlabd.debug(f"{dt}: power deviation limit reach for {objname}.{propname} = {value}")

                    # reset the property to its original value
                    prop.set_value(base)

                    # record the load limit
                    if not objname in limit_list.keys() or not propname in limit_list[objname].keys():
                        load_limit = base - value
                        limit_list[objname][propname] = {
                            "timestamp" : str(datetime.datetime.fromtimestamp(t)), 
                            "real" : load_limit.real, 
                            "reactive" : load_limit.imag}
                    limit_list[objname][propname]["violation"] = "VOLTAGELIMIT"

                    # flag that processing is done
                    done = objname


                # if no violation has occurred
                else:
                    gridlabd.debug(f"{dt}: updating {objname}.{propname} = {value}")

                    # set the new value of the property
                    prop.set_value(value)

                    # compute the load limit implied by this value
                    load_limit = base - value

                    # record the load limit
                    limit_list[objname][propname] = {
                        "timestamp":str(datetime.datetime.fromtimestamp(t)), 
                        "real":load_limit.real, 
                        "reactive":load_limit.imag,
                        "violation" : "NONE"
                        }

        # the property list is empty
        else:

            # flag that processing is done
            done = objname


        # if done
        if done:
            gridlabd.debug(f"{dt}: finished with {objname}")

            # if property list is empty
            if proplist == {}:

                # remove the object from the list of properties to consider
                del property_list[objname]

            # the property list is not empty
            else:

                # clear the property list (this will allow an extra solver iteration to clear the violation)
                property_list[objname] = {}

            # if the property list is non-empty
            if property_list:
                gridlabd.debug(f"{dt}: next is {list(property_list.keys())[0]}")

        # if a violation occurred
        if violation_active:

            # clear the violation
            gridlabd.debug(f"{dt}: clearing violation")
            gridlabd.set_global("powerflow::violation_active","0")

        # wait 1 minute for controls to settle before trying the next value
        tt = t+60
        gridlabd.debug(f"updating to {datetime.datetime.fromtimestamp(tt)}")
        return tt

    # no objects or properties left to consider
    else:

        # nothing left to do
        gridlabd.debug(f"updating to NEVER")
        return gridlabd.NEVER
Example #5
0
def on_init(t):
    """GridLAB-D initialization event handler

    Parameter:
        t (int): initial timestamp

    Return:
        bool: success (True) or failure (False)
    """
    global output_folder
    global object_list
    global target_properties

    # get the output folder name from the global variable list
    output_folder = gridlabd.get_global("OUTPUT")

    # if none is defined
    if not output_folder:

        # use the current working direction
        output_folder = "."

    # if objects to consider are not specified
    if not object_list:

        # use list of all objects
        object_list = gridlabd.get("objects")

    # for each object in the object list
    for objname in object_list:

        # the object's class
        classname = gridlabd.get_value(objname,"class")

        # if the class is listed among the targets
        for classname, target_list in target_properties.items():

            # get the object's data
            objdata = gridlabd.get_object(objname)

            # if the object has phase data
            if "phases" in objdata.keys():

                # get the object's class structure
                classdata = gridlabd.get_class(classname)

                # for each property in the class's target property list
                for property_name, limittype in target_list.items():

                    # get the property pattern to use, and replace phase information pattern, if any
                    pattern = property_name.replace("{phases}",f"[{objdata['phases']}]")

                    # for each property in the class
                    for propname in classdata.keys():

                        # if the property matches the pattern
                        if re.match(pattern,propname):

                            # add the property to the list of properties to consider
                            add_property(objname,propname,limittype,nonzero=False)

    # successfully initialized
    return True