def execute(self):
        """
        Calculates weather sensitivity using Spearman rank.
        Also, outputs data points for energy signature scatter plot.
        """

        self.out.log("Starting application: energy signature.", logging.INFO)

        self.out.log("Querying database.", logging.INFO)
        load_query = self.inp.get_query_sets('load', group_by='hour',
                                             group_by_aggregation=Avg,
                                             exclude={'value':None},
                                             wrap_for_merge=True)
        oat_query = self.inp.get_query_sets('oat', group_by='hour',
                                             group_by_aggregation=Avg,
                                             exclude={'value':None},
                                             wrap_for_merge=True)

        self.out.log("Getting unit conversions.", logging.INFO)
        base_topic = self.inp.get_topics()
        meta_topics = self.inp.get_topics_meta()

        load_unit = meta_topics['load'][base_topic['load'][0]]['unit']
        self.out.log(
            "Convert loads from [{}] to [kW].".format(load_unit),
            logging.INFO
            )
        load_convertfactor = cu.getFactor_powertoKW(load_unit)

        temperature_unit = meta_topics['oat'][base_topic['oat'][0]]['unit']
        self.out.log(
            "Convert temperatures from [{}] to [F].".format(temperature_unit),
            logging.INFO
            )

        #print('merge load', merged_load_oat)
        load_values = []
        oat_values = []

        self.out.log("Pulling data from database.", logging.INFO)
        merged_load_oat = self.inp.merge(load_query, oat_query)
        for x in merged_load_oat:
            if temperature_unit == 'celcius':
                convertedTemp = cu.convertCelciusToFahrenheit(x['oat'][0])
            elif temperature_unit == 'kelvin':
                convertedTemp = cu.convertKelvinToCelcius(
                                cu.convertCelciusToFahrenheit(x['oat'][0]))
            else:
                convertedTemp = x['oat'][0]

            load_values.append(x['load'][0]*load_convertfactor)
            oat_values.append(convertedTemp)
            self.out.insert_row(LOAD_VS_OAT_TABLE_NAME, {
                "oat": x['oat'][0],
                "load": x['load'][0]
                })

        self.out.log("Calculating the Spearman rank.", logging.INFO)
        #print(load_values)
        #print(oat_values)
        weather_sensitivity = findSpearmanRank(load_values, oat_values)

        self.out.log("Adding weather sensitivity to table.", logging.INFO)
        self.out.insert_row(WEATHER_SENSITIVITY_TABLE_NAME, {
            "value": "{:.2f}".format(weather_sensitivity)
            })
Beispiel #2
0
    def run(self, current_time, points):
        '''
        Check algorithm pre-quisites and assemble data set for analysis.
        '''
        device_dict = {}
        result = Results()
        topics = self.inp.get_topics()
        topic = topics[self.hws_temp_name][0]
        current_time = self.inp.localize_sensor_time(topic, current_time)
        base_topic = self.inp.get_topics()
        meta_topics = self.inp.get_topics_meta()

        unit_dict = {}
        if len(base_topic[self.oa_temp_name]) > 0:
            unit_dict[self.oa_temp_name] = meta_topics[self.oa_temp_name][
                base_topic[self.oa_temp_name][0]]['unit']
        if len(base_topic[self.hws_temp_name]) > 0:
            unit_dict[self.hws_temp_name] = meta_topics[self.hws_temp_name][
                base_topic[self.hws_temp_name][0]]['unit']
        if len(base_topic[self.hwr_temp_name]) > 0:
            unit_dict[self.hwr_temp_name] = meta_topics[self.hwr_temp_name][
                base_topic[self.hwr_temp_name][0]]['unit']
        if len(base_topic[self.hw_stsp_name]) > 0:
            unit_dict[self.hw_stsp_name] = meta_topics[self.hw_stsp_name][
                base_topic[self.hw_stsp_name][0]]['unit']

        for key, value in points.items():
            device_dict[key.lower()] = value

        oatemp_data = []
        loop_dp_values = []
        loop_dp_stpt_values = []
        hw_pump_status_values = []
        boiler_status_values = []
        hw_pump_vfd_values = []
        hw_stsp_values = []
        hws_temp_values = []
        hwr_temp_values = []

        for key, value in device_dict.items():
            if key.startswith(self.loop_dp_stpt_name) and value is not None:
                loop_dp_stpt_values.append(value)
            elif key.startswith(self.loop_dp_name) and value is not None:
                loop_dp_values.append(value)
            elif key.startswith(
                    self.hw_pump_status_name) and value is not None:
                hw_pump_status_values.append(value)
            elif key.startswith(self.boiler_status_name) and value is not None:
                boiler_status_values.append(value)
            elif key.startswith(self.hw_pump_vfd_name) and value is not None:
                hw_pump_vfd_values.append(value)
            elif key.startswith(self.hw_stsp_name) and value is not None:
                hw_stsp_values.append(value)
            elif key.startswith(self.hws_temp_name) and value is not None:
                hws_temp_values.append(value)
            elif key.startswith(self.hwr_temp_name) and value is not None:
                hwr_temp_values.append(value)
            elif (key.startswith(self.oa_temp_name)  #OAT
                  and value is not None):
                oatemp_data.append(value)

        if 'celcius' or 'kelvin' in unit_dict.values:
            if self.oa_temp_name in unit_dict:
                if unit_dict[self.oa_temp_name] == 'celcius':
                    oatemp_data = cu.convertCelciusToFahrenheit(oatemp_data)
                elif unit_dict[self.oa_temp_name] == 'kelvin':
                    oatemp_data = cu.convertKelvinToCelcius(
                        cu.convertCelciusToFahrenheit(oatemp_data))
            if self.hw_stsp_name in unit_dict:
                if unit_dict[self.hw_stsp_name] == 'celcius':
                    hw_stsp_values = cu.convertCelciusToFahrenheit(
                        hw_stsp_values)
                elif unit_dict[self.hw_stsp_name] == 'kelvin':
                    hw_stsp_values = cu.convertKelvinToCelcius(
                        cu.convertCelciusToFahrenheit(hw_stsp_values))
            if self.hw_stsp_name in unit_dict:
                if unit_dict[self.hws_temp_name] == 'celcius':
                    hws_temp_values = cu.convertCelciusToFahrenheit(
                        hws_temp_values)
                elif unit_dict[self.hws_temp_name] == 'kelvin':
                    hws_temp_values = cu.convertKelvinToCelcius(
                        cu.convertCelciusToFahrenheit(hws_temp_values))
            if self.hwr_temp_name in unit_dict:
                if unit_dict[self.hwr_temp_name] == 'celcius':
                    hwr_temp_values = cu.convertCelciusToFahrenheit(
                        hwr_temp_values)
                elif unit_dict[self.hwr_temp_name] == 'kelvin':
                    hwr_temp_values = cu.convertKelvinToCelcius(
                        cu.convertCelciusToFahrenheit(hwr_temp_values))

        oatemp = hw_stsp_temp = hws_temp = hwr_temp = None
        loop_dp = loop_dp_stpt = None
        hw_pump_status = boiler_status = None
        hw_pump_vfd = None

        if oatemp_data:
            oatemp = (sum(oatemp_data) / len(oatemp_data))
        if hw_stsp_values:
            hw_stsp_temp = (sum(hw_stsp_values) / len(hw_stsp_values))
        if hws_temp_values:
            hws_temp = (sum(hws_temp_values) / len(hws_temp_values))
        if hwr_temp_values:
            hwr_temp = (sum(hwr_temp_values) / len(hwr_temp_values))

        if loop_dp_stpt_values:
            loop_dp_stpt = (sum(loop_dp_stpt_values) /
                            len(loop_dp_stpt_values))
        if loop_dp_values:
            loop_dp = (sum(loop_dp_values) / len(loop_dp_values))

        if hw_pump_status_values:
            hw_pump_status = (sum(hw_pump_status_values) /
                              len(hw_pump_status_values))
        if boiler_status_values:
            boiler_status = (sum(boiler_status_values) /
                             len(boiler_status_values))

        if hw_pump_vfd_values:
            hw_pump_vfd = (sum(hw_pump_vfd_values) / len(hw_pump_vfd_values))

        out_data = {
            'datetime': str(current_time),
        }

        if not oatemp is None:
            out_data['OutdoorAirTemperature'] = oatemp
        if not hws_temp is None:
            out_data['HotWaterSupplyTemperature'] = hws_temp
        if not hwr_temp is None:
            out_data['HotWaterReturnTemperature'] = hwr_temp
        if not hw_stsp_temp is None:
            out_data['HotWaterTemperatureSetPoint'] = hw_stsp_temp

        if not loop_dp is None:
            out_data['LoopDifferentialPressure'] = loop_dp
        if not loop_dp_stpt is None:
            out_data['LoopDifferentialPressureSetPoint'] = loop_dp_stpt

        if not hw_pump_status is None:
            out_data['PumpStatus'] = hw_pump_status
        if not boiler_status is None:
            out_data['BoilerStatus'] = boiler_status

        if not hw_pump_vfd is None:
            out_data['HotWaterPumpVfd'] = hw_pump_vfd

        result.insert_table_row(self.table_name, out_data)

        return result
