def add_bin_data(self, s): d = {} rr = set() a = s.split('\n') for i in a: j = i.split('|') if len(j) < 3: continue rr.add(j[0]) k = '%s.%d' % (j[0], int(j[1])) if k in d: print('%s ???' % k) continue d[k] = Obj(name=j[2]) if j[3] != '' if len(j) >= 4 else False: gg = j[3].split(':') d[k].grayed = bool(int(gg[0])) if len(gg) > 1: base = 10 if gg[1][0:2] == '0x': base = 16 d[k].value = int(gg[1], base) if j[4] != '' if len(j) >= 5 else False: d[k].msg = j[4] #kk = sorted(list(rr), key=lambda r: int(r[1:], 16)) kk = list(self['hex'].keys()) for r in kk: rk = list(filter(lambda x: x.find(r + '.') == 0, d.keys())) f = lambda k: int(k.split('.')[-1]) rk = sorted(rk, key=f) self.add_page(r) for j in rk: self.add_bits(f(j), finalize=(j == rk[-1]), **d[j]) return kk
def get_val(self, **kwargs): """ Evaluate the dependent parameter as a function of the other parameters for the namespace. @param kwargs: the parameters to be used as input to the dependent variable """ return self.func(Obj(**kwargs))
def scdp_cb1(self): if not self.get_data: return False cmd = dev_io_cb(self.data.dev, 'dispose') obj = Obj(cmdid='tmp', cmd=cmd, dev=self.data.dev, srv=self.data.dev[c_server]) self.io.qo.put(obj) return True
def init_calc(self, f, prefix1='calc', prefix2=None): ncalc = 0 if self.standalone: for k, v in self.data.iterkw(prefix1, prefix2): self.add_row(v, f) ncalc += 1 if ncalc == 0: self.add_row( { 'label1': Obj(label='.'.join( [self.data.dev['name'], self.data.dev['type']])) }, f)
def simulate(self, num_gens=DEFAULT_GENERATIONS, pop_size=100, start_state=None, graph=True, return_labeled=True, burn=0, class_end=False, frac_invasions=False, strategy_indx=0): """ Simulate a game in the presence of group selection for a specific number of generations optionally graphing the results @param num_gens: the number of iterations of the simulation. @type num_gens: int @param group_size: Fixed population in each group. @type group_size: int @param rate: Rate of group selection vs individual selection @type rate: float @param start_state: whether the starting state is to be predetermined @type start_state: list @param graph: the type of graph (false if no graph is wished) @type graph: dict, bool @param return_labeled: whether the distribution of classified equilibria that are returned should be labelled or simply listed with their keys inferred by their order @type return_labeled: bool @param class_end: if False the equilibria are classified at all generations and if True only the last generation is classified. @type class_end: bool @param frac_invasions: Whether the given simulation is to compute the fraction of invasions for a strategy. @type: bool @param strategy_indx: The index of the strategy whose fraction of invasions is to be computed @type strategy_indx: int @return: the frequency of time spent in each equilibria, defined by the game @rtype: numpy.ndarray or dict TO DO: Explain what 'burn' does """ game = self.game_cls(**self.game_kwargs) dyn = self.dynamics_cls(payoff_matrix=game.pm, player_frequencies=game.player_frequencies, pop_size=pop_size, **self.dynamics_kwargs) # Group Selection simulation for a given number of generations. results_total, payoffs_total = dyn.simulate(num_gens, start_state, frac_invasions, strategy_indx) # Classify the equilibria and plot the results params = Obj(**self.game_kwargs) frequencies = np.zeros(self.game_cls.num_equilibria() ) # one extra for the Unclassified key if dyn.stochastic: classifications = [] if class_end: # Only classify the final generation lastGenerationState = [ np.zeros(len(player[0])) for player in results_total ] for playerIdx, player in enumerate(results_total): for stratIdx, strat in enumerate(player[-1]): lastGenerationState[playerIdx][stratIdx] = strat lastGenerationState[playerIdx] /= lastGenerationState[ playerIdx].sum() equi = game.classify(params, lastGenerationState, game.equilibrium_tolerance) frequencies = np.zeros(self.game_cls.num_equilibria()) frequencies[equi] = 1 else: # Classify every generation for state in zip(*results_total): state = [x / x.sum() for x in state] equi = game.classify(params, state, game.equilibrium_tolerance) # note, if equi returns -1, then the -1 index gets the last entry in the array classifications.append(equi) frequencies[equi] += 1 else: last_generation_state = [results_total[-1][-1]] classification = game.classify(params, last_generation_state, game.equilibrium_tolerance) frequencies[classification] = 1 if graph: setupGraph(graph, game, dyn, burn, num_gens, results_total, payoffs_total) else: if return_labeled: return self._convert_equilibria_frequencies(frequencies) else: return frequencies, results_total, payoffs_total
def simulate(self, num_gens=DEFAULT_GENERATIONS, graph=True, burn=0, return_labeled=True, start_state=None, class_end=False): """ Simulate the game for the given number of generations with the specified dynamics class and optionally graph the results @param num_gens: the number of iterations of the simulation. @type num_gens: int @param graph: the type of graph (false if no graph is wished) @type graph: dict, bool @param return_labeled: whether the distribution of classified equilibria that are returned should be labelled or simply listed with their keys inferred by their order @type return_labeled: bool @param start_state: whether the starting state is to be predeterined @type start_state: list @param graph_payoffs: to graph the payoffs for each generation @type graph_payoffs: bool @param graph_payoff_line: to show the dominate strategy for each generation of the game underneath the graph @type graph_payoff_line: bool @return: the frequency of time spent in each equilibria, defined by the game @rtype: numpy.ndarray or dict """ game = self.game_cls(**self.game_kwargs) dyn = self.dynamics_cls(payoff_matrix=game.pm, player_frequencies=game.player_frequencies, **self.dynamics_kwargs) results, payoffs = dyn.simulate(num_gens=num_gens, debug_state=start_state) # results_obj = SingleSimulationOutcome(self.dynamics_cls, self.dynamics_kwargs, self.game_cls, self.game_kwargs, results) # TODO: serialize results to file params = Obj(**self.game_kwargs) frequencies = numpy.zeros(self.game_cls.num_equilibria() ) # one extra for the Unclassified key for playerIdx, player in enumerate(payoffs): payoffs[playerIdx] = numpy.delete(player, (0), axis=0) if burn: for index, array in enumerate(results): results[index] = array[burn:] if dyn.stochastic: classifications = [] if class_end: # Only classify the final generation lastGenerationState = [ numpy.zeros(len(player[0])) for player in results ] for playerIdx, player in enumerate(results): for stratIdx, strat in enumerate(player[-1]): lastGenerationState[playerIdx][stratIdx] = strat lastGenerationState[playerIdx] /= lastGenerationState[ playerIdx].sum() equi = game.classify(params, lastGenerationState, game.equilibrium_tolerance) frequencies = numpy.zeros(self.game_cls.num_equilibria()) frequencies[equi] = 1 else: # Classify every generation for state in zip(*results): state = [x / x.sum() for x in state] equi = game.classify(params, state, game.equilibrium_tolerance) # note, if equi returns -1, then the -1 index gets the last entry in the array classifications.append(equi) frequencies[equi] += 1 else: last_generation_state = results[-1] classification = game.classify(params, last_generation_state, game.equilibrium_tolerance) frequencies[classification] = 1 if graph: setupGraph(graph, game, dyn, burn, num_gens, results, payoffs) else: if return_labeled: return self._convert_equilibria_frequencies(frequencies) else: return frequencies, results, payoffs
def validate_classifier(cls, timeout=None, tolerance=0.05, **kwargs): game_kwargs = cls.DEFAULT_PARAMS game_kwargs.update(kwargs) g = cls(**game_kwargs) params = Obj(**game_kwargs) def generate_state_from_pure_strategy(p_idx, n_strategies): s = numpy.zeros((n_strategies, )) s[p_idx] = 1.0 return s def convert_state(s): return [{ cls.STRATEGY_LABELS[j][i]: s_i[i] for i in range(len(s_i)) if s_i[i] > 0 } for j, s_i in enumerate(s)] false_negatives = [] false_positives = [] n_players = g.pm.num_player_types # 1. first validate all pure strategy equilibria (non mixed) by iterating through all permutations of all strategies for perm in g.pm.get_all_strategy_tuples(): assert len(perm) == n_players state = [] for i, s in enumerate(perm): state.append( generate_state_from_pure_strategy(s, g.pm.num_strats[i])) eq = cls.classify(params, state, tolerance) is_eq = g.pm.is_pure_equilibrium(perm) if is_eq == True: if eq == -1: false_negatives.append(state) else: profitable_deviation = is_eq if eq != -1: false_positives.append((state, eq, profitable_deviation)) def print_results(false_negatives, false_positives, kwargs, num_sims): output = StringIO.StringIO() print >> output, 'Parameters: %s' % kwargs print >> output, 'Total states tried: %d' % num_sims print >> output, "# False negatives: %d" % len(false_negatives) print >> output, "# False positives: %d" % len(false_positives) if len(false_negatives) > 0: print >> output, "False negatives:" for fn in false_negatives: print >> output, convert_state(fn) if len(false_positives) > 0: print >> output, "False positives:" for state, eq, p_dev in false_positives: first = 'State: %s, Classification: %s. ' % ( convert_state(state), cls.EQUILIBRIA_LABELS[eq]) if p_dev[0]: # mixed strategy deviation second = 'Profitable deviation: player %d - strategies (%s:%f, %s:%f) don\'t have same exp payoff' % ( p_dev[1], cls.STRATEGY_LABELS[p_dev[1]][p_dev[2][0][0]], p_dev[2][0][1], cls.STRATEGY_LABELS[p_dev[1]][p_dev[2][1][0]], p_dev[2][1][1]) else: # pure strategy deviation second = 'Profitable deviation: player %d - %s' % ( p_dev[1], cls.STRATEGY_LABELS[p_dev[1]][p_dev[2]]) print >> output, first + second fd, name = tempfile.mkstemp(suffix='.txt') os.write(fd, output.getvalue()) os.close(fd) return name def generate_strat_mixins(n_strats, p_i, prefix): if len(prefix) == n_strats: yield prefix return if (p_i, len(prefix)) in g.pm.dominated_strategies: choices = [False] else: choices = [False, True] for c in choices: for mix in generate_strat_mixins(n_strats, p_i, prefix + (c, )): if any(mix): yield mix # for all players, generate all possible mixes of available strategies that are not dominated strategies strategy_permutations = [] for p_i in range(n_players): n_strats = g.pm.num_strats[p_i] strategy_permutations.append( list(generate_strat_mixins(n_strats, p_i, ()))) product = itertools.product(*strategy_permutations) product = list(product) # TODO: filter out any mixes over strategies that have the same payoff for all players def mix_over_strategies(s_tuple): n = sum(int(x) for x in s_tuple) r = numpy.random.dirichlet([1] * n) mix_idx = 0 state_partition = numpy.zeros((len(s_tuple, ))) for i, should_mix in enumerate(s_tuple): if should_mix: state_partition[i] = r[mix_idx] mix_idx += 1 return state_partition # start the timer start = time.time() # while the timer hasn't run out ATTEMPTS_PER_PERMUTATION = 10 def should_end(): if timeout is None: return False else: return time.time() - start > timeout def do_work(): permutations = 0 while not should_end(): for i in range(ATTEMPTS_PER_PERMUTATION): for perm in product: permutations += 1 # if none are mixed strategies, then skip mixed = False for s_tuple in perm: n = sum(int(x) for x in s_tuple) if n > 1: mixed = True if not mixed: continue state = [ mix_over_strategies(player_strats) for player_strats in perm ] eq = cls.classify(params, state, tolerance) is_eq = g.pm.is_mixed_equilibrium(state) if is_eq == True: if eq == -1: false_negatives.append(state) else: profitable_deviation = is_eq if eq != -1: false_positives.append( (state, eq, profitable_deviation)) return permutations num_sims = do_work() output_file = print_results(false_negatives, false_positives, game_kwargs, num_sims) print('Saved results to file: %s' % output_file)
# -*- coding: utf-8 -*- # @Author: Arius # @Email: [email protected] # @Date: 2019-01-23 16:10:52 from util import Obj mysql = Obj({ 'host': '127.0.0.1', 'usr': '******', 'pwd': 'ForAiur!1', 'db': 'Khala', }) redis = Obj({ 'host': '127.0.0.1', 'port': '6379', 'db': 9, }) # default config secret = Obj({ 'jwt': 'aiur_world', 'sig': 'link', }) tables = Obj({ 'usr': '******', 'room': 'Room', 'join': 'Join',
def simulate(self, num_gens=DEFAULT_GENERATIONS, graph=True, return_labeled=True): """ Simulate the game for the given number of generations with the specified dynamics class and optionally graph the results @param num_gens: the number of iterations of the simulation. @type num_gens: int @param graph: whether or not the results should be graphed @type graph: bool @param return_labeled: whether the distribution of classified equilibria that are returned should be labelled or simply listed with their keys inferred by their order @type return_labeled: bool @return: the frequency of time spent in each equilibria, defined by the game @rtype: numpy.ndarray or dict """ game = self.game_cls(**self.game_kwargs) dyn = self.dynamics_cls(payoff_matrix=game.pm, player_frequencies=game.player_frequencies, **self.dynamics_kwargs) results = dyn.simulate(num_gens=num_gens) #results_obj = SingleSimulationOutcome(self.dynamics_cls, self.dynamics_kwargs, self.game_cls, self.game_kwargs, results) # TODO: serialize results to file params = Obj(**self.game_kwargs) frequencies = numpy.zeros(self.game_cls.num_equilibria() ) # one extra for the Unclassified key if dyn.stochastic: classifications = [] for state in zip(*results): state = [x / x.sum() for x in state] equi = game.classify(params, state, game.equilibrium_tolerance) # note, if equi returns -1, then the -1 index gets the last entry in the array classifications.append(equi) frequencies[equi] += 1 else: last_generation_state = results[-1] classification = game.classify(params, last_generation_state, game.equilibrium_tolerance) frequencies[classification] = 1 if graph: graph_options = {} if game.STRATEGY_LABELS is not None: graph_options[ GraphOptions. LEGEND_LABELS_KEY] = lambda p, s: game.STRATEGY_LABELS[p][s ] if game.PLAYER_LABELS is not None: graph_options[ GraphOptions.TITLE_KEY] = lambda p: game.PLAYER_LABELS[p] graph_options[GraphOptions.NO_MARKERS_KEY] = True plot_data_for_players(results, range(num_gens), "Generation #", dyn.pm.num_strats, num_players=dyn.num_players, graph_options=graph_options) else: if return_labeled: return self._convert_equilibria_frequencies(frequencies) else: return frequencies