예제 #1
0
파일: test_models.py 프로젝트: rchml/MPCPy
 def test_estimate_error_nofreeparameters(self):
     '''Test error raised if no free parameters passed.'''
     # Set model paths
     mopath = os.path.join(self.MPCPyPath, 'resources', 'model',
                           'Simple.mo')
     modelpath = 'Simple.RC_noinputs'
     # Instantiate model
     self.model_no_params = models.Modelica(models.JModelica, \
                                            models.RMSE, \
                                            self.measurements, \
                                            moinfo = (mopath, modelpath, {}))
     # Check error raised with no parameters
     with self.assertRaises(ValueError):
         self.model_no_params.estimate(self.start_time, self.final_time, [])
     # Set parameters
     parameter_data = {}
     parameter_data['C'] = {}
     parameter_data['C']['Value'] = variables.Static(
         'C_Value', 55000, units.J_K)
     parameter_data['C']['Minimum'] = variables.Static(
         'C_Min', 10000, units.J_K)
     parameter_data['C']['Maximum'] = variables.Static(
         'C_Max', 100000, units.J_K)
     parameter_data['C']['Free'] = variables.Static('C_Free', False,
                                                    units.boolean)
     # Instantiate model
     self.model_no_free = models.Modelica(models.JModelica, \
                                            models.RMSE, \
                                            self.measurements, \
                                            moinfo = (mopath, modelpath, {}), \
                                            parameter_data = parameter_data)
     # Check error raised with no free parameters
     with self.assertRaises(ValueError):
         self.model_no_params.estimate(self.start_time, self.final_time, [])
예제 #2
0
 def setUp(self):
     self.start_time = '1/1/2017'
     self.final_time = '1/2/2017'
     # Set .mo path
     self.mopath = os.path.join(utility.get_MPCPy_path(), 'resources',
                                'model', 'Simple.mo')
     # Gather inputs
     control_csv_filepath = utility.get_MPCPy_path(
     ) + os.sep + 'resources' + os.sep + 'model' + os.sep + 'SimpleRC_Input.csv'
     control_variable_map = {
         'q_flow_csv': ('q_flow', units.W)
     }
     self.controls = exodata.ControlFromCSV(control_csv_filepath,
                                            control_variable_map)
     self.controls.collect_data(self.start_time, self.final_time)
     # Set measurements
     self.measurements = {}
     self.measurements['T_db'] = {
         'Sample': variables.Static('T_db_sample', 1800, units.s)
     }
     self.measurements['q_flow'] = {
         'Sample': variables.Static('q_flow_sample', 1800, units.s)
     }
     # Gather constraints
     constraint_csv_filepath = utility.get_MPCPy_path(
     ) + os.sep + 'resources' + os.sep + 'optimization' + os.sep + 'SimpleRC_Constraints.csv'
     constraint_variable_map = {'q_flow_min' : ('q_flow', 'GTE', units.W), \
                                'T_db_min' : ('T_db', 'GTE', units.K), \
                                'T_db_max' : ('T_db', 'LTE', units.K)}
     self.constraints = exodata.ConstraintFromCSV(constraint_csv_filepath,
                                                  constraint_variable_map)
     self.constraints.collect_data(self.start_time, self.final_time)
     self.constraints.data['T_db']['Initial'] = variables.Static(
         'T_db_start', 295, units.K)
예제 #3
0
 def setUp(self):
     # Setup building
     self.building_source_file_path = os.path.join(self.get_unittest_path(), 'resources', 'building', \
                                                   'LBNL71T_Emulation_JModelica_v2.fmu');   
     self.zone_names = ['wes', 'hal', 'eas'];
     weather_path = os.path.join(self.get_unittest_path(), 'resources', 'weather', \
                                 'USA_IL_Chicago-OHare.Intl.AP.725300_TMY3.epw');
     internal_path = os.path.join(self.get_unittest_path(), 'resources', 'internal', 'sampleCSV.csv');
     internal_variable_map = {'intRad_wes' : ('wes', 'intRad', units.W_m2), \
                              'intCon_wes' : ('wes', 'intCon', units.W_m2), \
                              'intLat_wes' : ('wes', 'intLat', units.W_m2), \
                              'intRad_hal' : ('hal', 'intRad', units.W_m2), \
                              'intCon_hal' : ('hal', 'intCon', units.W_m2), \
                              'intLat_hal' : ('hal', 'intLat', units.W_m2), \
                              'intRad_eas' : ('eas', 'intRad', units.W_m2), \
                              'intCon_eas' : ('eas', 'intCon', units.W_m2), \
                              'intLat_eas' : ('eas', 'intLat', units.W_m2)};        
     control_path = os.path.join(self.get_unittest_path(), 'resources', 'building', 'ControlCSV_0.csv');
     control_variable_map = {'conHeat_wes' : ('conHeat_wes', units.unit1), \
                                  'conHeat_hal' : ('conHeat_hal', units.unit1), \
                                  'conHeat_eas' : ('conHeat_eas', units.unit1)};        
     # Measurements
     self.measurements = {};
     self.measurements['wesTdb'] = {'Sample' : variables.Static('wesTdb_sample', 600, units.s)};
     self.measurements['halTdb'] = {'Sample' : variables.Static('halTdb_sample', 1200, units.s)};
     self.measurements['easTdb'] = {'Sample' : variables.Static('easTdb_sample', 1200, units.s)};           
     # Exodata
     self.weather = exodata.WeatherFromEPW(weather_path);
     self.internal = exodata.InternalFromCSV(internal_path, internal_variable_map, tz_name = self.weather.tz_name);
     self.control = exodata.ControlFromCSV(control_path, control_variable_map, tz_name = self.weather.tz_name);
     # Parameters
     self.parameter_data = {};
     self.parameter_data['lat'] = {};
     self.parameter_data['lat']['Value'] = self.weather.lat;