Beispiel #3
0
    def run(self, current_time, points):
        """
            Main run method that is called by the DrivenBaseClass.
        """
        device_dict = {}
        result = Results()
        topics = self.inp.get_topics()
        topic = topics[self.oa_temp_name][0]
        current_time = self.inp.localize_sensor_time(topic, current_time)
        base_topic = self.inp.get_topics()
        meta_topics = self.inp.get_topics_meta()
        unit_dict = {
            self.oa_temp_name: meta_topics[self.oa_temp_name][base_topic[self.oa_temp_name][0]]['unit']
        }

        if len(base_topic[self.ma_temp_name]) > 0:
            unit_dict[self.ma_temp_name] = meta_topics[self.ma_temp_name][base_topic[self.ma_temp_name][0]]['unit']
        if len(base_topic[self.ra_temp_name]) > 0:
            unit_dict[self.ra_temp_name] = meta_topics[self.ra_temp_name][base_topic[self.ra_temp_name][0]]['unit']
        if len(base_topic[self.da_temp_name]) > 0:
            unit_dict[self.da_temp_name] = meta_topics[self.da_temp_name][base_topic[self.da_temp_name][0]]['unit']
        if len(base_topic[self.da_temp_setpoint_name]) > 0:
            unit_dict[self.da_temp_setpoint_name] = \
                meta_topics[self.da_temp_setpoint_name][base_topic[self.da_temp_setpoint_name][0]]['unit']

        for key, value in points.items():
            device_dict[key.lower()] = value

        damper_data = []
        oatemp_data = []
        matemp_data = []
        ratemp_data = []
        datemp_data = []
        datemp_stpt_data = []
        ccv_data = []
        fan_speedcmd_data = []
        fan_status_data = []
        hcv_data = []
        return_fan_speedcmd_data = []
        occ_data = []
        discharge_sp_data = []
        staticpressure_sp_data = []

        for key, value in device_dict.items():
            if (key.startswith(self.outdoor_damper_name) #Damper
                    and value is not None):
                damper_data.append(value)
            elif (key.startswith(self.oa_temp_name) #OAT
                  and value is not None):
                oatemp_data.append(value)
            elif (key.startswith(self.ma_temp_name) #MAT
                  and value is not None):
                matemp_data.append(value)
            elif (key.startswith(self.ra_temp_name) #RAT
                  and value is not None):
                ratemp_data.append(value)
            elif (key.startswith(self.da_temp_name) #DAT
                  and value is not None):
                datemp_data.append(value)
            elif (key.startswith(self.da_temp_setpoint_name) #DAT SetPoint
                  and value is not None):
                datemp_stpt_data.append(value)
            elif (key.startswith(self.cc_valve_name) #CoolCoilValvePos
                  and value is not None):
                ccv_data.append(value)
            elif (key.startswith(self.hc_valve_name) #HeatCoilValvePos
                  and value is not None):
                hcv_data.append(value)
            elif (key.startswith(self.fan_speedcmd_name) #Fan speed
                  and value is not None):
                fan_speedcmd_data.append(value)
            elif (key.startswith(self.fan_status_name) #Fan status
                  and value is not None):
                fan_status_data.append(value)
            elif (key.startswith(self.returnfan_speedcmd_name) #returnfan_speedcmd_name
                  and value is not None):
                return_fan_speedcmd_data.append(value)
            elif (key.startswith(self.occ_name) #Occupancy
                  and value is not None):
                occ_data.append(value)
            elif (key.startswith(self.discharge_sp_name) #discharge_sp_data
                  and value is not None):
                discharge_sp_data.append(value)
            elif (key.startswith(self.sp_setpoint_name) #staticpressure_sp_data
                  and value is not None):
                staticpressure_sp_data.append(value)

        if not oatemp_data:
            return result

        if 'celcius' or 'kelvin' in unit_dict.values:
            if unit_dict[self.oa_temp_name] == 'celcius':
                oatemp_data = cu.convertCelciusToFahrenheit(oatemp_data)
            elif unit_dict[self.oa_temp_name] == 'kelvin':
                oatemp_data = cu.convertKelvinToCelcius(
                    cu.convertCelciusToFahrenheit(oatemp_data))
            #if self.ma_temp_name in unit_dict:
            if unit_dict[self.ma_temp_name] == 'celcius':
                matemp_data = cu.convertCelciusToFahrenheit(matemp_data)
            elif unit_dict[self.ma_temp_name] == 'kelvin':
                matemp_data = cu.convertKelvinToCelcius(
                    cu.convertCelciusToFahrenheit(matemp_data))
            if self.ra_temp_name in unit_dict:
                if unit_dict[self.ra_temp_name] == 'celcius':
                    ratemp_data = cu.convertCelciusToFahrenheit(ratemp_data)
                elif unit_dict[self.ra_temp_name] == 'kelvin':
                    ratemp_data = cu.convertKelvinToCelcius(
                        cu.convertCelciusToFahrenheit(ratemp_data))
            if self.da_temp_name in unit_dict:
                if unit_dict[self.da_temp_name] == 'celcius':
                    datemp_data = cu.convertCelciusToFahrenheit(datemp_data)
                elif unit_dict[self.da_temp_name] == 'kelvin':
                    datemp_data = cu.convertKelvinToCelcius(
                        cu.convertCelciusToFahrenheit(datemp_data))
            if self.da_temp_setpoint_name in unit_dict:
                if unit_dict[self.da_temp_setpoint_name] == 'celcius':
                    datemp_stpt_data = cu.convertCelciusToFahrenheit(datemp_stpt_data)
                elif unit_dict[self.da_temp_setpoint_name] == 'kelvin':
                    datemp_stpt_data = cu.convertKelvinToCelcius(
                        cu.convertCelciusToFahrenheit(datemp_stpt_data))


        oatemp = (sum(oatemp_data) / len(oatemp_data))
        matemp = (sum(matemp_data) / len(matemp_data))
        matemp_data = None
        ratemp = datemp = datemp_stpt = None
        fanstatus = fanspeed = outdoor_damper = ccv = hcv = None
        oaf = None

        return_fan_speedcmd = None
        occupancy = None
        discharge_sp = staticpressure_sp = None

        if matemp_data:
            matemp = (sum(matemp_data) / len(matemp_data))
        if ratemp_data:
            ratemp = (sum(ratemp_data) / len(ratemp_data))
        if datemp_data:
            datemp = (sum(datemp_data) / len(datemp_data))
        if datemp_stpt_data:
            datemp_stpt = (sum(datemp_stpt_data) / len(datemp_stpt_data))
        if fan_status_data:
            fanstatus = (sum(fan_status_data) / len(fan_status_data))
        if fan_speedcmd_data:
            fanspeed = (sum(fan_speedcmd_data) / len(fan_speedcmd_data))
        if damper_data:
            outdoor_damper = (sum(damper_data) / len(damper_data))
        if ccv_data:
            ccv = (sum(ccv_data) / len(ccv_data))
        if hcv_data:
            hcv = (sum(hcv_data) / len(hcv_data))
        if matemp_data and ratemp_data:
            denominator = oatemp - ratemp
            if denominator == 0:
                oaf = 0
            else:
                oaf = (matemp - ratemp) / denominator
            if oaf > 1:
                oaf = 1
            elif oaf < 0:
                oaf = 0
            oaf *= 100

        if return_fan_speedcmd_data:
            return_fan_speedcmd = (sum(return_fan_speedcmd_data) / len(return_fan_speedcmd_data))
        if occ_data:
            occupancy = (sum(occ_data) / len(occ_data))*100
        if discharge_sp_data:
            discharge_sp = (sum(discharge_sp_data) / len(discharge_sp_data))
        if staticpressure_sp_data:
            staticpressure_sp = (sum(staticpressure_sp_data) / len(staticpressure_sp_data))

        out_data = {
            'datetime': str(current_time),
            'OutdoorAirTemperature': oatemp,
            'MixedAirTemperature': None if not matemp else matemp,
            'ReturnAirTemperature': None if ratemp is None else ratemp,
            'DischargeAirTemperature': None if datemp is None else datemp,
            'DischargeAirTemperatureSetPoint': None if datemp_stpt is None else datemp_stpt,
            'SupplyFanStatus': None if fanstatus is None else fanstatus,
            'SupplyFanSpeed': None if fanspeed is None else fanspeed,
            'OutdoorDamper': None if outdoor_damper is None else outdoor_damper,
            'CCV': None if ccv is None else ccv,
            'HCV': None if hcv is None else hcv,
            'OutdoorAirFraction': None if oaf is None else oaf,
            'ReturnFanSpeed': None if return_fan_speedcmd is None else return_fan_speedcmd,
            'OccupancyMode': None if occupancy is None else occupancy,
            'DuctStaticPressure': None if discharge_sp is None else discharge_sp,
            'DuctStaticPressureSetPoint': None if staticpressure_sp is None else staticpressure_sp,
        }
        result.insert_table_row('AhuEcam', out_data)
        return result
