Exemplo n.º 1
0
def mcr(a,b,error,N,f,dim):
 import mc
 [y,cerror]=mc.mc(a,b,N,f,dim)
 while cerror > error: 
  x=2*x
  print x
  [y,cerror]=mc.mc(a,b,x,f,dim)
 return [y,cerror]
Exemplo n.º 2
0
def open_database(path):
    """Check and set up database based on "path", then return an mc ("MasterChess") instance."""
    try:
        conn = sqlite3.connect(path)
        if conn:
            players = conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='players';")
            if len(players.fetchall()) == 0:
                conn.execute("CREATE TABLE 'players' (id INTEGER PRIMARY KEY, deleted INTEGER, first_name TEXT, last_name TEXT, grade INTEGER);")
            
            matches = conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='matches';")
            if len(matches.fetchall()) == 0:
                conn.execute("CREATE TABLE 'matches' (id INTEGER PRIMARY KEY, enabled INTEGER, timestamp INTEGER, white_player INTEGER, black_player INTEGER, outcome INTEGER);")
            
            prefs = conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='prefs';")
            if len(prefs.fetchall()) == 0:
                conn.execute("CREATE TABLE 'prefs' (name TEXT UNIQUE NOT NULL, value TEXT);")
            
            conn.commit()
            conn.close()
            mc_instance = mc(path)
            if mc_instance:
                return mc_instance
            else:
                print >> sys.stderr, "open_database WARNING:", "No mc; received:", mc_instance
    except:
        exc_type, exc_value = sys.exc_info()[:2]
        print >> sys.stderr, "open_database ERROR:", exc_type, exc_value
Exemplo n.º 3
0
    def holland(self):

        cols = ['w' + name for name in radcols]

        varn = ['rmse', 'dph', 'b', 'rmaxh', 'k', 'np.max(V)', 'vmax1']
        mcdic = {el: [] for el in varn}

        hpar = pd.DataFrame(mcdic)

        # clean the values if present
        try:
            dcols = [unicode(x) for x in varn]
            self.data = self.data.drop(dcols, 1)
        except Exception as e:
            print e
            pass

        for it in range(self.data.shape[0]):

            vmax = self.data.loc[it].vmax

            #
            #try:
            #    dp=tc.loc[it].dp
            #except:
            #    pass

            R = self.data.ix[it, radcols].values

            V = self.data.ix[it, cols].values

            vmax0vt = self.data.vmax0vt.values[it]

            time = self.data.time.values[it]

            sinfi = self.data.sinfi.values[it]

            lat = self.data.lat.values[it]

            w = R > 0.

            R = R[w].astype(float)

            V = V[w].astype(float)

            if R.size > 0:
                rmc = mc(R, V, sinfi, lat, vmax0vt)
            else:
                rmc = {el: np.nan for el in varn}

            df = pd.DataFrame(rmc, index=[it])

            hpar = hpar.append(df)

        self.data = pd.concat([self.data, hpar], axis=1)
Exemplo n.º 4
0
def open_database(path):
    """Check and set up database based on "path", then return an mc ("MasterChess") instance."""
    try:
        conn = sqlite3.connect(path)
        if conn:
            players = conn.execute(
                "SELECT name FROM sqlite_master WHERE type='table' AND name='players';"
            )
            if len(players.fetchall()) == 0:
                conn.execute(
                    "CREATE TABLE 'players' (id INTEGER PRIMARY KEY, deleted INTEGER, first_name TEXT, last_name TEXT, grade INTEGER);"
                )

            matches = conn.execute(
                "SELECT name FROM sqlite_master WHERE type='table' AND name='matches';"
            )
            if len(matches.fetchall()) == 0:
                conn.execute(
                    "CREATE TABLE 'matches' (id INTEGER PRIMARY KEY, enabled INTEGER, timestamp INTEGER, white_player INTEGER, black_player INTEGER, outcome INTEGER);"
                )

            prefs = conn.execute(
                "SELECT name FROM sqlite_master WHERE type='table' AND name='prefs';"
            )
            if len(prefs.fetchall()) == 0:
                conn.execute(
                    "CREATE TABLE 'prefs' (name TEXT UNIQUE NOT NULL, value TEXT);"
                )

            conn.commit()
            conn.close()
            mc_instance = mc(path)
            if mc_instance:
                return mc_instance
            else:
                print >> sys.stderr, "open_database WARNING:", "No mc; received:", mc_instance
    except:
        exc_type, exc_value = sys.exc_info()[:2]
        print >> sys.stderr, "open_database ERROR:", exc_type, exc_value
