Execute a single model iteration

        :return: Iteration_id, Incremental node status (dictionary node->status)
195866
def iteration(self, node_status=True):
        
        # One iteration changes the opinion of N agent pairs using the following procedure:
        # - first one agent is selected
        # - then a second agent is selected based on a probability that decreases with the distance to the first agent
        # - if the two agents have a distance smaller than epsilon, then they change their status to the average of
        # their previous statuses

        self.clean_initial_status(None)

        actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)}

        if self.actual_iteration == 0:
            self.actual_iteration += 1
            delta, node_count, status_delta = self.status_delta(self.status)
            if node_status:
                return {"iteration": 0, "status": self.status.copy(),
                        "node_count": node_count.copy(), "status_delta": status_delta.copy()}
            else:
                return {"iteration": 0, "status": {},
                        "node_count": node_count.copy(), "status_delta": status_delta.copy()}

        # interact with peers
        for i in range(0, self.graph.number_of_nodes()):
            # select a random node
            n1 = list(self.graph.nodes())[np.random.randint(0, self.graph.number_of_nodes())]
            # select all of the node's neighbours (no digraph possible)
            neighbours = list(self.graph.neighbors(n1))
            if len(neighbours) == 0:
                continue
        
            # compute probabilities to select a second node among the neighbours
            selection_prob = np.array([self.prob(np.abs(actual_status[neighbours[i]]-actual_status[n1]),
                                               self.params['model']['gamma'],0.00001) for i in range(len(neighbours))])
            selection_prob = selection_prob/np.sum(selection_prob)
            cumulative_selection_probability = np.cumsum(selection_prob)

            # select second nodebased on selection probabilities above
            r = np.random.random_sample()
            n2 = 0
            while cumulative_selection_probability[n2] < r:
                n2 = n2+1

            n2 = neighbours[n2]
            # update status of n1 and n2
            diff = np.abs(actual_status[n1]-actual_status[n2])
            if diff < self.params['model']['epsilon']:
                avg = (actual_status[n1]+actual_status[n2])/2.0
                actual_status[n1] = avg
                actual_status[n2] = avg
            
        delta, node_count, status_delta = self.status_delta(actual_status)
        self.status = actual_status
        self.actual_iteration += 1

        if node_status:
            return {"iteration": self.actual_iteration - 1, "status": delta.copy(),
                    "node_count": node_count.copy(), "status_delta": status_delta.copy()}
        else:
            return {"iteration": self.actual_iteration - 1, "status": {},
                    "node_count": node_count.copy(), "status_delta": status_delta.copy()}
516193
def _on_iteration(self, *args, **kwargs) -> None:
        

        # Update timing and the iteration number in the monitoring context.
        current_timestamp = get_hr_time()
        self._context.optimisation_time += current_timestamp - self._last_timestamp
        self._context.total_time = current_timestamp - self._start_timestamp
        self._context.optimiser_updated = False
        if not self._context.optimisation_finished:
            self._context.iteration_no += 1

        # Call all monitoring functions
        for func in self._monitor_tasks:
            func(self._context, *args, **kwargs)

        # Remember the time when the control is returned back to the optimiser, so that the next
        # optimisation step can be accurately timed.
        self._last_timestamp = get_hr_time()
8306
def on_backward_end(self, iteration:int, **kwargs)->None:
        ""
        if iteration == 0: return
        self._update_batches_if_needed()
        #TODO:  This could perhaps be implemented as queues of requests instead but that seemed like overkill. 
        # But I'm not the biggest fan of maintaining these boolean flags either... Review pls.
        if iteration % self.stats_iters == 0: self.gen_stats_updated, self.crit_stats_updated = False, False
        if not (self.gen_stats_updated and self.crit_stats_updated): self._write_model_stats(iteration=iteration)