Beispiel #4
0
    def run(self, current_time, points):
        """
            Main run method that is called by the DrivenBaseClass.
        """
        device_dict = {}
        result = Results()
        topics = self.inp.get_topics()
        topic = topics[self.oa_temp_name][0]
        current_time = self.inp.localize_sensor_time(topic, current_time)
        base_topic = self.inp.get_topics()
        meta_topics = self.inp.get_topics_meta()
        unit_dict = {
            self.oa_temp_name:
            meta_topics[self.oa_temp_name][base_topic[self.oa_temp_name][0]]
            ['unit']
        }

        if len(base_topic[self.ma_temp_name]) > 0:
            unit_dict[self.ma_temp_name] = meta_topics[self.ma_temp_name][
                base_topic[self.ma_temp_name][0]]['unit']
        if len(base_topic[self.ra_temp_name]) > 0:
            unit_dict[self.ra_temp_name] = meta_topics[self.ra_temp_name][
                base_topic[self.ra_temp_name][0]]['unit']
        if len(base_topic[self.da_temp_name]) > 0:
            unit_dict[self.da_temp_name] = meta_topics[self.da_temp_name][
                base_topic[self.da_temp_name][0]]['unit']
        if len(base_topic[self.da_temp_setpoint_name]) > 0:
            unit_dict[self.da_temp_setpoint_name] = \
                meta_topics[self.da_temp_setpoint_name][base_topic[self.da_temp_setpoint_name][0]]['unit']

        for key, value in points.items():
            device_dict[key.lower()] = value

        damper_data = []
        oatemp_data = []
        matemp_data = []
        ratemp_data = []
        datemp_data = []
        datemp_stpt_data = []
        ccv_data = []
        fan_speedcmd_data = []
        fan_status_data = []
        hcv_data = []
        return_fan_speedcmd_data = []
        occ_data = []
        discharge_sp_data = []
        staticpressure_sp_data = []

        for key, value in device_dict.items():
            if (key.startswith(self.outdoor_damper_name)  #Damper
                    and value is not None):
                damper_data.append(value)
            elif (key.startswith(self.oa_temp_name)  #OAT
                  and value is not None):
                oatemp_data.append(value)
            elif (key.startswith(self.ma_temp_name)  #MAT
                  and value is not None):
                matemp_data.append(value)
            elif (key.startswith(self.ra_temp_name)  #RAT
                  and value is not None):
                ratemp_data.append(value)
            elif (key.startswith(self.da_temp_name)  #DAT
                  and value is not None):
                datemp_data.append(value)
            elif (key.startswith(self.da_temp_setpoint_name)  #DAT SetPoint
                  and value is not None):
                datemp_stpt_data.append(value)
            elif (key.startswith(self.cc_valve_name)  #CoolCoilValvePos
                  and value is not None):
                ccv_data.append(value)
            elif (key.startswith(self.hc_valve_name)  #HeatCoilValvePos
                  and value is not None):
                hcv_data.append(value)
            elif (key.startswith(self.fan_speedcmd_name)  #Fan speed
                  and value is not None):
                fan_speedcmd_data.append(value)
            elif (key.startswith(self.fan_status_name)  #Fan status
                  and value is not None):
                fan_status_data.append(value)
            elif (key.startswith(
                    self.returnfan_speedcmd_name)  #returnfan_speedcmd_name
                  and value is not None):
                return_fan_speedcmd_data.append(value)
            elif (key.startswith(self.occ_name)  #Occupancy
                  and value is not None):
                occ_data.append(value)
            elif (key.startswith(self.discharge_sp_name)  #discharge_sp_data
                  and value is not None):
                discharge_sp_data.append(value)
            elif (key.startswith(
                    self.sp_setpoint_name)  #staticpressure_sp_data
                  and value is not None):
                staticpressure_sp_data.append(value)

        if not oatemp_data:
            return result

        if 'celcius' or 'kelvin' in unit_dict.values:
            if unit_dict[self.oa_temp_name] == 'celcius':
                oatemp_data = cu.convertCelciusToFahrenheit(oatemp_data)
            elif unit_dict[self.oa_temp_name] == 'kelvin':
                oatemp_data = cu.convertKelvinToCelcius(
                    cu.convertCelciusToFahrenheit(oatemp_data))
            #if self.ma_temp_name in unit_dict:
            if unit_dict[self.ma_temp_name] == 'celcius':
                matemp_data = cu.convertCelciusToFahrenheit(matemp_data)
            elif unit_dict[self.ma_temp_name] == 'kelvin':
                matemp_data = cu.convertKelvinToCelcius(
                    cu.convertCelciusToFahrenheit(matemp_data))
            if self.ra_temp_name in unit_dict:
                if unit_dict[self.ra_temp_name] == 'celcius':
                    ratemp_data = cu.convertCelciusToFahrenheit(ratemp_data)
                elif unit_dict[self.ra_temp_name] == 'kelvin':
                    ratemp_data = cu.convertKelvinToCelcius(
                        cu.convertCelciusToFahrenheit(ratemp_data))
            if self.da_temp_name in unit_dict:
                if unit_dict[self.da_temp_name] == 'celcius':
                    datemp_data = cu.convertCelciusToFahrenheit(datemp_data)
                elif unit_dict[self.da_temp_name] == 'kelvin':
                    datemp_data = cu.convertKelvinToCelcius(
                        cu.convertCelciusToFahrenheit(datemp_data))
            if self.da_temp_setpoint_name in unit_dict:
                if unit_dict[self.da_temp_setpoint_name] == 'celcius':
                    datemp_stpt_data = cu.convertCelciusToFahrenheit(
                        datemp_stpt_data)
                elif unit_dict[self.da_temp_setpoint_name] == 'kelvin':
                    datemp_stpt_data = cu.convertKelvinToCelcius(
                        cu.convertCelciusToFahrenheit(datemp_stpt_data))

        oatemp = (sum(oatemp_data) / len(oatemp_data))
        matemp = (sum(matemp_data) / len(matemp_data))
        matemp_data = None
        ratemp = datemp = datemp_stpt = None
        fanstatus = fanspeed = outdoor_damper = ccv = hcv = None
        oaf = None

        return_fan_speedcmd = None
        occupancy = None
        discharge_sp = staticpressure_sp = None

        if matemp_data:
            matemp = (sum(matemp_data) / len(matemp_data))
        if ratemp_data:
            ratemp = (sum(ratemp_data) / len(ratemp_data))
        if datemp_data:
            datemp = (sum(datemp_data) / len(datemp_data))
        if datemp_stpt_data:
            datemp_stpt = (sum(datemp_stpt_data) / len(datemp_stpt_data))
        if fan_status_data:
            fanstatus = (sum(fan_status_data) / len(fan_status_data))
        if fan_speedcmd_data:
            fanspeed = (sum(fan_speedcmd_data) / len(fan_speedcmd_data))
        if damper_data:
            outdoor_damper = (sum(damper_data) / len(damper_data))
        if ccv_data:
            ccv = (sum(ccv_data) / len(ccv_data))
        if hcv_data:
            hcv = (sum(hcv_data) / len(hcv_data))
        if matemp_data and ratemp_data:
            denominator = oatemp - ratemp
            if denominator == 0:
                oaf = 0
            else:
                oaf = (matemp - ratemp) / denominator
            if oaf > 1:
                oaf = 1
            elif oaf < 0:
                oaf = 0
            oaf *= 100

        if return_fan_speedcmd_data:
            return_fan_speedcmd = (sum(return_fan_speedcmd_data) /
                                   len(return_fan_speedcmd_data))
        if occ_data:
            occupancy = (sum(occ_data) / len(occ_data)) * 100
        if discharge_sp_data:
            discharge_sp = (sum(discharge_sp_data) / len(discharge_sp_data))
        if staticpressure_sp_data:
            staticpressure_sp = (sum(staticpressure_sp_data) /
                                 len(staticpressure_sp_data))

        out_data = {
            'datetime':
            str(current_time),
            'OutdoorAirTemperature':
            oatemp,
            'MixedAirTemperature':
            None if not matemp else matemp,
            'ReturnAirTemperature':
            None if ratemp is None else ratemp,
            'DischargeAirTemperature':
            None if datemp is None else datemp,
            'DischargeAirTemperatureSetPoint':
            None if datemp_stpt is None else datemp_stpt,
            'SupplyFanStatus':
            None if fanstatus is None else fanstatus,
            'SupplyFanSpeed':
            None if fanspeed is None else fanspeed,
            'OutdoorDamper':
            None if outdoor_damper is None else outdoor_damper,
            'CCV':
            None if ccv is None else ccv,
            'HCV':
            None if hcv is None else hcv,
            'OutdoorAirFraction':
            None if oaf is None else oaf,
            'ReturnFanSpeed':
            None if return_fan_speedcmd is None else return_fan_speedcmd,
            'OccupancyMode':
            None if occupancy is None else occupancy,
            'DuctStaticPressure':
            None if discharge_sp is None else discharge_sp,
            'DuctStaticPressureSetPoint':
            None if staticpressure_sp is None else staticpressure_sp,
        }
        result.insert_table_row('AhuEcam', out_data)
        return result
    def execute(self):
        # Called after User hits GO
        """
        Calculates weather sensitivity using Spearman rank.
        Also, outputs data points for energy signature scatter plot.
        """
        self.out.log("Starting Day Time Temperature Analysis", logging.INFO)

        # Gather loads and outside air temperatures. Reduced to an hourly average
        
        load_query = self.inp.get_query_sets('load', group_by='hour',
                                             group_by_aggregation=Avg,
                                             exclude={'value':None},
                                             wrap_for_merge=True)
        oat_query = self.inp.get_query_sets('oat', group_by='hour', 
                                             group_by_aggregation=Avg,
                                             exclude={'value':None},
                                             wrap_for_merge=True)

        # Get conversion factor
        base_topic = self.inp.get_topics()
        meta_topics = self.inp.get_topics_meta()
        load_unit = meta_topics['load'][base_topic['load'][0]]['unit']
        temperature_unit = meta_topics['oat'][base_topic['oat'][0]]['unit']
        
        load_convertfactor = cu.conversiontoKWH(load_unit)
        
        # Match the values by timestamp
        merged_load_oat = self.inp.merge(load_query, oat_query) 

        load_values = []
        oat_values = []
        datetime_values = []

        for x in merged_load_oat:
            if temperature_unit == 'celcius':
                convertedTemp = cu.convertCelciusToFahrenheit(x['oat'][0])
            elif temperature_unit == 'kelvin':
                convertedTemp = cu.convertKelvinToCelcius(
                                cu.convertCelciusToFahrenheit(x['oat'][0]))
            else: 
                convertedTemp = x['oat'][0]
                
            load_values.append(x['load'][0] * load_convertfactor) #Converted to kWh
            oat_values.append(convertedTemp)
            datetime_values.append(dt.datetime.strptime(x['time'],'%Y-%m-%d %H'))
            
        indexList = {}
        indexList['trainingStart'] = ttow.findDateIndex(datetime_values, self.baseline_start)
        self.out.log('@trainingStart '+str(indexList['trainingStart']), logging.INFO)
        indexList['trainingStop'] = ttow.findDateIndex(datetime_values, self.baseline_stop)
        self.out.log('@trainingStop '+str(indexList['trainingStop']), logging.INFO)
        indexList['predictStart'] = ttow.findDateIndex(datetime_values, self.savings_start)
        self.out.log('@predictStart '+str(indexList['predictStart']), logging.INFO)
        indexList['predictStop'] = ttow.findDateIndex(datetime_values, self.savings_stop)
        self.out.log('@predictStop '+str(indexList['predictStop']), logging.INFO)
        
        for indx in indexList.keys():
            if indexList[indx] == None:
                self.out.log("Date not found in the datelist", logging.WARNING)
                
        # Break up data into training and prediction periods.
        timesTrain = datetime_values[indexList['trainingStart']:indexList['trainingStop']]
        timesPredict = datetime_values[indexList['predictStart']:indexList['predictStop']]

        valsTrain = load_values[indexList['trainingStart']:indexList['trainingStop']]
        valsActual = load_values[indexList['predictStart']:indexList['predictStop']]

        oatsTrain = oat_values[indexList['trainingStart']:indexList['trainingStop']]
        oatsPredict = oat_values[indexList['predictStart']:indexList['predictStop']]

        # Generate other information needed for model.
        timeStepMinutes = (timesTrain[1] - timesTrain[0]).total_seconds()/60  
        # TODO: Should this be calculated in the utility function
        binCt = 6  # TODO: Allow caller to pass this in as an argument.

        # Form the temperature-time-of-week model.
        self.out.log("Starting baseline model", logging.INFO)
        ttowModel = ttow.formModel(timesTrain, 
                                   oatsTrain, 
                                   valsTrain,
                                   timeStepMinutes, 
                                   binCt)

        # Apply the model.
        self.out.log("Applying baseline model", logging.INFO)
        valsPredict = ttow.applyModel(ttowModel, timesPredict, oatsPredict)
        
        # Output for scatter plot
        prevSum = 0
        for ctr in range(len(timesPredict)):
            # Calculate cumulative savings. 
            prevSum += (valsPredict[ctr] - valsActual[ctr])
            self.out.insert_row("DayTimeTemperatureModel", { 
                                "datetimeValues": timesPredict[ctr],
                                "measured": valsActual[ctr],
                                "predicted": valsPredict[ctr],
                                "cumulativeSum": prevSum
                                })
