def run(self, run_choice_model=True, choose_job_only_in_residence_zone=False, *args, **kwargs):
        agent_set = kwargs['agent_set']
        if run_choice_model:
            choices = ChoiceModel.run(self, *args, **kwargs)
            #prob_work_at_home = self.upc_sequence.probabilities[:, 0]
                
            agent_set.set_values_of_one_attribute(self.choice_attribute_name, 
                                                  choices, 
                                                  index=kwargs['agents_index'])
            at_home_worker_index = kwargs['agents_index'][choices==1]
            logger.log_status("%s workers choose to work at home, %s workers chose to work out of home." % 
                              (where(agent_set.get_attribute_by_index(self.choice_attribute_name, kwargs['agents_index']) == 1)[0].size,
                               where(agent_set.get_attribute_by_index(self.choice_attribute_name, kwargs['agents_index']) == 0)[0].size))            
        else:
            at_home_worker_index = where(logical_and( 
                                                     agent_set.get_attribute(self.choice_attribute_name) == 1,
                                                     agent_set.get_attribute('job_id') <= 0
                                                     )
                                        )[0]
        
        if self.filter is not None:
            jobs_set_index = where( self.job_set.compute_variables(self.filter) )[0]
        else:
            jobs_set_index = arange( self.job_set.size() )
            
        logger.log_status("Total: %s workers work at home, (%s workers work out of home), will try to assign %s workers to %s jobs." % 
                          (where(agent_set.get_attribute(self.choice_attribute_name) == 1)[0].size,
                           where(agent_set.get_attribute(self.choice_attribute_name) == 0)[0].size,
                          at_home_worker_index.size,
                          jobs_set_index.size
                          ))

        if not choose_job_only_in_residence_zone:
            assigned_worker_index, assigned_job_index = self._assign_job_to_worker(at_home_worker_index, jobs_set_index)
        else:
            agent_set.compute_variables("urbansim_parcel.person.zone_id")
            self.job_set.compute_variables("urbansim_parcel.job.zone_id")
            agent_zone_ids = agent_set.get_attribute_by_index('zone_id', at_home_worker_index)
            job_zone_ids = self.job_set.get_attribute_by_index('zone_id', jobs_set_index)
            unique_zones = unique(job_zone_ids)
            assigned_worker_index = array([], dtype="int32")
            assigned_job_index = array([], dtype="int32")
            for this_zone in unique_zones:
                logger.log_status("zone_id: %s" % this_zone)
                if this_zone <= 0: continue
                at_home_worker_in_this_zone = where(agent_zone_ids == this_zone)[0]
                job_set_in_this_zone = where(job_zone_ids == this_zone)[0]
                assigned_worker_in_this_zone, assigned_job_set_in_this_zone = self._assign_job_to_worker(at_home_worker_in_this_zone, job_set_in_this_zone)
                assigned_worker_index = concatenate((assigned_worker_index, at_home_worker_index[assigned_worker_in_this_zone]))
                assigned_job_index = concatenate((assigned_job_index, jobs_set_index[assigned_job_set_in_this_zone]))

        ## each worker can only be assigned to 1 job
        #assert assigned_worker_index.size == unique(assigned_worker_index).size
        agent_set.set_values_of_one_attribute(self.job_set.get_id_name()[0], 
                                              self.job_set.get_id_attribute()[assigned_job_index], 
                                              index=assigned_worker_index)
        agent_set.compute_variables([self.location_id_name], dataset_pool=self.dataset_pool)
        self.job_set.modify_attribute(name=VariableName(self.location_id_name).get_alias(), 
                                      data=agent_set.get_attribute_by_index(self.location_id_name, assigned_worker_index),
                                      index=assigned_job_index)
 def run(self,
         specification,
         coefficients,
         agent_set,
         agents_index=None,
         **kwargs):
     choices = ChoiceModel.run(self,
                               specification,
                               coefficients,
                               agent_set,
                               agents_index=agents_index,
                               **kwargs)
     if agents_index is None:
         agents_index = arange(agent_set.size())
     movers_indices = agents_index[where(choices > 0)]
     if self.movers_ratio is not None:
         n = rint(self.movers_ratio * agents_index.size)
         if n < movers_indices.size:
             movers_indices = sample_noreplace(movers_indices, n)
     # add unplaced agents
     unplaced_agents = agents_index[agent_set.get_attribute_by_index(
         self.location_id_name, agents_index) <= 0]
     logger.log_status(
         "%s agents selected by the logit model; %s agents without %s." %
         (movers_indices.size, unplaced_agents.size, self.location_id_name))
     movers_indices = unique(concatenate((movers_indices, unplaced_agents)))
     logger.log_status("Number of movers: " + str(movers_indices.size))
     return movers_indices