예제 #4
0
 def test_estimate_error_nomeasurements(self):
     '''Test error raised if measurement_variable_list not in measurements dictionary.'''
     # Set model paths
     mopath = os.path.join(self.get_unittest_path(), 'resources', 'model',
                           'Simple.mo')
     modelpath = 'Simple.RC_noinputs'
     # Set parameters
     parameter_data = {}
     parameter_data['heatCapacitor.C'] = {}
     parameter_data['heatCapacitor.C']['Value'] = variables.Static(
         'C_Value', 55000, units.J_K)
     parameter_data['heatCapacitor.C']['Minimum'] = variables.Static(
         'C_Min', 10000, units.J_K)
     parameter_data['heatCapacitor.C']['Maximum'] = variables.Static(
         'C_Max', 100000, units.J_K)
     parameter_data['heatCapacitor.C']['Free'] = variables.Static(
         'C_Free', True, units.boolean)
     # Instantiate model
     model_no_meas = models.Modelica(models.JModelica, \
                                            models.RMSE, \
                                            self.measurements, \
                                            moinfo = (mopath, modelpath, {}), \
                                            parameter_data = parameter_data)
     # Check error raised with no free parameters
     with self.assertRaises(ValueError):
         model_no_meas.estimate(self.start_time, self.final_time,
                                ['wrong_meas'])
예제 #5
0
 def update_params(self, param, value, unit):
     # Add a new value fixed value to parameters
     self.parameters.data[param] = {
         'Free': variables.Static('FreeOrNot', False, units.boolean),
         'Minimum': variables.Static(param, value, unit),
         'Covariance': variables.Static('Covar', 0, unit),
         'Value': variables.Static(param, value, unit),
         'Maximum': variables.Static(param, value, unit)
     }
     store_namespace('params_upd_' + self.building, self.parameters)
예제 #6
0
파일: models.py 프로젝트: cyy1991/MPCPy
    def _estimate(self, Model):
        '''Use measured occupancy data to estimate the queue model parameters.

        '''

        # Set estimation options
        res = self.estimate_options['res']
        margin = self.estimate_options['margin']
        n_max = self.estimate_options['n_max']
        # Initialize variables
        Model.parameters_data['lam'] = {}
        Model.parameters_data['mu'] = {}
        self.seg_point = []
        self.empty_time = []
        # Estimate a queue model for each day of the week using training data
        for day in range(7):
            # Format training data
            self._format_training_data(Model, day)
            # Find breakpoints - segment the day into some homogeneous pieces
            self.seg_point.append(
                adaptive_breakpoint_placement(self.data_train,
                                              res=res,
                                              margin=margin,
                                              n_max=n_max))
            # Learn the arrival and departure rates for each segment
            self.seg_point[day] = np.sort(self.seg_point[day])
            val_size = self.data_train.shape[0]
            seg_num = len(self.seg_point[day]) + 1
            lam_all = np.empty((seg_num, val_size))
            mu_all = np.empty((seg_num, val_size))
            presence = np.where(np.mean(self.data_train, axis=0) != 0)
            self.empty_time.append(presence[0][-1] + 1)
            for i in range(val_size):
                x = self.data_train[i, :]
                [lam_temp, mu_temp
                 ] = parameter_inference_given_segment(x, self.seg_point[day],
                                                       self.empty_time[day])
                lam_all[:, i] = lam_temp
                mu_all[:, i] = mu_temp
            self.lam = np.mean(lam_all, axis=1)
            self.mu = np.mean(mu_all, axis=1)
            # Store estimated model parameters
            Model.parameters_data['lam'][day] = {}
            Model.parameters_data['lam'][day]['Free'] = variables.Static(
                'lam_' + str(day) + '_free', True, units.boolean)
            Model.parameters_data['lam'][day]['Value'] = variables.Static(
                'lam_' + str(day) + '_value', self.lam, units.unit1)
            Model.parameters_data['mu'][day] = {}
            Model.parameters_data['mu'][day]['Free'] = variables.Static(
                'mu_' + str(day) + '_free', True, units.boolean)
            Model.parameters_data['mu'][day]['Value'] = variables.Static(
                'mu_' + str(day) + '_value', self.mu, units.unit1)