Beispiel #6
0
    def execute(self):
        """
        Calculates weather sensitivity using Spearman rank.
        Also, outputs data points for energy signature scatter plot.
        """

        self.out.log("Starting application: energy signature.", logging.INFO)

        self.out.log("Querying database.", logging.INFO)
        load_query = self.inp.get_query_sets('load',
                                             group_by='hour',
                                             group_by_aggregation=Avg,
                                             exclude={'value': None},
                                             wrap_for_merge=True)
        oat_query = self.inp.get_query_sets('oat',
                                            group_by='hour',
                                            group_by_aggregation=Avg,
                                            exclude={'value': None},
                                            wrap_for_merge=True)

        self.out.log("Getting unit conversions.", logging.INFO)
        base_topic = self.inp.get_topics()
        meta_topics = self.inp.get_topics_meta()

        load_unit = meta_topics['load'][base_topic['load'][0]]['unit']
        self.out.log("Convert loads from [{}] to [kW].".format(load_unit),
                     logging.INFO)
        load_convertfactor = cu.getFactor_powertoKW(load_unit)

        temperature_unit = meta_topics['oat'][base_topic['oat'][0]]['unit']
        self.out.log(
            "Convert temperatures from [{}] to [F].".format(temperature_unit),
            logging.INFO)

        #print('merge load', merged_load_oat)
        load_values = []
        oat_values = []

        self.out.log("Pulling data from database.", logging.INFO)
        merged_load_oat = self.inp.merge(load_query, oat_query)
        for x in merged_load_oat:
            if temperature_unit == 'celcius':
                convertedTemp = cu.convertCelciusToFahrenheit(x['oat'][0])
            elif temperature_unit == 'kelvin':
                convertedTemp = cu.convertKelvinToCelcius(
                    cu.convertCelciusToFahrenheit(x['oat'][0]))
            else:
                convertedTemp = x['oat'][0]

            load_values.append(x['load'][0] * load_convertfactor)
            oat_values.append(convertedTemp)
            self.out.insert_row(LOAD_VS_OAT_TABLE_NAME, {
                "oat": x['oat'][0],
                "load": x['load'][0]
            })

        self.out.log("Calculating the Spearman rank.", logging.INFO)
        #print(load_values)
        #print(oat_values)
        weather_sensitivity = findSpearmanRank(load_values, oat_values)

        self.out.log("Adding weather sensitivity to table.", logging.INFO)
        self.out.insert_row(WEATHER_SENSITIVITY_TABLE_NAME,
                            {"value": "{:.2f}".format(weather_sensitivity)})