362746
def create_iteration(self, num_suggestions):
        """"""
        from db.models.experiment_groups import ExperimentGroupIteration

        iteration_config = BaseIterationConfig(iteration=0,
                                               num_suggestions=num_suggestions,
                                               experiment_ids=[])

        return ExperimentGroupIteration.objects.create(
            experiment_group=self.experiment_group,
            data=iteration_config.to_dict())
341260
def _run_custom_data_engine(self, start_id_obj, end_id_obj, start_timeperiod, end_timeperiod):
        
        collection_name = context.process_context[self.process_name].source
        iteration = 0
        while True:
            cursor = self.ds.cursor_fine(collection_name,
                                         start_id_obj,
                                         end_id_obj,
                                         iteration,
                                         start_timeperiod,
                                         end_timeperiod)

            if iteration == 0 and cursor.count(with_limit_and_skip=True) == 0:
                msg = 'No entries in {0} at range [{1} : {2}]'.format(collection_name, start_id_obj, end_id_obj)
                self.logger.warning(msg)
                break

            start_id_obj = None
            for document in cursor:
                start_id_obj = document['_id']
                self._process_single_document(document)
                self.performance_tracker.increment_success()
            if start_id_obj is None:
                break
            iteration += 1

        self._cursor_exploited()
        msg = 'Cursor exploited after {0} iterations'.format(iteration)
        self.logger.info(msg)
1366303
def run_iteration
      param_key = @current_params.to_s
      result = nil
      # lookup the result if possible
      if @scores.key? param_key
        result = @scores[param_key]
      else
        # create temp dir
        curdir = Dir.pwd
        Dir.chdir(self.create_tempdir) unless Settings.instance.no_tempdirs
        # run the target
        raw_output = @target.run @current_params.merge(@options)
        # evaluate with objectives
        result = @objective.run_for_output(raw_output, @threads, nil)
        @iteration_count += 1
        self.print_progress(@iteration_count, @current_params, result, @best)
        @scores[@current_params.to_s] = result
        self.cleanup
        Dir.chdir(curdir) unless Settings.instance.no_tempdirs
      end
      # get next steps from optimiser
      @current_params = @algorithm.run_one_iteration(@current_params, result)
    end
1192060
public static function array_next_element($arr, $nested_key, $iteration = 1)
    {
        foreach ($arr as $key => $v) {
            current($arr);

            if ($key == $nested_key) {
                for ($i = 0; $i < $iteration; $i++) {
                    $return = next($arr);
                }

                if (!empty($return)) {
                    return $return;
                } else {
                    return false;
                }
            }

            next($arr);
        }

        return false;
    }
906873
def iteration(self, node_status=True):
        

        # One iteration changes the opinion of at most q voters using the following procedure:
        # - select randomly q voters
        # - compute majority opinion
        # - if tie all agents take opinion +1
        # - if not tie, all agents take majority opinion

        self.clean_initial_status(self.available_statuses.values())

        if self.actual_iteration == 0:
            self.actual_iteration += 1
            delta, node_count, status_delta = self.status_delta(self.status)
            if node_status:
                return {"iteration": 0, "status": self.status.copy(),
                        "node_count": node_count.copy(), "status_delta": status_delta.copy()}
            else:
                return {"iteration": 0, "status": {},
                        "node_count": node_count.copy(), "status_delta": status_delta.copy()}

        # select q random nodes
        discussion_group = [list(self.graph.nodes())[i]
                            for i in np.random.randint(0, self.graph.number_of_nodes(), self.params['model']['q'])]

        # compute majority
        majority_vote = 1
        vote_sum = sum([self.status[node] for node in discussion_group])
        if vote_sum < (self.params["model"]["q"] / 2.0):
            majority_vote = 0  # in case of tie, majority_vote remains 1

        # update status of nodes in discussion group
        delta = {}
        status_delta = {st: 0 for st in self.available_statuses.values()}

        for listener in discussion_group:
            if majority_vote != self.status[listener]:
                delta[listener] = majority_vote

                status_delta[self.status[listener]] += 1
                for x in self.available_statuses.values():
                    if x != self.status[listener]:
                        status_delta[x] -= 1

            self.status[listener] = majority_vote

        # fix
        node_count = {st: len([n for n in self.status if self.status[n] == st])
                      for st in self.available_statuses.values()}

        self.actual_iteration += 1

        if node_status:
            return {"iteration": self.actual_iteration - 1, "status": delta.copy(),
                    "node_count": node_count.copy(), "status_delta": status_delta.copy()}
        else:
            return {"iteration": self.actual_iteration - 1, "status": {},
                    "node_count": node_count.copy(), "status_delta": status_delta.copy()}