Пример #3
0
 def run(self, zones, run_choice_model=True, choose_job_only_in_residence_zone=True, **kwargs):
     agent_set = kwargs['agent_set']
     agents_index = kwargs.get('agents_index', None)
     if agents_index is None:
         agents_index = arange(agent_set.size())
     cond_array = zeros(agent_set.size(), dtype="bool8")
     cond_array[agents_index] = True
     zone_ids = zones.get_id_attribute()
     agents_zones = agent_set.compute_variables(['urbansim_parcel.%s.%s' % (agent_set.get_dataset_name(),
                                                     zones.get_id_name()[0])], dataset_pool=self.dataset_pool)
     if self.filter is not None:
         jobs_set_index = where( self.job_set.compute_variables(self.filter) )[0]
     else:
         jobs_set_index = arange( self.job_set.size() )  
     #self.job_set.compute_variables("urbansim_parcel.job.zone_id")
     agent_set.compute_variables("urbansim_parcel.person.zone_id")
     # remove job links from all workers
     agent_set.set_values_of_one_attribute(self.choice_attribute_name, -1*ones(agents_index.size, dtype='int32'), 
                                           index=agents_index)
     for zone_id in zone_ids:
         new_index = where(logical_and(cond_array, agents_zones == zone_id))[0]
         logger.log_status("%s for zone %s" % (self.model_short_name, zone_id))
         if run_choice_model:
             kwargs['agents_index'] = new_index
             choices = ChoiceModel.run(self, **kwargs)
             prob_work_at_home = self.upc_sequence.get_probabilities()[:, 1]
             job_set_in_this_zone = jobs_set_index[self.job_set['zone_id'][jobs_set_index] == zone_id]
             number_of_hb_jobs = job_set_in_this_zone.size
             # sample workers for the number of jobs
             draw = probsample_noreplace(kwargs['agents_index'], min(kwargs['agents_index'].size, number_of_hb_jobs), 
                                         prob_work_at_home)
             agent_set.set_values_of_one_attribute(self.choice_attribute_name, 
                                               ones(draw.size, dtype=agent_set[self.choice_attribute_name].dtype), 
                                               index=draw)
             logger.log_status("%s workers choose to work at home, %s workers chose to work out of home." % 
                           (where(agent_set.get_attribute_by_index(self.choice_attribute_name, kwargs['agents_index']) == 1)[0].size,
                            where(agent_set.get_attribute_by_index(self.choice_attribute_name, kwargs['agents_index']) == 0)[0].size))            
         at_home_worker_in_this_zone = kwargs['agents_index'][agent_set[self.choice_attribute_name][kwargs['agents_index']] == 1]
         assigned_worker_in_this_zone, assigned_job_set_in_this_zone = self._assign_job_to_worker(at_home_worker_in_this_zone, 
                                                                                                  job_set_in_this_zone)
         agent_set.set_values_of_one_attribute(self.job_set.get_id_name()[0], 
                                           self.job_set.get_id_attribute()[assigned_job_set_in_this_zone], 
                                           index=assigned_worker_in_this_zone)
         agent_set.compute_variables([self.location_id_name], dataset_pool=self.dataset_pool)
         self.job_set.modify_attribute(name=VariableName(self.location_id_name).get_alias(), 
                                   data=agent_set.get_attribute_by_index(self.location_id_name, assigned_worker_in_this_zone),
                                   index=assigned_job_set_in_this_zone)
         agent_set.flush_dataset()
         self.job_set.flush_dataset()
         
         
     logger.log_status("Total: %s workers work at home, %s workers work out of home." % 
                       (where(agent_set.get_attribute(self.choice_attribute_name) == 1)[0].size,
                        where(agent_set.get_attribute(self.choice_attribute_name) == 0)[0].size
                       ))
    def run(self, specification, coefficients, agent_set,
            agents_index=None, chunk_specification=None,
            data_objects=None, run_config=None, debuglevel=0):
        """ Run a simulation and return a numpy array of length agents_index, giving agent choices (ids of locations).
            'specification' is of type EquationSpecification,
            'coefficients' is of type Coefficients,
            'agent_set' is of type Dataset,
            'agent_index' are indices of individuals in the agent_set for which
                        the model runs. If it is None, the whole agent_set is considered.
            'chunk_specification' determines number of chunks in which the simulation is processed.
                        Default is to use 300 rows per chunk.
            'data_objects' is a dictionary where each key is the name of an data object
                    ('zone', ...) and its value is an object of class  Dataset.
            'run_config' is of type Resources, it gives additional arguments for the run.
            'debuglevel' overwrites the constructor 'debuglevel'.
        """
        if run_config == None:
            run_config = Resources()
        self.run_config = run_config.merge_with_defaults(self.run_config)
        if data_objects is not None:
            self.dataset_pool.add_datasets_if_not_included(data_objects)
        self.dataset_pool.add_datasets_if_not_included({agent_set.get_dataset_name():agent_set})
        
        ## what is the use of compute location_id string in run? it gets new values anyway
        #if self.location_id_string is not None:
        #    location_id = agent_set.compute_variables(self.location_id_string, dataset_pool=self.dataset_pool)

        ## done in choice_model
        #location_id_name = self.choice_set.get_id_name()[0]
        #if (location_id_name not in agent_set.get_known_attribute_names()):
        #    agent_set.add_attribute(name=location_id_name, data=resize(array([-1]), agent_set.size()))
                    
        if self.run_config.get("agent_units_string", None): # used when agents take different amount of capacity from the total capacity
            agent_set.compute_variables([self.run_config["agent_units_string"]], dataset_pool=self.dataset_pool)

        self.compute_capacity_flag = self.run_config.get("compute_capacity_flag",  False)
        capacity_string = None
        self.capacity = None
        if self.compute_capacity_flag:
            capacity_string = self.run_config.get("capacity_string", None)
            if capacity_string is None:
                raise KeyError, \
                    "Entry 'capacity_string' has to be specified in 'run_config' if 'compute_capacity_flag' is True"
            
        ## if weights is None, use capacity for weights
        if self.run_config.get("weights_for_simulation_string", None) is None and capacity_string is not None:
            self.run_config.merge({"weights_for_simulation_string" : capacity_string})
            
        return ChoiceModel.run(self,specification, coefficients, agent_set,
                agents_index=agents_index, chunk_specification=chunk_specification, run_config=self.run_config,
                debuglevel=debuglevel)