Beispiel #7
0
    def run(self, current_time, points):
        '''
        Check algorithm pre-quisites and assemble data set for analysis.
        '''
        device_dict = {}
        result = Results()
        topics = self.inp.get_topics()
        topic = topics[self.hws_temp_name][0]
        current_time = self.inp.localize_sensor_time(topic, current_time)
        base_topic = self.inp.get_topics()
        meta_topics = self.inp.get_topics_meta()

        unit_dict = {}
        if len(base_topic[self.oa_temp_name]) > 0:
            unit_dict[self.oa_temp_name] = meta_topics[self.oa_temp_name][base_topic[self.oa_temp_name][0]]['unit']
        if len(base_topic[self.hws_temp_name]) > 0:
            unit_dict[self.hws_temp_name] = meta_topics[self.hws_temp_name][base_topic[self.hws_temp_name][0]]['unit']
        if len(base_topic[self.hwr_temp_name]) > 0:
            unit_dict[self.hwr_temp_name] = meta_topics[self.hwr_temp_name][base_topic[self.hwr_temp_name][0]]['unit']
        if len(base_topic[self.hw_stsp_name]) > 0:
            unit_dict[self.hw_stsp_name] = meta_topics[self.hw_stsp_name][base_topic[self.hw_stsp_name][0]]['unit']

        for key, value in points.items():
            device_dict[key.lower()] = value

        oatemp_data = []
        loop_dp_values = []
        loop_dp_stpt_values = []
        hw_pump_status_values = []
        boiler_status_values = []
        hw_pump_vfd_values = []
        hw_stsp_values = []
        hws_temp_values = []
        hwr_temp_values = []

        for key, value in device_dict.items():
            if key.startswith(self.loop_dp_stpt_name) and value is not None:
                loop_dp_stpt_values.append(value)
            elif key.startswith(self.loop_dp_name) and value is not None:
                loop_dp_values.append(value)
            elif key.startswith(self.hw_pump_status_name) and value is not None:
                hw_pump_status_values.append(value)
            elif key.startswith(self.boiler_status_name) and value is not None:
                boiler_status_values.append(value)
            elif key.startswith(self.hw_pump_vfd_name) and value is not None:
                hw_pump_vfd_values.append(value)
            elif key.startswith(self.hw_stsp_name) and value is not None:
                hw_stsp_values.append(value)
            elif key.startswith(self.hws_temp_name) and value is not None:
                hws_temp_values.append(value)
            elif key.startswith(self.hwr_temp_name) and value is not None:
                hwr_temp_values.append(value)
            elif (key.startswith(self.oa_temp_name) #OAT
                  and value is not None):
                oatemp_data.append(value)

        if 'celcius' or 'kelvin' in unit_dict.values:
            if self.oa_temp_name in unit_dict:
                if unit_dict[self.oa_temp_name] == 'celcius':
                    oatemp_data = cu.convertCelciusToFahrenheit(oatemp_data)
                elif unit_dict[self.oa_temp_name] == 'kelvin':
                    oatemp_data = cu.convertKelvinToCelcius(
                        cu.convertCelciusToFahrenheit(oatemp_data))
            if self.hw_stsp_name in unit_dict:
                if unit_dict[self.hw_stsp_name] == 'celcius':
                    hw_stsp_values = cu.convertCelciusToFahrenheit(hw_stsp_values)
                elif unit_dict[self.hw_stsp_name] == 'kelvin':
                    hw_stsp_values = cu.convertKelvinToCelcius(
                        cu.convertCelciusToFahrenheit(hw_stsp_values))
            if self.hw_stsp_name in unit_dict:
                if unit_dict[self.hws_temp_name] == 'celcius':
                    hws_temp_values = cu.convertCelciusToFahrenheit(hws_temp_values)
                elif unit_dict[self.hws_temp_name] == 'kelvin':
                    hws_temp_values = cu.convertKelvinToCelcius(
                        cu.convertCelciusToFahrenheit(hws_temp_values))
            if self.hwr_temp_name in unit_dict:
                if unit_dict[self.hwr_temp_name] == 'celcius':
                    hwr_temp_values = cu.convertCelciusToFahrenheit(hwr_temp_values)
                elif unit_dict[self.hwr_temp_name] == 'kelvin':
                    hwr_temp_values = cu.convertKelvinToCelcius(
                        cu.convertCelciusToFahrenheit(hwr_temp_values))


        oatemp = hw_stsp_temp = hws_temp = hwr_temp = None
        loop_dp = loop_dp_stpt = None
        hw_pump_status = boiler_status = None
        hw_pump_vfd = None

        if oatemp_data:
            oatemp = (sum(oatemp_data) / len(oatemp_data))
        if hw_stsp_values:
            hw_stsp_temp = (sum(hw_stsp_values) / len(hw_stsp_values))
        if hws_temp_values:
            hws_temp = (sum(hws_temp_values) / len(hws_temp_values))
        if hwr_temp_values:
            hwr_temp = (sum(hwr_temp_values) / len(hwr_temp_values))

        if loop_dp_stpt_values:
            loop_dp_stpt = (sum(loop_dp_stpt_values) / len(loop_dp_stpt_values))
        if loop_dp_values:
            loop_dp = (sum(loop_dp_values) / len(loop_dp_values))

        if hw_pump_status_values:
            hw_pump_status = (sum(hw_pump_status_values) / len(hw_pump_status_values))
        if boiler_status_values:
            boiler_status = (sum(boiler_status_values) / len(boiler_status_values))

        if hw_pump_vfd_values:
            hw_pump_vfd = (sum(hw_pump_vfd_values) / len(hw_pump_vfd_values))


        out_data = {
            'datetime': str(current_time),
        }

        if not oatemp is None:
            out_data['OutdoorAirTemperature'] = oatemp
        if not hws_temp is None:
            out_data['HotWaterSupplyTemperature'] = hws_temp
        if not hwr_temp is None:
            out_data['HotWaterReturnTemperature'] = hwr_temp
        if not hw_stsp_temp is None:
            out_data['HotWaterTemperatureSetPoint'] = hw_stsp_temp

        if not loop_dp is None:
            out_data['LoopDifferentialPressure'] = loop_dp
        if not loop_dp_stpt is None:
            out_data['LoopDifferentialPressureSetPoint'] = loop_dp_stpt

        if not hw_pump_status is None:
            out_data['PumpStatus'] = hw_pump_status
        if not boiler_status is None:
            out_data['BoilerStatus'] = boiler_status

        if not hw_pump_vfd is None:
            out_data['HotWaterPumpVfd'] = hw_pump_vfd

        result.insert_table_row(self.table_name, out_data)

        return result