258160
def run(self):
        
        if self.is_root_state:
            self.execution_history.push_call_history_item(self, CallType.EXECUTE, None, self.input_data)

        logger.debug("Running {0}{1}".format(self, " (backwards)" if self.backward_execution else ""))
        if self.backward_execution:
            self.setup_backward_run()
        else:
            self.setup_run()

        try:
            outcome = self._execute(self.input_data, self.output_data, self.backward_execution)
            self.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE

            if self.backward_execution:
                # outcome handling is not required as we are in backward mode and the execution order is fixed
                result = self.finalize()
            else:
                # check output data
                self.check_output_data_type()
                result = self.finalize(outcome)

            if self.is_root_state:
                self.execution_history.push_return_history_item(self, CallType.EXECUTE, None, self.output_data)
            return result
        except Exception as e:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            formatted_exc = traceback.format_exception(exc_type, exc_value, exc_traceback)
            truncated_exc = []
            for line in formatted_exc:
                if os.path.join("rafcon", "core") not in line:
                    truncated_exc.append(line)
            logger.error("{0} had an internal error: {1}: {2}\n{3}".format(self, type(e).__name__, e,
                                                                           ''.join(truncated_exc)))
            # write error to the output_data of the state
            self.output_data["error"] = e
            self.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE
            return self.finalize(Outcome(-1, "aborted"))
446341
def refresh(self):
        
        self._pre_action_check('refresh')
        if hasattr(self, 'id'):
            request = self.cypher("MATCH (n) WHERE id(n)={self}"
                                            " RETURN n")[0]
            if not request or not request[0]:
                raise self.__class__.DoesNotExist("Can't refresh non existent node")
            node = self.inflate(request[0][0])
            for key, val in node.__properties__.items():
                setattr(self, key, val)
        else:
            raise ValueError("Can't refresh unsaved node")
613990
def ids_from_seqs_iterative(seqs, app, query_parser, \
    scorer=keep_everything_scorer, max_iterations=None, blast_db=None,\
    max_seqs=None, ):
    
    if isinstance(scorer, int):
        scorer = make_shotgun_scorer(scorer)
    seqs_to_check = list(seqs)
    checked_ids = {}
    curr_iteration = 0
    while seqs_to_check:
        unchecked_ids = {}
        #pass seqs to command
        all_output = app(seqs_to_check)
        output = all_output.get('BlastOut', all_output['StdOut'])

        for query_id, match_id, match_score in query_parser(output):
            if query_id not in checked_ids:
                checked_ids[query_id] = {}
            checked_ids[query_id][match_id] = match_score
            if match_id not in checked_ids:
                unchecked_ids[match_id] = True
        all_output.cleanUp()
        if unchecked_ids:
            seq_file = fasta_cmd_get_seqs(unchecked_ids.keys(),
                app.Parameters['-d'].Value)['StdOut']
            seqs_to_check = []
            for s in FastaCmdFinder(fasta_cmd_get_seqs(\
                unchecked_ids.keys(), app.Parameters['-d'].Value)['StdOut']):
                seqs_to_check.extend(s)
        else:
            seqs_to_check = []
        #bail out if max iterations or max seqs was defined and we've reached it
        curr_iteration += 1
        if max_iterations and (curr_iteration >= max_iterations):
            break
        if max_seqs:
            curr = scorer(checked_ids)
            if len(curr) >= max_seqs:
                return curr
    return scorer(checked_ids)
