示例#1
0
    def test_run_experiment(self):
        mockMSI = mock.Mock(spec=Model)
        mockMSI.name = 'test'
        mockMSI.uncertainties = [RealParameter("a", 0, 10),
                                 RealParameter("b", 0, 10)]
        
        msis = NamedObjectMap(AbstractModel)
        msis['test'] = mockMSI

        runner = ExperimentRunner(msis)
        
        experiment = Experiment('test',
                                mockMSI.name,
                                Policy('none'),  
                                Scenario(a=1, b=2), 0)
        
        runner.run_experiment(experiment)
        
        sc, p = mockMSI.run_model.call_args[0]
        self.assertEqual(sc.name, experiment.scenario.name)
        self.assertEqual(p, experiment.policy)
        
        mockMSI.reset_model.assert_called_once_with()
        
   
        # assert handling of case error
        mockMSI = mock.Mock(spec=Model)
        mockMSI.name = 'test'
        mockMSI.run_model.side_effect = Exception('some exception')
        msis = NamedObjectMap(AbstractModel)
        msis['test'] = mockMSI
        
        runner = ExperimentRunner(msis)
    
        experiment = Experiment('test',mockMSI.name,Policy('none'),  
                      Scenario(a=1, b=2),0)

        with self.assertRaises(EMAError):
            runner.run_experiment(experiment)
           
        # assert handling of case error
        mockMSI = mock.Mock(spec=Model)
        mockMSI.name = 'test'
        mockMSI.run_model.side_effect = CaseError("message", {})
        msis = NamedObjectMap(AbstractModel)
        msis['test'] = mockMSI
        runner = ExperimentRunner(msis)
    
        experiment = Experiment('test',mockMSI.name,Policy('none'),  
                      Scenario(a=1, b=2),0)

        runner.run_experiment(experiment)
    def get_sd_results(self, experiment):
        results = {}
        error = False
        for variable in self.output_variables:

            if "SD_" in variable:
                variable = variable.replace('SD_', '')
                res = vensim.get_data(self.vensim_model_output, variable)
                result, er = self.check_data(np.asarray(res))
                error = error or er
                variable = "SD_" + variable
                results[variable] = result

        if error:
            raise CaseError("run not completed", experiment)

        return results
    def get_sd_results(self, experiment):
        results = {}
        error = False
        for variable in self.output_variables:

            if "SD_" in variable:
                variable = variable.replace('SD_', '')
                res = vensim.get_data(self.vensim_model_output, variable)
                result, er = self.check_data(np.asarray(res))
                error = error or er
                variable = "SD_" + variable
                results[variable] = result

        for variable in self.SD_subscripted_output:
            sub_res = get_subscripted_data(variable[0],
                                           self.subscript_dict[variable[1]],
                                           self.vensim_model_output)
            results[variable[0]] = sub_res.transpose().to_numpy().squeeze(
            )  # reduce dimension

        if error:
            raise CaseError("run not completed", experiment)

        return results
    def run_experiment(self, experiment):
        #netlogo = pyNetLogo.core.NetLogoLink(netlogo_home = 'C:/Program Files/Netlogo 6.1.1', netlogo_version = '6.1')

        full_run = True
        filepath_netlogo = os.path.join(self.working_directory, 'ABM', 'Input')

        ticks = 2020
        end = 2060

        # VENSIM experiments
        for key, value in experiment.items():
            if "SD_" in key:
                key = key.replace("SD_", "")
                set_value(key, value)

        #NETLOGO experiments
        self.netlogo.command('reset-initials')

        for key, value in experiment.items():
            if "ABM_" in key:
                key = key.replace("ABM_", "")
                self.netlogo.command("set " + key + " " + str(value))

        # setup datasheet for recovering globals from ABM
        time_col = []
        for i in range(ticks, end + 1):
            time_col = np.append(time_col, i)
        self.abm_globals = pd.DataFrame(time_col).set_index(0)

        while ticks <= end:

            # RUN SD until TICKS
            run_partial_SD_model(ticks, self.vensim_model_output)
            #get globals from SD
            output_vars = [
                'Average Gas Price', 'Average Heat Price',
                'Average Electricity Price', 'Relocation mobility factor'
            ]
            globals_SD_output = extract_SD_data(output_vars,
                                                self.vensim_model_output)

            # Ask netlogo to update globals
            self.netlogo.command(
                'set gas-price ' +
                str(globals_SD_output.loc[ticks]['Average Gas Price']))
            self.netlogo.command(
                'set electricity-price ' +
                str(globals_SD_output.loc[ticks]['Average Electricity Price']))
            self.netlogo.command(
                'set heat-price ' +
                str(globals_SD_output.loc[ticks]['Average Heat Price']))
            self.netlogo.command('set relocation-mobility ' + str(
                globals_SD_output.loc[ticks]['Relocation mobility factor']))

            # Retrieve subscripted output from Vensim and save to be updated in NetLogo
            get_demolition(self.working_directory,
                           self.vensim_model_output).to_csv(
                               os.path.join(filepath_netlogo,
                                            'SD_output_demolition.csv'))
            get_new_construction(self.working_directory,
                                 self.vensim_model_output).to_csv(
                                     os.path.join(
                                         filepath_netlogo,
                                         'SD_output_construction.csv'))
            get_new_energy_use(self.working_directory,
                               self.vensim_model_output).to_csv(
                                   os.path.join(
                                       filepath_netlogo,
                                       'SD_output_e-use_new-construction.csv'))
            get_system_cost_reduction(
                self.working_directory, self.vensim_model_output).to_csv(
                    os.path.join(filepath_netlogo,
                                 'SD_output_systemcost-reduction.csv'))
            get_insulation_cost_reduction(
                self.working_directory, self.vensim_model_output).to_csv(
                    os.path.join(filepath_netlogo,
                                 'SD_output_insulationcost-reduction.csv'))

            # Ask netlogo to update all subscipted vars from csv's. Unfortunately directly asking netlogo to update
            # the datafiles doesn't work due to the need for strings in strings.
            self.netlogo.command('update-SD-data-import')

            #RUN once
            try:
                self.netlogo.command('repeat 1 [go]')
            except:
                raise CaseError("Netlogo run not completed at " + str(ticks),
                                experiment)
            # Save Model Output
        # systems_dict = {}

            save_ABM_globals(self, ticks)

            if full_run == True:
                # Do not overwrite ABM results of full run with partial run
                save_ABM_output(os.path.join(self.working_directory, 'ABM'),
                                os.path.join(self.working_directory, 'SD'))

            ticks += 1

        SD_results = self.get_sd_results(experiment)
        ABM_results = self.get_abm_results()

        results = SD_results
        results.update(ABM_results)

        return results