예제 #7
0
    def test_set_problem_type(self):
        '''Test the dynamic setting of a problem type.

        '''

        modelpath = 'Simple.RC'
        # Instantiate model
        parameter_data = {}
        parameter_data['heatCapacitor.C'] = {}
        parameter_data['heatCapacitor.C']['Free'] = variables.Static(
            'C_free', False, units.boolean)
        parameter_data['heatCapacitor.C']['Value'] = variables.Static(
            'C_value', 3e6, units.boolean)
        model = models.Modelica(models.JModelica, \
                                models.RMSE, \
                                self.measurements, \
                                moinfo = (self.mopath, modelpath, {}), \
                                control_data = self.controls.data, \
                                parameter_data = parameter_data)
        # Instantiate optimization problem
        opt_problem = optimization.Optimization(model, \
                                                optimization.EnergyMin, \
                                                optimization.JModelica, \
                                                'q_flow', \
                                                constraint_data = self.constraints.data)
        # Solve optimization problem
        opt_problem.optimize(self.start_time, self.final_time)
        # Update model
        model = opt_problem.Model
        # Check references
        df_test = model.display_measurements('Simulated')
        self.check_df_timeseries(df_test, 'optimize_energy.csv')
        # Set new problem type
        opt_problem.set_problem_type(optimization.EnergyCostMin)
        # Gather prices
        price_csv_filepath = os.path.join(utility.get_MPCPy_path(),
                                          'resources', 'optimization',
                                          'SimpleRC_Prices.csv')
        price_variable_map = {
            'energy': ('pi_e', units.unit1)
        }
        price = exodata.PriceFromCSV(price_csv_filepath, price_variable_map)
        price.collect_data(self.start_time, self.final_time)
        opt_problem.optimize(self.start_time,
                             self.final_time,
                             price_data=price.data)
        # Update model
        model = opt_problem.Model
        # Check references
        df_test = model.display_measurements('Simulated')
        self.check_df_timeseries(df_test, 'optimize_energycost.csv')
예제 #8
0
    def test_initial_constraint(self):
        '''Test the optimization of a model with an initial constraint.
        
        '''

        modelpath = 'Simple.RC_nostart'
        # Instantiate model
        model = models.Modelica(models.JModelica, \
                                models.RMSE, \
                                self.measurements, \
                                moinfo = (self.mopath, modelpath, {}), \
                                control_data = self.controls.data)
        # Add initial constraint
        self.constraints.data['T_db']['Initial'] = variables.Static(
            'T_db_initial', 21, units.degC)
        # Instantiate optimization problem
        opt_problem = optimization.Optimization(model, \
                                                optimization.EnergyMin, \
                                                optimization.JModelica, \
                                                'q_flow', \
                                                constraint_data = self.constraints.data)
        # Solve optimization problem
        opt_problem.optimize(self.start_time, self.final_time)
        # Check references
        df_test = opt_problem.display_measurements('Simulated')
        self.check_df(df_test, 'optimize_initial_constraint.csv')
        opt_statistics = opt_problem.get_optimization_statistics()
        # Check references (except execution time)
        df_test = pd.DataFrame(columns=['message', 'iterations', 'objective'],
                               index=[0])
        df_test.loc[0] = opt_statistics[:-1]
        self.check_df(df_test,
                      'statistics_initial_constraint.csv',
                      timeseries=False)
예제 #9
0
파일: models.py 프로젝트: cyy1991/MPCPy
    def _validate(self, Model, validate_filename, plot=1):
        '''Perform the validation.
        
        '''

        Model.RMSE = {}
        for key in Model.measurements.keys():
            data = Model.measurements[key]['Measured'].get_base_data(
            ).loc[Model.start_time_utc:Model.final_time_utc]
            data_est = Model.measurements[key]['Simulated'].get_base_data(
            ).loc[Model.start_time_utc:Model.final_time_utc]
            summed = 0
            length = 0
            for i in range(len(data_est)):
                t = data_est.index.values[i]
                try:
                    diff = (data_est.loc[t] - data.loc[t])**2
                    summed = summed + diff
                    length = length + 1
                except KeyError:
                    print(
                        'WARNING: Time {0} missing in measured data.  Model value at time is {1}.'
                        .format(t, data_est.loc[t]))
            RMSE = np.sqrt(summed / length)
            unit_class = Model.measurements[key]['Measured'].get_base_unit()
            Model.RMSE[key] = variables.Static('RMSE_' + key, RMSE, unit_class)
        if plot == 1:
            self._plot_simple(Model, validate_filename)
