def _test_get_entropy_TO(self): """ de を記録して entropy を算出する """ path = os.path.join(self.PATH, "AlCu/wien/TO") fcc = FCCXtal.from_pickle_ecis(os.path.join(path, 'cluster.pickle'), arrange='random', conc=0.25, size=30) mc = MonteCarlo(fcc, T=10000) mc.loop_fcc_micro_single(2000)
def _test_AlCu_mc_grand_TO(self): """ グランドカノニカルの計算テスト TO 近似 """ fcc = FCCXtal.from_pickle_ecis( os.path.join(self.PATH, "cluster_AlCu_TO.pickle"), arrange='random', conc=0.6, size=30) # fcc.from_pickle_cell(os.path.join(self.PATH, 'AlCu.pickle')) mc = MonteCarlo(fcc, T=1000) mc.loop_fcc_grand(100) fcc.make_poscar(os.path.join(self.PATH, 'POSCAR')) fcc.save_cell(os.path.join(self.PATH, 'AlCu'))
def main(args): if args.verbose: logging.basicConfig(level=logging.INFO) elif args.debug: logging.basicConfig(level=logging.DEBUG) # initializations gridworld = GridWorld(args.size, args.interval, args.obstacles, args.vision, args.phase) logging.info("Generated grid world!") logging.info("Visuals created") mc = MonteCarlo(gridworld, mode=args.method) logging.info("Initialized Monte Carlo method") mc.run()
def _test_mc_bcci(self): path = os.path.join(self.PATH, "i-s/bcci/TiC_spin_r_R6N4") path = os.path.join(self.PATH, "i-s/bcci/TiC_R6N4_330str") CEMParser02.from_dirc_bcci(path, BcciOctaSite) CrC = SubLattXtal.from_pickle_ecis( 5, os.path.join(path, 'cluster.pickle'), BcciOctaSite, arrange='random', conc=(0.1, 0.1)) # CrC = SubLattXtal(2, out, BcciOctaSite, arrange='A3C', conc=(0.1, 0.1)) CrC.make_poscar(os.path.join(self.PATH, "i-s/bcci/TiC_R6N4_330str/POSCAR_init"), 1, 1) mc = MonteCarlo(CrC, T=1000) e = mc.loop_bcci_micro_single(1) CrC.make_poscar(os.path.join(self.PATH, "i-s/bcci/TiC_R6N4_330str/POSCAR"), 1, 1) print(e)
def play_game(board_size, fnet, mcts_sims): """ Generate a single game and batch """ game_batch = [] try: eprint ("instantiating sim") simulator = MonteCarlo(board_size, fnet, mcts_sims) # Create a MCTS simulator game_batch = simulator.play_game() except: tb = traceback.format_exc() else: tb = "No error" finally: eprint(tb) return game_batch
def burgers(): x_range = [-2.0, 3.0] nx = 200 nu = 150 C = .3 tmax = 0.6 num_realizations = 800 debug = False savefilename = 'burgers0' + str(num_realizations) + '.npy' MC = MonteCarlo(num_realizations=num_realizations, x_range=x_range, tmax=tmax, debug=debug, savefilename=savefilename, nx=nx, C=C) MC.multiSolve("gaussians") MCprocess = MCprocessing(savefilename) #MCprocess.buildHist(40) MCprocess.buildKDE(nu, plot=True)
def play_game(nrows, ncols, inarow, fnet, mcts_sims): """ Generate a single game and batch """ game_batch = [] try: eprint("Instantiating Sim") simulator = MonteCarlo(nrows, ncols, inarow, fnet, mcts_sims) # Create a MCTS simulator game_batch = simulator.play_game() except: tb = traceback.format_exc() raise # else: # tb = "No error" # finally: # eprint(tb) return game_batch
def chooseParentUsingFitness(self, choices): """ Chooses a parent from a set of choices, using fitness to effect the probability of choosing that parent. """ # This should probably use something more like laplace smoothing. # Right now, it only checks to ensure that the total probability is not # zero. But we should probably be using Laplace smoothing to ensure that # zero fitness scores have a (small) chance of being selected. This is # only really important for the first few generations, whether there # are genes with zero fitness. totalFitness = sum([self.fitness[i] for i in choices]) if totalFitness > 0: probOfChoices = [float(self.fitness[i])/float(totalFitness) for i in choices] else: probOfChoices = [1/float(len(choices)) for i in choices] mc = MonteCarlo(choices, probOfChoices) return mc.getWeightedSelection()
def _test_AlCu_mc_grand(self): """ グランドカノニカルの計算テスト """ fcc = FCCXtal.from_pickle_ecis( os.path.join(self.PATH, "cluster_AlCu_09.pickle"), arrange='random', conc=0.05, size=10) # fcc.from_pickle_cell(os.path.join(self.PATH, 'AlCu.pickle')) # eci_point = - 454.351346 # -3250 @ 1500 # -3800 @ 8000 0.92 # -4000 @ 10000 0.92 # -4700 @ 13500 fcc.eci_point = 89.45 mc = MonteCarlo(fcc, T=0) mc.loop_fcc_grand(20) fcc.make_poscar(os.path.join(self.PATH, 'POSCAR')) fcc.save_cell(os.path.join(self.PATH, 'AlCu'))
def _test_gs(self): """ 基底状態探索 エネルギーのみを出力 """ path = os.path.join(self.PATH, "AlCu/voldep/4.0/") fcc = FCCXtal.from_pickle_ecis(os.path.join(path, 'cluster.pickle'), arrange='random', conc=0.90, size=10) fcc.from_pickle_cell(os.path.join(path, 'AlCu.pickle')) # mc = MonteCarlo(fcc, T=500) # mc.loop_fcc_micro_single(500) # 90 300 mc = MonteCarlo(fcc, T=20) mc.loop_fcc_micro_single(10000) fcc.make_poscar(os.path.join(path, 'POSCAR')) fcc.save_cell(os.path.join(path, 'AlCu'))
def chooseParentUsingFitness(self, choices): """ Chooses a parent from a set of choices, using fitness to effect the probability of choosing that parent. """ # This should probably use something more like laplace smoothing. # Right now, it only checks to ensure that the total probability is not # zero. But we should probably be using Laplace smoothing to ensure that # zero fitness scores have a (small) chance of being selected. This is # only really important for the first few generations, whether there # are genes with zero fitness. totalFitness = sum([self.fitness[i] for i in choices]) if totalFitness > 0: probOfChoices = [ float(self.fitness[i]) / float(totalFitness) for i in choices ] else: probOfChoices = [1 / float(len(choices)) for i in choices] mc = MonteCarlo(choices, probOfChoices) return mc.getWeightedSelection()
def _test_mc_micro_nacl(self): """ i-s 系での mc 計算のてすと """ nacl = NaClXtal.from_pickle_ecis( os.path.join(self.PATH, "i-s/fcci/Ti1C1/cluster.pickle"), arrange='random', conc=(0.001, 0.999), size=2) # print((-nacl.get_flip_de_int()/80)) mc = MonteCarlo(nacl, T=1000) # mc.loop_flip_nacl_fix_conc(100) e = mc.loop_nacl_micro(10) lines = "" for i in range(len(e[0])): lines += str(i) + "\t" + str(e[0][i][2]) + "\t" for val in e[1][i][0]: lines += str(val) + "\t" for val in e[1][i][1]: lines += str(val) + "\t" lines += "\n" print(lines)
self.outputs += p_out.tolist() else: self.outputs.append(self.p_out) else: self.p_out = self.dist_types["Default"](*self.dist_args["Default"]) self.outputs.append(self.p_out) else: # parameters is none: default to num_parameters and utilize defaults self._args = self.dist_args["Default"][:] self._args.append(self.num_parameters) self.outputs = self.dist_types["Default"](*self._args) self._outputs = array(self.outputs) return self._outputs else: raise StopIteration() if __name__ == "__main__": from numpy import random from montecarlo import MonteCarlo _test = MonteCarlo() _test.num_parameters = 7 _test.parameters = ["x", "y", "z", "u"] _test.num_samples = 10 _test.dist_types = {"Default": random.uniform, "y": random.standard_normal} _test.dist_args = {"Default": [0, 1], "y": []} for iters in _test: A = iters print(A)
def EstimateDOS(system, eps_log_modification_factor, restart=None): """ イタレーションによって DOS を求める """ rand = numpy.random.mtrand.RandomState(100) # 乱数ジェネレーター if not restart: # 各エネルギーに対してインデックスを持つヒストグラムと状態密度 histgram = numpy.array([0 for i in range(system.number_of_energies)]) log_density_of_state = [0 for i in range(system.number_of_energies)] # 修正ファクター: DOS を積み上げていくのに使用 log_modification_factor = 1 # モンテカルロステップカウンター 定期的にヒストグラムの平滑化具合をチェックするのに使用 current_energy = system.GetEnergy() # エネルギー最小、最大の状態を保存する用意 minimum_energy = current_energy maximum_energy = current_energy minimum_e_cell = system.state.cell.copy() maximum_e_cell = system.state.cell.copy() else: histgram = restart["histgram"] log_density_of_state = restart["log_DOS"] log_modification_factor = restart["log_modification_factor"] system.state.cell = restart["current_state"] current_energy = system.GetEnergy() minimum_energy = restart["minimum_state"][0] maximum_energy = restart["maximum_state"][0] minimum_e_cell = restart["minimum_state"][1] maximum_e_cell = restart["maximum_state"][1] counter_mc = 0 def save_conditions(): """状態を保存""" conditions = {"minimum_state":[minimum_energy, minimum_e_cell], "maximum_state":[maximum_energy, maximum_e_cell], "current_state": system.state.cell, "log_DOS": log_density_of_state, "log_modification_factor": log_modification_factor, "histgram": histgram} fname = "work/save.pickle" with open(fname, 'wb') as wbfile: pickle.dump(conditions, wbfile) num = 0 system.GoNextState() while log_modification_factor > eps_log_modification_factor: counter_mc += 1 #状態変化前後でのエネルギー値を取得 new_energy = system.GetEnergy() mc = MonteCarlo(system.state, T=0) try: log_dos_new = log_density_of_state[new_energy[1]] except IndexError: save_conditions() print("out of energy range !") print(new_energy) exit() log_dos_current = log_density_of_state[current_energy[1]] if rand.rand() < min(1.0, numpy.exp(log_dos_current - log_dos_new)): log_density_of_state[new_energy[1]] += log_modification_factor histgram[new_energy[1]] += 1 current_energy = new_energy else: system.BackPreviousState() log_density_of_state[current_energy[1]] += log_modification_factor histgram[current_energy[1]] += 1 system.GoNextState() if current_energy < minimum_energy: minimum_energy = current_energy minimum_e_cell = system.state.cell.copy() print('search_stable_state') print(system.state.get_energy()) system.BackPreviousState() mc.trans_prob = mc.trans_prob_stable mc.loop_fcc_micro_single(5000) system.state.energy = system.state.get_energy() if current_energy > maximum_energy: maximum_energy = current_energy maximum_e_cell = system.state.cell.copy() print('search_unstable_state') print(current_energy) print(system.state.get_energy()) system.BackPreviousState() mc.trans_prob = mc.trans_prob_unstable print(system.state.get_energy()) mc.loop_fcc_micro_single(5000) system.state.energy = system.state.get_energy() if counter_mc % 1000 == 0: # print(minimum_energy, maximum_energy, log_modification_factor) # print(histgram) if counter_mc % 100000 == 0: counter_mc = 0 save_conditions() judge = IsFlat_with_gap(histgram, num) if judge: num = judge histgram = numpy.array([0 for i in range(system.number_of_energies)]) log_modification_factor *= 0.5 # print('here') # print(log_modification_factor) save_conditions() return log_density_of_state
(2. * a**2 * c) / (4. * alpha**2 * c * eta**2 + 2. * c * sigma**2 + 1.))) right_denom = np.sqrt(4. * alpha**2 * c * eta**2 + 2. * c * sigma**2 + 1.) return left_nom / left_denom - right_nom / right_denom from covariances import ExpCov, MaternCov, GaussCov from data import ToyInverseProblem from montecarlo import MonteCarlo from pointsets import Random, Mesh1d cov_fct = MaternCov() IP = ToyInverseProblem(0.1) dim = 1 num_pts_mc = 10000 monte_carlo = MonteCarlo(num_pts_mc, dim) #pt_x = Random(1,1) # pt_z = Random(1,1) # print(pt_x.points, pt_z.points) print(IP.true_observations) print(IP.locations.points) def integration(pt_x, cov_fct, IP, monte_carlo): def integrand(pt_z, pt_x=pt_x, cov_fct=cov_fct, IP=IP): eta = cov_fct.assemble_entry_cov_mtrx(pt_x, pt_x) alpha = cov_fct.assemble_entry_cov_mtrx(pt_z, pt_x) / eta sigma = cov_fct.assemble_entry_cov_mtrx( pt_z, pt_z) - alpha * cov_fct.assemble_entry_cov_mtrx(pt_x, pt_z)
def update(self, alpha, delta): for s in self.q: for a in [Action.HIT, Action.STICK]: self.q[s][a] += alpha * delta * self.E[s][a] self.E[s][a] = Sarsa.GAMMA * self._lambda * self.E[s][a] if __name__ == "__main__": g = graph.graphxy(width=30, x=graph.axis.linear(min=100, max=1000), y=graph.axis.linear(), key=graph.key.key(pos="bl")) plots = [] """ Re-calculate V* """ m = MonteCarlo() for i in range(1, 50000): m.run() for _l in [e / 10.0 for e in range(0, 11, 1)]: print("Training Sarsa(%s)" % _l) s = Sarsa(_l) c1 = [] c2 = [] for j in range(1, 1001): s.run() if j % 100 == 0: c1.append(j) e = s.mean_squared_error(m.q) c2.append(e) if j % 100 == 0:
self.p_out = self.dist_types[parameter](*self.dist_args[parameter]) if type(self.p_out) == 'numpy.ndarray': self.outputs += p_out.tolist() else: self.outputs.append(self.p_out) else: self.p_out = self.dist_types['Default'](*self.dist_args['Default']) self.outputs.append(self.p_out) else: #parameters is none: default to num_parameters and utilize defaults self._args = self.dist_args['Default'][:] self._args.append(self.num_parameters) self.outputs = self.dist_types['Default'](*self._args) self._outputs = array(self.outputs) return self._outputs else: raise StopIteration() if __name__ == "__main__": from numpy import random from montecarlo import MonteCarlo _test = MonteCarlo() _test.num_parameters = 7 _test.parameters = ['x','y','z','u'] _test.num_samples = 10 _test.dist_types = {'Default':random.uniform,'y':random.standard_normal} _test.dist_args = {'Default':[0,1],'y':[]} for iters in _test: A = iters print(A)
stats[1] += 1 break if len(strategy1.moves) == 42: break stats[2 + turn % 2] += time.perf_counter() - start if n == 1: strategy1.print() turn += 1 strategy1.print() print() print(stats[0], stats[1], "{:.6f}".format(stats[2]), "{:.6f}".format(stats[3])) #fight(10, MonteCarlo(1), MonteCarlo(1)) #fight(10, SimpleRandom(),SimpleRandom()) fight(10, MonteCarlo(20), Minimax(5)) #fight(1, Human(), Minimax(6)) # r = SimpleRandom() # r.load([0,6,1,5,2,4,3]) # assert r.winning_move() == True # r.reset(1) # r.load([0,6,1,5,2,4,3]) # assert r.winning_move() == False #fight(1000, Random(), Random()) #fight(100, MonteCarlo(0.00001), Random()) # Vinner 99-100 av 100, oberoende av tid? #fight(1, MonteCarlo(0.1),MonteCarlo(0.1)) # Vinner 99-100 av 100, oberoende av tid?
y2 = y * y L2 = L * L xL2 = (x - L) * (x - L) yL2 = (y - L) * (y - L) c1 = x2 + y2 <= L2 c2 = xL2 + y2 <= L2 c3 = x2 + yL2 <= L2 c4 = xL2 + yL2 <= L2 tc = c1 and c2 and c3 and c4 return 1 if tc else 0 mc = MonteCarlo(seed, samples, target_function_L, 2) print(mc.run()) def target_function(random_vector): ''' Function receives a uniform random vector in [0] ''' x = random_vector[0] y = random_vector[1] c1 = x + y < 1 return 1 if c1 else 0 samples = 10000 mc = MonteCarlo(seed, samples, target_function, 2)
['b', 'b', 'w', 'w', 'w', 'b', 'b', 'b', 'w', 'w', 'w', 'b']] # Cria o mapa de probabilidades # Quantidade de linhas e colunas do mapa x = len(map) y = len(map[0]) p = 1.0 / (x * y) p_map = [[p for j in range(y)] for i in range(x)] # Inicia a simulação por um tempo para o robô e os sensores inicializarem start_angle = 90 robot.step(1000) # Instancia da localização (passa o mapa com as características) localize = MonteCarlo(map) while robot.step(timestep) != -1: # Mede a posição atual z = robotGetColor() # Atualiza o mapa de probabilidades com a medição p_map = localize.measure(p_map, z) print_map(p_map) # Printa a posição atual mais provável pos, prob = localize.where(p_map) print("- O robô tem %.1f%% de chance de estar na posição %d - %d" % (prob, pos[0], pos[1]))