def main(): # creates cells to build lists a = cell.Cell(4) b = cell.Cell(3, a) c = cell.Cell(2, b) d = cell.Cell(1, c) e = cell.Cell(9) f = cell.Cell(8, e) g = cell.Cell(7, f) h = cell.Cell(6, g) i = cell.Cell(5, h) z = cell.Cell(0) # prints list A A = linkedList.LinkedList(d) print "list A:" A.echo() # prints list B B = linkedList.LinkedList(i) print "list B:" B.echo() # prints the concatenated list X = list_concat(A, B) print "concatenation:" X.echo()
def test_find_occurence(self): '''Test how long a basic function takes.''' tries = 1000 print 'Time per operation: find_occurences (average over {0} tries):\n'.format(tries) sequences = [';' + 'AG' * 10 + ';', ';' + 'AG' * 500 + ';'] for sequence in sequences: c = cell.Cell(sequence) before = time.time() for i in range(tries): c.find_occurences('own', 0, len(sequence), 'AGA', 1000) time_passed = 1000 * (time.time() - before)/tries print 'Normal: Length sequence: {0}, Time/Action: {1} ms'.format(len(sequence), time_passed) prom_sequences = [';' + 'PAGAC' * 5 + ';', ';' + 'PAGAC' * 190 + ';'] for sequence in prom_sequences: c = cell.Cell(sequence) before = time.time() for i in range(tries): c.find_occurences('prom', 0, len(sequence), 'AGA', 1000) time_passed = 1000 * (time.time() - before)/tries print 'Promoter: Length sequence: {0}, Time/Action: {1} ms'.format(len(sequence), time_passed) time.sleep(0.1)
def __init__(self, height, width, mines): self.height = height self.width = width self.mines = mines self.minesLoc = [] self.marks = [] self.totalCells = width * height self.uncovered = 0 # Mines locations generation minesUsed = 0 while (minesUsed < mines): rdR = rd.randint(0, height - 1) rdC = rd.randint(0, width - 1) mineLoc = str(rdR) + ',' + str(rdC) if mineLoc not in self.minesLoc: self.minesLoc.append(mineLoc) minesUsed = minesUsed + 1 # Board filling self.board = [[cell.Cell() for r in range(width)] for c in range(height)] for i in range(len(self.minesLoc)): pos = self.minesLoc[i].split(',') row = int(pos[0]) col = int(pos[1]) self.board[row][col] = cell.Cell(True) self.seekMines()
def test_prob1(length): start = cell.Cell(20) next_c = start # creates a cell list of size length for i in (range(1, length)): new_c = cell.Cell(random.randint(1, length)) # add new_cell to list list_concat(next_c, new_c) # move to next cell next_c = new_c
def main(): # creates cells to build lists a = cell.Cell(4) b = cell.Cell(3, a) c = cell.Cell(2, b) d = cell.Cell(1, c) e = cell.Cell(9) f = cell.Cell(8, e) g = cell.Cell(7, f) h = cell.Cell(6, g) i = cell.Cell(5, h) # prints list A A = linkedList.LinkedList(d) print "list A:" A.echo() # prints list B B = linkedList.LinkedList(i) print "list B:" B.echo() # prints the concatenated list X = list_concat_copy(A, B) print "concatenation:" X.echo() # demonstrates that changing A does not affect X print "changing A:" A = B A.echo() print "concatenation is unaffected:" X.echo()
def init_matrix(x_range, y_range): matrix = [] for x in range(x_range): temp = [] for y in range(y_range): if random.random() > 0.5: temp.append(cell.Cell(True)) else: temp.append(cell.Cell(False)) matrix.append(temp) return matrix
def createWorld(self): """ Creates (initiates) the world using the world.dat. """ # Init the world with the data from world.dat file with open(const.WORLD_FILE, 'r') as f: for row in range(const.WORLD_SIZE): self.world.append([]) for col in range(const.WORLD_SIZE): c = f.read(1) while c not in const.WORLD_CELLS: c = f.read(1) if c == "E": # Create cell of type 'earth' self.world[row].append( cell.Cell(echoSystem=self, coordinates=(row, col), cellType="earth")) if c == "C": # Create cell of type 'city' self.world[row].append( cell.Cell(echoSystem=self, coordinates=(row, col), cellType="city")) if c == "F": # Create cell of type 'forest' and update the forests counter self.world[row].append( cell.Cell(echoSystem=self, coordinates=(row, col), cellType="forest")) self.forests += 1 if c == "S": # Create cell of type 'sea' and update the seas counter self.world[row].append( cell.Cell(echoSystem=self, coordinates=(row, col), cellType="sea")) self.sea += 1 if c == "G": # Create cell of type 'glaciers' and update the glaciers count self.world[row].append( cell.Cell(echoSystem=self, coordinates=(row, col), cellType="glacier")) self.glaciers += 1 # Let every cell update its neighbors for row in self.world: for column in row: column.updateNeighbors()
def _check_and_move(self, iter_range, row_range, col_range, row_add, col_add): for _ in iter_range: for row in row_range: for col in col_range: if self._cells[row][col].is_empty() and not self._cells[ row + row_add][col + col_add].is_empty(): self._cells[row][col] = self._cells[row + row_add][col + col_add] self._cells[row + row_add][col + col_add] = cell.Cell() elif self._cells[row][col].can_combine( self._cells[row + row_add][col + col_add]): self._cells[row][col].increase_value() self._cells[row + row_add][col + col_add] = cell.Cell()
def __create_cell(self): cells = [] for i in range(self.__NUMBER_RECTS): for j in range(self.__NUMBER_RECTS): cells.append( cell.Cell(i, j, self.__R_WIDTH, self.__NUMBER_RECTS)) return cells
def _create_grid(self): """ Instantiates a ndims array of Cell instances that hold the value of various quantities at certain locations in the simulation space. Parameters: ----------- None Returns: -------- grid : ndarray An ndims dimensional array of Cell instances """ # Initialize empty array grid = np.empty([self.ncells] * self.ndims, dtype=object) # Initialize each cell in the grid. This is done using the nditer iterator in # order to loop over each element in the ndims dimensional grid. The multi_index # flag tells the iterator to yield the index for the current array element it = np.nditer(grid, flags=['multi_index', 'refs_ok']) while not it.finished: # Get location of cell center from cell index (x0,x1,x2,...,xn). This is just # the number of half deltas in each dimension, where delta is the width of the # cell. The number of half deltas is just 2k + 1, where k is the cell index # along a dimension. ind = np.array(it.multi_index) loc = (2 * ind + 1) * (self.cellWidth / 2.) grid[it.multi_index] = cell.Cell(loc, self.cellWidth) # Go to the next element. Without this, it's an infinite loop it.iternext() return grid
def maze(maze_map1, start1, end1): global current_maze, temp, end, start, maze_map maze_map = maze_map1 start = start1 end = end1 current_maze = maze_runner_initialization(maze_map) temp = [] temp.append(start[0]) temp.append(start[1]) current_maze[temp[0]][temp[1]] = cell.Cell([temp[0], temp[1]], [temp[0], temp[1]], start, end) current_maze[temp[0]][temp[1]].set_discovered(True) current_maze[temp[0]][temp[1]].set_g_cost(0) current_maze = runner_surround(maze_map, current_maze, temp[0], temp[1], start, end) fen1.resizable(width=False, height=False) imageFixe=PhotoImage(file='grilleMap.gif') mon_cadre.create_image(0,0,image=imageFixe, anchor=NW) display_mur(maze_map) mon_cadre.pack() update() fen1.mainloop() #return current_maze return None
def create_cells(self, size=CELL_INIT_SIZE): for i in range(self.messages["cells_y"]): self.cells.append([]) for j in range(self.messages["cells_x"]): self.cells[i].append(cl.Cell(size=size)) self.cells[i][j].set_location(i * size + 1, j * size + 1) self.cells[i][j].render(self.canvas)
def fill_grid(self): for y in range(self.y_size): x_list = [] for x in range(self.x_size): new_cell = cell.Cell() x_list.append(new_cell) self.grid.append(x_list)
def getRMP(self, parameters, debug=False): if not self.stop: # Simulation parameters h.load_file('stdrun.hoc') h.load_file('negative_init.hoc') tstop = 100 dt = 0.025 h.stdinit() h.celsius = 37.0 h.tstop = tstop h.v_init = -65 # Instantiate and parameterize cells testCell = cell.Cell(0, (0, 0), self.synvars, 'granulecell', 'output0_updated.swc') self.parameterizeCell(testCell, parameters) # Instrument cells self.RMPv = h.Vector() self.RMPv.record(testCell.c.soma[0](0.5)._ref_v) # Run simulation h.run() # Get RMP self.RMP = self.RMPv[-1] if debug: return [np.array([self.RMP]), np.array([self.RMPv])] else: return np.array([self.RMP]) else: return 1e9
def readFile(name): with open(name) as fd: N,M,C,R=fd.readline().split() N,M,C,R=int(N),int(M),int(C),int(R) customers=[] map=[] for i in range(C): col, row, reward=fd.readline().split() row, col, reward = int(row),int(col),int(reward) customers.append(customer.Customer(row,col,reward)) for i in range(M): l=list(fd.readline()) map_list=[] for j in range(N): c=cell.Cell(l[j]) map_list.append(c) map.append(map_list) param = {} param['N'] = N param['M'] = M param['C'] = C param['R'] = R return customers,map, param
def __init__(self, size, mineCount): self.__board = dict() self.__width = size self.__height = size self.__mineCount = mineCount for x in range(0, self.__width): for y in range(0, self.__height): self.__board.update({ (x, y) : cell.Cell() }) # populate board with mines while mineCount > 0: x = random.randrange(self.__width) y = random.randrange(self.__height) self.__board[(x, y)].setMine() if (self.__board[(x, y)].isMined()): mineCount -= 1 # calculate mine counts for x in range(0, self.__width): for y in range(0, self.__height): if not self.__board[(x, y)].isMined(): self.__board[(x, y)].setCount(self.__getAdjMineCount(x, y)) else: self.__board[(x, y)].setCount(-1)
def make_game_board(): game_board = board.Board(BOARD_WIDTH, BOARD_HEIGHT) for x in range(BOARD_WIDTH): for y in range(BOARD_HEIGHT): game_board._board[x][y] = cell.Cell(x, y, random.choice(states)) return game_board
def create_body(size_1, size_2): reply = [] for x in range(size_1): temp = [] for y in range(size_2): temp.append(cell.Cell()) reply.append(temp) return reply
def test_correct_click_inside(self): input_x = 1 input_y = 1 x1 = y1 = cell_id = x = y = 0 x2 = y2 = 2 c = cell.Cell(x1, y1, x2, y2, cell_id, x, y) expected_output = True self.assertEqual(expected_output, c.is_click_inside(input_x, input_y))
def init_grid(self, walls): for x in range(self.grid_width): for y in range(self.grid_height): if (x, y) in walls: reachable = False else: reachable = True self.cells.append(cell.Cell(x, y, reachable))
def test_correct_cell_status_change(self): input_empty_cell = CellStatus.Empty input_cross_cell = CellStatus.Cross input_circle_cell = CellStatus.Circle c = cell.Cell(0, 0, 0, 0, 0, 0, 0) self.assertEqual(c.change_cell_type(input_empty_cell), c.status) self.assertEqual(c.change_cell_type(input_circle_cell), c.status) self.assertEqual(c.change_cell_type(input_cross_cell), c.status)
def loadBoard(filename): with open(filename) as f: content = f.readlines() rows = len(content) cols = len(content[0].strip().split(",")) board = [[None for x in range(rows)] for y in range(cols)] for r in range(rows): curRow = content[r].strip().split(",") for c in range(cols): curCellInt = int(curRow[c]) if curCellInt == 0: board[r][c] = cell.Cell(False) else: board[r][c] = cell.Cell(True) return board
def upcast_logic_cell(logic_cell, root, width, height): this_cell = cell.Cell(root, color=logic_cell.color, width=width, height=height, row=logic_cell.row, column=logic_cell.column) return this_cell
def getMembraneTimeConstant(self, parameters, debug=False): if not self.stop: ###################################### # Membrane Time Constant Experiments # ###################################### # Simulation parameters h.load_file('stdrun.hoc') h.load_file('negative_init.hoc') tstop = self.subthresh_dur + 300 dt = 0.025 h.stdinit() h.celsius = 37.0 h.tstop = tstop h.v_init = -65 # Instantiate and parameterize cells testCell = cell.Cell(0, (0, 0), self.synvars, 'granulecell', 'output0_updated.swc') self.parameterizeCell(testCell, parameters) # Make sure the cell doesn't spike # Create inputs for experiments stim = h.IClamp(0.5, sec=testCell.c.soma[0]) stim.amp = self.threshAmp # amp at which neuron no longer spikes stim.dur = self.subthresh_dur # subthresh is duration where neuron no longer spikes stim.delay = 0 # Instrument cells self.tauV = h.Vector() self.tauV.record(testCell.c.soma[0](0.5)._ref_v) t = h.Vector() t.record(h._ref_t) tvec = h.Vector() nc = testCell.connect_pre(None, 0, 0) nc.record(tvec) # Run simulation h.run() # Calculate membrane time constant self.tauV = np.array(self.tauV) t = np.array(t) t_idx = t >= self.subthresh_dur t = t[t_idx] - self.subthresh_dur v = self.tauV[t_idx] try: popt, pcov = curve_fit(self.expFunc, t, v, p0=(1, -0.1, -60)) self.tau = -1 / popt[1] except RuntimeError: self.tau = 1000 if debug: return [np.array([self.tau]), v, t, popt] else: return np.array([self.tau]) else: return 1e9
def test_one_operation(self): '''Test how long one operation takes. Subtract baseline of cell creation (empty sequence)...''' sequences = [ ('Baseline', ';XXXXXXXXXXXXXXXXXXXXXX;'), #baseline: cell and unit creation, one round. no action ('Protection', ';Q1[]TT1SXXXXXXXXTTXXXX;'), #one protection ('Promoter', ';N1[]1SP1N1[]1XXXXXXXXX;'), #one promoter ('Restriction', ';R1[]T!T1SXXXXXXXXXTTXX;'), #one cut ('Ligation', ';L1[]T!T1SXXXXXT;;TXXXX;'), #one ligation ('Mutation', ';M1[]1SXXXXXXXXXXXXXXXX;'), #one mutation ('Copy', ';O1[]T!T1SXXXXXXXTTXXXX;'), #one copy ('Degradation', ';D1[]TT1XXXXXXXXXTTXXXX;'), #one degradation ('Factor', ';N1[]1F1[]T!T1SPTTXXXXX;'), #one transcription factor ('Export', ';E1[]T!T1SXXXTTXXXXXXXX;'), #one export ('Four Units', ';N0[]1N0[]1N0[]1N0[]1XX;'), #a unit exporting itself into the pool ('Unit Export', ';U1(self)[](self)2XXXXX;'), ('Substance Creation', ';V1[]()(a)1XXXXXXXXXXXX;'), ('Multi Creation', ';V1[]()(a,b,c,d,e,f,g)1;'), ('3x Promoter', ';N3[]1SP3N1[]1XXXXXXXXX;') ] num_cells = 2500 print '\nTime per operation of a specific unit (average over {0} cells):\n'.format(num_cells) res_dict = {} for label, seq in sequences: before = time.time() for i in range(num_cells): c = cell.Cell(seq) c.read_seq() c.run_all() res_dict[label] = ((time.time() - before), seq) baseline = res_dict['Baseline'][0] for test in res_dict.keys(): per_cell = 1000 * (res_dict[test][0] - baseline) / num_cells res_dict[test] = ( per_cell , res_dict[test][1] ) res = {} for k in res_dict.keys(): res[k] = res_dict[k][0] sorted_res = sorted(res.iteritems(), key=operator.itemgetter(1)) print 'Baseline (subtracted from all other): {1} ms / cell\nSequence: {0}'.format(res_dict['Baseline'][1], baseline) print 'All tests ordered by time / action:\n' for i in range(1, len(sorted_res)): current = sorted_res[i] percentage = round(current[1]/(baseline / 100),1) position = '{0}. {1}: {2}\n'.format(i, current[0], res_dict[current[0]][1]) position += '\t{0}% of baseline time, {1} ms / action'.format(percentage, round(current[1], 4)) print position #wait, so that end message of test does not conflict with printing of last results time.sleep(0.1)
def load(self, filename): self.blank_board() with open(filename, 'r') as maz_file: for line in maz_file: line = line.strip("\n") my_cell = cell.Cell() row, col = my_cell.deserialize(line) self.board[row][col] = my_cell
def __init__(self): self.board = [] self.board_length = 9 self.allDiffsLen = 3 self.checkAll = ((0, 0), (1, 3), (2, 6), (3, 1), (4, 4), (5, 7), (6, 2), (7, 5), (8, 8)) for y in range(self.board_length): row = [cell.Cell() for x in range(self.board_length)] self.board.append(row)
def ini_cell(self, size): cells = [] cells_line = [] for i in range(size): for j in range(size): cells_line.append(cell.Cell(i, j)) cells.append(cells_line) cells_line = [] return cells
def __init__(self, filepart, x): self.cells = [] print("@%i - %s" % (x, filepart)) self.x = x y = 0 for l in filepart.split("|"): self.cells.append(cell.Cell(l, x, y)) y += 1 print("%i cells in this line" % len(self.cells))
def __init__(self, height=4, width=4): self._height = height self._width = width self._cells = [] for _ in range(self.height): new_row = [] for _ in range(self.width): new_row.append(cell.Cell(0)) self._cells.append(new_row)