예제 #10
0
    def _validate(self, Model, plot):
        '''Compare occupancy predictions to measurements.

        '''

        # Load prediction and measurement data
        prediction = Model.measurements[self.occ_key]['Simulated'].display_data();
        std = Model.measurements[self.occ_key]['SimulatedError'].display_data();
        measurements = Model.measurements[self.occ_key]['Measured'].display_data()[Model.start_time:Model.final_time];
        prediction_pstd = prediction+std;
        prediction_mstd = prediction-std;
        prediction_mstd = (prediction_mstd>=0)*prediction_mstd;
        
        Model.RMSE = {};
        for key in Model.measurements.keys():
            data = Model.measurements[key]['Measured'].get_base_data()[Model.start_time:Model.final_time];
            data_est = Model.measurements[key]['Simulated'].get_base_data()[Model.start_time:Model.final_time];
            RMSE = np.sqrt(sum((data_est-data)**2)/len(data));
            unit_class = Model.measurements[key]['Measured'].get_base_unit();
            Model.RMSE[key] = variables.Static('RMSE_'+key, RMSE, unit_class);
        if plot == 1:
            # Plot data to compare
            measurements.plot(label = 'measured', color = 'k', alpha = 0.5);
            prediction.plot(label='prediction', color = 'r', alpha = 0.5);
            plt.fill_between(prediction.index, prediction_pstd, prediction_mstd, color = 'r', alpha = 0.5);     
            plt.legend();
            plt.savefig(Model.validate_filename+'.png')        
예제 #11
0
    def _get_unit_class_from_fmu_variable_units(self, variable_name,
                                                fmu_variable_units):
        '''Get units.unit class for the given variable.
        
        Parameters
        ----------
        variable_name : string
            Name of the fmu variable for which to get the mpcpy unit class.
        fmu_variable_units : dictionary
            Dictionary where the keys are variable names and values are unit
            strings.  Can be gotten by ``_get_fmu_variable_units``.
            
        Returns
        -------
        unit_class : units.unit
            mpcpy unit class of fmu variable.
        
        '''

        unit_class_items = inspect.getmembers(units)
        unit_class = []
        for unit_class_item in unit_class_items:
            try:
                temp_var = variables.Static('tempvar', 1, unit_class_item[1])
                if fmu_variable_units[
                        variable_name] == temp_var.get_display_unit_name():
                    unit_class = unit_class_item[1]
                    break
            except:
                continue

        return unit_class
예제 #12
0
def get_unit_class_from_unit_string(unit_string):
    '''Get mpcpy.unit class for the given variable string.

    Parameters
    ----------
    unit_string : string
        Unit string.  For example, the unit string for a heat transfer
        coefficient in SI units would be ``'W/(m2.K)'``.
        
    Returns
    -------
    unit_class : units.unit class
        The mpcpy unit class for the given unit string.  This class can be used
        to define an mpcpy variable object.  See ``variables``.
    
    '''

    unit_class_items = inspect.getmembers(units)
    unit_class = []
    for unit_class_item in unit_class_items:
        try:
            temp_var = variables.Static('tempvar', 1, unit_class_item[1])
            if unit_string == temp_var.get_display_unit_name():
                unit_class = unit_class_item[1]
                break
        except:
            continue

    return unit_class
예제 #13
0
파일: test_models.py 프로젝트: rchml/MPCPy
 def setUp(self):
     # Testing time
     self.start_time = '3/8/2013'
     self.final_time = '3/15/2013 23:59'
     # Set path variable(s)
     self.MPCPyPath = utility.get_MPCPy_path()
     # Setup building measurement collection from csv
     self.csv_filepath = self.MPCPyPath + os.sep + 'resources' + os.sep + 'building' + os.sep + 'OccData.csv'
     # Measurements
     self.measurements = {}
     self.measurements['occupancy'] = {
         'Sample': variables.Static('occupancy_sample', 300, units.s)
     }
     self.measurement_variable_map = {
         'Total People Count for the whole building (+)':
         ('occupancy', units.unit1)
     }
     # Instantiate building measurement source
     self.building = systems.RealFromCSV(self.csv_filepath, \
                                         self.measurements,
                                         self.measurement_variable_map,
                                         time_header = 'Date')
     # Where to save ref occupancy model
     self.occupancy_model_file = self.get_ref_path(
     ) + os.sep + 'occupancy_model_estimated.txt'
