Esempio n. 1
0
def main():
    # Handles command line args
    if len(sys.argv) != 3:
        print("Incorrect amount of args")
        return
    
    args = sys.argv[1:]
    try:
        int(args[0])
        float(args[1])
    except ValueError:
        print("Incorrect arg types")
        return
    

    if(int(args[0]) != 1 and float(args[1]) != 2):
        print("Turn arg must be 1 or 2")
        return

    # Initializes board
    board = init_board()
    turn = int(args[0])
    print("Initial board:")
    utils.print_board(board)

    # Loops until someone wins
    while len(utils.get_next_board_states(board, turn)) > 0:
        board = montecarlo(board, turn, float(args[1]))
        print(f"{turn} goes")
        utils.print_board(board)
        turn = utils.next_turn(turn)
    
    print(f"{utils.next_turn(turn)} wins!")
Esempio n. 2
0
def parallel(N, comm=MPI.COMM_WORLD):
    rank = comm.Get_rank()
    size = comm.Get_size()

    # usamos seed=rank para ter resultados diferentes para cada processo
    # cada processo eh responsavel por calcular o resultado para uma parcela menor do problema, de tamanho N/size
    return montecarlo(int(N / size), seed=rank)
Esempio n. 3
0
    interval = num_episodes - 1
    decay = num_episodes / 10

    QSAtable = tdlambda(sim,
                        l=0.5,
                        alpha=0.1,
                        initial_epsilon=0.1,
                        num_episodes=num_episodes,
                        interval=interval,
                        decay=decay,
                        return_qsa=True)
    plot_QSAtable(QSAtable,
                  title='q(s, a) values for TD Lambda(0.5)',
                  path='plots/tdlambda',
                  name='QSA %d' % num_episodes,
                  show=False)

    PItable = derive_pi_table(QSAtable)
    plot_PItable(PItable,
                 title='Optimal Policy using TD Lambda(0.5)',
                 path='plots/tdlambda',
                 name='PI %d' % num_episodes,
                 show=False)

    # Evaluating the policy
    Qtable = montecarlo(sim, PItable, num_episodes=500000)
    plot_Qtable(Qtable,
                title='V(s) values for TD Lambda(0.5)',
                path='plots/tdlambda',
                name='V %d' % num_episodes,
                show=False)
Esempio n. 4
0
		P = int( np.log2( N - 1 ) )
## Loop over the base scale methods
		for delta_method in [ 'med', ] :
## Create the necessary directory structure
			target_path = os.path.join( basepath, "FBM_%d" % ( P, ), delta_method )
			os.makedirs( target_path )
## Run simulations for different Hurst exponents
			for H in np.linspace( .5, .9, num = 5 ) :
## Initalize the generator
				generator = fbm( N = N, H = H, time = True )
				print "Monte-Carlo (%d) for FBM(2**%d+1, %.4f), %s:" % ( M, P, H, delta_method, )
## Get the current timestamp
				start_dttm = datetime.utcnow( )
## Run the experiment
				results = montecarlo( generator, mc_kernel,
					processes = 2, debug = False, quiet = False, parallel = True,
					replications = M, delta = delta_method, L = 20, K = 40 )
## Create a meaningful name for the output data blob
				file_name = "FBM_%s_%s_%d_%.4f_%d" % ( delta_method.lower( ),
					start_dttm.strftime( "%Y%m%d-%H%M%S" ), P, H, M )
## Save the data blob
				sim_save( os.path.join( target_path, file_name ), results, save_durations = True )
####################################################################################################
	if False :
## Hermite processes
## The parameters of the simulation
		N, K, M = 2**18+1, 2**4, 1000
		P = int( np.log2( N - 1 ) )
		for delta_method in [ 'med', ] :
			for D in [ 2, 3, 4, ] :
				target_path = os.path.join( basepath,
Esempio n. 5
0
from montecarlo import montecarlo
from random import randint

def flip_is_heads(g):
    return randint(0, 1) == 0

mc = montecarlo(flip_is_heads)
result = mc.run()
print("Result returned: " + str(result))
Esempio n. 6
0
from montecarlo import montecarlo
from random import randint

def flip_is_heads(g):
    return randint(0, 1) == 0

mc = montecarlo(flip_is_heads)
result = mc.run()
print "Result returned: " + str(result)
Esempio n. 7
0
def sequential(N):
    acertos = montecarlo(N)
    return (acertos / N) * 4
	else :
		T = T[ 0 ]
	return path_kernel( T, X, **op )

if __name__ == '__main__' :
	# basepath = os.path.join( '.', 'output', 'HRM_2_20-32' )
	basepath = os.path.join( '.', 'output', 'HRM_3_20-32' )
	path = [ os.path.join( basepath, H ) for H in [
		'0.5000', '0.6000', '0.7000', '0.8000',  ] ]
	for p in path :
## Go!
		files = list_files( p, pattern = r"\.mat$" )
		print( "Sweeping through %s: %d files found." %( p, len( files ), ) )
## Pick the first file and extract as much information as possible from its filename
		prefix, degree, size, hurst = os.path.basename( files[0] ).split( "_" )[:4]
		prefix += "-%s"%( degree, )
## Loop thorugh all the possible base scale calculation methods
		for delta_method in [ 'std', 'iqr', 'med', ] :
## Get the current timestamp
			run_dttm = datetime.utcnow( )
## Run the analyzer in parallel
			result = montecarlo( empty( ), offline_kernel,
				processes = 1, debug = False, quiet = False, parallel = False,
				replications = files, delta = delta_method, L = 20, K = 40 )
## Get the datetime after the simulation has finished
			end_dttm = datetime.utcnow( )
## Create a meaningful name for the output data blob
			sim_save( os.path.join( basepath, "%s_%s_%s_%s_%s_%d" % ( prefix, delta_method.lower( ),
				run_dttm.strftime( "%Y%m%d-%H%M%S" ), size, hurst, len( files ) ) ),
				result, save_durations = True )
Esempio n. 9
0
import montecarlo

a = montecarlo.montecarlo()
a.diffusion_tree()
a.structure_geometry()
a.rebar_calc()
a.crack_calc()
a.derating_calc()
a.parameter_fill()
a.monte_zeroes()
a.monte_fill()
a.histogram()
a.outputs()
a.normalization()
a.plot_damage()

print a.monte_bincount
print a.x

Esempio n. 10
0
import sys
#import time
#import numpy as np
#
from header import header
from montecarlo import montecarlo
from fire import fire
from control import control

effect = ""
try:
    effect = sys.argv[1]
except IndexError:
    print("")

# Initialize Pixels
num_pixels, pixels = header(300)

if (effect == "montecarlo"):
    montecarlo(num_pixels, pixels)
elif (effect == "fire"):
    fire(num_pixels, pixels)
elif (effect == "control"):
    control(num_pixels, pixels)