def RandomGraph(nodes=list(range(10)), min_links=2, width=400, height=300, curvature=lambda: random.uniform(1.1, 1.5)): """Construct a random graph, with the specified nodes, and random links. The nodes are laid out randomly on a (width x height) rectangle. Then each node is connected to the min_links nearest neighbors. Because inverse links are added, some nodes will have more connections. The distance between nodes is the hypotenuse times curvature(), where curvature() defaults to a random number between 1.1 and 1.5.""" g = UndirectedGraph() g.locations = {} # Build the cities for node in nodes: g.locations[node] = (random.randrange(width), random.randrange(height)) # Build roads from each city to at least min_links nearest neighbors. for i in range(min_links): for node in nodes: if len(g.get(node)) < min_links: here = g.locations[node] def distance_to_node(n): if n is node or g.get(node, n): return infinity return distance(g.locations[n], here) neighbor = argmin(nodes, key=distance_to_node) d = distance(g.locations[neighbor], here) * curvature() g.connect(node, neighbor, int(d)) return g
def determine_optimum_variants(unit1, unit2): """Determines the optimum variants between two units.""" # TODO - improve performance by considering variants (1,1) (1, 2) and (2,1) # as equivalent. outcomes = defaultdict(dict) for v1 in MeleeRangedStrategy.VARIANTS: if not MeleeRangedStrategy.is_compatible(unit1, v1): continue unit1.strategy = MeleeRangedStrategy(unit1, v1) for v2 in MeleeRangedStrategy.VARIANTS: if not MeleeRangedStrategy.is_compatible(unit2, v2): continue unit2.strategy = MeleeRangedStrategy(unit2, v2) turn_order = (unit1, unit2) game_state = AveragingVersusGameState(turn_order, verbosity=0) game_state.run_combat() outcomes[v1][v2] = game_state.hp_delta # What's your best strategy? unit_1_strategies = { v1: min(outcomes[v1].values()) for v1 in outcomes } unit1_strategy = utils.argmax(unit_1_strategies) unit2_strategy = utils.argmin(outcomes[unit1_strategy]) # for v1 in outcomes: # for v2, hp_delta in sorted(outcomes[v1].items()): # print '(%d, %d) => %+.2f' % (v1, v2, hp_delta) # print '%s\'s strategy: %s' % (unit1, unit1_strategy) # print '%s\'s strategy: %s' % (unit2, unit2_strategy) return (unit1_strategy, unit2_strategy)
def buildMonthFr( text ): "Return the month number out of the french month name in `text`." scores = map( partialCostLambda(text), monthsFrRE ) best = argmin( scores ) if best < 0 or scores[best] == float("inf"): raise Exception("Could not find a satisfying month value for %s" % text ) if best == 0: best = 12 return best
def run(self, evaluator): results = list(self.map(evaluator.eval, self.params)) self.best_result = np.min(results) self.best_params = self.params[argmin(results)] return self.best_params, self.best_result
def sample_motif_with_ic(n,L): matrix = sample_matrix(L,sigma=1) ringer_site = "".join(["ACGT"[argmin(col)] for col in matrix]) mu = approximate_mu(matrix,10*n,G=5*10**6) Nes = range(2,10) trials = 10 motifs = [[sample_motif_mh(matrix, mu, Ne, n) for t in range(trials)] for Ne in tqdm(Nes)]
def trim(self): """Merge adjacent bins to decrease bin count to the maximum value. This method implements Steps 5-6 from Algorithm 1 (Update) in ref [1]. """ while len(self.bins) > self.maxbins: index = argmin(bin_diff(self.bins, self.weighted)) prv = self.bins.pop(index) self.bins[index] += prv return self
def query(self, query_text, n=10): """Return a list of n (score, docid) pairs for the best matches. Also handle the special syntax for 'learn: command'.""" if query_text.startswith("learn:"): doctext = os.popen(query_text[len("learn:"):], 'r').read() self.index_document(doctext, query_text) return [] qwords = [w for w in words(query_text) if w not in self.stopwords] shortest = argmin(qwords, key=lambda w: len(self.index[w])) docids = self.index[shortest] return heapq.nlargest(n, ((self.total_score(qwords, docid), docid) for docid in docids))
def sample_motif_mh(matrix, mu, Ne, N, iterations=None): nu = Ne - 1 L = len(matrix) if iterations is None: iterations = 10*L phat = lambda ep:(1/(1+exp(ep-mu)))**(nu) best_site = "".join(["ACGT"[argmin(col)] for col in matrix]) def f(site): ep = score_seq(matrix, site) return phat(ep) def sample_site(): return mh(f, mutate_site, best_site, iterations=10*L, verbose=0)[-1] return [sample_site() for i in range(N)]
def sample_site_cftp_dep(matrix, mu, Ne): L = len(matrix) def log_phat(s): ep = score_seq(matrix,s) nu = Ne - 1 return -nu*log(1 + exp(ep - mu)) first_site = "A"*L last_site = "T"*L best_site = "".join(["ACGT"[argmin(row)] for row in matrix]) worst_site = "".join(["ACGT"[argmax(row)] for row in matrix]) trajs = [[best_site],[random_site(L)],[random_site(L)],[random_site(L)], [worst_site]] def mutate_site(site,(ri,rb)): return subst(site,"ACGT"[rb],ri)
def alg_list(): with open(sys.argv[1], 'r') as file: n = load_line(file)[0] tasks = [Task(*load_line(file), i) for i in range(n)] tasks = sorted(tasks, key=lambda task: task.r) schedules = [[], [], [], []] timers = [0, 0, 0, 0] criterium = 0 awaiting = [] counter = 0 it = 0 while True: timerId = argmin(timers) if it != n: for i in range(it, n): if tasks[i].r <= timers[timerId]: awaiting += [tasks[i]] else: it = i break else: it = n if not awaiting: timers[timerId] = tasks[it].r for i in range(it, n): if tasks[i].r <= timers[timerId]: awaiting += [tasks[i]] else: it = i break else: it = n awaiting.sort(key=lambda task: (min(0, timers[timerId] + task.p - task.d), -task.p)) popped = awaiting.pop() schedules[timerId] += [popped] timers[timerId] = max(timers[timerId], popped.r) + popped.p criterium += max(0, timers[timerId] - popped.d) counter += 1 if counter == n: break with open(sys.argv[2], 'w') as output: output.write( str(criterium) + '\n' + '\n'.join([ ' '.join([str(task.i + 1) for task in schedule]) for schedule in schedules ]))
def min_value(node): if game.terminal_test(node): return game.utility(node, player) self.change_list.append(('a', node)) self.change_list.append(('h',)) min_a = argmin(game.actions(node), key=lambda x: max_value(game.result(node, x))) min_node = game.result(node, min_a) self.utils[node] = self.utils[min_node] x1, y1 = self.node_pos[node] x2, y2 = self.node_pos[min_node] self.change_list.append(('l', (node, min_node - 3*node - 1))) self.change_list.append(('e', node)) self.change_list.append(('p',)) self.change_list.append(('h',)) return self.utils[node]
def sample_motif_mh(matrix, mu, Ne, N, iterations=None): nu = Ne - 1 L = len(matrix) if iterations is None: iterations = 10 * L phat = lambda ep: (1 / (1 + exp(ep - mu)))**(nu) best_site = "".join(["ACGT"[argmin(col)] for col in matrix]) def f(site): ep = score_seq(matrix, site) return phat(ep) def sample_site(): return mh(f, mutate_site, best_site, iterations=10 * L, verbose=0)[-1] return [sample_site() for i in range(N)]
def sample_site_spec(matrix, mu, Ne): nu = Ne - 1 L = len(matrix) best_site = "".join(["ACGT"[argmin(col)] for col in matrix]) worst_site = "".join(["ACGT"[argmax(col)] for col in matrix]) def phat(s): assert len(s) == L ep = score_seq(matrix,s) return (1 + exp(ep - mu))**(-nu) chosen_site = "" def best_completion(s): l = len(s) return phat(s + best_site[l:]) def worst_completion(s): l = len(s) return s + worst_site[l:] return chosen_site
def __call__(self, s1): # as of now s1 is a state rather than a percept if self.problem.goal_test(s1): self.a = None return self.a else: if s1 not in self.H: self.H[s1] = self.problem.h(s1) if self.s is not None: # self.result[(self.s, self.a)] = s1 # no need as we are using problem.output # minimum cost for action b in problem.actions(s) self.H[self.s] = min(self.LRTA_cost(self.s, b, self.problem.output(self.s, b), self.H) for b in self.problem.actions(self.s)) # an action b in problem.actions(s1) that minimizes costs self.a = argmin(self.problem.actions(s1), key=lambda b:self.LRTA_cost(s1, b, self.problem.output(s1, b), self.H)) self.s = s1 return self.a
def RandomGraph(nodes=list(range(10)), min_links=2, width=400, height=300, curvature=lambda: random.uniform(1.1, 1.5)): g = UndirectedGraph() g.locations = {} for node in nodes: g.locations[node] = (random.randrange(width), random.randrange(height)) for i in range(min_links): for node in nodes: if len(g.get(node)) < min_links: here = g.locations[node] def distance_to_node(n): if n is node or g.get(node, n): return infinity return distance(g.locations[n], here) neighbor = argmin(nodes, key=distance_to_node) d = distance(g.locations[neighbor], here) * curvature() g.connect(node, neighbor, int(d)) return g
def sample_site_cftp(matrix, mu, Ne): L = len(matrix) f = seq_scorer(matrix) def log_phat(s): ep = f(s) nu = Ne - 1 return -nu*log(1 + exp(ep - mu)) first_site = "A"*L last_site = "T"*L best_site = "".join(["ACGT"[argmin(row)] for row in matrix]) worst_site = "".join(["ACGT"[argmax(row)] for row in matrix]) #middle_sites = [[random_site(L)] for i in range(10)] #trajs = [[best_site]] + middle_sites + [[worst_site]] trajs = [[best_site],[worst_site]] ords = [rslice("ACGT",sorted_indices(row)) for row in matrix] def mutate_site(site,(ri,direction)): b = (site[ri]) idx = ords[ri].index(b) idxp = min(max(idx + direction,0),3) bp = ords[ri][idxp] return subst(site,bp,ri)
def find_mean_field_approximation(ks,q,ps=None): eps = eps_from_ks(ks) if ps is None: ps = occupancies_ref(ks,q) mu_min = -10 mu_max = 10 mu_steps = 1000 mus = interpolate(mu_min,mu_max,mu_steps) coeffs = map(lambda mu:polyfit(ps,probs(eps,mu),1)[0], mus) max_coeff_idx = argmax(coeffs) # find mu corresponding to best fit. Cutoff at peak, since curve # has two intersections with y = 1. mu_idx = argmin(map(lambda coeff:(1-coeff)**2,coeffs[:max_coeff_idx])) best_mu = mus[mu_idx] qs = probs(eps,best_mu) print "best_mu:",best_mu print "mean copy number: %s (sd: %s) vs. sum(ps) %s" %(mean_occ(eps,best_mu),sd_occ(eps,best_mu),sum(ps)) print "pearson correlation:",pearsonr(ps,qs) print "best linear fit: p = %s*q + %s" % tuple(polyfit(qs,ps,1)) return best_mu
def run(self, evaluator): for particle in self.swarm: particle.set_eval_fn(evaluator) for _ in range(self.num_generations + 1): # evaluate particles fitnesses = list( self.map(lambda p: p.evaluate_fitness(), self.swarm)) # current best particle current_best_fitness = min(fitnesses) current_best_position = self.swarm[argmin(fitnesses)].position # overall best particle if current_best_fitness <= self.best_fitness: self.best_fitness = current_best_fitness self.best_position = current_best_position # update particles for particle in self.swarm: particle.update_position(self.best_position) return self.best_position, self.best_fitness
def choose_min_nonrenew_demand(eligibles): return utils.argmin([ max(p.demands[j, r] for r in p.non_renewables) for j in eligibles ])
def critical_lamb_actual(sigma, G=5 * 10**6, trials=10): Ls = range(1, 30) occs = [meanify(occ2, trials)(sigma, L, G) for L in Ls] idx = argmin([(x - 0.5)**2 for x in occs]) return Ls[idx]
def fit_voxel_grid(voxel_grid, max_num_fitted_models=5, use_sphere=True, use_cuboid=True, use_capsule=True, visualize_intermediate=False, loss_type=LossType.BEST_EFFORT, use_cuda=False, cuda_device=None, component_threshold=0.05): fitted_models = [] num_voxels_total = voxel_grid.sum().item() voxels_remaining = voxel_grid.clone() connected_components = voxel.connected_components(voxels_remaining) i = 0 while len(connected_components) > 0 and i < max_num_fitted_models: component = argmax(connected_components, lambda comp: comp.shape[0]) if (float(component.shape[0]) / num_voxels_total) <= component_threshold: break component_points = component.float() if use_cuda: component_points = component_points.cuda(device=cuda_device) lambda_ = 1.0 potential_models = [] if use_sphere: potential_models.append(SphereModel(component_points, lambda_)) if use_cuboid: potential_models.append(CuboidModel(component_points, lambda_)) if use_capsule: potential_models.append(CapsuleModel(component_points, lambda_)) if use_cuda: for model in potential_models: model.cuda(device=cuda_device) best_model = argmin( potential_models, partial(optimize, component_points, loss_type=loss_type)) if visualize_intermediate: fig = plt.figure() ax = fig.gca(projection='3d') draw.draw_voxels(ax, voxels_remaining) best_model.draw(ax) plt.show() points_inside_mask = best_model.exact_containment(component_points) indices_covered = component[points_inside_mask, :] voxel.batch_set(voxels_remaining, indices_covered, False) if points_inside_mask.sum().item() > 0: fitted_models.append(best_model) else: # We failed to fit to any of the voxels in this component, so just ignore it # Todo: try splitting the component up and fit to those pieces voxel.batch_set(voxels_remaining, component, False) i += 1 connected_components = voxel.connected_components(voxels_remaining) return fitted_models
def _min_conflicts_value(problem, assignment, variable): ''' Return the value generate the less number of conflicts. In case of tie, a random value is selected among this values subset. ''' return argmin(problem.domains[variable], lambda x: _count_conflicts(problem, assignment, variable, x))
def alg_list(): env = {'start': time(), 'break': False} with open(sys.argv[1], 'r') as file: n = load_line(file)[0] env['originalTasks'] = [Task(*load_line(file), i) for i in range(n)] tasks = sorted(env['originalTasks'], key=lambda x: x.r) schedules = [[], [], [], []] started = [[], [], [], []] timers = [0, 0, 0, 0] criterium = 0 awaiting = [] counter = 0 it = 0 while True: timer_id = argmin(timers) if it != n: for i in range(it, n): if tasks[i].r <= timers[timer_id]: awaiting += [tasks[i]] else: it = i break else: it = n if not awaiting: timers[timer_id] = tasks[it].r for i in range(it, n): if tasks[i].r <= timers[timer_id]: awaiting += [tasks[i]] else: it = i break else: it = n awaiting.sort( key=lambda x: (min(0, timers[timer_id] + x.p - x.d), -x.p)) popped = awaiting.pop() schedules[timer_id] += [popped] started[timer_id] += [max(timers[timer_id], popped.r)] timers[timer_id] = max(timers[timer_id], popped.r) + popped.p criterium += max(0, timers[timer_id] - popped.d) counter += 1 if counter == n: break env.update({ 'bestSchedules': deepcopy(schedules), 'bestCriterium': criterium, 'schedules': schedules, 'started': started, 'counter': counter, 'timers': timers, 'awaiting': [], 'n': n }) while True: for _ in range(env['n']): popped_id = argmax(j[-1] if j else -1 for j in env['started']) popped = env['schedules'][popped_id].pop() env['started'][popped_id].pop() env['awaiting'] += [popped] if env['started'][popped_id]: env['timers'][popped_id] = env['started'][popped_id][-1] + env[ 'schedules'][popped_id][-1].p else: env['timers'][popped_id] = 0 env['counter'] -= 1 alg_adv(popped_id, env) if env['break']: env['break'] = False break if (time() - env['start']) * 100 > env['n']: save_results(env) return else: save_results(env) return
def sample_motif_reestimate(matrix, mu, Ne, N): best_site = "".join("ACGT"[argmin(col)] for col in matrix) psfm = [best_site for i in range(N)]
def load( verbose, # pylint: disable=unused-argument embedded_code, apb, layers, bias, quantization, # pylint: disable=unused-argument group_map, output_chan, streaming, debug, # pylint: disable=unused-argument ): """ Write `bias` values for the network to C code. """ # Bias: Each group has one bias memory (size BIAS_SIZE bytes). Use only the bias memory in # one selected group for the layer, and only if the layer uses a bias. Keep track of the # offsets so they can be programmed into the mask count register later. if embedded_code: bias_values = np.zeros((tc.dev.P_NUMGROUPS, tc.dev.BIAS_SIZE), dtype=np.int64) group_bias_max = [0] * tc.dev.P_NUMGROUPS bias_offs = [None] * layers bias_group = [None] * layers for ll in range(layers): if bias[ll] is None: continue if len(bias[ll]) != output_chan[ll]: eprint( f'Layer {ll}: output channel count {output_chan[ll]} does not match the number ' f'of bias values {len(bias[ll])}.') sys.exit(1) q = 8 # Fixed to 8 bits instead of quantization[ll] qfactor = 8 // q # Round up the divided length of bias values # FIXME: Is it necessary to handle gaps in the next layer? bias_len = (output_chan[ll] + qfactor - 1) // qfactor if ll == 0 and streaming[ll] and tc.dev.FIX_STREAM_BIAS: # Work around a problem on AI85 bias_len += 1 if streaming[ll] and tc.dev.FIX_STREAM_BIAS: eprint( f'Layer {ll} uses streaming and a bias. ' 'THIS COMBINATION MIGHT NOT BE FUNCTIONING CORRECTLY!!!', error=False) # Pick the group with the least amount of data in it group = argmin(group_bias_max[t] for t in group_map[ll]) if group_bias_max[group] + bias_len > tc.dev.BIAS_SIZE: eprint( f'Layer {ll}: bias memory capacity exceeded - available groups: ' f'{group_map[ll]}, used so far: {group_bias_max}, needed: {bias_len}.' ) sys.exit(1) bias_group[ll] = group bias_offs[ll] = group_bias_max[group] # Each layer has output_channel number of bias values i = 0 target_offs = 0 if ll == 0 and streaming[ll] and tc.dev.FIX_STREAM_BIAS: # Work around a problem on AI85 if not embedded_code: apb.write_bias(group, bias_offs[ll], 0) else: # Store for later bias_values[group][bias_offs[ll]] = 0 target_offs += 1 while i < output_chan[ll]: b = combine(bias[ll], q, i, output_chan[ll]) if not embedded_code: apb.write_bias(group, bias_offs[ll] + target_offs, b) else: # Store for later bias_values[group][bias_offs[ll] + target_offs] = b & 0xff i += qfactor target_offs += 1 group_bias_max[group] += bias_len if embedded_code: if max(group_bias_max) > 0: # At least one bias value exists, output defines for group in range(tc.dev.P_NUMGROUPS): if group_bias_max[group] == 0: continue # but not for this group apb.output_define(bias_values[group][:group_bias_max[group]], f'BIAS_{group}', '0x%02x', 16) # Output variables for group in range(tc.dev.P_NUMGROUPS): if group_bias_max[group] == 0: continue apb.output( f'static const uint8_t bias_{group}[] = BIAS_{group};\n') apb.output('\n') # Finally, create function and do memcpy() apb.output( 'void memcpy_8to32(uint32_t *dst, const uint8_t *src, size_t n)\n{\n' ) apb.output(' while (n-- > 0) {\n *dst++ = *src++;\n }\n}\n\n') apb.output('void load_bias(void)\n{\n') for group in range(tc.dev.P_NUMGROUPS): if group_bias_max[group] == 0: continue addr = apb.apb_base + tc.dev.C_GROUP_OFFS * group + tc.dev.C_BRAM_BASE apb.output( f' memcpy_8to32((uint32_t *) 0x{addr:08x}, bias_{group}, ' f'sizeof(uint8_t) * {group_bias_max[group]});\n') apb.output('}\n\n') return bias_offs, bias_group, group_bias_max
def ringer_motif(matrix,n): best_site = "".join(["ACGT"[argmin(col)] for col in matrix]) best_motif = [best_site]*n return best_motif
def sample_motif_mh(matrix, mu, Ne, n, iterations=None): L = len(matrix) iterations = 20*L ringer_site = "".join(["ACGT"[argmin(col)] for col in matrix]) return [sample_site_mh(matrix, mu, Ne, ringer_site, iterations=iterations)[-1] for i in xrange(n)]
from utils import triangleGen, pentagonGen, hexagonGen, argmin, equals Z = T, P, H = triangleGen(), pentagonGen(), hexagonGen() z = t, p, h = map( next, ( T, P, H ) ) while not equals( *z ) or z[0] in ( 1, 40755 ): m = argmin( *z ) z[ m ] = next( Z[ m ] ) print z[ 0 ]