def DFS2(self): # Get map map = self.getMap() # Push start data into stack stack = Stack() entry = Cell(0, 1) stack.push(entry) print('\n DFS2: using Stack Data Structure: ') while not stack.isEmpty(): here = stack.pop() print(here, end='->') x = here.row y = here.col if map[x][y] == 'x': # target point return True else: map[x][y] = '.' # Mark visited # Inspect to see if it can be moved to an adjacent location if self.isValidPos(x - 1, y, map): stack.push(Cell(x - 1, y)) if self.isValidPos(x + 1, y, map): stack.push(Cell(x + 1, y)) if self.isValidPos(x, y - 1, map): stack.push(Cell(x, y - 1)) if self.isValidPos(x, y + 1, map): stack.push(Cell(x, y + 1)) return False
def getLat(jName,aList,relax,reRelax,runLength,nCores,nNodes): """ creates the necessary POSCARs, generates a subdirectory for each run, moves subdirectories to work directory and runs submission script """ # make results directories if relax: sp.call(['mkdir','%s_relax_results'%(jName)]) sp.call(['mv','%s_relax_results'%(jName),WORK]) if reRelax: sp.call(['mkdir','%s_re-relax_results'%(jName)]) sp.call(['mv','%s_re-relax_results'%(jName),WORK]) sp.call(['mkdir','%s_static_results'%(jName)]) sp.call(['mv','%s_static_results'%(jName),WORK]) for a in aList: cell = Cell().loadFromPOSCAR() cell.setA0(float(a)) cell.sendToPOSCAR() # copy files to subdirectory, move subdirectory to WORK dirName = '%s_%.5f'%(jName,a) sp.call(['mkdir',dirName]) sp.call('cp POSCAR INCAR_static KPOINTS POTCAR'.split()+\ [dirName]) if relax: sp.call(['cp','INCAR_relax',dirName]) if reRelax: sp.call(['cp','INCAR_re-relax',dirName]) sp.call(['cp', '-r', dirName, WORK]) # create submission script and run genSubScript(relax,reRelax,jName,dirName,runLength,nCores,nNodes) sp.call(['chmod', '+x', '%s_submit'%dirName]) sp.call(['sbatch','%s_submit'%dirName])
def DFS3(self): # Get map map = self.getMap() # Push(addRear) start data into circular deque deq = CircularDeque() entry = Cell(0, 1) deq.addRear(entry) print('\n DFS3: using Deque Data Structure: ') while not deq.isEmpty(): here = deq.deleteRear() print(here, end='->') x = here.row y = here.col if map[x][y] == 'x': # target point return True else: map[x][y] = '.' # Mark visited # Inspect to see if it can be moved to an adjacent location if self.isValidPos(x - 1, y, map): deq.addRear(Cell(x - 1, y)) if self.isValidPos(x + 1, y, map): deq.addRear(Cell(x + 1, y)) if self.isValidPos(x, y - 1, map): deq.addRear(Cell(x, y - 1)) if self.isValidPos(x, y + 1, map): deq.addRear(Cell(x, y + 1)) return False
class ISOEliminator: def __init__(self, db_config, table): self.db_ = ArkDBMySQL(db_config_file=db_config) self.table_ = table self.db_.set_table(self.table_) self.cell_ = Cell(self.db_) def get_iso_cell_ids_based_on_id(self, id_cell): self.cell_.init_based_on_id(id_cell) id_list = self.cell_.fetch_ids() id_list.remove(id_cell) return id_list def eliminate_iso(self, start, cnt): query = f'SELECT DISTINCT CELL_BSF_UNIFIED FROM {self.table_} LIMIT {start},{cnt}' bsf_uni_list = list() for row in self.db_.run_query_get_all_row(query): bsf_uni_list.append(row['CELL_BSF_UNIFIED'].decode("utf-8")) runner_idx = start // cnt for bsf in tqdm(bsf_uni_list, desc=f'Eliminating str iso[{runner_idx:02}]:'): query = f'SELECT idCELL FROM {self.table_} WHERE CELL_BSF_UNIFIED=%s' id_list = list() removed_ids = set() for row in self.db_.run_query_get_all_row(query, [bsf]): id_list.append(row['idCELL']) for id_cell in tqdm(id_list, desc=f'Cells in {bsf}: '): if id_cell in removed_ids: continue dup_ids = self.get_iso_cell_ids_based_on_id(id_cell) removed_ids.update(dup_ids) if len(dup_ids) != 0: str_temp = ', '.join([str(x) for x in dup_ids]) query = f'DELETE FROM {self.table_} WHERE idCELL IN ({str_temp})' self.db_.run_sql_nocommit(query)
def main(self): matrix = self.engine.readDataFromFile(self.filename) self.player = Player(TypePlayer.HUMAN) self.noRows = len(matrix) self.noColumns = len(matrix[0]) self.width = (self.noColumns + 1) * self.size self.height = (self.noRows + 1 ) * self.size self.canvas = Canvas(self, width = self.width, height = self.height, bg="gray") self.canvas.pack(anchor=NE,side=LEFT) self.ListboxOptionsTypeField = StringVar(self) self.options = OptionMenu(self, self.ListboxOptionsTypeField, *(self.optionsField),command = self.onOptionsMenuSelection) self.ListboxOptionsTypePlayer = StringVar(self) self.optionsTypePlayer = OptionMenu(self, self.ListboxOptionsTypePlayer, *(self.optionsPlayer),command = self.onOptionsPlayerSelection) self.ListboxOptionsTypePlayer.set("HUMAN") self.labelInfoCellPosition = Label(self,text="") self.options.pack(fill="x", padx = 5, pady = 5) self.labelInfoCellPosition.pack(fill="x" ,padx = 5, pady = 5) self.labelInfoCellVisited = Label(self,text="") self.labelInfoCellVisited.pack(fill="x" ,padx = 5, pady = 5) self.optionsTypePlayer.pack(fill="x", padx = 5, pady = 5) self.labelInfoCellMark = Label(self,text="") self.labelInfoCellMark.pack(fill="x" ,padx = 5, pady = 5) self.labelInfoPlayer = Label(self,text="") self.labelInfoPlayer.pack(fill="x" ,padx = 5, pady = 5) self.master.bind("<Key>", self.onKeyPress) self.background_image = PhotoImage(file = os.path.join("assets","Floor.gif")) self.generateCoords() j = 0 for row in matrix: i = 0 self.field.append([]) for cell in row: square = Cell(i,j) square.celltype = TypeCell(int(cell)) idRectangle = "rec:" + str(i) + "," + str(j) x = (i + 1 ) * self.size y = (j + 1 ) * self.size x1 = x + self.size y1 = y + self.size rectangle = self.canvas.create_rectangle(x,y,x1,y1, fill="black", tag = idRectangle,outline="",width="2") square.itemId = rectangle self.canvas.tag_bind(idRectangle, "<Button-1>", self.callback) self.ItemList[rectangle] = (i,j) self.field[j].append(square) i += 1 j += 1 self.markPlayer = self.canvas.create_oval( ((self.cursor[0] + 1) * self.size) + self.size / 4,((self.cursor[0] + 1) * self.size) + self.size / 4, self.size, self.size, outline="red", fill="red", width=2) self.togleHighlightPosition(self.position)
def write(self, col, label, style): self.__adjust_height(style) self.__adjust_bound_col_idx(col) if isinstance(label, (str, unicode)): if len(label) > 0: self.__cells.extend([ Cell.StrCell(self, col, self.__parent_wb.add_style(style), self.__parent_wb.add_str(label)) ]) self.__total_str += 1 else: self.__cells.extend([ Cell.BlankCell(self, col, self.__parent_wb.add_style(style)) ]) elif isinstance(label, (int, long, float)): self.__cells.extend([ Cell.NumberCell(self, col, self.__parent_wb.add_style(style), label) ]) elif isinstance(label, (dt.datetime, dt.time)): self.__cells.extend([ Cell.NumberCell(self, col, self.__parent_wb.add_style(style), self.__excel_date_dt(label)) ]) else: self.__cells.extend([ Cell.FormulaCell(self, col, self.__parent_wb.add_style(style), label) ])
def readLayers(filename="POSCAR"): """ read in y periodicity, z-positions of layers from POSCAR, cleans up z-coordinates so everything is less than 1.0 """ print "Reading from %s..." % filename cell = Cell().loadFromPOSCAR(filename) print "Done" # first loop through sites to get ny and the number of layers zList = [] yList = [] for i in range(cell.numberOfElements()): for j in range(cell.numberOfAtomsOfElement(i)): x, y, z = cell.sites[i][j].position if z >= 1.0: z += -1.0 # keep everything under 1.0 cell.sites[i][j].move([x, y, z]) zList += [z] yList += [y] zList = list(set(zList)) zList.sort() nLayers = len(zList) yList = list(set(yList)) ny = len(yList) / 6 # 2 y values per layer, 3 distinct layers print "Found %d layers" % nLayers print "y periodicity %d" % ny, "\n" cell.sendToPOSCAR(filename) return zList, ny
def create_maze_algorithm(self): for i in range(Maze.ROOM_SIZE * Maze.MAZE_LENGTH + 1): for j in range(Maze.ROOM_SIZE * Maze.MAZE_LENGTH + 1): if i % Maze.ROOM_SIZE == 0: Mediator.ALL_WALLS.append(Cell(i,j)) elif j % Maze.ROOM_SIZE == 0: Mediator.ALL_WALLS.append(Cell(i,j)) for cell in Mediator.ALL_WALLS: if not cell.x == 0 and not cell.x == Maze.ROOM_SIZE* Maze.MAZE_LENGTH: if not cell.y == 0 and not cell.y == Maze.ROOM_SIZE * Maze.MAZE_LENGTH: print(cell.x,end= " ") print(cell.y) if cell.x % Maze.ROOM_SIZE == (Maze.ROOM_SIZE/2)-1: Mediator.ALL_WALLS.remove(cell) elif cell.x % Maze.ROOM_SIZE == Maze.ROOM_SIZE/2: Mediator.ALL_WALLS.remove(cell) elif cell.x % Maze.ROOM_SIZE == (Maze.ROOM_SIZE/2)+1: Mediator.ALL_WALLS.remove(cell) if cell.y % Maze.ROOM_SIZE == (Maze.ROOM_SIZE/2)-1: Mediator.ALL_WALLS.remove(cell) elif cell.y % Maze.ROOM_SIZE == Maze.ROOM_SIZE/2: Mediator.ALL_WALLS.remove(cell) elif cell.y % Maze.ROOM_SIZE == (Maze.ROOM_SIZE/2)+1: Mediator.ALL_WALLS.remove(cell)
def __init__(self, N, p, maze=None): self.openList = [] self.closeList = set() heapq.heapify(self.openList) if maze == None: self.grid = [] self.N = N self.p = p # generate the maze for i in range(N): for j in range(N): b = random.uniform(0, 1) if b <= p: self.grid.append(Cell(i, j, True)) else: self.grid.append(Cell(i, j, False)) # set the start point and the destination point self.start = self.getCell(0, 0) self.start.__setattr__('isWall', False) self.destination = self.getCell(N - 1, N - 1) self.destination.__setattr__('isWall', False) else: self.grid = maze self.N = int(np.sqrt(len(maze))) self.p = 0 self.start = maze[0] self.destination = maze[self.N * self.N - 1]
def BFS2(self): # Get map map = self.getMap() # Push(enqueue) start data into queue. que = CircularQueue() entry = Cell(0, 1) que.enqueue(entry) print('\n BFS2: using Queue Data Structure: ') while not que.isEmpty(): here = que.dequeue() print(here, end='->') x = here.row y = here.col if map[x][y] == 'x': # target point return True else: map[x][y] = '.' # Mark visited # Inspect to see if it can be moved to an adjacent location if self.isValidPos(x - 1, y, map): que.enqueue(Cell(x - 1, y)) if self.isValidPos(x + 1, y, map): que.enqueue(Cell(x + 1, y)) if self.isValidPos(x, y - 1, map): que.enqueue(Cell(x, y - 1)) if self.isValidPos(x, y + 1, map): que.enqueue(Cell(x, y + 1)) return False
def __init__(self): self.table = [] i = 0 while i < 3: row = [Cell(), Cell(), Cell()] self.table.append(row) i = i + 1 self.turn = 'X'
def new_game(self): self.table = [] i = 0 while i < 3: row = [Cell(), Cell(), Cell()] self.table.append(row) i = i + 1 self.turn = 'X'
def create_square_map(self): for i in range(Maze.SQUARE_SIZE + 1): for j in range(Maze.SQUARE_SIZE + 1): if i == 0 or i == Maze.SQUARE_SIZE: Mediator.ALL_WALLS.append(Cell(i,j)) elif j == 0 or j == Maze.SQUARE_SIZE: Mediator.ALL_WALLS.append(Cell(i,j))
def test_get_other_side(self): a = CellModule.Cell(Coord(1, 3)) b = CellModule.Cell(Coord(2, 3)) door = Door(a, SOUTH, b) answer = door.get_other_side(a) self.assertEqual(answer, b) answer = door.get_other_side(b) self.assertEqual(answer, a)
def __init__(self, width, height): self.width = width self.height = height self.maze = [[Cell() for x in range(height)] for y in range(width)] for i in range(0, width): for j in range(0, height): cell = Cell() cell.position = Position(i, j) self.maze[i][j] = cell
def __init__(self, dimension): self.dimension = dimension # dimension is the width x height of the maze self.maze_grid = [[Cell.Cell(x, y) for x in range(dimension)] for y in range(dimension)] self.start = Cell.Cell(0, 0) # start cell of the maze self.maze_grid[0][0] = self.start self.end = Cell.Cell(dimension - 1, dimension - 1) # end cell of the maze self.maze_grid[dimension - 1][dimension - 1] = self.end self.matrix = np.zeros([(2 * dim) + 1, (2 * dim) + 1], dtype=np.uint8) # init matrix to all 0s
def initialize_cells_uniformly(number_of_regions=4): global Active_cells initial_cell_positions = [] region_size = (WIN_WIDTH / (number_of_regions / 2), WIN_HEIGHT / (number_of_regions / 2)) # Generating random non overlapping cells positions Active_cells.append( Cell.Cell(random.randint(PADDING, WIN_WIDTH - PADDING), random.randint(PADDING, WIN_HEIGHT - PADDING), 0)) for i in range(POPULATION): Active_cells.append(Cell.Cell(id=i + 1))
def generateMaze(self, mazeSize, p): tempMaze = [] for i in range(mazeSize): for j in range(mazeSize): b = random.uniform(0, 1) if b <= p: tempMaze.append(Cell(i, j, True)) else: tempMaze.append(Cell(i, j, False)) tempMaze[0].isWall = False tempMaze[mazeSize * mazeSize - 1].isWall = False return tempMaze
def write_blanks(self, c1, c2, style): self.__adjust_height(style) self.__adjust_bound_col_idx(c1, c2) assert c1 <= c2, 'start column (%d) must preceed end column (%d)' % ( c1, c2) if (c1 == c2): self.__cells.extend( [Cell.BlankCell(self, c1, self.__parent_wb.add_style(style))]) else: self.__cells.extend([ Cell.MulBlankCell(self, c1, c2, self.__parent_wb.add_style(style)) ])
def generateCell(self, x, y): cell = Cell() pos = len(self.cells) cell.x = x cell.y = y #keeping track of max_x if cell.x > self.max_x: self.max_x = cell.x #keeping track of max_y if cell.y > self.max_y: self.max_y = cell.y #keeping track of min_x if cell.x < self.min_x: self.min_x = cell.x #keeping track of min_y if cell.y < self.min_y: self.min_y = cell.y #getting current cell's position self.cell_lookup[str(x) + "," + str(y)] = pos cell.position = pos #WEBBING~~~~ #north try: n = self.cell_lookup[str(cell.x) + "," + str((cell.y) + 1)] except KeyError: pass else: self.cells[n].south = pos cell.north = n #east try: e = self.cell_lookup[str((cell.x) + 1) + "," + str(cell.y)] except KeyError: pass else: self.cells[e].west = pos cell.east = e #south try: s = self.cell_lookup[str(cell.x) + "," + str((cell.y) - 1)] except KeyError: pass else: self.cells[s].north = pos cell.south = s #west try: w = self.cell_lookup[str((cell.x) - 1) + "," + str(cell.y)] except KeyError: pass else: self.cells[w].east = pos cell.west = w self.cells.append(cell)
def replication(environment): """ """ print("\n") print("-" * 80) print("\t\t\tReplication") print("-" * 80) print("\n") new_environment = [] for embryo in environment: print("Embryo: {}".format(embryo)) embryo_network = embryo.get_network() embryo_network_parameters = embryo.get_network_parameters( ) # FOR NOW, no mutations here. Just pass them along. embryo_network_copy_1 = copy.deepcopy(embryo_network) embryo_network_copy_2 = copy.deepcopy(embryo_network) embryo_network_copies = [embryo_network_copy_1, embryo_network_copy_2] i = 0 for network in embryo_network_copies: mutate = r.sample([True, False], 1)[0] print("\n--------------") print("Offspring {}".format(i + 1)) if mutate: print("**Mutation**") new_network = Genetic_Network(network) new_network.mutate() traits = { "network": new_network.get_network(), "parameters": embryo_network_parameters } new_cell = Cell(**traits) new_environment.append(new_cell) else: print("No Mutation") traits = { "network": network, "parameters": embryo_network_parameters } new_cell = Cell(**traits) new_environment.append(new_cell) i += 1 return new_environment
def addTail(self, v): print("adding value", v, " at the end of the list") cell = Cell() cell.value = v cell.next = None if self.tail == None: cell.previous = None self.head = cell self.tail = cell else: cell.previous = self.tail self.tail.next = cell self.tail = cell self.dump()
def addHead(self, value): print("adding value", value, " at the head of the list") cell = Cell() cell.value = value cell.previous = None if self.head == None: cell.next = None self.head = cell self.tail = cell else: cell.next = self.head self.head.previous = cell self.head = cell self.dump()
def outputInfo3D(labels, filename): cellList = [] counter = 0 filename = filename.split("X")[1] filename = filename.split(".")[0] filename = filename.split("L") time = int(filename[0]) for lab in labels: cell = Cell(counter) cell.addLocTime(time, int(lab.centroid[0]), int(lab.centroid[1]), int(lab.centroid[2])) cellList.append(cell) counter = counter + 1 return cellList
def searchAStar(self, initialX, initialY, finalX, finalY): heap = [] cell = Cell(initialX, initialY, finalX, finalY) heapq.heappush(heap, cell) while len(heap) > 0 and (heap[0].x != finalX or heap[0].y != finalY): cell = heapq.heappop(heap) for dir in self.v: x = cell.x + dir[0] y = cell.y + dir[1] if self.repository.getMap().isEmpty(x, y): new_cell = Cell(x, y, finalX, finalY, cell.cost + 1) heapq.heappush(heap, new_cell) self.repository.getMap().markVisited(x, y, cell.x, cell.y) return self.getPath(initialX, initialY, finalX, finalY, heap)
def searchGreedy(self, mapM, droneD, initialX, initialY, finalX, finalY): pq = [] cell = Cell(initialX, initialY, finalX, finalY) heapq.heappush(pq, cell) while len(pq) > 0 and (pq[0].x != finalX or pq[0].y != finalY): cell = heapq.heappop(pq) for dir in self.v: x = cell.x + dir[0] y = cell.y + dir[1] if self.repository.getMap().isEmpty(x, y): new_cell = Cell(x, y, finalX, finalY) heapq.heappush(pq, new_cell) self.repository.getMap().markVisited(x, y, cell.x, cell.y) return self.getPath(initialX, initialY, finalX, finalY, pq)
def gen_landscape(self, p_flat, p_hilly, p_forest, p_cave): landscape = [['0' for col in range(self.dim)] for row in range(self.dim)] for i in range(self.dim): for j in range(self.dim): p = random.random() if p < p_flat: landscape[i][j] = Cell('flat') elif p < p_flat + p_hilly: landscape[i][j] = Cell('hilly') elif p < p_flat + p_hilly + p_forest: landscape[i][j] = Cell('forest') elif p < p_flat + p_hilly + p_forest + p_cave: landscape[i][j] = Cell('cave') return landscape
def set_agent_pieces(board): #setting pieces for the top side, agent for x in range(0, board.side_length, 3): #Double check 3 is the counter #Wumpus piece = Wumpus(False, 'b') board.my_grid[x][0].piece = piece board.agent_pieces.append(Cell(x, 0, piece, False)) #Hero piece = Hero(False, 'b') board.my_grid[x + 1][0].piece = piece board.agent_pieces.append(Cell(x + 1, 0, piece, False)) #Mage piece = Mage(False, 'b') board.my_grid[x + 2][0].piece = piece board.agent_pieces.append(Cell(x + 2, 0, piece, False))
def autoSubdivisions(length, a0=0, POSCAR='POSCAR'): """ Calculate subdivisions automatically from POSCAR """ # Load POSCAR cell = Cell().loadFromPOSCAR(POSCAR) if a0 == 0: a0 = cell.a0 nAtoms = sum(cell.elementCounts) # Calculate reciprocal lattice vectors a1, a2, a3 = cell.latticeVectors b1 = np.cross(a2, a3) / (np.dot(a1, np.cross(a2, a3))) / a0 b2 = np.cross(a3, a1) / (np.dot(a2, np.cross(a3, a1))) / a0 b3 = np.cross(a1, a2) / (np.dot(a3, np.cross(a1, a2))) / a0 bNorms = [np.linalg.norm(b) for b in [b1, b2, b3]] print bNorms # Calculate subdivision as per # http://cms.mpi.univie.ac.at/vasp/vasp/Automatic_k_mesh_generation.html subdivisions = [1] * 3 for i in [0, 1, 2]: subdivisions[i] = int(max(1, ((length * bNorms[i]) + 0.5))) KPPRA = int(np.prod(subdivisions) * nAtoms) # k-points per recip. atom print 'Subdivisions are %d %d %d' % tuple(subdivisions) print 'KPPRA = %d' % KPPRA return subdivisions
def set_adversary_pieces(board): #setting pieces for the bottom side, adversary side = board.side_length for x in range(0, side, 3): #Double check 3 is the counter #Wumpus piece = Wumpus(False, 'w') board.my_grid[x][side - 1].piece = piece board.adversary_pieces.append(Cell(x, side - 1, piece, False)) #Hero piece = Hero(False, 'w') board.my_grid[x + 1][side - 1].piece = piece board.adversary_pieces.append(Cell(x + 1, side - 1, piece, False)) #Mage piece = Mage(False, 'w') board.my_grid[x + 2][side - 1].piece = piece board.adversary_pieces.append(Cell(x + 2, side - 1, piece, False))
def draw(self, init=False): if init: self.root.wm_title("Game of Life") self.root.geometry("%dx%d" % (600, 600)) self.width = 500 self.height = 500 self.canvas = Canvas(self.root, bg="white") self.root.bind("<Configure>", self.resize) self.root.bind("<Key>", self.handleKey) # add cells for y in range(self.n): for x in range(self.n): self.cells.append(Cell(self, pos=(x, y))) for c in self.cells: c.initNeighbours() self.root.update() self.resize()
def radialSetup(self): """Set up the islet such that the distance of any cell from the center is one-half the radius""" [k, c] = [0, 0] for i in range(self.dimensions): for j in range(self.dimensions): while k < self.dimensions: # only create cells if within some distance of the center if (math.sqrt((self.dimensions / 2 - i)**2 + (self.dimensions / 2 - j)**2 + (self.dimensions / 2 - k)**2) > self.dimensions / 2): k += 1 continue typ = self.getCell(random.random(), i, j, k) # if position is vacant, add cell to space # create cell cell_obj = Cell.Cell(c, i, j, k, typ) print( str(datetime.datetime.now()) + '\tSpace.RadialSetup Added cell to islet: id', cell_obj) self.cells[i][j][k] = cell_obj # store type and position self.cell_positions.append([typ, i, j, k]) self.cell_sizes.append(cell_obj.diam) c += 1 k += 1 k = 0
def __init__(self): super().__init__() self.maze = [None] * N_COLS for i in range(N_COLS): self.maze[i] = [None] * N_ROWS for j in range(N_ROWS): self.maze[i][j] = Cell((i, j))
def initialize_game(self): """Initialize the cells in a new list""" for row in range(0, self.height): for col in range(0, self.width): self.solved_puzzle.append( Cell(row, col, self.get_box(row, col), self.puzzle, self.get_value(row, col)))
def generateCell(self,x,y): cell = Cell() pos = len(self.cells) cell.x = x cell.y = y #keeping track of max_x if cell.x > self.max_x: self.max_x = cell.x #keeping track of max_y if cell.y > self.max_y: self.max_y = cell.y #keeping track of min_x if cell.x < self.min_x: self.min_x = cell.x #keeping track of min_y if cell.y < self.min_y: self.min_y = cell.y #getting current cell's position self.cell_lookup[str(x)+","+str(y)] = pos cell.position = pos #WEBBING~~~~ #north try: n = self.cell_lookup[str(cell.x)+","+str((cell.y)+1)] except KeyError: pass else: self.cells[n].south = pos cell.north = n #east try: e = self.cell_lookup[str((cell.x)+1)+","+str(cell.y)] except KeyError: pass else: self.cells[e].west = pos cell.east = e #south try: s = self.cell_lookup[str(cell.x)+","+str((cell.y)-1)] except KeyError: pass else: self.cells[s].north = pos cell.south = s #west try: w = self.cell_lookup[str((cell.x)-1)+","+str(cell.y)] except KeyError: pass else: self.cells[w].east = pos cell.west = w self.cells.append(cell)
def getLatHex(jName, aList, caList, runLength,NCORES): """ creates the necessary POSCARs for a hexagonal structure generates a subdirectory for each vasp run, each with the necessary files, moves subdirectories to work directory and runs submission script """ dirList = [] for a in aList: for ca in caList: cell = Cell().loadFromPOSCAR() cell.setA0(float(a)) (x,y,z) = cell.latticeVectors # assumes these lattice vectors: # 1.00000 0.00000000000000 0.00000 # -0.50000 0.86602540378444 0.00000 # 0.00000 0.00000000000000 c/a # where a is the overall scaling factor cell.setLatticeVectors([x,y,[0,0,ca]]) cell.sendToPOSCAR() # copy files to subdirectory, move subdirectory to WORK dirName = '%s_%.5f_%.5f'%(jName,a,ca) dirList += [dirName] sp.call(['mkdir',dirName]) sp.call('cp POSCAR INCAR KPOINTS POTCAR'.split()+\ [dirName]) sp.call(('cp -r %s '%dirName)+WORK,shell=True) # create submission script and run genSubScript(jName,dirList,runLength,NCORES) sp.call('chmod u+x %s_submit'%jName,shell=True) sp.call(['sbatch','%s_submit'%jName])
def test_1(): allcells=[] x = 10 y = 10 g = Grid.grid(10,10) print g for i in range(0,y): column = [] for j in range(0,x): column.append(Cell.cell((i,j))) allcells.append(column) c = Cell.cell((0,0)) c.getNeighbours()
def __init__(self): self.rows = 9 self.columns = 9 self.cells = [] for row in range(9): # Add an empty array that will hold each cell in this row self.cells.append([]) for column in range(9): self.cells[row].append(Cell.cell(row, column, 0)) # Append a cell
def simulation(individual,time): def changeLights(index,board,individual): # 1 board[0][3].open = 1 if individual[0][index]==1 else 0 board[2][3].open = 0 if individual[0][index]==1 else 1 # 2 board[0][8].open = 1 if individual[1][index]==1 else 0 board[3][3].open = 0 if individual[1][index]==1 else 1 # 3 board[1][3].open = 1 if individual[2][index]==1 else 0 board[2][8].open = 0 if individual[2][index]==1 else 1 # 4 board[1][8].open = 1 if individual[3][index]==1 else 0 board[3][8].open = 0 if individual[3][index]==1 else 1 return board def printBoard(board): import PrintBoard PrintBoard.printBoard(board) inputCars=0 index=0 board = Cell.getDefaultConfiguration() for i in range(time): if (i%5==0): board[0][0].addCar();board[1][0].addCar();board[2][0].addCar();board[3][0].addCar(); inputCars+=4 if (i%10==0): board = deepcopy(changeLights(index,board,individual)) index+=1 newBoard = deepcopy(board) # Intersection newBoard[3][4].actualize(board[0][8],board[3][3],board[0][10],board[3][5]) newBoard[3][9].actualize(board[1][8],board[3][8],board[1][10],board[3][10]) newBoard[2][4].actualize(board[0][3],board[2][3],board[0][5],board[2][5]) newBoard[2][9].actualize(board[1][3],board[2][8],board[1][5],board[2][10]) for j in range(0,len(board),1): for k in range(len(board[0])): if (k==0): newBoard[j][k].actualize(board[j][k+1]) if (k==1 or k==2 or k==6 or k==7 or k==11 or k==12): newBoard[j][k].actualize(board[j][k-1],board[j][k+1]) if (k==3 or k==8): newBoard[j][k].actualize(board[j][k-1],board[j][k+1]) if (k==5 or k==10): if (j<=1): newBoard[j][k].actualize(board[j][k-1],board[j][k+1],True) else: newBoard[j][k].actualize(board[j][k-1],board[j][k+1],False) if (k==13): newBoard[j][k].actualize(board[j][k-1]) # copy new board board = deepcopy(newBoard) fit = (board[0][13].getOutput() + board[1][13].getOutput() + board[2][13].getOutput() + board[3][13].getOutput()) return float(fit)/float(inputCars)
def makeISF(nShifts): print 'Reading from POSCAR...' # make reading from POSCAR a separate function cell = Cell().loadFromPOSCAR() # first loop through sites to get ny and the number of layers yList = [] zList = [] for element in cell.sites: for i in range(cell.numberOfElements()): for j in range(cell.numberOfAtomsOfElement(i)): x,y,z = cell.sites[i][j].position yList += [y] zList += [z] zList = list(set(zList)) zList.sort() nLayers = len(zList) print 'Found %d layers'%nLayers yList = list(set(yList)) yList.sort() print yList ny = len(yList)/6 # 3 different layers, 2 y values per period yA = yList[0] yB = yList[1] yC = yList[3] sequence = '' # loop through to get sequence for zPoint in zList: for element in cell.sites: for i in range(cell.numberOfElements()): for j in range(cell.numberOfAtomsOfElement(i)): x,y,z = cell.sites[i][j].position if z == zPoint: if y == yA: sequence += 'A' elif y == yB: sequence += 'B' elif y == yC: sequence += 'C' print sequence #firstLayer = raw_input('First layer to shift: ') #lastLayer = raw_input('Last layer to shift: ') # loop through displacements and created shifted POSCARs """
def runITS(jName,aList,runLength,NCORES): """ generate subdirectory, copies files, and submits job to relax a strained cell """ # copy files to subdirectory, move subdirectory to WORK for a in aList: # create submission script genSubScript(jName,aList,runLength,NCORES) # apply perpendicular strains cell = Cell().loadFromPOSCAR('POSCAR.EN') strainCell(cell, [0,a,a,0,0,0]) cell.sendToPOSCAR() # copy files to subdirectory, move subdirectory to WORK sp.call(['mkdir','%s_%.5f'%(jName,a)]) sp.call('cp POSCAR INCAR KPOINTS POTCAR'.split()+[jName+'_submit']+\ ['%s_%.5f'%(jName,a)]) sp.call('cp -r %s_%.5f '%(jName,a)+WORK,shell=True) sp.call('chmod u+x %s_submit'%jName,shell=True) # run submission script sp.call(['sbatch','%s_submit'%jName])
def __init__(self): self.rows = 5 self.columns = 5 self.cells = [] self.possibilities = [] # to store possible values for all cells for row in range(self.rows): # Add an empty array that will hold each cell in this row self.cells.append([]) self.possibilities.append([]) for column in range(self.columns): self.cells[row].append(Cell.cell(row, column, 0)) # Append a cell self.possibilities[row].append([1, 2, 3, 4, 5]) self.constraints = []
def getLatCubic(jName, aList,runLength,NCORES): """ creates the necessary POSCARs for a cubic structure generates a subdirectory for each vasp run, each with the necessary files, moves subdirectories to work directory and runs submission script """ dirList = [] for a in aList: cell = Cell().loadFromPOSCAR() cell.setA0(float(a)) cell.sendToPOSCAR() # copy files to subdirectory, move subdirectory to WORK dirName = '%s_%.5f'%(jName,a) dirList += [dirName] sp.call(['mkdir',dirName]) sp.call('cp POSCAR INCAR KPOINTS POTCAR'.split()+\ [dirName]) sp.call(('cp -r %s '%dirName)+WORK,shell=True) # create submission script and run genSubScript(jName,dirList,runLength,NCORES) sp.call('chmod u+x %s_submit'%jName,shell=True) sp.call(['sbatch','%s_submit'%jName])
def getCxx(jName,eN,tList,runType,runLength,NCORES): """ generates a subdirectory for each vasp run, each with the necessary files moves subdirectories to $WORK directory and runs submission scripts ??? """ if eN == 0.0: CONTCAR = 'CONTCAR.E0' else: CONTCAR = HOME+'%.5f_main_results/'%eN+'%.5f_main/CONTCAR'%eN for t in tList: # generate lattice w/ applied strain # start from equilibrium lattice sp.call(['cp',CONTCAR,'POSCAR']) if runType == 'relaxed': sp.call('cp INCAR.isif2 INCAR'.split()) else: sp.call('cp INCAR.static INCAR'.split()) # create submission script, place copy in appropriate subdirectory genSubScript(jName,tList,runLength,NCORES) # sp.call(('cp submission_script '+jName+"_%.5f/"%t).split()) cell = Cell().loadFromPOSCAR('POSCAR') # strain tensors from Cerny 2004 if 'cprime' in jName: strainCell(cell, [t,-t,0,0,0,0]) elif 'c44' in jName: strainCell(cell, [0,0,0,t,0,0]) else: # 'c66' in jName strainCell(cell, [0,0,0,0,0,t]) cell.setSiteMobilities(True,True,True) # allow all directions to relax cell.sendToPOSCAR() # copy files to subdirectory, move subdirectory to $WORK sp.call(['mkdir',jName+'_%.5f'%t]) sp.call('cp POSCAR INCAR KPOINTS POTCAR'.split()+[jName+'_submit']+\ [jName+'_%.5f/'%t]) sp.call('cp -r '+jName+'_%.5f '%t + WORK,shell=True) sp.call('chmod u+x %s_submit'%jName,shell=True) # run submission script sp.call(['sbatch','%s_submit'%jName])
def makeISF(nShifts,nLayers,ny,nGap): halfz = .5*(nLayers-1)/(nLayers+nGap) # z position right between the surface layers topTwo = 1.5/(nLayers+nGap) bottomTwo = (nLayers-2.5)/(nLayers+nGap) displacements = np.linspace(0.0, 1.0, nShifts+1) for disp in displacements: cell = Cell().loadFromPOSCAR() cell.setSiteMobilities(False,False,True) for element in cell.sites: for i in range(cell.numberOfElements()): for j in range(cell.numberOfAtomsOfElement(i)): x,y,z = cell.sites[i][j].position if z > halfz: cell.sites[i][j].move([x-disp*0.5, y - disp*(1.0/6.0)/ny, z]) if z < topTwo or z > bottomTwo: cell.sites[i][j].zfree = False cell.sendToPOSCAR(('POSCAR_%.5f'%disp).replace('.',''))
def makeESF(nShifts,nLayers,ny,nGap): topTwo = 1.5/(nLayers+nGap) bottomTwo = (nLayers-2.5)/(nLayers+nGap) halfz = .5*(nLayers-3)/(nLayers+nGap) # z position below the ISF displacements = np.linspace(0.0, 1.0, nShifts+1) for disp in displacements[1:]: cell = Cell().loadFromPOSCAR(('POSCAR_%.5f'%(1.0)).replace('.','')) cell.setSiteMobilities(False,False,True) for element in cell.sites: for i in range(cell.numberOfElements()): for j in range(cell.numberOfAtomsOfElement(i)): x,y,z = cell.sites[i][j].position if z < halfz: cell.sites[i][j].move([x+disp*0.5, y+disp*(1.0/6.0)/ny, z]) if z < topTwo or z > bottomTwo: cell.sites[i][j].zfree = False num = disp + 1.0 cell.sendToPOSCAR(('POSCAR_%.5f'%num).replace('.',''))
def shiftLayers(layers, displacement, zList, ny, filename="POSCAR", output="POSCAR"): """ shift the given layers through a given fractional displacement indexing the layers from 0 at z = 0 """ cell = Cell().loadFromPOSCAR(filename) # cut zList down to only the layers in question, by index zNew = [] for i in layers: zNew += [zList[i]] zList = zNew dy = displacement / (3.0 * ny) for i in range(cell.numberOfElements()): for j in range(cell.numberOfAtomsOfElement(i)): x, y, z = cell.sites[i][j].position if z in zList: cell.sites[i][j].move([x, y + dy, z]) cell.setSiteMobilities(False, False, True) # allow only z relaxations cell.sendToPOSCAR(output)
def makePOSCAR(header, element, a, nx, ny, nGap, sequence): """ makes a POSCAR representing the given stacking sequence """ # calculate and set lattice vectors ax = math.sqrt(2) / 2 ay = math.sqrt(6) / 2 az = math.sqrt(3) / 3 layers = list(sequence) nLayers = len(layers) nz = nLayers + nGap bx, by, bz = nx * ax, ny * ay, nz * az cell = Cell() cell.setHeader(header) cell.setElements([element]) cell.setA0(a) # overall scaling cell.setCoordinateSystem("Direct") # change to direct cell.setLatticeVectors([[bx, 0, 0], [0, by, 0], [0, 0, bz]]) # build up layers, starting at z = 0 zPoint = 0.0 while layers: next = layers.pop(0) if next == "A": addA(cell, nx, ny, zPoint) elif next == "B": addB(cell, nx, ny, zPoint) else: # next == 'C' addC(cell, nx, ny, zPoint) zPoint += 1.0 / nz ### make selective dynamics a different function cell.setSiteMobilities(False, False, True) # allow only z relaxations cell.sendToPOSCAR()
#============================================================================== # Jonas Kaufman [email protected] # July 20, 2015 # Script to convert a bestsqs.out file from ATAT to a POSCAR file for use # with VASP # Uses direct coordinates #============================================================================== """ Make script executable using 'chmod +x _____.py' to call as bash script Requires Cell.py """ from Cell import * # get filenames sqs = raw_input('SQS filename (input): ') if not sqs: sqs = 'bestsqs.out' print sqs,'\n' pos = raw_input('POSCAR filename (output):') if not pos: pos = 'POSCAR' print pos,'\n' # load SQS print 'Converting SQS...' cell = Cell().loadFromSQS(sqs) print 'Done\n' # send to POSCAR print 'Sending to POSCAR...' cell.sendToPOSCAR(pos) print 'Done\n'
else: NCORES = int(NCORES) print NCORES,'\n' resultsDir = raw_input('Put results in home or work: ') if 'w' in resultsDir or 'W' in resultsDir: HOME = WORK print HOME,'\n' sequence = 'ABCABCABCABC' layers = list(sequence) nLayers = len(layers) ax = math.sqrt(2)/2 ay = math.sqrt(6)/2 az = math.sqrt(3)/3 bx,by,bz = ax,ny*ay,az*(nLayers+nGap) # make perfect crystal to start from cell = Cell() # Cartesian coordinates by default cell.setHeader(jobName) cell.setElements(elements) cell.setA0(a) cell.setCoordinateSystem('Direct') # change to direct cell.setLatticeVectors([[bx,0,0],[0,by,0],[0,0,bz]]) zpoint = 0.0 while layers: next = layers.pop(0) if next == 'A': addA(cell,ny,zpoint) elif next == 'B': addB(cell,ny,zpoint) else: # next == 'C' addC(cell,ny,zpoint) zpoint += (1.0/(nLayers+nGap))
sp.call('cp -r %s_%.5f '%(jName,a)+WORK,shell=True) sp.call('chmod u+x %s_submit'%jName,shell=True) # run submission script sp.call(['sbatch','%s_submit'%jName]) #=========================================================================== # MAIN PROGRAM #=========================================================================== NCORES = float(raw_input('Number of cores per simulation: ')) emax = float(raw_input('Maximum strain (%): '))/100.0 # e.g. 15% inc = float(raw_input('Strain step size (%): '))/100.0 # e.g. 1% NLAT = int(raw_input('Number of perpendicular lattice vector strains to run: ')) job = raw_input('Job name: ') valid = 0 while not valid: try: runLength = int(raw_input("Maximum run time in minutes: ")) valid = 1 except: print "Run time must be a whole number" eList = np.arange(inc,emax+inc,inc) for eN in eList: aList = np.linspace(0.0, -eN, NLAT) # apply strain cell = Cell().loadFromPOSCAR('CONTCAR.E0') # starts from provided POSCAR strainCell(cell,[eN,0,0,0,0,0]) cell.sendToPOSCAR('POSCAR.EN') jName = job+'_%.3f'%eN # run VASP job print 'Running %.3f strain'%eN runITS(jName,aList,runLength,NCORES)