def cast_unit_spell(self, unit=None, unit_id=None, path=None, path_id=None, cell=None, row=None, col=None, spell=None, spell_id=None): if spell is None and spell_id is None: return None if spell is None: spell = self.get_spell_by_id(spell_id) if row is not None and col is not None: cell = Cell(row, col) if unit is not None: unit_id = unit.unit_id if path is not None: path_id = path.id message = Message(type="castSpell", turn=self.get_current_turn(), info={ "typeId": spell.type_id, "cell": { "row": cell.row, "col": cell.col }, "unitId": unit_id, "pathId": path_id }) self.queue.put(message)
def _handle_turn_units(self, msg, is_dead_unit=False): if not is_dead_unit: self.map.clear_units() for player in self.players: player.units.clear() player.played_units.clear() player.hasted_units.clear() player.duplicate_units.clear() player.range_upgraded_unit = None player.damage_upgraded_unit = None else: for player in self.players: player.died_units.clear() for unit_msg in msg: unit_id = unit_msg["unitId"] player = self.get_player_by_id(player_id=unit_msg["playerId"]) base_unit = self.base_units[unit_msg["typeId"]] if not unit_msg['target'] == -1: target_cell = Cell(row=unit_msg["targetCell"]["row"], col=unit_msg["targetCell"]["col"]) else: target_cell = None unit = Unit(unit_id=unit_id, base_unit=base_unit, cell=self.map.get_cell(unit_msg["cell"]["row"], unit_msg["cell"]["col"]), path=self.map.get_path_by_id(unit_msg["pathId"]), hp=unit_msg["hp"], damage_level=unit_msg["damageLevel"], range_level=unit_msg["rangeLevel"], is_duplicate=unit_msg["isDuplicate"], is_hasted=unit_msg["isHasted"], range=unit_msg["range"], attack=unit_msg["attack"], target=unit_msg["target"], target_cell=target_cell, affected_spells=[self.get_cast_spell_by_id(cast_spell_id) for cast_spell_id in unit_msg["affectedSpells"]], target_if_king=None if self.get_player_by_id( unit_msg["target"]) is None else self.get_player_by_id(unit_msg["target"]).king, player_id=unit_msg["playerId"]) if not is_dead_unit: self.map.add_unit_in_cell(unit.cell.row, unit.cell.col, unit) player.units.append(unit) if unit_msg["wasDamageUpgraded"]: player.damage_upgraded_unit = unit if unit_msg["wasRangeUpgraded"]: player.range_upgraded_unit = unit if unit_msg["wasPlayedThisTurn"]: player.played_units.append(unit) if unit.is_hasted: player.hasted_units.append(unit) if unit.is_duplicate: player.duplicate_units.append(unit) else: player.died_units.append(unit) for unit in self.map.units: if unit.target == -1 or unit.target_if_king is not None: unit.target = None else: unit.target = self.map.get_unit_by_id(unit.target)
def get_area_spell_targets(self, center: Cell = None, row: int = None, col: int = None, spell: Spell = None, type_id: int = None) -> List["Unit"]: if spell is None: if type_id is not None: spell = self.get_cast_spell_by_id(type_id) else: return [] if type(spell) is not Spell: Logs.show_log("invalid spell chosen in get_area_spell_targets") return [] if not spell.is_area_spell(): return [] if center is None: center = Cell(row, col) ls = [] for i in range(max(0, center.row - spell.range), min(center.row + spell.range + 1, self._map.row_num)): for j in range( max(0, center.col - spell.range), min(center.col + spell.range + 1, self._map.col_num)): cell = self._map.get_cell(i, j) for u in cell.units: if self._is_unit_targeted(u, spell.target): ls.append(u) return ls
def __init__(self, C, num_classes, layers, genotype, do_SE=True, C_stem=56): stem_activation = nn.ReLU super(NetworkImageNet, self).__init__() self._layers = layers self.drop_path_prob = 0 self.do_SE = do_SE self.C_stem = C_stem self.stem0 = nn.Sequential( nn.Conv2d(3, C_stem // 2, kernel_size=3, stride=2, padding=1, bias=False), nn.BatchNorm2d(C_stem // 2), stem_activation(inplace=True), nn.Conv2d(C_stem // 2, C_stem, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(C_stem), ) self.stem1 = nn.Sequential( stem_activation(inplace=True), nn.Conv2d(C_stem, C_stem, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(C_stem), ) C_prev_prev, C_prev, C_curr = C_stem, C_stem, C self.cells = nn.ModuleList() self.cells_SE = nn.ModuleList() reduction_prev = True for i in range(layers): if i in [layers // 3, 2 * layers // 3]: C_curr *= 2 reduction = True else: reduction = False cell = Cell(genotype, C_prev_prev, C_prev, C_curr, reduction, reduction_prev) reduction_prev = reduction self.cells += [cell] C_prev_prev, C_prev = C_prev, cell.multiplier * C_curr if self.do_SE and i <= layers * 2 / 3: if C_curr == C: reduction_factor_SE = 4 else: reduction_factor_SE = 8 self.cells_SE += [ SELayer(C_curr * 4, reduction=reduction_factor_SE) ] self.global_pooling = nn.AvgPool2d(7) self.classifier = nn.Linear(C_prev, num_classes)
def get_cell(self, number): ''' returns i-th cell (if necessary, compute it, or use cache) :param i: integer in range [0, size()) :return: i-th cell as a object of class Cell ''' return Cell(dmga2py.diagram_get_cell(self._diagram_handle, number))
def __init__(self, v): # Width and Height passed in as cells self.view = v self.width = 10 self.height = 15 self.number_of_cells = self.width * self.height # Create a 2D array of cells self.grid = [[Cell.Cell(x, y) for y in range(self.height)] for x in range(self.width)]
def cast_unit_spell(self, unit: Unit = None, unit_id: int = None, path: Path = None, path_id: int = None, cell: Cell = None, row: int = None, col: int = None, spell: Spell = None, spell_id: int = None) -> None: if spell is None and spell_id is None: Logs.show_log("cast_unit_spell function called with no spell input!") return None if spell is None: if type(spell_id) is not int: Logs.show_log("spell_id is not an integer in cast_unit_spell function call!") return spell = self.get_spell_by_id(spell_id) if row is not None and col is not None: if type(row) is not int or type(col) is not int: Logs.show_log("row and column arguments are invalid in cast_unit_spell function call") return cell = Cell(row, col) if unit is not None: if type(unit) is not Unit: Logs.show_log("unit argument is invalid in cast_unit_spell function call") return unit_id = unit.unit_id if path is not None: if type(path) is not Path: Logs.show_log("path argument is invalid in cast_unit_spell function call") return path_id = path.id if type(unit_id) is not int: Logs.show_log("unit_id argument is invalid in cast_unit_spell function call") return if type(path_id) is not int: Logs.show_log("path_id argument is invalid in cast_unit_spell function call") return message = Message(type="castSpell", turn=self.get_current_turn(), info={ "typeId": spell.type_id, "cell": { "row": cell.row, "col": cell.col }, "unitId": unit_id, "pathId": path_id }) self._queue.put(message)
def _map_init(self, map_msg): row_num = map_msg["rows"] col_num = map_msg["cols"] input_cells = [[Cell(row=row, col=col) for col in range(col_num)] for row in range(row_num)] paths = [Path(id=path["id"], cells=[input_cells[cell["row"]][cell["col"]] for cell in path["cells"]] ) for path in map_msg["paths"]] kings = [King(player_id=king["playerId"], center=input_cells[king["center"]["row"]][king["center"]["col"]], hp=king["hp"], attack=king["attack"], range=king["range"], target=None, target_cell=None, is_alive=True) for king in map_msg["kings"]] self.players = [Player(player_id=map_msg["kings"][i]["playerId"], king=kings[i], deck=[], hand=[], ap=self.game_constants.max_ap, paths_from_player=self._get_paths_starting_with(kings[i].center, paths), path_to_friend=self._find_path_starting_and_ending_with(kings[i].center, kings[i ^ 1].center, paths), units=[], cast_area_spell=None, cast_unit_spell=None, duplicate_units=[], hasted_units=[], played_units=[], died_units=[], range_upgraded_unit=None, damage_upgraded_unit=None, spells=[]) for i in range(4)] for player in self.players: player.paths_from_player.remove(player.path_to_friend) self.player = self.players[0] self.player_friend = self.players[1] self.player_first_enemy = self.players[2] self.player_second_enemy = self.players[3] self.map = Map(row_num=row_num, col_num=col_num, paths=paths, kings=kings, cells=input_cells, units=[])
def get_area_spell_targets(self, center, row=None, col=None, spell=None, type_id=None): if spell is None: if type_id is not None: spell = self.get_cast_spell_by_id(type_id) else: return [] if not spell.is_area_spell(): return [] if center is None: center = Cell(row, col) ls = [] for i in range(max(0, center.row - spell.range), min(center.row + spell.range, self.map.row_num)): for j in range(max(0, center.col - spell.range), min(center.col + spell.range, self.map.column_num)): cell = self.map.get_cell(i, j) for u in cell.units: if self._is_unit_targeted(u, spell.target): ls.append(u)
def initialHeartMatrix(self): matrix = [] with open("./resources/heart.csv", 'r') as f: # TODO filename as function argument heart = list( csv.reader(f, delimiter=";") ) # TODO check: what if open() has failed for some reason? # TODO read count of rows and columns from CSV directly for i in range(int(self.rows)): # loop as many times as variable rows r = [] # create a row list for j in range(int( self.columns)): # loop as many times as variable columns # TODO replace the if-elif tree by a switcher. if heart[i][j] == '0': no_heart_cell = Cell(Celltype.NO_HEART_CELL) r.append(no_heart_cell) elif heart[i][j] == '1': right_atrium = Cell(Celltype.RIGHT_ATRIUM) r.append(right_atrium) elif heart[i][j] == '2': sinus_knot = Cell(Celltype.SINUS_KNOT) sinus_knot.trigger() # sine knot immediately triggered. r.append(sinus_knot) elif heart[i][j] == '3': av_knot = Cell(Celltype.AV_KNOT) r.append(av_knot) elif heart[i][j] == '4': his_bundle = Cell(Celltype.HIS_BUNDLE) r.append(his_bundle) elif heart[i][j] == '5': tawara = Cell(Celltype.TAWARA) r.append(tawara) elif heart[i][j] == '6': purkinje = Cell(Celltype.PURKINJE) r.append(purkinje) elif heart[i][j] == '7': left_atrium = Cell(Celltype.LEFT_ATRIUM) r.append(left_atrium) elif heart[i][j] == '8': myokard = Cell(Celltype.MYOKARD) r.append(myokard) matrix.append( r) # add the rows filled with columns to existing matrix list return matrix
def __init__(self, shape_cell_handle, cell_handle, contour_handle, number): Cell.__init__(self, cell_handle) self._sasa_cell_handle = shape_cell_handle self._cell_handle = cell_handle self._contour_handle = contour_handle
def __init__(self, C, num_classes, layers, auxiliary, genotype, in_channels=55, reduce_spacing=None, mixed_aux=False, op_dict=None, C_mid=None, stem_multiplier=3): super(NetworkNASCOSTAR, self).__init__() self._layers = layers self._auxiliary = auxiliary self._in_channels = in_channels self.drop_path_prob = 0. self.stem0 = nn.Sequential( nn.Conv2d(in_channels, C // 2, kernel_size=3, stride=2, padding=1, bias=False), nn.BatchNorm2d(C // 2), nn.ReLU(inplace=True), nn.Conv2d(C // 2, C, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(C), ) self.stem1 = nn.Sequential( nn.ReLU(inplace=True), nn.Conv2d(C, C, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(C), ) C_prev_prev, C_prev, C_curr = C, C, C self.cells = nn.ModuleList() reduction_prev = True for i in range(layers): if i in [layers // 3, 2 * layers // 3]: C_curr *= 2 reduction = True cell = Cell(genotype.reduce, genotype.reduce_concat, C_prev_prev, C_prev, C_curr, reduction, reduction_prev, op_dict=op_dict, C_mid=C_mid) else: reduction = False cell = Cell(genotype.normal, genotype.reduce_concat, C_prev_prev, C_prev, C_curr, reduction, reduction_prev, op_dict=op_dict, C_mid=C_mid) reduction_prev = reduction self.cells += [cell] C_prev_prev, C_prev = C_prev, cell.multiplier * C_curr if i == 2 * layers // 3: C_to_auxiliary = C_prev if auxiliary: self.auxiliary_head = AuxiliaryHeadImageNet( C_to_auxiliary, num_classes) self.global_pooling = nn.AvgPool2d(7) self.classifier = nn.Linear(C_prev, C_prev) self.classifier2 = nn.Linear(C_prev, num_classes)
def __iter__(self): return Cell.__iter__(self)
def _handle_turn_units(self, msg, is_dead_unit=False): if not is_dead_unit: self._map._clear_units() for player in self._players: player.units.clear() player.played_units.clear() player.hasted_units.clear() player.duplicate_units.clear() player.range_upgraded_unit = None player.damage_upgraded_unit = None else: for player in self._players: player.died_units.clear() unit_input_list = [] for unit_msg in msg: unit_id = unit_msg["unitId"] player = self.get_player_by_id(player_id=unit_msg["playerId"]) base_unit = self._base_units[unit_msg["typeId"]] if not unit_msg['target'] == -1: target_cell = Cell(row=unit_msg["targetCell"]["row"], col=unit_msg["targetCell"]["col"]) else: target_cell = None unit = Unit( unit_id=unit_id, base_unit=base_unit, cell=self._map.get_cell(unit_msg["cell"]["row"], unit_msg["cell"]["col"]), path=self._map.get_path_by_id(unit_msg["pathId"]), hp=unit_msg["hp"], damage_level=unit_msg["damageLevel"], range_level=unit_msg["rangeLevel"], is_duplicate=unit_msg["isDuplicate"], is_hasted=unit_msg["isHasted"], range=unit_msg["range"], attack=unit_msg["attack"], target=None, # will be set later when all units are in set target_cell=target_cell, affected_spells=[ self.get_cast_spell_by_id(cast_spell_id) for cast_spell_id in unit_msg["affectedSpells"] ], target_if_king=None if self.get_player_by_id(unit_msg["target"]) is None else self.get_player_by_id(unit_msg["target"]).king, player_id=unit_msg["playerId"]) unit_input_list.append(unit) if unit.path is not None: if self.get_player_by_id( unit.player_id ).king.center in unit.path.cells and unit.path.cells[ 0] != self.get_player_by_id( unit.player_id).king.center: unit.path = Path(path=unit.path) unit.path.cells.reverse() if self._get_friend_by_id( unit.player_id ).king.center in unit.path.cells and unit.path.cells[ 0] != self._get_friend_by_id( unit.player_id).king.center: unit.path = Path(path=unit.path) unit.path.cells.reverse() if not is_dead_unit: self._map._add_unit_in_cell(unit.cell.row, unit.cell.col, unit) player.units.append(unit) if unit_msg["wasDamageUpgraded"]: player.damage_upgraded_unit = unit if unit_msg["wasRangeUpgraded"]: player.range_upgraded_unit = unit if unit_msg["wasPlayedThisTurn"]: player.played_units.append(unit) if unit.is_hasted: player.hasted_units.append(unit) if unit.is_duplicate: player.duplicate_units.append(unit) else: player.died_units.append(unit) for i in range(len(unit_input_list)): unit = unit_input_list[i] if unit.target_if_king is not None: unit.target = None else: unit.target = self.get_unit_by_id(msg[i]["target"])
def a_star_search(maze): """ Parameter: Maze object\n Returns: {'route': [], 'steps': []}\n """ pretty_maze = maze.maze end_x = maze.end_coords[0] end_y = maze.end_coords[1] not_visited_cells = [] visited_cells = [] # set start cell in to not_visited_cells cell = Cell(maze.start_coords[0], maze.start_coords[1], "start", "start", end_x, end_y, 0) not_visited_cells.append(cell) # Start of a-star while len(not_visited_cells) > 0: # Set next cords to look from current_cell = not_visited_cells[-1] x = current_cell.x y = current_cell.y g = current_cell.g # Move from open to closed visited_cells.append(not_visited_cells[-1]) del not_visited_cells[-1] # Check if this cell is the final cell if pretty_maze[x][y] == "2": route = backtrace_route(visited_cells) steps = cell_to_cords(visited_cells) return {"route": route, "steps": steps} # Check cell right if (y < len(pretty_maze[0]) - 1 and is_in_visited_cells(visited_cells, x, y + 1) is False and (pretty_maze[x][y + 1] == "0" or pretty_maze[x][y + 1] == "2")): cell = Cell(x, y + 1, x, y, end_x, end_y, g + 1) not_visited_cells.append(cell) # Check cell down if (x < len(pretty_maze) - 1 and is_in_visited_cells(visited_cells, x + 1, y) is False and (pretty_maze[x + 1][y] == "0" or pretty_maze[x + 1][y] == "2")): cell = Cell(x + 1, y, x, y, end_x, end_y, g + 1) not_visited_cells.append(cell) # Check cell left if (y > 0 and is_in_visited_cells(visited_cells, x, y - 1) is False and (pretty_maze[x][y - 1] == "0" or pretty_maze[x][y - 1] == "2")): cell = Cell(x, y - 1, x, y, end_x, end_y, g + 1) not_visited_cells.append(cell) # Check cell up if (x > 0 and is_in_visited_cells(visited_cells, x - 1, y) is False and (pretty_maze[x - 1][y] == "0" or pretty_maze[x - 1][y] == "2")): cell = Cell(x - 1, y, x, y, end_x, end_y, g + 1) not_visited_cells.append(cell) # Sorting list acending not_visited_cells.sort(key=lambda x: x.f, reverse=True)
class CellTests(unittest.TestCase): def setUp(self): self.c = Cell() def tearDown(self): pass def testAsyncOutputFalseWhenBothInputsFalse(self): self.c.driveInputs([False, False]) self.assertFalse(self.c.asyncOutput()) def testAsyncOutputFalseWhenOneInputFalse(self): self.c.driveInputs([True, False]) self.assertFalse(self.c.asyncOutput()) def testAsyncOutputTrueWhenBothInputsTrue(self): self.c.driveInputs([True, True]) self.assertTrue(self.c.asyncOutput()) def testSyncOutputResetsToFalse(self): self.assertFalse(self.c.syncOutput()) def testSyncOutputFalseWhenBothInputsFalse(self): self.c.driveInputs([False, False]) self.c.clk() self.assertFalse(self.c.syncOutput()) def testSyncOutputTrueWhenBothInputsTrue(self): self.c.driveInputs([True, True]) self.c.clk() self.assertTrue(self.c.syncOutput()) def testSyncOutputUpdatesWith2ndClk(self): self.c.driveInputs([True, True]) self.c.clk() self.c.driveInputs([False, False]) self.c.clk() self.assertFalse(self.c.syncOutput()) def testSyncOutputHolds(self): self.c.driveInputs([True, True]) self.c.clk() self.c.clk() self.assertTrue(self.c.syncOutput()) def testAsyncStableWhenFalse(self): self.c.driveInputs([False, False]) self.c.driveInputs([False, False]) self.assertTrue(self.c.isStable()) def testAsyncStableWhenBothTrue(self): self.c.driveInputs([True, True]) self.c.driveInputs([True, True]) self.assertTrue(self.c.isStable()) def testAsyncStableWhenBothFalse(self): self.c.driveInputs([False, False]) self.c.driveInputs([False, False]) self.assertTrue(self.c.isStable()) def testAsyncNotStableWhenAChanges(self): self.c.driveInputs([True, True]) self.c.driveInputs([False, True]) self.assertFalse(self.c.isStable()) def testAsyncNotStableWhenBChanges(self): self.c.driveInputs([True, True]) self.c.clk() self.c.driveInputs([True, False]) self.c.clk() self.assertFalse(self.c.isStable()) def testCellCanBeOr(self): self.c.setOperator(CellType._or) self.c.driveInputs([False, True]) self.assertTrue(self.c.asyncOutput()) def testCellCanBeXor(self): self.c.setOperator(CellType._xor) self.c.driveInputs([True, True]) self.assertFalse(self.c.asyncOutput()) self.c.driveInputs([False, False]) self.assertFalse(self.c.asyncOutput()) self.c.driveInputs([False, True]) self.assertTrue(self.c.asyncOutput()) def testSetForAsyncOutput(self): self.c.setOutputType(OutputType. async) self.c.driveInputs([True, True]) self.assertTrue(self.c.output()) def testSetForSyncOutput(self): self.c.setOutputType(OutputType.sync) self.c.driveInputs([True, True]) self.assertFalse(self.c.output()) self.c.clk() self.assertTrue(self.c.output()) def testGetOutputType(self): self.c.setOutputType(OutputType.sync) self.assertTrue(self.c.getOutputType() == OutputType.sync) def testCellHistory(self): self.c.setOutputType(OutputType.sync) self.c.driveInputs([True, True]) for i in range(50): if i == 49: self.c.driveInputs([False, False]) self.c.clk() self.c.output() self.assertEqual(len(self.c.cellHistory()), 50) self.assertEqual(self.c.cellHistory(), [True] * 49 + [False]) def testCellHistoryFixed(self): self.c.setOutputType(OutputType.sync) self.c.driveInputs([True, True]) for i in range(50): self.c.clk() self.c.output() self.assertTrue(self.c.cellHistoryFixed()) def testCellHistoryNotFixed(self): self.c.setOutputType(OutputType.sync) self.c.driveInputs([True, True]) self.c.clk() self.c.output() self.c.driveInputs([False, True]) self.c.clk() self.c.output() self.assertFalse(self.c.cellHistoryFixed()) def testNoCellHistoryForAsync(self): self.c.setOutputType(OutputType. async) self.c.driveInputs([True, True]) self.c.output() self.c.driveInputs([False, True]) self.c.output() self.assertFalse(self.c.cellHistoryFixed())
def __init__(self, shape_cell_handle, cell_handle, complex_handle): Cell.__init__(self, cell_handle) self._shape_cell_handle = shape_cell_handle self._cell_handle = cell_handle self._complex_handle = complex_handle
def setUp(self): self.c = Cell()