Beispiel #8
0
    def execute(self):
        # Called after User hits GO
        """
        Calculates weather sensitivity using Spearman rank.
        Also, outputs data points for energy signature scatter plot.
        """
        self.out.log("Starting Day Time Temperature Analysis", logging.INFO)

        self.out.log('@operating_sched'+str(self.operating_sched), logging.INFO)
        self.out.log('@building_area'+str(self.building_area), logging.INFO)
        self.out.log('@electricity_cost'+str(self.electricity_cost), logging.INFO)
        
        # Query the database
        zat_query = self.inp.get_query_sets('zat', exclude={'value':None},
                                                   wrap_for_merge=True,
                                                   group_by='minute')
                                                   
        dat_query = self.inp.get_query_sets('dat', exclude={'value':None},
                                                   wrap_for_merge=True,
                                                   group_by='minute')
                                                   
        oat_query = self.inp.get_query_sets('oat', exclude={'value':None},
                                                   wrap_for_merge=True,
                                                   group_by='minute')
                                                   
        status_query = self.inp.get_query_sets('hvacstatus', exclude={'value':None},
                                                   wrap_for_merge=True,
                                                   group_by='minute')
        # Merge temperatures and the HVACStatus
        merged_temperatures_status = self.inp.merge(zat_query, oat_query, dat_query,status_query)
        
        # Get conversion factor
        base_topic = self.inp.get_topics()
        meta_topics = self.inp.get_topics_meta()
        zat_unit = meta_topics['zat'][base_topic['zat'][0]]['unit']
        dat_unit = meta_topics['dat'][base_topic['dat'][0]]['unit']
        oat_unit = meta_topics['oat'][base_topic['oat'][0]]['unit']
        
        #From the merged values make the arrays for the models
        datetime_ZAT = []
        datetime_DAT = []
        datetime_OAT = []
        datetime_HVACStatus = []
        for line in merged_temperatures_status:
            # Convert datetime str to datetime obj
            datetimeObj = dt.datetime.strptime(line['time'],'%Y-%m-%d %H:%M')
            
            # Convert ZAT
            if zat_unit == 'celcius':
                convertedZAT = cu.convertCelciusToFahrenheit(line['zat'][0])
            elif zat_unit == 'kelvin':
                convertedZAT = cu.convertKelvinToCelcius(
                                cu.convertCelciusToFahrenheit(line['zat'][0]))
            else: 
                convertedZAT = line['zat'][0]
            #    
            datetime_ZAT.append((datetimeObj, convertedZAT)) 
        
            # Convert DAT
            if dat_unit == 'celcius':
                convertedDAT = cu.convertCelciusToFahrenheit(line['dat'][0])
            elif dat_unit == 'kelvin':
                convertedDAT = cu.convertKelvinToCelcius(
                                cu.convertCelciusToFahrenheit(line['dat'][0]))
            else: 
                convertedDAT = line['dat'][0]        
            #
            datetime_DAT.append((datetimeObj, convertedDAT)) 
                
            # Convert OAT
            if oat_unit == 'celcius':
                convertedOAT = cu.convertCelciusToFahrenheit(line['oat'][0])
            elif oat_unit == 'kelvin':
                convertedOAT = cu.convertKelvinToCelcius(
                                cu.convertCelciusToFahrenheit(line['oat'][0]))
            else: 
                convertedOAT = line['oat'][0]
            #
            datetime_OAT.append((datetimeObj, convertedOAT)) 
            #
            datetime_HVACStatus.append((datetimeObj, line['hvacstatus'][0])) 
        # Apply the comfort_and_setpoint model.
        comfort_flag, setback_flag = cs.comfort_and_setpoint(datetime_ZAT, 
                                                   datetime_DAT, 
                                                   self.operating_sched, 
                                                   self.building_area, 
                                                   self.electricity_cost, 
                                                   datetime_HVACStatus)
        if comfort_flag != {}:
            self.out.insert_row('SensorSuitcaseHVAC', { 
                                'analysis': 'Comfort Optimization',
                                'problem': comfort_flag['Problem'],
                                'diagnostic': comfort_flag['Diagnostic'],
                                'recommendation': comfort_flag['Recommendation'],
                                'savings': '${:.2f}'.format(comfort_flag['Savings'])
                                })
                                
        if setback_flag != {}:
            self.out.insert_row('SensorSuitcaseHVAC', { 
                                'analysis': 'Comfort Optimization',
                                'problem': setback_flag['Problem'],
                                'diagnostic': setback_flag['Diagnostic'],
                                'recommendation': setback_flag['Recommendation'],
                                'savings': '${:.2f}'.format(setback_flag['Savings'])
                                })
                                
        # Apply the economizer model.
        economizer_flag = ecn.economizer(datetime_DAT, 
                                         datetime_OAT, 
                                         datetime_HVACStatus, 
                                         self.electricity_cost, 
                                         self.building_area)    
        if economizer_flag != {}:
            self.out.insert_row('SensorSuitcaseHVAC', { 
                                'analysis': 'Economizer Diagnostics',
                                'problem': economizer_flag['Problem'],
                                'diagnostic': economizer_flag['Diagnostic'],
                                'recommendation': economizer_flag['Recommendation'],
                                'savings': '${:.2f}'.format(economizer_flag['Savings'])
                                })
        
        # Apply the setback_non_op model.
        setback_nonop_flag = sb.setback_non_op(datetime_ZAT, 
                                         datetime_DAT, 
                                         self.operating_sched, 
                                         self.electricity_cost, 
                                         self.building_area, 
                                         datetime_HVACStatus)
        if setback_nonop_flag != {}:
            self.out.insert_row('SensorSuitcaseHVAC', { 
                                'analysis': 'Setback During Unoccupied Hours',
                                'problem': setback_nonop_flag['Problem'],
                                'diagnostic': setback_nonop_flag['Diagnostic'],
                                'recommendation': setback_nonop_flag['Recommendation'],
                                'savings': '${:.2f}'.format(setback_nonop_flag['Savings'])
                                })
        
        # Apply the short_cycling model.
        shortcycling_flag = shc.short_cycling(datetime_HVACStatus, 
                                              self.electricity_cost)
        if shortcycling_flag != {}:
            self.out.insert_row('SensorSuitcaseHVAC', { 
                                'analysis': 'Shortcycling',
                                'problem': shortcycling_flag['Problem'],
                                'diagnostic': shortcycling_flag['Diagnostic'],
                                'recommendation': shortcycling_flag['Recommendation'],
                                'savings': '${:.2f}'.format(shortcycling_flag['Savings'])
                                })