예제 #14
0
 def setUp(self):
     self.start_time = '1/1/2017'
     self.final_time = '1/10/2017'
     # Set measurements
     self.measurements = {}
     self.measurements['T_db'] = {
         'Sample': variables.Static('T_db_sample', 1800, units.s)
     }
     # Set model paths
     mopath = os.path.join(self.get_unittest_path(), 'resources', 'model',
                           'Simple.mo')
     modelpath = 'Simple.RC_nostart'
     self.moinfo = (mopath, modelpath, {})
     # Gather parameters
     parameter_csv_filepath = os.path.join(self.get_unittest_path(),
                                           'resources', 'model',
                                           'SimpleRC_Parameters.csv')
     self.parameters = exodata.ParameterFromCSV(parameter_csv_filepath)
     self.parameters.collect_data()
     # Gather control inputs
     control_csv_filepath = os.path.join(self.get_unittest_path(),
                                         'resources', 'model',
                                         'SimpleRC_Input.csv')
     variable_map = {
         'q_flow_csv': ('q_flow', units.W)
     }
     self.controls = exodata.ControlFromCSV(control_csv_filepath,
                                            variable_map)
     self.controls.collect_data(self.start_time, self.final_time)
     # Instantiate system
     self.system = systems.EmulationFromFMU(self.measurements, \
                                            moinfo = self.moinfo, \
                                            control_data = self.controls.data)
     # Get measurements
     self.system.collect_measurements(self.start_time, self.final_time)
예제 #15
0
 def test_add_static(self):
     '''Add static and timeseries variables.'''   
     self.a = variables.Static('a', 5, units.degC)         
     self.f = self.a + self.e;
     self.assertEqual('ae', self.f.name);
     self.assertIs(self.f.get_display_unit(), units.degC);
     for i in range(len(self.dataC)):
         self.assertEqual(self.f.display_data().get_values()[i], 5 + self.dataC[i]);
예제 #16
0
 def setUp(self):
     self.start_time = '1/1/2017'
     self.final_time = '1/2/2017'
     # Set measurements
     self.measurements = {}
     self.measurements['T_db'] = {
         'Sample': variables.Static('T_db_sample', 1800, units.s)
     }
예제 #17
0
 def test_set_data_array(self):
     '''Test setting data that is an array.'''
     x_array = np.array([1, 2, 3, 4.5])
     self.var_array = variables.Static('var_array', x_array, units.degC)
     i = 0
     for x in x_array:
         self.assertEqual(self.var_array.display_data()[i], x)
         i = i + 1
예제 #18
0
 def test_set_data_list(self):
     '''Test setting data that is an array.'''
     x_list = [1, 2, 3, 4.5]
     self.var_list = variables.Static('var_list', x_list, units.degC)
     i = 0
     for x in x_list:
         self.assertEqual(self.var_list.display_data()[i], x)
         i = i + 1
예제 #19
0
파일: test_models.py 프로젝트: rchml/MPCPy
 def setUp(self):
     self.start_time = '1/1/2017'
     self.final_time = '1/2/2017'
     self.MPCPyPath = utility.get_MPCPy_path()
     # Set measurements
     self.measurements = {}
     self.measurements['T_db'] = {
         'Sample': variables.Static('T_db_sample', 1800, units.s)
     }
예제 #20
0
    def _parse_building_kwargs(self, kwargs):
        '''Parse the kwargs associated with initializing a building model.
        
        Yields
        ------
        zone_names : list
            Zone name list attribute.
        weather_data : dictionary
            Weather ``exodata`` data dictionary attribute.
        internal_data : dictionary
            Internal load ``exodata`` data dictionary attribute.
        control_data : dictionary
            Control ``exodata`` data dictionary attribute.
        other_inputs : dictionary
            Other input ``exodata`` data dictionary attribute.
        parameter_data : dictionary
            Parameter ``exodata`` data dictionary attribute.

        '''

        # Zone names
        if 'zone_names' in kwargs:
            self.zone_names = kwargs['zone_names']
        else:
            self.zone_names = {}
        # Weather
        if 'weather_data' in kwargs:
            self.weather_data = kwargs['weather_data']
        else:
            self.weather_data = {}
        # Internal
        if 'internal_data' in kwargs:
            self.internal_data = kwargs['internal_data']
        else:
            self.internal_data = {}
        # Control
        if 'control_data' in kwargs:
            self.control_data = kwargs['control_data']
        else:
            self.control_data = {}
        # Other inputs
        if 'other_inputs' in kwargs:
            self.other_inputs = kwargs['other_inputs']
        else:
            self.other_inputs = {}
        # Parameters
        if 'parameter_data' in kwargs:
            self.parameter_data = kwargs['parameter_data']
            # Check if free tag exists
            for key in self.parameter_data.keys():
                if 'Free' not in self.parameter_data[key]:
                    self.parameter_data[key]['Free'] = variables.Static(
                        key + '_free', False, units.boolean)
        else:
            self.parameter_data = {}