Пример #5
0
 def run(self, specification, coefficients, agent_set, agents_index=None, **kwargs):
     hh_to_init_workers = agent_set.compute_variables("_hh_to_init = ((household.workers)==-1)")
     idx_to_init = where(hh_to_init_workers)[0]
     if idx_to_init.size > 0:
         results = ChoiceModel.run(self, specification, coefficients, agent_set, agents_index=idx_to_init, **kwargs)
         agent_set.modify_attribute('workers', results, idx_to_init)
     #Ensure that predicted workers does not exceed # persons who are eligible to work
     workeligible = agent_set.compute_variables('_work_eligible = household.aggregate(person.age>15)')
     agent_set.add_attribute(name='work_eligible', data=agent_set.compute_variables('household.aggregate(person.age>15)'))
     workers_exceeds_eligible = agent_set.compute_variables("_overpredict_workers = ((household.workers) > _work_eligible)")
     idx_excess_workers = where(logical_and(workers_exceeds_eligible,hh_to_init_workers))[0]
     if idx_excess_workers.size > 0:
         agent_set.modify_attribute('workers', workeligible[idx_excess_workers], idx_excess_workers)
     #When a household with 4+ eligible workers is assigned "3+ workers", a more specific number of workers needs to be assigned
     #When household with 4 eligible workers is predicted to have 3+ workers, the household can be assigned 3 workers or 4 workers
     four_eligible_three_predicted = agent_set.compute_variables('_four_eligible_three_predicted = (_work_eligible==4)*((household.workers)==3)')
     idx_four_elig = where(logical_and(four_eligible_three_predicted,hh_to_init_workers))[0]
     if idx_four_elig.size > 0:
         four_numworker_prob = ([.62,.38]) #probabilities from crosstab of base-year workers vs. base-year persons eligible to work
         four_cum_prob = cumsum(four_numworker_prob)
         for hh in idx_four_elig:
             r = uniform(0,1)
             agent_set['workers'][hh] = searchsorted(four_cum_prob, r) + 3
     #When household with 5 eligible workers is predicted to have 3+ workers, the household can be assigned 3, 4, or 5 workers
     five_eligible_three_predicted = agent_set.compute_variables('_five_eligible_three_predicted = (_work_eligible==5)*((household.workers)==3)')
     idx_five_elig = where(logical_and(five_eligible_three_predicted,hh_to_init_workers))[0]
     if idx_five_elig.size > 0:
         five_numworker_prob = ([.44,.33,.23])
         five_cum_prob = cumsum(five_numworker_prob)
         for hh in idx_five_elig:
             r = uniform(0,1)
             agent_set['workers'][hh] = searchsorted(five_cum_prob, r) + 3
     #When household with 6 eligible workers is predicted to have 3+ workers, the household can be assigned 3, 4, 5, or 6 workers
     six_eligible_three_predicted = agent_set.compute_variables('_six_eligible_three_predicted = (_work_eligible==6)*((household.workers)==3)')
     idx_six_elig = where(logical_and(six_eligible_three_predicted,hh_to_init_workers))[0]
     if idx_six_elig.size > 0:
         six_numworker_prob = ([.32,.23,.24,.21])
         six_cum_prob = cumsum(six_numworker_prob)
         for hh in idx_six_elig:
             r = uniform(0,1)
             agent_set['workers'][hh] = searchsorted(six_cum_prob, r) + 3
     #When household with 7+ eligible workers is predicted to have 3+ workers, the household is randomly asssigned a number of workers no less than 3 and no greater than the number of persons eligible to work
     many_eligible_three_predicted = agent_set.compute_variables('_many_eligible_three_predicted = (_work_eligible>6)*((household.workers)==3)')
     idx_many_elig = where(logical_and(many_eligible_three_predicted,hh_to_init_workers))[0]
     if idx_many_elig.size > 0:
         for hh in idx_many_elig:
             agent_set['workers'][hh] = randint(3, ((agent_set['work_eligible'][hh])+1))
     if 'numworker_id' in agent_set.get_primary_attribute_names():
         agent_set.delete_one_attribute('numworker_id')
     agent_set.delete_one_attribute('work_eligible')
 def run(self, specification, coefficients, agent_set, agents_index=None, **kwargs):
     choices = ChoiceModel.run(self, specification, coefficients, agent_set, agents_index=agents_index, **kwargs)
     if agents_index is None:
         agents_index=arange(agent_set.size())
     movers_indices = agents_index[where(choices>0)]
     if self.movers_ratio is not None:
         n = rint(self.movers_ratio*agents_index.size)
         if n < movers_indices.size:
             movers_indices = sample_noreplace(movers_indices, n)
     # add unplaced agents
     unplaced_agents = agents_index[agent_set.get_attribute_by_index(self.location_id_name, agents_index) <= 0]
     logger.log_status("%s agents selected by the logit model; %s agents without %s." % 
                       (movers_indices.size, unplaced_agents.size, self.location_id_name))
     movers_indices = unique(concatenate((movers_indices, unplaced_agents)))
     logger.log_status("Number of movers: " + str(movers_indices.size))
     return movers_indices
    def run(self, agents_index=None, n=500, *args, **kwargs):
        agent_set = self.proposal_set
        if self.filter is not None:
            agents_index = where( self.proposal_set.compute_variables(self.filter) )[0]
            
        choices = ChoiceModel.run(self, agent_set=agent_set, agents_index=agents_index, *args, **kwargs)

        #logger.log_status("%s workers chose to work at home, %s workers chose to work out of home." % 
                          #(where(agent_set.get_attribute_by_index(self.choice_attribute_name, kwargs['agents_index']) == 1)[0].size,
                           #where(agent_set.get_attribute_by_index(self.choice_attribute_name, kwargs['agents_index']) == 2)[0].size))
        #logger.log_status("Total: %s workers work at home, %s workers work out of home." % 
                          #(where(agent_set.get_attribute(self.choice_attribute_name) == 1)[0].size,
                           #where(agent_set.get_attribute(self.choice_attribute_name) == 2)[0].size))

        self.proposal_set.set_values_of_one_attribute('is_chosen', 
                                                      choices, 
                                                      index=agents_index)
 def run(self, specification, coefficients, agent_set,
         agents_index=None, chunk_specification=None,
         data_objects=None, run_config=None, debuglevel=0):
     self.lct_probabilities = {}
     for ichoice in range(self.choice_set.size()):
         probname = "probs_" + str(self.choice_set.get_id_attribute()[ichoice])
         if  probname not in agent_set.get_known_attribute_names():
             agent_set.add_attribute(name=probname, data=zeros(agent_set.size(), dtype=float32))
     result = ChoiceModel.run(self,specification, coefficients, agent_set,
             agents_index=agents_index, chunk_specification=chunk_specification,
             data_objects=data_objects, run_config=run_config,
             debuglevel=debuglevel)
     ## next four lines creates recoded lct (shifts index)....
     changed_idx = where(result>0)[0]
     if agents_index is None:
         agents_index = arange(agent_set.size())
     agent_set.modify_attribute(data=result[changed_idx].astype(int8),
                                 name=self.choice_attribute_name.get_alias(),
                                 index=agents_index[changed_idx]) ## <-------------- lct recode occurs here
     agent_set.compute_variables("biocomplexity.land_cover.lct_recoded")
     return result