812087
def run(self, n_iterations=1, min_n_workers=1, iteration_kwargs = {},):
		

		self.wait_for_workers(min_n_workers)
		
		iteration_kwargs.update({'result_logger': self.result_logger})

		if self.time_ref is None:
			self.time_ref = time.time()
			self.config['time_ref'] = self.time_ref
		
			self.logger.info('HBMASTER: starting run at %s'%(str(self.time_ref)))

		self.thread_cond.acquire()
		while True:

			self._queue_wait()
			
			next_run = None
			# find a new run to schedule
			for i in self.active_iterations():
				next_run = self.iterations[i].get_next_run()
				if not next_run is None: break

			if not next_run is None:
				self.logger.debug('HBMASTER: schedule new run for iteration %i'%i)
				self._submit_job(*next_run)
				continue
			else:
				if n_iterations > 0:	#we might be able to start the next iteration
					self.iterations.append(self.get_next_iteration(len(self.iterations), iteration_kwargs))
					n_iterations -= 1
					continue

			# at this point there is no imediate run that can be scheduled,
			# so wait for some job to finish if there are active iterations
			if self.active_iterations():
				self.thread_cond.wait()
			else:
				break

		self.thread_cond.release()
		
		for i in self.warmstart_iteration:
			i.fix_timestamps(self.time_ref)
			
		ws_data = [i.data for i in self.warmstart_iteration]
		
		return Result([copy.deepcopy(i.data) for i in self.iterations] + ws_data, self.config)
500903
def create_iteration(self, num_suggestions):
        """"""
        from db.models.experiment_groups import ExperimentGroupIteration

        iteration_config = self.experiment_group.iteration_config

        if iteration_config is None:
            iteration = 0
            old_experiment_ids = None
            old_experiments_configs = None
            old_experiments_metrics = None
        else:
            iteration = iteration_config.iteration + 1
            old_experiment_ids = iteration_config.combined_experiment_ids
            old_experiments_configs = iteration_config.combined_experiments_configs
            old_experiments_metrics = iteration_config.combined_experiments_metrics

        # Create a new iteration config
        iteration_config = BOIterationConfig(
            iteration=iteration,
            num_suggestions=num_suggestions,
            old_experiment_ids=old_experiment_ids,
            old_experiments_configs=old_experiments_configs,
            old_experiments_metrics=old_experiments_metrics,
            experiment_ids=[],
            experiments_configs=[],
        )
        return ExperimentGroupIteration.objects.create(
            experiment_group=self.experiment_group,
            data=iteration_config.to_dict())
1290218
def get_statuses(self, batch_ids):
        
        with self._lock:
            return {b: self.get_status(b) for b in batch_ids}
186416
def iterate(self):
        
        self.counter += 1
        self.counter0 += 1
        self.revcounter -= 1
        self.revcounter0 -= 1
        self.first = False
        self.last = (self.revcounter0 == self.len_values - 1)
120791
def iter_ancestors(self):
        
        node = self
        while node.up is not None:
            yield node.up
            node = node.up
1322018
def node_state(id_):
    '''
    
    '''
    states_int = {
        0: 'RUNNING',
        1: 'REBOOTING',
        2: 'TERMINATED',
        3: 'PENDING',
        4: 'UNKNOWN',
        5: 'STOPPED',
        6: 'SUSPENDED',
        7: 'ERROR',
        8: 'PAUSED'}
    states_str = {
        'running': 'RUNNING',
        'rebooting': 'REBOOTING',
        'starting': 'STARTING',
        'terminated': 'TERMINATED',
        'pending': 'PENDING',
        'unknown': 'UNKNOWN',
        'stopping': 'STOPPING',
        'stopped': 'STOPPED',
        'suspended': 'SUSPENDED',
        'error': 'ERROR',
        'paused': 'PAUSED',
        'reconfiguring': 'RECONFIGURING'
    }
    return states_str[id_] if isinstance(id_, six.string_types) else states_int[id_]