예제 #21
0
def emulate_jmod(emulation, measured_var_dict, sample_rate, start_time,
                 end_time):
    # function to emulate with J-Modelica

    print("%%%%%%%%%%%%%%%----Starting Emulation---%%%%%%%%%%%%%")
    for key in measured_var_dict.keys():
        var_str = 'sample_rate_' + key
        measured_var_dict[key]['Sample'] = variables.Static(
            var_str, sample_rate, units.s)

    return emulation.collect_measurements(start_time, end_time)
예제 #22
0
 def setUp(self):
     # Setup building measurement collection from csv
     self.csv_filepath = os.path.join(self.get_unittest_path(), 'resources', 'building', 'OccData.csv');
     # Measurements
     self.measurements = {};
     self.measurements['occupancy'] = {'Sample' : variables.Static('occupancy_sample', 300, units.s)};
     self.measurement_variable_map = {'Total People Count for the whole building (+)' : ('occupancy', units.unit1)};                        
     # Instantiate building measurement source
     self.building = systems.RealFromCSV(self.csv_filepath, \
                                         self.measurements, 
                                         self.measurement_variable_map,
                                         time_header = 'Date');
예제 #23
0
    def _parse_time_zone_kwargs(self, kwargs):
        '''Set the timezone using geography or timezone name.
        
        If no timezone is supplied, than utc is assigned.
        
        Parameters
        ----------
        tz_name : string, optional
            Name of timezone according to the package ``tzwhere``.  If 
            ``'from_geography'``, than geography kwarg is required.
        geography : string, optional
            List or tuple with latitude in the first position and longitude in
            the second position, both in degrees.
            
        Yields
        ------
        tz_name : string
            Attribute for timezone name.
        
        '''

        # Geography
        if 'geography' in kwargs:
            self.lat = variables.Static('lat', kwargs['geography'][0],
                                        units.deg)
            self.lon = variables.Static('lon', kwargs['geography'][1],
                                        units.deg)
        else:
            self.lat = None
            self.lon = None
        # UTC Time Input
        if 'tz_name' in kwargs:
            if kwargs['tz_name'] == 'from_geography':
                self.tz = tzwhere.tzwhere()
                self.tz_name = self.tz.tzNameAt(kwargs['geography'][0],
                                                kwargs['geography'][1])
            else:
                self.tz_name = kwargs['tz_name']
        else:
            self.tz_name = 'UTC'
예제 #24
0
 def setUp(self):
     self.start_time = '1/1/2017'
     self.final_time = '1/2/2017'
     # Set measurements
     self.measurements = {}
     self.measurements['T_db'] = {
         'Sample': variables.Static('T_db_sample', 1800, units.s)
     }
     # Set model paths
     mopath = os.path.join(self.get_unittest_path(), 'resources', 'model',
                           'Simple.mo')
     modelpath = 'Simple.RC_noinputs'
     self.moinfo = (mopath, modelpath, {})
예제 #25
0
 def test_estimate_two_par(self):
     '''Test the estimation of two parameters of a model.'''
     # Set model paths
     mopath = os.path.join(self.get_unittest_path(), 'resources', 'model',
                           'Simple.mo')
     modelpath = 'Simple.RC_noinputs'
     # Instantiate system
     system = systems.EmulationFromFMU(self.measurements, \
                                            moinfo = (mopath, modelpath, {}))
     system.collect_measurements(self.start_time, self.final_time)
     # Define parameters
     parameter_data = {}
     parameter_data['heatCapacitor.C'] = {}
     parameter_data['heatCapacitor.C']['Value'] = variables.Static(
         'C_Value', 55000, units.J_K)
     parameter_data['heatCapacitor.C']['Minimum'] = variables.Static(
         'C_Min', 10000, units.J_K)
     parameter_data['heatCapacitor.C']['Maximum'] = variables.Static(
         'C_Max', 1000000, units.J_K)
     parameter_data['heatCapacitor.C']['Free'] = variables.Static(
         'C_Free', True, units.boolean)
     parameter_data['thermalResistor.R'] = {}
     parameter_data['thermalResistor.R']['Value'] = variables.Static(
         'R_Value', 0.02, units.K_W)
     parameter_data['thermalResistor.R']['Minimum'] = variables.Static(
         'R_Min', 0.001, units.K_W)
     parameter_data['thermalResistor.R']['Maximum'] = variables.Static(
         'R_Max', 0.1, units.K_W)
     parameter_data['thermalResistor.R']['Free'] = variables.Static(
         'R_Free', True, units.boolean)
     # Instantiate model
     self.model = models.Modelica(models.JModelica, \
                                  models.RMSE, \
                                  self.measurements, \
                                  moinfo = (mopath, modelpath, {}), \
                                  parameter_data = parameter_data)
     # Estimate models
     self.model.estimate(self.start_time, self.final_time, ['T_db'])
     # Check references
     data = [
         self.model.parameter_data['heatCapacitor.C']
         ['Value'].display_data(),
         self.model.parameter_data['thermalResistor.R']
         ['Value'].display_data(),
     ]
     index = ['heatCapacitor.C', 'thermalResistor.R']
     df_test = pd.DataFrame(data=data, index=index, columns=['Value'])
     self.check_df(df_test, 'estimate_two_par.csv', timeseries=False)