Пример #9
0
                          ])
      )

households.add_primary_attribute(data=[1,2,2,2,1,3,3,1,2,1], name="choice_id")

coefficients, other_results = choicemodel.estimate(specification,
                         households, procedure="opus_core.bhhh_mnl_estimation")
                         
#
# Uncomment to output mycoef.tab
#
#coefficients.write(out_storage=storage, out_table_name="mycoef")

from numpy.random import seed
seed(1)
choices = choicemodel.run(
                 specification,  coefficients, households, debuglevel=1)
households.modify_attribute(name="choice_id", data=choices)

from opus_core.coefficients import Coefficients
coefficients = Coefficients(
                     names=array(["beta01", "beta12", "beta03", "beta13"]),
                     values=array([0.5,      0.2,       -5.0,     1.3]))

# LCM
locations = Dataset(in_storage = storage,
                        in_table_name = 'locations', 
                        id_name='location',
                        dataset_name='gridcell')


coefficients = Coefficients(names=("costcoef", ), values=(-0.01,))
Пример #10
0
    def run(self, run_choice_model=True, choose_job_only_in_residence_zone=False, 
            residence_id='zone_id', *args, **kwargs):
        agent_set = kwargs['agent_set']
        agents_index = kwargs.get('agents_index', None)
        if agents_index is None:
            agents_index = arange(agent_set.size())
        if agents_index.size <= 0:
            logger.log_status("Nothing to be done.")
            return
        
        if self.filter is not None:
            jobs_set_index = where( self.job_set.compute_variables(self.filter) )[0]
        else:
            jobs_set_index = arange( self.job_set.size() )
            
        if run_choice_model:
            choices = ChoiceModel.run(self, *args, **kwargs)
            if self.match_number_of_jobs:
                prob_work_at_home = self.upc_sequence.probabilities[:, 1]
                # sample as many workers as there are jobs
                draw = probsample_noreplace(arange(agents_index.size), min(agents_index.size, jobs_set_index.size), 
                                            prob_work_at_home)
                choices = zeros(agents_index.size, dtype='int32')
                choices[draw] = 1
                
            agent_set.set_values_of_one_attribute(self.choice_attribute_name, 
                                                  choices, 
                                                  index=agents_index)
            at_home_worker_index = agents_index[choices==1]
            logger.log_status("%s workers choose to work at home, %s workers chose to work out of home." % 
                              (where(agent_set.get_attribute_by_index(self.choice_attribute_name, agents_index) == 1)[0].size,
                               where(agent_set.get_attribute_by_index(self.choice_attribute_name, agents_index) == 0)[0].size))            
        else:
            at_home_worker_index = where(logical_and( 
                                                     agent_set.get_attribute(self.choice_attribute_name) == 1,
                                                     agent_set.get_attribute('job_id') <= 0
                                                     )
                                        )[0]
        
            
        logger.log_status("Total: %s workers work at home, (%s workers work out of home), will try to assign %s workers to %s jobs." % 
                          (where(agent_set.get_attribute(self.choice_attribute_name) == 1)[0].size,
                           where(agent_set.get_attribute(self.choice_attribute_name) == 0)[0].size,
                          at_home_worker_index.size,
                          jobs_set_index.size
                          ))

        if not choose_job_only_in_residence_zone:
            assigned_worker_index, assigned_job_index = self._assign_job_to_worker(at_home_worker_index, jobs_set_index)
        else:
            agent_set.compute_one_variable_with_unknown_package(residence_id, dataset_pool=self.dataset_pool)
            self.job_set.compute_one_variable_with_unknown_package(residence_id, dataset_pool=self.dataset_pool)
            agent_zone_ids = agent_set.get_attribute_by_index(residence_id, at_home_worker_index)
            job_zone_ids = self.job_set.get_attribute_by_index(residence_id, jobs_set_index)
            unique_zones = unique(job_zone_ids)
            assigned_worker_index = array([], dtype="int32")
            assigned_job_index = array([], dtype="int32")
            for this_zone in unique_zones:
                logger.log_status("%s: %s" % (residence_id, this_zone))
                if this_zone <= 0: continue
                at_home_worker_in_this_zone = where(agent_zone_ids == this_zone)[0]
                job_set_in_this_zone = where(job_zone_ids == this_zone)[0]
                assigned_worker_in_this_zone, assigned_job_set_in_this_zone = self._assign_job_to_worker(at_home_worker_in_this_zone, job_set_in_this_zone)
                assigned_worker_index = concatenate((assigned_worker_index, at_home_worker_index[assigned_worker_in_this_zone]))
                assigned_job_index = concatenate((assigned_job_index, jobs_set_index[assigned_job_set_in_this_zone]))

        ## each worker can only be assigned to 1 job
        #assert assigned_worker_index.size == unique(assigned_worker_index).size
        agent_set.set_values_of_one_attribute(self.job_set.get_id_name()[0], 
                                              self.job_set.get_id_attribute()[assigned_job_index], 
                                              index=assigned_worker_index)
        agent_set.compute_variables([self.location_id_name], dataset_pool=self.dataset_pool)
        self.job_set.modify_attribute(name=VariableName(self.location_id_name).get_alias(), 
                                      data=agent_set.get_attribute_by_index(self.location_id_name, assigned_worker_index),
                                      index=assigned_job_index)
    def run(self,
            run_choice_model=True,
            choose_job_only_in_residence_zone=False,
            *args,
            **kwargs):
        agent_set = kwargs['agent_set']
        if run_choice_model:
            choices = ChoiceModel.run(self, *args, **kwargs)
            #prob_work_at_home = self.upc_sequence.probabilities[:, 0]

            agent_set.set_values_of_one_attribute(self.choice_attribute_name,
                                                  choices,
                                                  index=kwargs['agents_index'])
            at_home_worker_index = kwargs['agents_index'][choices == 1]
            logger.log_status(
                "%s workers choose to work at home, %s workers chose to work out of home."
                % (where(
                    agent_set.get_attribute_by_index(
                        self.choice_attribute_name, kwargs['agents_index']) ==
                    1)[0].size,
                   where(
                       agent_set.get_attribute_by_index(
                           self.choice_attribute_name, kwargs['agents_index'])
                       == 0)[0].size))
        else:
            at_home_worker_index = where(
                logical_and(
                    agent_set.get_attribute(self.choice_attribute_name) == 1,
                    agent_set.get_attribute('job_id') <= 0))[0]

        if self.filter is not None:
            jobs_set_index = where(self.job_set.compute_variables(
                self.filter))[0]
        else:
            jobs_set_index = arange(self.job_set.size())

        logger.log_status(
            "Total: %s workers work at home, (%s workers work out of home), will try to assign %s workers to %s jobs."
            % (where(agent_set.get_attribute(self.choice_attribute_name) ==
                     1)[0].size,
               where(agent_set.get_attribute(self.choice_attribute_name) == 0)
               [0].size, at_home_worker_index.size, jobs_set_index.size))

        if not choose_job_only_in_residence_zone:
            assigned_worker_index, assigned_job_index = self._assign_job_to_worker(
                at_home_worker_index, jobs_set_index)
        else:
            agent_set.compute_variables("urbansim_parcel.person.zone_id")
            self.job_set.compute_variables("urbansim_parcel.job.zone_id")
            agent_zone_ids = agent_set.get_attribute_by_index(
                'zone_id', at_home_worker_index)
            job_zone_ids = self.job_set.get_attribute_by_index(
                'zone_id', jobs_set_index)
            unique_zones = unique(job_zone_ids)
            assigned_worker_index = array([], dtype="int32")
            assigned_job_index = array([], dtype="int32")
            for this_zone in unique_zones:
                logger.log_status("zone_id: %s" % this_zone)
                if this_zone <= 0: continue
                at_home_worker_in_this_zone = where(
                    agent_zone_ids == this_zone)[0]
                job_set_in_this_zone = where(job_zone_ids == this_zone)[0]
                assigned_worker_in_this_zone, assigned_job_set_in_this_zone = self._assign_job_to_worker(
                    at_home_worker_in_this_zone, job_set_in_this_zone)
                assigned_worker_index = concatenate(
                    (assigned_worker_index,
                     at_home_worker_index[assigned_worker_in_this_zone]))
                assigned_job_index = concatenate(
                    (assigned_job_index,
                     jobs_set_index[assigned_job_set_in_this_zone]))

        ## each worker can only be assigned to 1 job
        #assert assigned_worker_index.size == unique(assigned_worker_index).size
        agent_set.set_values_of_one_attribute(
            self.job_set.get_id_name()[0],
            self.job_set.get_id_attribute()[assigned_job_index],
            index=assigned_worker_index)
        agent_set.compute_variables([self.location_id_name],
                                    dataset_pool=self.dataset_pool)
        self.job_set.modify_attribute(
            name=VariableName(self.location_id_name).get_alias(),
            data=agent_set.get_attribute_by_index(self.location_id_name,
                                                  assigned_worker_index),
            index=assigned_job_index)
    def run(self,
            specification,
            coefficients,
            agent_set,
            agents_index=None,
            chunk_specification=None,
            data_objects=None,
            run_config=None,
            debuglevel=0):
        """ Run a simulation and return a numpy array of length agents_index, giving agent choices (ids of locations).
            'specification' is of type EquationSpecification,
            'coefficients' is of type Coefficients,
            'agent_set' is of type Dataset,
            'agent_index' are indices of individuals in the agent_set for which
                        the model runs. If it is None, the whole agent_set is considered.
            'chunk_specification' determines number of chunks in which the simulation is processed.
                        Default is to use 300 rows per chunk.
            'data_objects' is a dictionary where each key is the name of an data object
                    ('zone', ...) and its value is an object of class  Dataset.
            'run_config' is of type Resources, it gives additional arguments for the run.
            'debuglevel' overwrites the constructor 'debuglevel'.
        """
        if run_config == None:
            run_config = Resources()
        self.run_config = run_config.merge_with_defaults(self.run_config)
        if data_objects is not None:
            self.dataset_pool.add_datasets_if_not_included(data_objects)
        self.dataset_pool.add_datasets_if_not_included(
            {agent_set.get_dataset_name(): agent_set})

        ## what is the use of compute location_id string in run? it gets new values anyway
        #if self.location_id_string is not None:
        #    location_id = agent_set.compute_variables(self.location_id_string, dataset_pool=self.dataset_pool)

        ## done in choice_model
        #location_id_name = self.choice_set.get_id_name()[0]
        #if (location_id_name not in agent_set.get_known_attribute_names()):
        #    agent_set.add_attribute(name=location_id_name, data=resize(array([-1]), agent_set.size()))

        if self.run_config.get(
                "agent_units_string", None
        ):  # used when agents take different amount of capacity from the total capacity
            agent_set.compute_variables(
                [self.run_config["agent_units_string"]],
                dataset_pool=self.dataset_pool)

        self.compute_capacity_flag = self.run_config.get(
            "compute_capacity_flag", False)
        capacity_string = None
        self.capacity = None
        if self.compute_capacity_flag:
            capacity_string = self.run_config.get("capacity_string", None)
            if capacity_string is None:
                raise KeyError, \
                    "Entry 'capacity_string' has to be specified in 'run_config' if 'compute_capacity_flag' is True"

        ## if weights is None, use capacity for weights
        if self.run_config.get("weights_for_simulation_string",
                               None) is None and capacity_string is not None:
            self.run_config.merge(
                {"weights_for_simulation_string": capacity_string})

        return ChoiceModel.run(self,
                               specification,
                               coefficients,
                               agent_set,
                               agents_index=agents_index,
                               chunk_specification=chunk_specification,
                               run_config=self.run_config,
                               debuglevel=debuglevel)
Пример #13
0
                          ])
      )

households.add_primary_attribute(data=[1,2,2,2,1,3,3,1,2,1], name="choice_id")

coefficients, other_results = choicemodel.estimate(specification,
                         households, procedure="opus_core.bhhh_mnl_estimation")
                         
#
# Uncomment to output mycoef.tab
#
#coefficients.write(out_storage=storage, out_table_name="mycoef")

from numpy.random import seed
seed(1)
choices = choicemodel.run(
                 specification,  coefficients, households, debuglevel=1)
households.modify_attribute(name="choice_id", data=choices)

from opus_core.coefficients import Coefficients
coefficients = Coefficients(
                     names=array(["beta01", "beta12", "beta03", "beta13"]),
                     values=array([0.5,      0.2,       -5.0,     1.3]))

# LCM
locations = Dataset(in_storage = storage,
                        in_table_name = 'locations', 
                        id_name='location',
                        dataset_name='gridcell')


coefficients = Coefficients(names=("costcoef", ), values=(-0.01,))