# possible netcdf variable names for time/lat/lon timenames = set(["time", "year"]) latnames = set(["lat", "latitude", "south_north"]) lonnames = set(["lon", "longitude", "west_east"]) ncmask = netCDF4.Dataset(path_mask) clat = ncmask.variables["latitude"][:] clon = ncmask.variables["longitude"][:] cmask = ncmask.variables["country_mask"][:] cname = ncmask.variables["country_name"][:] ccode = ncmask.variables["country_code"][:] #print("nvkds ",nc.dimensions) #print("nvkds ",nc.dimensions.keys()) #mask_file_dimensions=list(nc.dimensions.keys()) #nc.close() cgrid = Grid(lat=clat, lon=clon) ################################### # It seems to be very important that the mask file does not have nan values, # only values between 0 and 1. Check for that. if np.isnan(cmask.min()) or np.isnan(cmask.max()): print("Mask file must not have NaN values! Please redo it so that") print("all values are between 0 and 1.") print("Min value: ", cmask.min()) print("Max value: ", cmask.max()) for icountry in range(cmask.shape[0]): if np.isnan(cmask.min()): print(icountry, cname[icountry], cmask[icountry, :, :].min(), cmask[icountry, :, :].max()) #endif #endfor
def setUp(self): self.data = ["..+..++", "++.B..+", ".....++", "++.....", ".T....+"] self.grid = Grid("", self.data)
}, { "pUndershoot": 0.1, "pOvershoot": 0.1 }) # With this in mind, the default distribution of the grid is now multiplied by these constants # to determine the POSTERIOR probability distribution of the grid. # print robot.sense(grid, ["red", "green"]) # Now we can test our robot's move method, by creating a new grid and passing it in to the method # move_grid = Grid(5) # move_grid.set_state("probability", [1, 0, 0, 0, 0]) # # for i in range(1000): # robot.move(move_grid, 1) # # print move_grid.get_state("probability") # Now we can test the sense_and_move approach, where we do multiple sense and movement cycles and then perform a posterior # distribution calculation sense_and_move_grid = Grid(5) sense_and_move_grid.set_state("probability", [0.2, 0.2, 0.2, 0.2, 0.2]) sense_and_move_grid.set_colors(["green", "red", "red", "green", "green"]) measurements = ["red", "green"] movements = [1, 1] print robot.sense_and_move(sense_and_move_grid, measurements, movements)
while not player_1_name: player_1_name = input('\tPlease enter Player 1\'s name: ') player_1_char = None while player_1_char not in ['X', 'O']: player_1_char = input('\tPlease enter Player 1\'s char: ') player_2_name = None while not player_2_name: player_2_name = input('\tPlease enter Player 2\'s name: ') player_2_char = 'X' if player_1_char is 'O' else 'O' print('Let\'s Begin!\n') init_state = State(' ', player_1_char, Grid(tuple([None] * 9))) init_node = GameNode(init_state) current_node = init_node while not current_node.state.is_final(): print(current_node.state) move = input("Enter move (eg. 'a1'): ") new_node = deepcopy(current_node) if move[0] == 'a': col_ix = 3 elif move[0] == 'b': col_ix = 4 elif move[0] == 'c': col_ix = 5
#!/usr/bin/env python from life import Life from grid import Grid, LIVE import time import sys # R-pentomino r_seed = Grid(50, 80) r_coords = [(25, 37), (25, 38), (26, 36), (26, 37), (27, 37)] for cell in r_coords: r_seed.set(cell[0], cell[1], LIVE) # Pulsar pulsar_seed = Grid(30, 50) pulsar_coords = [(1, 5), (1, 11), (2, 5), (2, 11), (3, 5), (3, 6), (3, 10), (3, 11), (5, 1), (5, 2), (5, 3), (5, 6), (5, 7), (5, 9), (5, 10), (5, 13), (5, 14), (5, 15), (6, 3), (6, 5), (6, 7), (6, 9), (6, 11), (6, 13), (7, 5), (7, 6), (7, 10), (7, 11), (9, 5), (9, 6), (9, 10), (9, 11), (10, 3), (10, 5), (10, 7), (10, 9), (10, 11), (10, 13), (11, 1), (11, 2), (11, 3), (11, 6), (11, 7), (11, 9), (11, 10), (11, 13), (11, 14), (11, 15), (13, 5), (13, 6), (13, 10), (13, 11), (14, 5), (14, 11), (15, 5), (15, 11)] for cell in pulsar_coords: pulsar_seed.set(cell[0], cell[1], LIVE) game = Life(pulsar_seed)
def tick(self): self._tick_enemies() all_alive = self._tick_agents() self.grid_image.append_frame(self.grid) return all_alive def play(self): count = 0 tick_count = 0 while True: if not self.tick(): break if count == 10: self.edibles += self.spawn(Edible, 10) #self.enemies += self.spawn(Enemy, int(self.grid.size/5)) self.enemies += self.spawn(Enemy, int(self.grid.size / 6)) count = 0 count += 1 tick_count += 1 print(tick_count) grid = Grid() grid_image = GridImage() game = Game(grid, grid_image) game.start(int(grid.size / 2), int(grid.size / 1.2), int(grid.size / 3)) game.play() grid_image.save_gif('game.gif')
#!/usr/bin/env python3 from page076_recursive_backtracker import RecursiveBacktracker from grid import Grid grid = Grid(20, 20) RecursiveBacktracker.on(grid) filename = 'recursive_backtracker.png' grid.write_png(filename) print('saved to', filename)
def get_grid(self): return self.grid def get_grid_copy(self): return self.grid_copy def print_solutions(self): for i in range(len(self.solutions)): self.solutions[i].printGrid() def get_solutions(self): return self.solutions example_grid = Grid() example_grid.set_grid([[0, 4, 0, 0, 0, 9, 0, 2, 0], [2, 0, 0, 0, 0, 7, 5, 0, 0], [0, 0, 0, 0, 1, 6, 7, 0, 0], [0, 0, 7, 0, 0, 0, 2, 0, 4], [5, 0, 0, 0, 0, 0, 0, 0, 3], [4, 0, 1, 0, 0, 0, 9, 0, 0], [0, 0, 2, 6, 5, 0, 0, 0, 0], [0, 0, 4, 8, 0, 0, 0, 0, 1], [0, 5, 0, 1, 0, 0, 0, 6, 2]]) several_solution_grid = Grid() several_solution_grid.set_grid([[5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3],
from grid import Grid from arraystack import ArrayStack f = open("data.txt", 'r') s = f.read() f.close() for i in range(len(s)): print(s[i], end="") g1 = Grid(15, 15, 0) enterPointRow = 2 enterPointCol = 0 exitPointRow = 14 exitPointCol = 10 for i in range(15): for j in range(15): block = s[i * 30 + 2 * j] if block == '#': g1[i][j] = '#' if block == ' ': g1[i][j] = ' ' #for i in range(15): # print(g1[2][i]) #for i in range(15): # for j in range(15): # print (g1[i][j],end=" ") # print()
def make_normal_grid(): return Grid(5, 5)
def test_init(): assert Grid(5, 5) is not None
0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]] new_grid = Grid() fill_grid(reflector, new_grid, 20, 10) grid_length = 60 grid_height = 50 window_width = new_grid.cols + 1 window_height = new_grid.rows + 1 sleep_time = 50 iterations = 300 screen = curses.initscr() window = curses.newwin(window_height, window_width, 0, 0) curses.start_color() curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_WHITE)
def main(): flags = FULLSCREEN | DOUBLEBUF screen = pygame.display.set_mode(SCREEN_SIZE, flags) screen.fill((0, 0, 0)) grid = Grid(screen) finding = Pathfinding() screen.set_alpha(None) pygame.event.set_allowed([QUIT, KEYDOWN, KEYUP]) start_alg = False # Booleans to determine if keys are pressed down shift_pressed = False q_key_pressed = False w_key_pressed = False while True: for event in pygame.event.get(): # Handle exit if event.type == QUIT: pygame.quit() sys.exit() pressed = pygame.key.get_pressed() # Toggle key booleans if event.type == pygame.KEYDOWN: if pressed[pygame.K_LSHIFT]: shift_pressed = True if pressed[pygame.K_q]: q_key_pressed = True if pressed[pygame.K_w]: w_key_pressed = True if event.type == pygame.KEYUP: if pressed[pygame.K_LSHIFT] == False: shift_pressed = False if pressed[pygame.K_q] == False: q_key_pressed = False if pressed[pygame.K_w] == False: w_key_pressed = False # Start selected algorithm if pressed[pygame.K_RETURN] and grid.start_node and grid.end_node: start_alg = True finding.open_list.add(grid.start_node) # Clear grid if pressed[pygame.K_SPACE]: grid.empty_grid(screen) finding = Pathfinding() # Exit application if pressed[pygame.K_ESCAPE]: pygame.quit() sys.exit() # Change nodes under where mouse clicked if pygame.mouse.get_pressed()[0]: if shift_pressed: # Erase node grid.update_node(event, 'blank') elif q_key_pressed: # Start Node grid.update_node(event, 'start') elif w_key_pressed: # End Node grid.update_node(event, 'end') else: # Wall Node grid.update_node(event, 'wall') # Continue pathfinding algorithm if not finished if start_alg: finding.continue_pathfinding(grid) if finding.finished: # Draw result path for i in range(len(finding.path)): if i == 0 or i == len(finding.path) - 1: continue node = finding.path[i] grid.draw_node(node[0], node[1], 'path') start_alg = False finding.finished = False pygame.display.flip() # Update display
plotting.plot_iterative_method_convergance(ret, None, 'hartree', 'Hartree', KNOWN_HE_GROUND_STATE_EV) plotting.plot_iterative_method_convergance(ret, None, 'hartree', 'Hartree', KNOWN_HE_GROUND_STATE_EV, skip=3) #plotting.plot_separate_wavefunctions2(eigenfunction, grid) def test_roothaan_method(n, m, Z, grid, N=2): start = time.process_time() ret = roothaan.roothaan(N, n, m, Z, verbose=True, return_progress=True) wavefunc = ret['eigenfunction'] print(f"Time to run: {time.process_time() - start}") print(units.atomic_to_ev(wavefunc.E)) print(wavefunc.C) plotting.plot_wavefunction(wavefunc, grid, None, 'roothaan') plotting.plot_iterative_method_convergance(ret, None, 'roothaan', 'Roothaan', KNOWN_HE_GROUND_STATE_EV) #test_no_interaction_method(24, 2, 5, 2) #test_hartree_method(24, 2, 5, 2) #test_roothaan_method(3, 2, 2, Grid(8, 5), N=2) test_roothaan_method(3, 2, 2, Grid(64, 5), N=4)
def __init__(self, venue_name, map_image_path): self.venue_name = venue_name self.map_image_path = map_image_path self.grid = Grid(map_image_path, DEBUG) self.branch = {} self.diffuse_params = 0
data = sock.recv(1024).decode() # length of a byte # creates a list that will be seen in CMD, splits the cellx,celly,your turn data data = data.split('-') x, y = int(data[0]), int(data[1]) if data[2] == 'your turn': turn = True if data[3] == 'False': grid.game_over = True if grid.get_cell_value(x, y) == 0: grid.set_cell_value(x, y, 'X') print(data) create_thread(receive_data) grid = Grid() # for the lines from the grid module running = True player = 'O' turn = False # server will go first playing = 'True' while running: # we set it as TRUE for event in pygame.event.get( ): # events basically read the keystrokes and do an action based on them if event.type == pygame.QUIT: # disables the module running = False # ends while loop if event.type == pygame.MOUSEBUTTONDOWN and not grid.game_over: # basically reads the user clicks # will only execute if game over is True # this returns a tuple, so when i click with my left mouse, itll give me (1,0,0)
def init_random_grid(r, c): g = Grid(r, c) for _ in range(random.randint(0, r * c)): g.set_alive(random.randint(0, r - 1), random.randint(0, c - 1)) return g
def main(): pygame.init() pygame.font.init() myfont = pygame.font.SysFont('Comic Sans MS', 30) display_size = width, height = 1000, 600 white = 255, 255, 255 screen = pygame.display.set_mode(display_size) # Set the x,y coordinates for each grid. board_x = 350 board_y = 150 row_top_x = board_x row_middle_x = board_x+100 row_bottom_x = board_x+200 column_left_y = board_y column_middle_y = board_y+100 column_right_y = board_y+200 # Row 1 grid_one = Grid(row_top_x, column_left_y) grid_two = Grid(row_middle_x, column_left_y) grid_three = Grid(row_bottom_x, column_left_y) # Row 2 grid_four = Grid(row_top_x, column_middle_y) grid_five = Grid(row_middle_x, column_middle_y) grid_six = Grid(row_bottom_x, column_middle_y) # Row 3 grid_seven = Grid(row_top_x, column_right_y) grid_eight = Grid(row_middle_x, column_right_y) grid_nine = Grid(row_bottom_x, column_right_y) board = [grid_one, grid_two, grid_three, grid_four, grid_five, grid_six, grid_seven, grid_eight, grid_nine] # Draw each grid at the specific x,y coordinate to make a board. for grid in board: pygame.draw.rect(screen, white, (grid.x, grid.y, grid.width, grid.height), grid.thickness) def handle_player_turn(mouse_position): success = False mouse_pos_x = mouse_position[0] mouse_pos_y = mouse_position[1] for grid in board: if (mouse_pos_x >= grid.x and mouse_pos_x <= grid.x+100) and (mouse_pos_y >= grid.y and mouse_pos_y <= grid.y+100) and grid.play is None: # Draw a circle in the middle of the grid. pygame.draw.circle(screen, white, (grid.x+50, grid.y+50), 30, 4) grid.play = 'player' success = True return success def handle_computer_turn(): success = False attempts = 5 while not success and attempts >= 0: index = random.randint(0, len(board)-1) selected_grid = board[index] if selected_grid.play is None: # Draw a cross in the middle of the grid. pygame.draw.line(screen, white, (selected_grid.x+10, selected_grid.y+90), (selected_grid.x+90, selected_grid.y+10), 4) pygame.draw.line(screen, white, (selected_grid.x+10, selected_grid.y+10), (selected_grid.x+90, selected_grid.y+90), 4) selected_grid.play = 'computer' success = True else: attempts -= 1 return success def check_winner(): # Check to see if valid series of plays have been played on the board. winner = '' if board[0].play is not None: if(board[0].play == board[1].play) and (board[0].play == board[2].play): winner = grid_one.play elif (board[0].play == board[3].play) and (board[0].play == board[6].play): winner = grid_one.play elif (board[0].play == board[4].play) and (board[0].play == board[8].play): winner = grid_one.play elif board[3].play is not None and (board[3].play == board[4].play) and (board[3].play == board[5].play): winner = grid_four.play elif board[6].play is not None and (board[6].play == board[7].play) and (board[6].play == board[8].play): winner = grid_seven.play elif board[1].play is not None and (board[1].play == board[4].play) and (board[1].play == board[7].play): winner = grid_two.play elif board[2].play is not None and (board[2].play == board[4].play) and (board[2].play == board[6].play): winner = grid_three.play elif board[2].play is not None and (board[2].play == board[5].play) and (board[2].play == board[8].play): winner = grid_three.play return winner while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() player_success = handle_player_turn(pos) if player_success: computer_success = handle_computer_turn() if computer_success: check_winner() winner = check_winner() if winner is not '': textsurface = myfont.render( winner + ' wins!', False, (255, 255, 255)) screen.blit(textsurface, (420, 70)) pygame.display.flip()
""" Algorithm to implements a 'perfect' maze. It has two major biases: a. There is always a 'diagonal' path from the South-west starting point to the North-east end b. The north-most row and the East-mode columns are always an unbroken corridor """ def __init__(self): pass @staticmethod def create(grid): for cell in grid.each_cell(): neighbors = [] if cell.cellNorth is not None: neighbors.append(cell.cellNorth) if cell.cellEast is not None: neighbors.append(cell.cellEast) if len(neighbors): index = random.randint(0, len(neighbors) - 1) neighbor = neighbors[index] cell.link(neighbor) if __name__ == "__main__": nRows = input("Enter number of rows: ") nColumns = input("Enter number of columns: ") g = Grid(nRows, nColumns) BinaryTreeMaze.create(g) print g
param.freq_plot = 10 param.freq_his = 0.005 param.freq_diag = 0.001 #plot param.plot_interactive = True param.plot_var = 'vorticity' param.cax = [-2000, 2000] param.colorscheme = 'imposed' # physics param.forcing = False param.noslip = True param.diffusion = False grid = Grid(param) param.Kdiff = 5e-2 * grid.dx # it's time to modify the mask and add obstacles if you wish, 0 is land #grid.msk[:param.ny/4,:param.nx/4]=0 #grid.msk[:55,35]=0 #grid.msk[:,:4]=0 #grid.finalize() f2d = Fluid2d(param, grid) model = f2d.model xr, yr = grid.xr, grid.yr vor = model.var.get('vorticity')
# Several simulation parameters nx = 32 # Number of cells in x ny = 32 # and y lx = 0.04 # Domains size in x ly = 0.04 # and y nParticles = 100000 # Number of macro particles weightInit = 1.e9 / nParticles # Initial weight of macro particles dt = 2.155172413795e-11 # Time step nTimeSteps = 10000 # Number of time steps of the simulation nAnimate = 20 # Number of time steps between graphical output nTimeStepsPartMan = 50 # Number of time steps between particle management nHistoryOut = 1000 # Number of time steps between history output # Generate all objects gridObj = Grid(nx, ny, lx, ly, 1) # Elliptical boundary with constant radius is circular beamObj = LHCBeam(gridObj, dt) # LHC beam type particlesObj = particles.Particles( 'electrons', 'variableWeight') # Particles types and kind particleBoundaryObj = AbsorbElliptical( gridObj, particlesObj) # Particle boundary fitting to grid/field boundary secElecEmitObj = FurmanEmitter( particleBoundaryObj, particlesObj) # Secondary emission at particle boundary poissonSolverObj = PoissonSolver( gridObj) # Poisson solver for electric field calculation # Some setup homoLoader(gridObj, particlesObj, particleBoundaryObj, nParticles, weightInit) # Loads a homogeneous particle distribution physicalParticleCount = numpy.zeros(
def get_grid(filename): f = open(filename) content = [list(line.strip()) for line in f.readlines()] f.close() return Grid(len(content), len(content[0]), content)
from z3 import * from grid import Grid from display import draw_grid g = Grid(9, 9) s = Solver() for i in range(9): s.add(Distinct([g.cell(i, j).var for j in range(9)])) s.add(Distinct([g.cell(j, i).var for j in range(9)])) for i in range(3): for j in range(3): s.add( Distinct([ g.cell(3 * i + di, 3 * j + dj).var for di in range(3) for dj in range(3) ])) for cell in g.cells: s.add(cell.var >= 1) s.add(cell.var <= 9) l = [ [5, 3, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 0, 0, 0, 1],
def create_layer(self, object_type): """Create a layer and populate it with the appropriate object.""" layer = Grid(object_type) layer.init_chunks() layer.init_objects() return layer
from grid import Grid from game import Game from player import Player players = [Player(0), Player(1)] #exit() grid = Grid(3) game = Game(grid, players)
# Update student entry with the stop information. f.geometry.coordinates = [coords[0], stp, coords[-1]] open(file_students, 'w').write(geojson.dumps(students, indent=2)) open(file_stops, 'w').write(json.dumps(stops_to_json_compatible(stops), indent=2)) return (students, stops) def stops_to_dict(file_json): stops = json.load(open(file_json, 'r')) school_stop_to_load = {} for [sch, stp, load] in stops: (sch, stp) = (tuple(sch), tuple(stp)) if sch not in school_stop_to_load: school_stop_to_load[sch] = {} if stp not in school_stop_to_load[sch]: school_stop_to_load[sch][stp] = load return school_stop_to_load def stops_to_json_compatible(stops): ''' Tuples cannot be keys in a JSON file, so we replace them with strings. ''' return [[sch, stp, stops[sch][stp]] for sch in stops for stp in stops[sch]] if __name__ == "__main__": grid = Grid('input/segments-prepared.geojson') (students, stops) = students_to_stops(grid, 'output/students.geojson', 'output/stops.json', 0.3, 15) ## eof
"""
def main(lines): sys.path.insert(0, os.path.join('..', '..', 'Helpers')) from grid import Grid from dummylog import DummyLog from program import Program SIF = False Program.debug(lines) msg = datetime.utcnow() g = Grid(default=" ") p = Program([int(x) for x in lines.split(",")], DummyLog()) width, height = None, None x, y = 0, 0 while p.flag_running: p.tick() if width is None and SIF: if len(p.output) == 2: width, height = p.get_output(to_get=2) print(width, height) else: if len(p.output) == (1 if SIF else 3): if SIF: i = p.get_output() else: x, y, i = p.get_output(to_get=3) if datetime.utcnow() >= msg: msg += timedelta(seconds=5) print("x: %4d, y: %4d, %3d, '%s'" % (x, y, i, chr(i))) g.set(x, y, chr(i)) if SIF: x += 1 if x >= width: y += 1 x = 0 g.show_grid(DummyLog(), dump_all=True) g.draw_grid(color_map={ " ": (0, 0, 0), "a": (0, 0, 170), "b": (0, 170, 0), "c": (0, 170, 170), "d": (170, 0, 0), "e": (170, 0, 170), "f": (170, 85, 0), "g": (170, 170, 170), "h": (85, 85, 85), "i": (85, 85, 255), "j": (85, 255, 85), "k": (85, 255, 255), "l": (255, 85, 85), "m": (255, 85, 255), "n": (255, 255, 85), "o": (255, 255, 255), "9": (0, 0, 0), "0": (0, 0, 170), "1": (0, 170, 0), "2": (0, 170, 170), "3": (170, 0, 0), "4": (170, 0, 170), "5": (170, 85, 0), "6": (170, 170, 170), "7": (85, 85, 85), "8": (85, 85, 255), }, cell_size=(2 if SIF else 5), show_lines=(False if SIF else True))
import os from graphics import draw_map from grid import Grid from pathfinding import find_path, ALGORITHMS if __name__ == "__main__": dir_name = os.getcwd() for filename in os.listdir(os.path.join(dir_name, 'boards')): for algorithm in ALGORITHMS: grid = Grid(os.path.join(dir_name, 'boards', filename)) image_name = filename.replace('.txt', '-{}.png'.format(algorithm)) image_path = os.path.join(dir_name, "report", "img", image_name) draw_map(grid, image_path, *find_path(grid, algorithm)) print "Wrote {}".format(image_name)
def test_turn_right(): rover = Rover('1 2 N', Grid(4, 5)) rover.process_command(north_right_turn) assert str(rover) == '1 2 E' assert repr(rover) == f'Rover: <1 2 E>'