예제 #26
0
 def setUp(self):
     self.start_time = '1/1/2017';
     self.final_time = '1/2/2017';
     # Set .mo path
     self.mopath = os.path.join(self.get_unittest_path(), 'resources', 'model', 'Simple.mo');
     # Gather inputs
     start_time_exo = '1/1/2017';
     final_time_exo = '1/10/2017';
     control_csv_filepath = os.path.join(self.get_unittest_path(), 'resources', 'model', 'SimpleRC_Input.csv');
     control_variable_map = {'q_flow_csv' : ('q_flow', units.W)};
     self.controls = exodata.ControlFromCSV(control_csv_filepath, control_variable_map);
     self.controls.collect_data(start_time_exo, final_time_exo);
     # Set measurements
     self.measurements = {};
     self.measurements['T_db'] = {'Sample' : variables.Static('T_db_sample', 1800, units.s)};
     self.measurements['q_flow'] = {'Sample' : variables.Static('q_flow_sample', 1800, units.s)};
     # Gather constraints       
     constraint_csv_filepath = os.path.join(self.get_unittest_path(), 'resources', 'optimization', 'SimpleRC_Constraints.csv');
     constraint_variable_map = {'q_flow_min' : ('q_flow', 'GTE', units.W), \
                                'T_db_min' : ('T_db', 'GTE', units.K), \
                                'T_db_max' : ('T_db', 'LTE', units.K)};
     self.constraints = exodata.ConstraintFromCSV(constraint_csv_filepath, constraint_variable_map);
     self.constraints.collect_data(start_time_exo, final_time_exo);
예제 #27
0
    def _validate(self, Model, validate_filename, plot = 1):
        '''Perform the validation.
        
        '''

        Model.RMSE = {};
        for key in Model.measurements.keys():
            data = Model.measurements[key]['Measured'].get_base_data()[Model.start_time:Model.final_time];
            data_est = Model.measurements[key]['Simulated'].get_base_data()[Model.start_time:Model.final_time];
            RMSE = np.sqrt(sum((data_est-data)**2)/len(data));
            unit_class = Model.measurements[key]['Measured'].get_base_unit();
            Model.RMSE[key] = variables.Static('RMSE_'+key, RMSE, unit_class);
        if plot == 1:
            self._plot_simple(Model, validate_filename);