Exemplo n.º 5
0
xSource = 1
xInterface = 0
# Specify the width of the bins for the tally mesh (recommend 0.1)
stepSize = 0.25
# Include analytical solution to the diffusion equation?
incl = 'yes'
#####################################################################################################
# END OF INPUT
#####################################################################################################
import matplotlib.pyplot as plt
if(incl == 'yes'):
	# Force the source point and interface to be the same location
	xInterface = xSource
	# Import the monte carlo solver; use to solve for the flux in the space defined by the input parameters. Note that the interface between the two regions of the problem MUST be defined as the position of the source for the analytical solution to make sense in conjunction with the mc solution
	import mc
	mcSoln = mc.mc(totalParticles, xs, rBound, lBound, xInterface, xSource, sourceStrength, stepSize)
	print('maximum relative error = '+str(max(mcSoln[3])))
	# Import the analytical solution script and functions; use to solve for the flux in the space defined by the input parameters
	import analytical_test
	analyticalSoln = analytical_test.ana_flux(xs, xSource, rBound, lBound, sourceStrength)
	fig_an=plt.plot(analyticalSoln[0], analyticalSoln[1], label='analytical')
#####################################################################################################
else:
	# Import the monte carlo solver; use to solve for the flux in the space defined by the input parameters. Note that the interface between the two regions of the problem MUST be defined as the position of the source for the analytical solution to make sense in conjunction with the mc solution
	import mc
	mcSoln = mc.mc(totalParticles, xs, rBound, lBound, xInterface, xSource, sourceStrength, stepSize)
	print('maximum relative error = '+str(max(mcSoln[3])))
# Compare the analytical and monte carlo results by plotting them together in space.
fig_mc=plt.plot(mcSoln[0], mcSoln[1], 'ro', label='mc')
fig_mc=plt.errorbar(mcSoln[0], mcSoln[1], yerr=mcSoln[3], linestyle="None")
#####################################################################################################
Exemplo n.º 6
0
def run_game():
    x_level_coor = 0
    y_level_coor = 0
    # ^ these are used to tell the program where the walls should be!
    pygame.init()
    font_name = pygame.font.match_font('times new roman')
    settings = Settings()
    screen = pygame.display.set_mode([settings.screen_width, settings.screen_height])
    pygame.display.set_caption("Jacob's Game")
    pygame.mixer.music.load("music/burbank-sorry-i-like-you_GgVcgbtHY9k.mp3")
    #i took everything from python crash course except music...

    #taken straight from kids can code, most initial set up for font stuff is kids can code
    def draw_text(surf, text, size, x, y):
        font = pygame.font.Font(font_name, size)
        text_surface = font.render(text, True, [255,255,255])
        text_rect = text_surface.get_rect()
        text_rect.midtop = (x, y)
        surf.blit(text_surface, text_rect)
    