Beispiel #9
0
    def execute(self):
        # Called after User hits GO
        """
        Calculates weather sensitivity using Spearman rank.
        Also, outputs data points for energy signature scatter plot.
        """
        self.out.log("Starting application: Sensor Suitcase HVAC.",
                     logging.INFO)

        self.out.log('@operating_sched' + str(self.operating_sched),
                     logging.INFO)
        self.out.log('@building_area' + str(self.building_area), logging.INFO)
        self.out.log('@electricity_cost' + str(self.electricity_cost),
                     logging.INFO)

        # Query the database
        zat_query = self.inp.get_query_sets('zat',
                                            exclude={'value': None},
                                            wrap_for_merge=True,
                                            group_by='minute')

        dat_query = self.inp.get_query_sets('dat',
                                            exclude={'value': None},
                                            wrap_for_merge=True,
                                            group_by='minute')

        oat_query = self.inp.get_query_sets('oat',
                                            exclude={'value': None},
                                            wrap_for_merge=True,
                                            group_by='minute')

        status_query = self.inp.get_query_sets('hvacstatus',
                                               exclude={'value': None},
                                               wrap_for_merge=True,
                                               group_by='minute')
        # Merge temperatures and the HVACStatus
        merged_temperatures_status = self.inp.merge(zat_query, oat_query,
                                                    dat_query, status_query)

        self.out.log("Getting unit conversions.", logging.INFO)
        base_topic = self.inp.get_topics()
        meta_topics = self.inp.get_topics_meta()

        zat_unit = meta_topics['zat'][base_topic['zat'][0]]['unit']
        self.out.log(
            "Convert zone air temperatures from [{}] to [F].".format(zat_unit),
            logging.INFO)

        dat_unit = meta_topics['dat'][base_topic['dat'][0]]['unit']
        self.out.log(
            "Convert discharge air temperatures from [{}] to [F].".format(
                dat_unit), logging.INFO)

        oat_unit = meta_topics['oat'][base_topic['oat'][0]]['unit']
        self.out.log(
            "Convert outside air temperatures from [{}] to [F].".format(
                oat_unit), logging.INFO)

        #From the merged values make the arrays for the models
        datetime_ZAT = []
        datetime_DAT = []
        datetime_OAT = []
        datetime_HVACStatus = []
        for line in merged_temperatures_status:
            # Convert datetime str to datetime obj
            #             datetimeObj = dt.datetime.strptime(line['time'],'%Y-%m-%d %H:%M')
            datetimeObj = line['time']

            # Convert ZAT
            if zat_unit == 'celcius':
                convertedZAT = cu.convertCelciusToFahrenheit(line['zat'][0])
            elif zat_unit == 'kelvin':
                convertedZAT = cu.convertKelvinToCelcius(
                    cu.convertCelciusToFahrenheit(line['zat'][0]))
            else:
                convertedZAT = line['zat'][0]
            #
            datetime_ZAT.append((datetimeObj, convertedZAT))

            # Convert DAT
            if dat_unit == 'celcius':
                convertedDAT = cu.convertCelciusToFahrenheit(line['dat'][0])
            elif dat_unit == 'kelvin':
                convertedDAT = cu.convertKelvinToCelcius(
                    cu.convertCelciusToFahrenheit(line['dat'][0]))
            else:
                convertedDAT = line['dat'][0]
            #
            datetime_DAT.append((datetimeObj, convertedDAT))

            # Convert OAT
            if oat_unit == 'celcius':
                convertedOAT = cu.convertCelciusToFahrenheit(line['oat'][0])
            elif oat_unit == 'kelvin':
                convertedOAT = cu.convertKelvinToCelcius(
                    cu.convertCelciusToFahrenheit(line['oat'][0]))
            else:
                convertedOAT = line['oat'][0]
            #
            datetime_OAT.append((datetimeObj, convertedOAT))
            #
            datetime_HVACStatus.append((datetimeObj, line['hvacstatus'][0]))
        # Apply the comfort_and_setpoint model.
        comfort_flag, setback_flag = cs.comfort_and_setpoint(
            datetime_ZAT, datetime_DAT, self.operating_sched,
            self.building_area, self.electricity_cost, datetime_HVACStatus)
        if comfort_flag != {}:
            self.out.insert_row(
                'SensorSuitcaseHVAC', {
                    'analysis': 'Comfort Optimization',
                    'problem': comfort_flag['Problem'],
                    'diagnostic': comfort_flag['Diagnostic'],
                    'recommendation': comfort_flag['Recommendation'],
                    'savings': '${:.2f}'.format(comfort_flag['Savings'])
                })

        if setback_flag != {}:
            self.out.insert_row(
                'SensorSuitcaseHVAC', {
                    'analysis': 'Comfort Optimization',
                    'problem': setback_flag['Problem'],
                    'diagnostic': setback_flag['Diagnostic'],
                    'recommendation': setback_flag['Recommendation'],
                    'savings': '${:.2f}'.format(setback_flag['Savings'])
                })

        # Apply the economizer model.
        economizer_flag = ecn.economizer(datetime_DAT, datetime_OAT,
                                         datetime_HVACStatus,
                                         self.electricity_cost,
                                         self.building_area)
        if economizer_flag != {}:
            self.out.insert_row(
                'SensorSuitcaseHVAC', {
                    'analysis': 'Economizer Diagnostics',
                    'problem': economizer_flag['Problem'],
                    'diagnostic': economizer_flag['Diagnostic'],
                    'recommendation': economizer_flag['Recommendation'],
                    'savings': '${:.2f}'.format(economizer_flag['Savings'])
                })

        # Apply the setback_non_op model.
        setback_nonop_flag = sb.setback_non_op(datetime_ZAT, datetime_DAT,
                                               self.operating_sched,
                                               self.electricity_cost,
                                               self.building_area,
                                               datetime_HVACStatus)
        if setback_nonop_flag != {}:
            self.out.insert_row(
                'SensorSuitcaseHVAC', {
                    'analysis': 'Setback During Unoccupied Hours',
                    'problem': setback_nonop_flag['Problem'],
                    'diagnostic': setback_nonop_flag['Diagnostic'],
                    'recommendation': setback_nonop_flag['Recommendation'],
                    'savings': '${:.2f}'.format(setback_nonop_flag['Savings'])
                })

        # Apply the short_cycling model.
        shortcycling_flag = shc.short_cycling(datetime_HVACStatus,
                                              self.electricity_cost,
                                              self.building_area)
        if shortcycling_flag != {}:
            self.out.insert_row(
                'SensorSuitcaseHVAC', {
                    'analysis': 'Shortcycling',
                    'problem': shortcycling_flag['Problem'],
                    'diagnostic': shortcycling_flag['Diagnostic'],
                    'recommendation': shortcycling_flag['Recommendation'],
                    'savings': '${:.2f}'.format(shortcycling_flag['Savings'])
                })
    def execute(self):
        # Called after User hits GO
        """
        Calculates weather sensitivity using Spearman rank.
        Also, outputs data points for energy signature scatter plot.
        """
        self.out.log("Starting application: whole building energy savings.",
                     logging.INFO)

        # Gather loads and outside air temperatures. Reduced to an hourly average
        self.out.log("Querying database.", logging.INFO)
        load_query = self.inp.get_query_sets('load',
                                             group_by='hour',
                                             group_by_aggregation=Avg,
                                             exclude={'value': None},
                                             wrap_for_merge=True)
        oat_query = self.inp.get_query_sets('oat',
                                            group_by='hour',
                                            group_by_aggregation=Avg,
                                            exclude={'value': None},
                                            wrap_for_merge=True)

        self.out.log("Getting unit conversions.", logging.INFO)
        base_topic = self.inp.get_topics()
        meta_topics = self.inp.get_topics_meta()

        load_unit = meta_topics['load'][base_topic['load'][0]]['unit']
        self.out.log("Convert loads from [{}] to [kW].".format(load_unit),
                     logging.INFO)
        load_convertfactor = cu.getFactor_powertoKW(load_unit)

        temperature_unit = meta_topics['oat'][base_topic['oat'][0]]['unit']
        self.out.log(
            "Convert temperatures from [{}] to [F].".format(temperature_unit),
            logging.INFO)

        # Match the values by timestamp
        merged_load_oat = self.inp.merge(load_query, oat_query)

        load_values = []
        oat_values = []
        datetime_values = []

        for x in merged_load_oat:
            if temperature_unit == 'celcius':
                convertedTemp = cu.convertCelciusToFahrenheit(x['oat'][0])
            elif temperature_unit == 'kelvin':
                convertedTemp = cu.convertKelvinToCelcius(
                    cu.convertCelciusToFahrenheit(x['oat'][0]))
            else:
                convertedTemp = x['oat'][0]

            load_values.append(x['load'][0] *
                               load_convertfactor)  #Converted to kWh
            oat_values.append(convertedTemp)
            datetime_values.append(x['time'])

        indexList = {}
        indexList['trainingStart'] = ttow.findDateIndex(
            datetime_values, self.baseline_start)
        self.out.log('@trainingStart ' + str(indexList['trainingStart']),
                     logging.INFO)
        indexList['trainingStop'] = ttow.findDateIndex(datetime_values,
                                                       self.baseline_stop)
        self.out.log('@trainingStop ' + str(indexList['trainingStop']),
                     logging.INFO)
        indexList['predictStart'] = ttow.findDateIndex(datetime_values,
                                                       self.savings_start)
        self.out.log('@predictStart ' + str(indexList['predictStart']),
                     logging.INFO)
        indexList['predictStop'] = ttow.findDateIndex(datetime_values,
                                                      self.savings_stop)
        self.out.log('@predictStop ' + str(indexList['predictStop']),
                     logging.INFO)

        for indx in indexList.keys():
            if indexList[indx] == None:
                self.out.log("Date not found in the datelist", logging.WARNING)

        # Break up data into training and prediction periods.
        timesTrain = datetime_values[
            indexList['trainingStart']:indexList['trainingStop']]
        timesPredict = datetime_values[
            indexList['predictStart']:indexList['predictStop']]

        valsTrain = load_values[
            indexList['trainingStart']:indexList['trainingStop']]
        valsActual = load_values[
            indexList['predictStart']:indexList['predictStop']]

        oatsTrain = oat_values[
            indexList['trainingStart']:indexList['trainingStop']]
        oatsPredict = oat_values[
            indexList['predictStart']:indexList['predictStop']]

        # Generate other information needed for model.
        timeStepMinutes = (timesTrain[1] - timesTrain[0]).total_seconds() / 60
        # TODO: Should this be calculated in the utility function
        binCt = 6  # TODO: Allow caller to pass this in as an argument.

        # Form the temperature-time-of-week model.
        self.out.log("Finding baseline model", logging.INFO)
        ttowModel = ttow.formModel(timesTrain, oatsTrain, valsTrain,
                                   timeStepMinutes, binCt)

        # Apply the model.
        self.out.log("Applying baseline model", logging.INFO)
        valsPredict = ttow.applyModel(ttowModel, timesPredict, oatsPredict)

        # Output for scatter plot
        prevSum = 0
        for ctr in range(len(timesPredict)):
            # Calculate cumulative savings.
            prevSum += (valsPredict[ctr] - valsActual[ctr])
            local_time = str(
                self.inp.localize_sensor_time(base_topic['load'][0],
                                              timesPredict[ctr]))
            self.out.insert_row(
                "DayTimeTemperatureModel", {
                    "datetimeValues": local_time,
                    "measured": valsActual[ctr],
                    "predicted": valsPredict[ctr],
                    "cumulativeSum": prevSum
                })