예제 #28
0
 def setUp(self):
     self.MPCPyPath = utility.get_MPCPy_path();
     ## Setup building fmu emulation
     self.building_source_file_path = self.MPCPyPath + os.sep + 'resources' + os.sep + 'building' + os.sep + 'LBNL71T_Emulation_JModelica_v2.fmu';
     self.zone_names = ['wes', 'hal', 'eas'];
     self.weather_path = self.MPCPyPath + os.sep + 'resources' + os.sep + 'weather' + os.sep + 'USA_IL_Chicago-OHare.Intl.AP.725300_TMY3.epw';
     self.internal_path = self.MPCPyPath + os.sep + 'resources' + os.sep + 'internal' + os.sep + 'sampleCSV.csv';
     self.internal_variable_map = {'intRad_wes' : ('wes', 'intRad', units.W_m2), \
                                   'intCon_wes' : ('wes', 'intCon', units.W_m2), \
                                   'intLat_wes' : ('wes', 'intLat', units.W_m2), \
                                   'intRad_hal' : ('hal', 'intRad', units.W_m2), \
                                   'intCon_hal' : ('hal', 'intCon', units.W_m2), \
                                   'intLat_hal' : ('hal', 'intLat', units.W_m2), \
                                   'intRad_eas' : ('eas', 'intRad', units.W_m2), \
                                   'intCon_eas' : ('eas', 'intCon', units.W_m2), \
                                   'intLat_eas' : ('eas', 'intLat', units.W_m2)};        
     self.control_path = self.MPCPyPath + os.sep + 'resources' + os.sep + 'building' + os.sep + 'ControlCSV_0.csv';
     self.control_variable_map = {'conHeat_wes' : ('conHeat_wes', units.unit1), \
                                  'conHeat_hal' : ('conHeat_hal', units.unit1), \
                                  'conHeat_eas' : ('conHeat_eas', units.unit1)};        
     # Measurements
     self.measurements = {};
     self.measurements['wesTdb'] = {'Sample' : variables.Static('wesTdb_sample', 1800, units.s)};
     self.measurements['halTdb'] = {'Sample' : variables.Static('halTdb_sample', 1800, units.s)};
     self.measurements['easTdb'] = {'Sample' : variables.Static('easTdb_sample', 1800, units.s)};
     self.measurements['wesPhvac'] = {'Sample' : variables.Static('easTdb_sample', 1800, units.s)};
     self.measurements['halPhvac'] = {'Sample' : variables.Static('easTdb_sample', 1800, units.s)};     
     self.measurements['easPhvac'] = {'Sample' : variables.Static('easTdb_sample', 1800, units.s)};
     self.measurements['Ptot'] = {'Sample' : variables.Static('easTdb_sample', 1800, units.s)};
     ## Setup model
     self.mopath = self.MPCPyPath + os.sep + 'resources' + os.sep + 'model' + os.sep + 'LBNL71T_MPC.mo';
     self.modelpath = 'LBNL71T_MPC.MPC';
     self.libraries = os.environ.get('MODELICAPATH');
     self.estimate_method = models.JModelica; 
     self.validation_method = models.RMSE;
     # Instantiate exo data sources
     self.weather = exodata.WeatherFromEPW(self.weather_path);
     self.internal = exodata.InternalFromCSV(self.internal_path, self.internal_variable_map, tz_name = self.weather.tz_name);
     self.control = exodata.ControlFromCSV(self.control_path, self.control_variable_map, tz_name = self.weather.tz_name);   
     # Parameters        
     self.parameters = exodata.ParameterFromCSV(self.MPCPyPath + os.sep + 'resources' + os.sep + 'model' + os.sep + 'LBNL71T_Parameters.csv');
     self.parameters.collect_data();
     self.parameters.data['lat'] = {};
     self.parameters.data['lat']['Value'] = self.weather.lat;    
     # Instantiate building
     building_parameters_data = {};
     building_parameters_data['lat'] = {};
     building_parameters_data['lat']['Value'] = self.weather.lat;  
     self.building = systems.EmulationFromFMU(self.measurements, \
                                              fmupath = self.building_source_file_path, \
                                              zone_names = self.zone_names, \
                                              parameter_data = building_parameters_data);
예제 #29
0
 def test_error_points_per_day(self):
     '''Test occupancy prediction.'''
     plt.close('all');
     # Time
     self.start_time = '3/1/2013';
     self.final_time = '3/7/2013 23:59';        
     # Load occupancy model
     with open(self.occupancy_model_file, 'r') as f:
         self.occupancy = pickle.load(f);
     # Change occupant measurements to not be whole number in points per day
     self.occupancy.measurements['occupancy']['Sample'] = variables.Static('occupancy_sample', 299, units.s);
     # Estimate occupancy model parameters and expect error
     with self.assertRaises(ValueError):
         np.random.seed(1);
         self.occupancy.estimate(self.start_time, self.final_time);    
예제 #30
0
    def test_collect_measurements_continue_cs_2(self):
        start_time = '1/1/2017'
        final_time = '1/2/2017'
        # Set measurements
        measurements = {}
        measurements['T_db'] = {
            'Sample': variables.Static('T_db_sample', 1800, units.s)
        }
        # Set model paths
        mopath = os.path.join(self.get_unittest_path(), 'resources', 'model',
                              'Simple.mo')
        modelpath = 'Simple.RC_nostart'
        moinfo = (mopath, modelpath, {})
        # Gather control inputs
        control_csv_filepath = os.path.join(self.get_unittest_path(),
                                            'resources', 'model',
                                            'SimpleRC_Input.csv')
        variable_map = {
            'q_flow_csv': ('q_flow', units.W)
        }
        controls = exodata.ControlFromCSV(control_csv_filepath, variable_map)
        controls.collect_data(start_time, final_time)
        # Instantiate model
        building = systems.EmulationFromFMU(measurements, \
                                            moinfo = moinfo, \
                                            control_data = controls.data,
                                            version = '2.0',
                                            target = 'cs')
        # Simulate model
        building.collect_measurements(start_time, final_time)
        # Check references
        df_test = building.display_measurements('Simulated')
        self.check_df(df_test, 'collect_measurements_display_cs.csv')

        # Simulate model in 4-hour chunks
        sim_steps = pd.date_range(start_time, final_time, freq=str('8H'))
        for i in range(len(sim_steps) - 1):
            if i == 0:
                building.collect_measurements(sim_steps[i], sim_steps[i + 1])
            else:
                building.collect_measurements('continue', sim_steps[i + 1])
            # Check references
            df_test = building.display_measurements('Simulated')
            self.check_df(df_test,
                          'collect_measurements_step_cs{0}.csv'.format(i))