#thank you kids can code
    def draw_grid():
        for x in range(0, settings.screen_width, settings.TILESIZE):
            pygame.draw.line(screen, (100, 100, 100), (x, 0), (x, settings.screen_height))
        for y in range(0, settings.screen_height, settings.TILESIZE):
            pygame.draw.line(screen, (100, 100, 100), (0, y), (settings.screen_width, y))

    #original code
    for row in gameboard_1:
        for column in row:
            #up here, i am transversing through the list to draw the level
            pos = [x_level_coor*settings.TILESIZE, y_level_coor*settings.TILESIZE]
            if column == "W":
                wall = Wall(pos, settings.wall_width, settings.wall_height, settings.wall_color)
                walls.add(wall)
                #print("this if works")
            elif column == "C":
                pos_hero = [x_level_coor*settings.TILESIZE, y_level_coor*settings.TILESIZE]
            elif column == "B":
                box = Box(pos, settings.wall_width, settings.wall_height, settings.box_color)
                boxes.add(box)
            elif column == "F":
                fin = Fin(pos, settings.wall_height, settings.wall_height, settings.fin_color)
            x_level_coor += 1
        y_level_coor += 1
        x_level_coor = 0
    hero = mc(screen, pos_hero)

    #from kids can code, thank you for the beginning screen
    def beginning_screen():
        draw_text(screen, "Welcome to the T-Maze", 64, settings.screen_width / 2, settings.screen_height / 4)
        draw_text(screen, "Use WASD to move. W to move up, A to move left, D to move right, and S to move down.", 25,
        settings.screen_width / 2, settings.screen_height / 2)
        draw_text(screen, "You can push the red boxes! Press Space to do so, but be careful, you don't want to get tired...", 18,
        settings.screen_width / 2, settings.screen_height * 3  / 5)
        draw_text(screen, "Press the letter b to begin...", 35, settings.screen_width / 2, settings.screen_height * 3 / 4)
        pygame.display.flip()

    #original code
    def score():
        if hero.score > 1:
            draw_text(screen, "Pushes Left: "+ str(hero.score), 20,
            settings.screen_width / 2, settings.screen_height / 276)
        else:
            draw_text(screen, "One Push Left!", 20,
            settings.screen_width / 2, settings.screen_height / 276)
    #template from kids can code
    def end_screen():
        draw_text(screen, "Game Over!", 64, settings.screen_width / 2, settings.screen_height / 2)
        #i seperated this into two logic statements so that it makes grammatical sense.
        if hero.score == 1:
            draw_text(screen, "You had one push left.",64,  settings.screen_width / 2, settings.screen_height*3/4)
        else:
            draw_text(screen, "You had " +str(hero.score)+ " pushes left.",64,  settings.screen_width / 2, settings.screen_height*3/4)
        pygame.display.flip()
    while True:
        #this is for beginning screen, if waiting is true, player is waiting to start.
        if hero.waiting == True and hero.game_over == False:
            screen.fill([0,0,0])
            beginning_screen()
            gf.check_events(hero, boxes, walls)
        #this is running the actual game
        elif hero.waiting == False and hero.game_over == False:
            screen.fill([0, 0, 0])
            draw_grid()
            gf.check_events(hero, boxes, walls)
            hero.update()
            walls.draw(screen)
            boxes.draw(screen)
            screen.blit(fin.image, fin.rect)
            score()
            gf.update_screen(settings, screen, hero, walls, boxes)
        #this is the game over screen, it shows it and fades out music
        if hero.rect.x > 1000 or hero.score == 0:
            hero.game_over = True
            pygame.mixer.music.fadeout(1000)
            gf.check_events(hero, boxes, walls)
            if hero.score == 0:
                screen.fill([89, 0, 0])
            else:
                screen.fill([0, 0, 105])
            end_screen()
Exemplo n.º 7
0
Arquivo: main.py Projeto: rwexler/gcmc
##############################
# GET STRUCTURAL INFORMATION #
##############################
xsf = xsf_info()
xsf.pop_attr(xsf_filename, el, buf_len)

####################################
# GET NEAREST NEIGHBOR INFORMATION #
####################################
bvo = bv()
bvo.init(xsf, el)

###################################
# INSTANTIATE MONTE CARLO ROUTINE #
###################################
mc_run = mc()
mc_run.init(T_move, max_disp, xsf)

###################################
# RUN GRAND CANONICAL MONTE CARLO #
###################################
os.system('mkdir -p temp')  # make temp directory for qe calculations
os.chdir('temp')  # enter temp
log_file = init_log('log.dat')  # initialize log file
axsf_opt_file = init_axsf(
    'coord_opt.axsf', niter,
    xsf)  # "        " axsf file recording optimized structure
axsf_new_file = init_axsf(
    'coord_new.axsf', niter, xsf
)  # "                            " structure created in current iteration
axsf_accept_file = init_axsf(
Exemplo n.º 8
0
xsf.get_at_coord() # get atomic coordinates
xsf.get_el_list() # get list of element symbols
xsf.get_num_each_el() # get number of each element
xsf.get_c_min_max(buf_len) # get c values within which atom can be added
xsf.get_vol() # get volume of variable composition region
xsf.get_ind_rem_at() # get indices of removable atoms

el = el_info(el_list_filename) # instantiates el_info object
el.get_el_sym() # get element symbols
el.get_at_wt() # get atomic weights
el.get_therm_db(T_exc) # get thermal de Broglie wavelengths
el.get_ind_to_el_dict() # get index-to-element symbol dictionary
el.get_el_to_ind_dict() # get element symbol-to-index dictionary

# instantiate mc object
mc_test = mc(T_move, T_exc, max_disp, xsf)

# run mc simulation
os.system('mkdir -p temp') # make temp directory for qe calculations
os.chdir('temp') # enter temp
log_file = init_log('log.dat') # initialize log file
axsf_file = init_axsf('coord.axsf', niter, xsf) # initialize axsf file
for i in range(niter) :
    # makes a copy of xsf attributes called xsf_old
    xsf_old.copy(xsf)

    # attempt uvt action and store xsf attributes in xsf_new
    xsf_new.at_coord, \
        xsf_new.ind_rem_at, \
        xsf_new.el_list, \
        xsf_new.num_each_el, \
Exemplo n.º 9
0
def advance_mc(config):

    mymc = mc(config)
    mymc.run()