def __init__(self): self.area_number = 1 self.area = Area() self.hero = Hero() self.characters = self.create_characters() self.monsters = self.characters[1:] self.kill_count = 0
def from_dict(request_dict): id = request_dict.get('id', generate_uuid()) request = TaskRequest(id=id) request.load_type = request_dict["loadType"] request.load_id = request_dict["loadId"] request.user_id = request_dict["userId"] request.earliest_pickup_time = TimeStamp.from_str( request_dict["earliestPickupTime"]) request.latest_pickup_time = TimeStamp.from_str( request_dict["latestPickupTime"]) pickup_area_dict = request_dict.get('pickup_pose', None) if pickup_area_dict: request.pickup_pose = Area.from_dict(pickup_area_dict) else: # when the provided dict is from json schema request.pickup_pose = Area() request.pickup_pose.name = request_dict.get("pickupLocation", '') request.pickup_pose.floor_number = request_dict.get( "pickupLocationLevel", 0) delivery_area_dict = request_dict.get('delivery_pose', None) if delivery_area_dict: request.delivery_pose = Area.from_dict(delivery_area_dict) else: # when the provided dict is from json schema request.delivery_pose = Area() request.delivery_pose.name = request_dict.get( "deliveryLocation", '') request.delivery_pose.floor_number = request_dict.get( "deliveryLocationLevel", 0) request.priority = request_dict["priority"] return request
def step_forward(board: Board, player_type: PlayerType): if board.distance.removable() == 0 or \ board.players[player_type].aura.receivable() == 0: raise BasicActionException('前進できません!') if board.distance() <= board.expert_distance: raise DistanceException('前進できません!') Area.move_flowers(board.distance, board.players[player_type].aura, 1)
def __init__(self): Gtk.VBox.__init__(self) self.screen = None self.area = Area() self.area.connect("body-selected", self._body_selected) self.info_view = InfoView() self.info_view.connect("change-cursor", self._change_cursor) adj = Gtk.Adjustment(10, 0.2, 100, 0.5, 1) s = Gtk.HScale() s.set_draw_value(False) s.set_adjustment(adj) s.connect("value-changed", self.change_zoom) self.pack_start(s, False, False, 0) adj = Gtk.Adjustment(1, 0.1, 5, 0.1, 1) s = Gtk.HScale() s.set_draw_value(False) s.set_adjustment(adj) s.connect("value-changed", self.change_speed) self.pack_start(s, False, False, 0) self.set_screen(Screen.SOLAR_SYSTEM) self.show_all()
def __init__(self, handle): activity.Activity.__init__(self, handle) self.screen = None self.toolbarbox = ToolbarBox(self) self.toolbarbox.connect("show-simulation", self._show_simulation_cb) self.toolbarbox.connect("show-info", self._show_info_cb) self.toolbarbox.connect("go-back", self._go_back_cb) self.toolbarbox.connect("go-forward", self._go_forward_cb) self.toolbarbox.connect("show-orbits", self._show_orbits_cb) self.toolbarbox.connect("show-body", self._show_body_cb) self.toolbarbox.connect("speed-changed", self._speed_changed_cb) self.toolbarbox.connect("zoom-changed", self._zoom_changed_cb) self.set_toolbar_box(self.toolbarbox) self.box = Gtk.VBox() self.set_canvas(self.box) self.area = Area() self.area.connect("body-selected", self._body_selected) self.info_view = InfoView() self.info_view.connect("change-cursor", self._change_cursor) self.info_view.connect("can-go-back", self._can_go_back_cb) self.info_view.connect("can-go-forward", self._can_go_forward_cb) self.set_screen(Screen.SOLAR_SYSTEM) self.show_all()
def __init__(self, ty, name): """Initialize the instance.""" super(MiddleIrGlobalVariable, self).__init__() Area.__init__(self) self.type = ty #self.value = None self.name = name self.module = None
def test_area_calculateDistances(self): area = Area(5) area.saveArea() testArea = Area('file') self.assertEqual(testArea.numberOfBlocks, 5) self.assertEqual(testArea.cords.shape, (5, 2)) self.assertEqual(testArea.sizes.shape, (5, )) self.assertEqual(testArea.distances.shape, (5, 5))
def next_area(self, canvas): self.area_number += 1 self.area = Area() self.hero.restore_health() self.characters = self.create_characters() self.monsters = self.characters[1:] self.area.draw_map(canvas) canvas.delete(self.hero.name) self.hero.direction = 'hero-down' self.spawn_characters(canvas)
def main(): print("\n1 - Area of Circle\n") print("2 - Area of Triangle\n") print("3 - Area of Square\n") print("4 - Quit\n") while True: try: choice = int(input("\nEnter your choice:\t")) except Exception as e: print("\nPlease enter valid integer\n") continue if choice == 1: try: radius = float(input("\nEnter radius of the Circle:\t")) print("\nArea is : " + str(Area.circle(radius))) except Exception as e: print(str(e)) print("\nPlease enter valid radius value\n") continue if choice == 2: try: base = float(input("\nEnter base of the Triangle:\t")) height = float(input("\nEnter height of the Triangle:\t")) print("\nArea is : " + str(Area.triangle(height, base))) except Exception as e: print("\nPlease enter valid integers\n") continue if choice == 3: try: side = float(input("\nEnter a side of the Square:\t")) print("\nArea is : " + str(Area.square(side))) except Exception as e: print("\nPlease enter valid integer\n") continue if choice == 4: print("Bye\n") break if (choice < 1) or (choice > 4): print("\n Invalid Choice \n")
def __init__(self, handle): activity.Activity.__init__(self, handle) self.make_toolbar() hbox = Gtk.HBox() self.set_canvas(hbox) self.area = Area() hbox.pack_start(self.area, True, False, 0) self.show_all()
def __init__(self, id=''): if not id: self.id = generate_uuid() else: self.id = id self.pickup_pose = Area() self.delivery_pose = Area() self.earliest_pickup_time = TimeStamp() self.latest_pickup_time = TimeStamp() self.user_id = '' self.load_type = '' self.load_id = '' self.priority = -1
def __init__(self, llvm_instruction=None, _type=None): """Initialize the intermediate level IR module class.""" #super(MiddleIrInstruction, self).__init__() # LLVM specific objects initialization. MiddleIrLLVMInstance.__init__(self, llvm_instruction) Area.__init__(self) self.print_address = True self.type = _type self.is_used = False self.yields = None
def run_game(vcstate): ''' The main game loop. Params: vcstate: An object that handles rendering & IO. ''' halfwidth = int(level_dim / 2) midpoint = Point(halfwidth, halfwidth) player = Player() area = Area(new_level(player, midpoint, 1, level_dim)) history = [''] vcwrapper = VCWrapper(vcstate) while True: # render & check IO vcwrapper.vcstate.render(player, area, history) time_taken = vcwrapper.run(player, area, history) if vcwrapper.done(): return if not time_taken: continue # cooldowns for abil in player.abilities: abil.cooldown = max(0, abil.cooldown - 1) # run the rest of the simulation if on_stairs(player, area): move_to_new_level(player, area, history) continue to_act = area.all_actors() while to_act: waiting_actors = [] for actor in to_act: actor_done = actor.act(area, history) if not actor_done: waiting_actors.append(actor) if waiting_actors == to_act: break to_act = waiting_actors if to_act: vcwrapper.vcstate.render(player, area, history) time.sleep(0.1) for actor in area.all_actors(): actor.end_of_turn_cleanup()
def _queryTrObjsByCatView(wlNames=None, areaIds=None, areaNames=None, branchNames=None, testerIds=None, bldTypes=None): def _argsWrapper(args): if not args: return [None] else: return args if not wlNames: wlIds = [None] else: from workload import Workload wlIds = Workload.getWorkloadIds(wlNames) if areaNames: areaIds = Area.getAreaIds(areaNames) elif areaIds: childrenIds = Area.getChildrenAreaIds(areaIds) if childrenIds: areaIds.extend(childrenIds) else: areaIds = [None] # The order for filterKey and filterLoop should be matched filterKey = ['workload', 'area__id__in', 'deliverables__build__branch__in', 'tester__id__in', 'deliverables__build__bldtype__in'] filterLoop = itertools.product(wlIds, areaIds, _argsWrapper(branchNames), _argsWrapper(testerIds), _argsWrapper(bldTypes)) filterLoop = list(filterLoop) trObjs = [] for item in filterLoop: filterMap = {} for i in range(len(item)): if item[i] is None: continue filterMap[filterKey[i]] = item[i] logger.info("Retrieving testrun data via RestAPI with filterInfo: %s", filterMap) tmpTrObjs = queryCatInfo('testrun', filterMap, limitDay=limitDay, limit=limitNumber, orderBy="-endtime") if tmpTrObjs: logger.info("Totally get %d testruns" % len(tmpTrObjs)) trObjs.extend(tmpTrObjs) return trObjs
def execute(self, source, target): if not len(target): return "Area name not specified" area_id = "_".join(target).lower() if self.load_object(Area, area_id): return "That area already exists" area = Area(area_id) area_name = " ".join(target) area.name = string.capwords(area_name) room = Room(area_id + ":0", "Area " + area.name + " Start", "The Initial Room in " + area.name + " Area") area.rooms.append(room) area.owner_id = source.dbo_id self.create_object(area) self.mud.add_area(area) source.parse("goto room " + room.dbo_id)
def execute(self, board, player_type): board.attacks.append(copy(self)) print(self) if not self.uncounterable: # 対応 board.players[player_type.opponent()].counter(board) # TODO: 対応後の諸々の判定(間合や決死などの条件の再確認) # TODO: 不可避の処理 attack = board.attacks.pop() if attack.canceled: # 攻撃が打ち消された(【攻撃後】効果も無し) return if attack.aura_damage is None or \ board.opponent_player().aura() < attack.aura_damage: # オーラダメージが - か、オーラが足りなければ強制的にライフで受ける select_aura = False elif attack.life_damage is None: select_aura = True else: # ダメージの受け方を尋ねる while True: print('ダメージ {}/{} をどちらで受けますか?'.format(attack.aura_damage, attack.life_damage)) damage_select = yield '[{}]: オーラ, [{}]: ライフ'\ .format(SELECT_AURA, SELECT_LIFE) if damage_select == SELECT_AURA: select_aura = True break elif damage_select == SELECT_LIFE: select_aura = False break else: print('入力が不正です!') if select_aura: # オーラダメージを選択 # TODO: 「無音壁」展開中かどうか確認し、 # 展開中ならダメージの受け方を尋ねる damage = min(board.players[player_type.opponent()].aura(), attack.aura_damage) Area.move_flowers(board.players[player_type.opponent()].aura, board.dust, damage) else: # ライフダメージを選択 damage = min(board.opponent_player().life(), attack.life_damage) Area.move_flowers(board.opponent_player().life, board.opponent_player().flare, damage)
def reset(self, navdb): # This ensures that the traffic arrays (which size is dynamic) # are all reset as well, so all lat,lon,sdp etc but also objects adsb super(Traffic, self).reset() self.ntraf = 0 # Reset models self.wind.clear() # Build new modules for area and turbulence self.area = Area(self) self.Turbulence = Turbulence(self) # Noise (turbulence, ADBS-transmission noise, ADSB-truncated effect) self.setNoise(False) # Import navigation data base self.navdb = navdb # Default: BlueSky internal performance model. # Insert your BADA files to the folder "BlueSky/data/coefficients/BADA" # for working with EUROCONTROL`s Base of Aircraft Data revision 3.12 self.perf = Perf(self) self.AMAN=AMAN(AllFlights,unique_runways) for rwy in unique_runways: self.AMAN.initial_schedule_popupflightsonly(intarrtime_AMAN_runway,rwy,simulation_start,unique_runways)
def reconstruction(self, no_damage=False): """ 山札の再構成を行う Args: no_damage (bool, optional): ダメージを受けない場合に ``True``. デフォルトは ``False`` """ # TODO: 設置・虚魚の処理 self.stock.push_bottom(self.downed.stack) self.downed.clear() self.stock.push_bottom(self.discarded.stack) self.discarded.clear() self.stock.shuffle() if not no_damage: Area.move_flowers(self.life, self.flare, 1)
def test_area_size(self): area = Area('draw', 10) self.assertEqual(area.numberOfBlocks, 10) self.assertEqual(area.cords.shape, (10, 2)) self.assertEqual(area.sizes.shape, (10, )) self.assertEqual(area.distances.shape, (10, 10))
def __init__(self): self.area = Area() self.ant_num = 20 self.ant_list = [] self.add_number = 0 for i in range(self.ant_num): self.ant_list.append(Ant(self.area.area))
def __call__(self, c): start = self.area.startFrom(c) end = self.area.endFrom(c) a = Area(start.x, start.y, end.x, end.y) for x in self.feature(a): yield x
def __call__(self, area): start = self.getStart(area) end = self.getEnd(area) a = Area(start.x, start.y, end.x, end.y) for (x, y, orientation) in self.algorithm(a): yield Coords(x, y, orientation)
def crawl_arcodes(self, limit=sys.maxsize, dynamo_conn=None): count = 0 for area in Area.crawl_areas(): if count >= limit: break area.save(dynamo_conn) count += 1 logger.info("%d areas are crawled" % count) return count
def canSee(self, other): cursor = self.cell.getCursor() l = list(algorithms.line(Area(self.x, self.y, other.x, other.y))) l = l[1:-1] for (x, y, _) in l: if cursor.move(x, y).isSolid: return False return True
def test_crawl_arcodes(self): count = 0 for area in Area.crawl_areas(): if area == Area('서울특별시', '강북구', 11305): break if count == 10: self.fail() else: count += 1 else: self.fail()
def reset(self): # This ensures that the traffic arrays (which size is dynamic) # are all reset as well, so all lat,lon,sdp etc but also objects adsb super(Traffic, self).reset() self.ntraf = 0 # Reset models self.wind.clear() # Build new modules for area and turbulence self.area = Area() self.Turbulence = Turbulence() # Noise (turbulence, ADBS-transmission noise, ADSB-truncated effect) self.setNoise(False) # Default: BlueSky internal performance model. # Insert your BADA files to the folder "BlueSky/data/coefficients/BADA" # for working with EUROCONTROL`s Base of Aircraft Data revision 3.12 self.perf = Perf() self.trails.reset()
def draw_single(self, board): """ 山札からカードを1枚ドローする 山札が無ければ焦燥ダメージを受ける """ if len(self.stock) == 0: # 焦燥ダメージ if self.aura == 0: print('焦燥ダメージをライフで受けます') select_aura = False else: # ダメージの受け方を尋ねる receive = yield '焦燥ダメージをどちらで受けますか?\n'\ '[0]: オーラ, [1]: ライフ' select_aura = True if receive == '0' else False if select_aura: Area.move_flowers(self.aura, board.dust, 1) else: Area.move_flowers(self.life, self.flare, 1) else: self.hand.push_bottom(self.stock.pop())
def convert_unit(self, value, input_unit, output_unit): if self.measurement is 'length': return Length(value, input_unit, output_unit).convert() if self.measurement is 'temperature': return Temperature(value, input_unit, output_unit).convert() if self.measurement is 'area': return Area(value, input_unit, output_unit).convert() if self.measurement is 'volume': return Volume(value, input_unit, output_unit).convert() if self.measurement is 'weight': return Weight(value, input_unit, output_unit).convert() return "Not a valid measurement is entered! Select from : length, temperature, volume, area, weight"
def from_dict(task_dict): task = Task() task.id = task_dict['id'] task.loadType = task_dict['loadType'] task.loadId = task_dict['loadId'] task.team_robot_ids = task_dict['team_robot_ids'] task.earliest_start_time = TimeStamp.from_str( task_dict['earliest_start_time']) task.latest_start_time = TimeStamp.from_str( task_dict['latest_start_time']) task.estimated_duration = datetime.timedelta( minutes=task_dict['estimated_duration']) task.earliest_finish_time = TimeStamp.from_str( task_dict['earliest_finish_time']) task.latest_finish_time = TimeStamp.from_str( task_dict['latest_finish_time']) start_time = task_dict.get('start_time', None) if start_time: task.start_time = TimeStamp.from_str(start_time) else: task.start_time = start_time finish_time = task_dict.get('finish_time', None) if finish_time: task.finish_time = TimeStamp.from_str(finish_time) else: task.finish_time = finish_time task.pickup_pose = Area.from_dict(task_dict['pickup_pose']) task.delivery_pose = Area.from_dict(task_dict['delivery_pose']) task.priority = task_dict['priority'] task.status = TaskStatus.from_dict(task_dict['status']) task.hard_constraints = task_dict['hard_constraints'] for robot_id, actions in task_dict['robot_actions'].items(): task.robot_actions[robot_id] = list() for action_dict in actions: action = Action.from_dict(action_dict) task.robot_actions[robot_id].append(action) return task
def getAllTeams(self): query = "SELECT * FROM teams;" if not self.connection: return False cur = self.connection.cursor() cur.execute(query) self.connection.commit() result = [] for record in cur.fetchall(): a = Area.fromDB(record) result.append(a) cur.close() return result
def test_fields(): # test initialization a = Area(name="area_name", desc="area_desc", domain=[9], action=lambda: 5, resource_id="r_id") # test fields assert a.name == "area_name" assert a.desc == "area_desc" assert len(a.domain) == 1 and a.domain[0] == 9 assert a.action() == 5 assert a.resource_id == "r_id" # test dump dump = a.dump() assert dump['name'] == "area_name" assert dump['desc'] == "area_desc" assert dump['domain'] == "[9]" assert str(dump) == str(a)
class ConnectTheDotsActivity(activity.Activity): def __init__(self, handle): activity.Activity.__init__(self, handle) self.make_toolbar() hbox = Gtk.HBox() self.set_canvas(hbox) self.area = Area() hbox.pack_start(self.area, True, False, 0) self.show_all() def make_toolbar(self): toolbarbox = ToolbarBox() self.set_toolbar_box(toolbarbox) button = ActivityToolbarButton(self) toolbarbox.toolbar.insert(button, -1) toolbarbox.toolbar.insert(Gtk.SeparatorToolItem(), -1) button_new = ToolButton("new-button") button_new.set_tooltip(_("New")) button_new.connect("clicked", self._next_level) toolbarbox.toolbar.insert(button_new, -1) separator = Gtk.SeparatorToolItem() separator.props.draw = False separator.set_expand(True) toolbarbox.toolbar.insert(separator, -1) button = StopButton(self) toolbarbox.toolbar.insert(button, -1) def _next_level(self, button): self.area.next_level()
def __init__(self, env): self.env = env self.actor_moved = [i for i in range(3)] self.areas = [Area(i, "area %d" %i, 100, env) for i in range(3)] self.actors = [Actor(i, self.areas[i], env) for i in range(self.ACTOR_COUNT)] self.actor_wait_event_procs = [env.process(self.actors[i].process_event()) for i in range(3)] # self.actor_procs = env.process(self.trigger_actor_events()) self.check_actors_procs = env.process(self.check_actors()) self.area_move_in_procs = [env.process(self.areas[i].move_in()) for i in range(self.AREA_COUNT)] self.area_move_out_procs = [env.process(self.areas[i].move_out()) for i in range(self.AREA_COUNT)]
def get_board(): numbers = [] for i in range(1, NUMBER_X * NUMBER_Y + 1): numbers.append(i) board = [] for i in range(NUMBER_X): areas = [] for j in range(NUMBER_Y): x = random.randint(0, len(numbers) - 1) position = i * ELEMENT_SIZE, j * ELEMENT_SIZE areas.append(Area(position, numbers[x])) numbers.pop(x) board.append(areas) return board
def frame(area): startX = area.left startY = area.top endX = area.right endY = area.bottom yield (startX, startY, "stationary") yield (startX, endY, "stationary") yield (endX, endY, "stationary") yield (endX, startY, "stationary") for coords in ((startX + 1, startY, endX - 1, startY), (startX, startY + 1, startX, endY - 1), (startX + 1, endY, endX - 1, endY), (endX, startY + 1, endX, endY - 1)): for point in line(Area(*coords)): yield point
from area import Area from item import Item from player import Player start = Area( "You find yourself stranded in the middle of a road. Looking to either " "side you see nothing but nondescript forest. It appears your only " "path is either forward, farther down to where you were apparently " "going, or backwards, from where you apparently came. ", "A barren stretch of road. How did you end up there? " ) keychain = Item( frozenset(["keys", "keychain", "key"]), "The keychain is made up of three keys and a key fob with the word " "\"TESIN\" inscribed on a tiny, rubber computer mouse. Two of the keys " "are rather plain but the third has a Toyota symbol on it. ", "There is a keychain at your feet. " ) wallet = Item( frozenset(["wallet", "billfold", "pocketbook"]), "Looking inside the wallet, you find a small photo of yourself with your " "arm around someone's sholders. There's a couple fives as well as an old " "library card. ", "There is a wallet laying on the road to your left. " ) forward = Area( "After a few hours of walking you notice it's starting to get dark. You " "decide it would be better to set up camp before night falls, so you "
class Traffic(DynamicArrays): """ Traffic class definition : Traffic data Methods: Traffic() : constructor reset() : Reset traffic database w.r.t a/c data create(acid,actype,aclat,aclon,achdg,acalt,acspd) : create aircraft delete(acid) : delete an aircraft from traffic data deletall() : delete all traffic update(sim) : do a numerical integration step id2idx(name) : return index in traffic database of given call sign engchange(i,engtype) : change engine type of an aircraft setNoise(A) : Add turbulence Members: see create Created by : Jacco M. Hoekstra """ def __init__(self, navdb): self.wind = WindSim() # Define the periodic loggers # ToDo: explain what these line sdo in comments (type of logs?) datalog.definePeriodicLogger('SNAPLOG', 'SNAPLOG logfile.', settings.snapdt) datalog.definePeriodicLogger('INSTLOG', 'INSTLOG logfile.', settings.instdt) datalog.definePeriodicLogger('SKYLOG', 'SKYLOG logfile.', settings.skydt) with RegisterElementParameters(self): # Register the following parameters for logging with datalog.registerLogParameters('SNAPLOG', self): # Aircraft Info self.id = [] # identifier (string) self.type = [] # aircaft type (string) # Positions self.lat = np.array([]) # latitude [deg] self.lon = np.array([]) # longitude [deg] self.alt = np.array([]) # altitude [m] self.hdg = np.array([]) # traffic heading [deg] self.trk = np.array([]) # track angle [deg] # Velocities self.tas = np.array([]) # true airspeed [m/s] self.gs = np.array([]) # ground speed [m/s] self.gsnorth = np.array([]) # ground speed [m/s] self.gseast = np.array([]) # ground speed [m/s] self.cas = np.array([]) # calibrated airspeed [m/s] self.M = np.array([]) # mach number self.vs = np.array([]) # vertical speed [m/s] # Atmosphere self.p = np.array([]) # air pressure [N/m2] self.rho = np.array([]) # air density [kg/m3] self.Temp = np.array([]) # air temperature [K] self.dtemp = np.array([]) # delta t for non-ISA conditions # Traffic autopilot settings self.aspd = np.array([]) # selected spd(CAS) [m/s] self.aptas = np.array([]) # just for initializing self.ama = np.array([]) # selected spd above crossover altitude (Mach) [-] self.apalt = np.array([]) # selected alt[m] self.avs = np.array([]) # selected vertical speed [m/s] # Speed offset self.spdoffset = np.array([]) # speed offset [kts] self.spdoffsetdev = np.array([]) # speed offset deviation [kts] self.spd_onoff = np.array([]) # speed offset on/off # Whether to perform LNAV and VNAV self.swlnav = np.array([], dtype=np.bool) self.swvnav = np.array([], dtype=np.bool) # Flight Models self.asas = ASAS(self) self.ap = Autopilot(self) self.pilot = Pilot(self) self.adsb = ADSB(self) self.trails = Trails(self) self.actwp = ActiveWaypoint(self) # Traffic performance data self.avsdef = np.array([]) # [m/s]default vertical speed of autopilot self.aphi = np.array([]) # [rad] bank angle setting of autopilot self.ax = np.array([]) # [m/s2] absolute value of longitudinal accelleration self.bank = np.array([]) # nominal bank angle, [radian] self.hdgsel = np.array([], dtype=np.bool) # determines whether aircraft is turning # Crossover altitude self.abco = np.array([]) self.belco = np.array([]) # limit settings self.limspd = np.array([]) # limit speed self.limspd_flag = np.array([], dtype=np.bool) # flag for limit spd - we have to test for max and min self.limalt = np.array([]) # limit altitude self.limvs = np.array([]) # limit vertical speed due to thrust limitation self.limvs_flag = np.array([]) # Display information on label self.label = [] # Text and bitmap of traffic label # Miscallaneous self.coslat = np.array([]) # Cosine of latitude for computations self.eps = np.array([]) # Small nonzero numbers # Default bank angles per flight phase self.bphase = np.deg2rad(np.array([15, 35, 35, 35, 15, 45])) self.reset(navdb) def reset(self, navdb): # This ensures that the traffic arrays (which size is dynamic) # are all reset as well, so all lat,lon,sdp etc but also objects adsb super(Traffic, self).reset() self.ntraf = 0 # Reset models self.wind.clear() # Build new modules for area and turbulence self.area = Area(self) self.Turbulence = Turbulence(self) # Noise (turbulence, ADBS-transmission noise, ADSB-truncated effect) self.setNoise(False) # Import navigation data base self.navdb = navdb # Default: BlueSky internal performance model. # Insert your BADA files to the folder "BlueSky/data/coefficients/BADA" # for working with EUROCONTROL`s Base of Aircraft Data revision 3.12 self.perf = Perf(self) self.AMAN=AMAN(AllFlights,unique_runways) for rwy in unique_runways: self.AMAN.initial_schedule_popupflightsonly(intarrtime_AMAN_runway,rwy,simulation_start,unique_runways) def mcreate(self, count, actype=None, alt=None, spd=None, dest=None, area=None): """ Create multiple random aircraft in a specified area """ idbase = chr(randint(65, 90)) + chr(randint(65, 90)) if actype is None: actype = 'B744' for i in xrange(count): acid = idbase + '%05d' % i aclat = random() * (area[1] - area[0]) + area[0] aclon = random() * (area[3] - area[2]) + area[2] achdg = float(randint(1, 360)) acalt = (randint(2000, 39000) * ft) if alt is None else alt acspd = (randint(250, 450) * kts) if spd is None else spd self.create(acid, actype, aclat, aclon, achdg, acalt, acspd) def create(self, acid=None, actype="B744", aclat=None, aclon=None, achdg=None, acalt=None, casmach=None): """Create an aircraft""" # Check if not already exist if self.id.count(acid.upper()) > 0: return False, acid + " already exists." # already exists do nothing # Catch missing acid, replace by a default if acid == None or acid =="*": acid = "KL204" flno = 204 while self.id.count(acid)>0: flno = flno+1 acid ="KL"+str(flno) # Check for (other) missing arguments if actype == None or aclat == None or aclon == None or achdg == None \ or acalt == None or casmach == None: return False,"CRE: Missing one or more arguments:"\ "acid,actype,aclat,aclon,achdg,acalt,acspd" super(Traffic, self).create() # Increase number of aircraft self.ntraf = self.ntraf + 1 # Aircraft Info self.id[-1] = acid.upper() self.type[-1] = actype # Positions self.lat[-1] = aclat self.lon[-1] = aclon self.alt[-1] = acalt self.hdg[-1] = achdg self.trk[-1] = achdg # Velocities self.tas[-1], self.cas[-1], self.M[-1] = casormach(casmach, acalt) self.gs[-1] = self.tas[-1] self.gsnorth[-1] = self.tas[-1] * cos(radians(self.hdg[-1])) self.gseast[-1] = self.tas[-1] * sin(radians(self.hdg[-1])) # Speed offset self.spd_onoff[-1] = 0. # Speed offset = 0 (off) on default # Atmosphere self.Temp[-1], self.rho[-1], self.p[-1] = vatmos(acalt) # Wind if self.wind.winddim > 0: vnwnd, vewnd = self.wind.getdata(self.lat[-1], self.lon[-1], self.alt[-1]) self.gsnorth[-1] = self.gsnorth[-1] + vnwnd self.gseast[-1] = self.gseast[-1] + vewnd self.trk[-1] = np.degrees(np.arctan2(self.gseast[-1], self.gsnorth[-1])) self.gs[-1] = np.sqrt(self.gsnorth[-1]**2 + self.gseast[-1]**2) # Traffic performance data #(temporarily default values) self.avsdef[-1] = 1500. * fpm # default vertical speed of autopilot self.aphi[-1] = radians(25.) # bank angle setting of autopilot self.ax[-1] = kts # absolute value of longitudinal accelleration self.bank[-1] = radians(25.) # Crossover altitude self.abco[-1] = 0 # not necessary to overwrite 0 to 0, but leave for clarity self.belco[-1] = 1 # Traffic autopilot settings self.aspd[-1] = self.cas[-1] self.aptas[-1] = self.tas[-1] self.apalt[-1] = self.alt[-1] # Display information on label self.label[-1] = ['', '', '', 0] # Miscallaneous self.coslat[-1] = cos(radians(aclat)) # Cosine of latitude for flat-earth aproximations self.eps[-1] = 0.01 # ----- Submodules of Traffic ----- self.ap.create() self.actwp.create() self.pilot.create() self.adsb.create() self.area.create() self.asas.create() self.perf.create() self.trails.create() return True def delete(self, acid): """Delete an aircraft""" # Look up index of aircraft idx = self.id2idx(acid) # Do nothing if not found if idx < 0: return False # Decrease number of aircraft self.ntraf = self.ntraf - 1 # Delete all aircraft parameters super(Traffic, self).delete(idx) # ----- Submodules of Traffic ----- self.perf.delete(idx) self.area.delete(idx) return True def update(self, simt, simdt): # Update only if there is traffic --------------------- if self.ntraf == 0: return #---------- Atmosphere -------------------------------- self.p, self.rho, self.Temp = vatmos(self.alt) #---------- ADSB Update ------------------------------- self.adsb.update(simt) #---------- Fly the Aircraft -------------------------- self.ap.update(simt) self.asas.update(simt) self.pilot.FMSOrAsas() #---------- Limit Speeds ------------------------------ self.pilot.FlightEnvelope() #---------- Kinematics -------------------------------- self.UpdateAirSpeed(simdt, simt) self.UpdateGroundSpeed(simdt) self.UpdatePosition(simdt) #---------- Performance Update ------------------------ self.perf.perf(simt) #---------- Simulate Turbulence ----------------------- self.Turbulence.Woosh(simdt) #---------- Aftermath --------------------------------- self.trails.update(simt) self.area.check(simt) #---------- AMAN -------------------------------------- i=0 while(i<self.ntraf): temp1, temp2 = qdrdist(self.lat[i], self.lon[i], 52.309, 4.764) # Check distance towards EHAM if temp2<2. and self.alt[i]<1.: # If aircraft within 2 nm from airport and below 1 meter, delete it self.delete(self.id[i]) i=i+1 # Calculate energy cost per flight self.AMAN.calculate_energy_cost(self.id,self.vs,self.tas,CD_0,CD_2,self.rho,WingSurface,self.hdg,self.trk,mass_nominal,simdt) # Increase iteration counter self.AMAN.IterationCounter=self.AMAN.IterationCounter+1 # Update trajectory predictor, scheduler and SARA every five seconds if self.AMAN.IterationCounter%2==0: # Check for speed offset self.AMAN.speed_offset_switch(self.id,AMAN_horizon,self.spd_onoff) # Update Trajectory Predictions self.AMAN.update_TP(self.id,self.lat,self.lon,self.tas/kts,self.actwp.lat,self.actwp.lon,simt) # Update schedule per runway for rwy in unique_runways: if '--node' in sys.argv: if var_TP==str('ASAPBASIC'): self.AMAN.scheduler_ASAP_basic(self.id,Take_into_account_schedule_horizon,rwy,intarrtime_AMAN_runway,Freeze_horizon,unique_runways) elif var_TP==str('DYNAMIC'): self.AMAN.scheduler_dynamic(self.id,Take_into_account_schedule_horizon,rwy,intarrtime_AMAN_runway) elif var_TP==str('ASAPUPGRADE'): self.AMAN.scheduler_ASAP_upgrade(self.id,Take_into_account_schedule_horizon,rwy,intarrtime_AMAN_runway,Freeze_horizon,unique_runways) else: self.AMAN.scheduler_ASAP_basic(self.id,Take_into_account_schedule_horizon,rwy,intarrtime_AMAN_runway,Freeze_horizon,unique_runways) # #self.AMAN.scheduler_dynamic(self.id,Take_into_account_schedule_horizon,rwy,intarrtime_AMAN_runway) # #self.AMAN.scheduler_ASAP_upgrade(self.id,Take_into_account_schedule_horizon,rwy,intarrtime_AMAN_runway,Freeze_horizon,unique_runways) # Update SARA advisories self.AMAN.update_SARA(self.id,self.alt,self.ap.route,SARA_horizon,simt,approach_margin) # Save variables in logger self.AMAN.AMAN_LOG_arrtimes_and_energycost(self.id,simulation_start) self.AMAN.AMAN_LOG_STAhistory(self.id,simt) self.AMAN.AMAN_LOG_lowleveldelay(self.id,simt) self.AMAN.AMAN_LOG_seqhistory(self.id) self.AMAN.AMAN_LOG_CBAShistory(self.id,simulation_start) #self.AMAN.AMAN_LOG_ETA_CBAShistory(self.id,simt) self.AMAN.AMAN_LOG_traffic_bunches(self.id,approach_margin,simt) return def UpdateAirSpeed(self, simdt, simt): # Acceleration self.delspd = self.pilot.spd - self.tas swspdsel = np.abs(self.delspd) > 0.4 # <1 kts = 0.514444 m/s ax = self.perf.acceleration(simdt) # Update velocities self.tas = self.tas + swspdsel * ax * np.sign(self.delspd) * simdt self.cas = vtas2cas(self.tas, self.alt) self.M = vtas2mach(self.tas, self.alt) # Turning turnrate = np.degrees(g0 * np.tan(self.bank) / np.maximum(self.tas, self.eps)) delhdg = (self.pilot.hdg - self.hdg + 180.) % 360 - 180. # [deg] self.hdgsel = np.abs(delhdg) > np.abs(2. * simdt * turnrate) # Update heading self.hdg = (self.hdg + simdt * turnrate * self.hdgsel * np.sign(delhdg)) % 360. # Update vertical speed delalt = self.pilot.alt - self.alt self.swaltsel = np.abs(delalt) > np.maximum(10 * ft, np.abs(2 * simdt * np.abs(self.vs))) self.vs = self.swaltsel * np.sign(delalt) * self.pilot.vs def UpdateGroundSpeed(self, simdt): # Compute ground speed and track from heading, airspeed and wind spd_random = self.spdoffset * kts + np.random.randn(self.ntraf) * self.spdoffsetdev * kts #self.spd_onoff = array([0 0 0 0 0 0 1 0 0 0 etc.]) # Array whether speed offset + randomness is on/off per aircraft tasx = self.tas + spd_random * self.spd_onoff #print(tasx) #tasx = self.tas + self.spdoffset * kts # np.random.randn(self.ntraf) * self.spdoffsetdev * kts if self.wind.winddim == 0: # no wind self.gsnorth = tasx * np.cos(np.radians(self.hdg)) self.gseast = tasx * np.sin(np.radians(self.hdg)) self.gs = self.tas self.trk = self.hdg else: windnorth, windeast = self.wind.getdata(self.lat, self.lon, self.alt) self.gsnorth = tasx * np.cos(np.radians(self.hdg)) + windnorth self.gseast = tasx * np.sin(np.radians(self.hdg)) + windeast self.gs = np.sqrt(self.gsnorth**2 + self.gseast**2) self.trk = np.degrees(np.arctan2(self.gseast, self.gsnorth)) % 360. def UpdatePosition(self, simdt): # Update position self.alt = np.where(self.swaltsel, self.alt + self.vs * simdt, self.pilot.alt) self.lat = self.lat + np.degrees(simdt * self.gsnorth / Rearth) self.coslat = np.cos(np.deg2rad(self.lat)) self.lon = self.lon + np.degrees(simdt * self.gseast / self.coslat / Rearth) def id2idx(self, acid): """Find index of aircraft id""" try: return self.id.index(acid.upper()) except: return -1 def setNoise(self, noise=None): """Noise (turbulence, ADBS-transmission noise, ADSB-truncated effect)""" if noise is None: return True, "Noise is currently " + ("on" if self.Turbulence.active else "off") self.Turbulence.SetNoise(noise) self.adsb.SetNoise(noise) return True def engchange(self, acid, engid): """Change of engines""" self.perf.engchange(acid, engid) return def move(self, idx, lat, lon, alt=None, hdg=None, casmach=None, vspd=None): self.lat[idx] = lat self.lon[idx] = lon if alt: self.alt[idx] = alt self.apalt[idx] = alt if hdg: self.hdg[idx] = hdg self.ap.trk[idx] = hdg if casmach: self.tas[idx], self.aspd[-1], dummy = casormach(casmach, alt) if vspd: self.vs[idx] = vspd self.swvnav[idx] = False def nom(self, idx): """ Reset acceleration back to nominal (1 kt/s^2): NOM acid """ self.ax[idx] = kts def setdeltaspeed(self, idx, offset=0.): self.spdoffset[idx] = offset def setdeltaspeeddev(self, idx, offset=0.): self.spdoffsetdev[idx] = offset def poscommand(self, scr, idxorwp):# Show info on aircraft(int) or waypoint or airport (str) """POS command: Show info or an aircraft, airport, waypoint or navaid""" # Aircraft index if type(idxorwp)==int and idxorwp >= 0: idx = idxorwp acid = self.id[idx] actype = self.type[idx] lat, lon = self.lat[idx], self.lon[idx] alt, hdg, trk = self.alt[idx] / ft, self.hdg[idx], round(self.trk[idx]) cas = self.cas[idx] / kts tas = self.tas[idx] / kts route = self.ap.route[idx] # Position report lines = "Info on %s %s index = %d\n" % (acid, actype, idx) \ + "Pos = %.2f, %.2f. Spd: %d kts CAS, %d kts TAS\n" % (lat, lon, cas, tas) \ + "Alt = %d ft, Hdg = %d, Trk = %d\n" % (alt, hdg, trk) # FMS AP modes if self.swlnav[idx] and route.nwp > 0 and route.iactwp >= 0: if self.swvnav[idx]: lines = lines + "VNAV, " lines += "LNAV to " + route.wpname[route.iactwp] + "\n" # Flight info: Destination and origin if self.ap.orig[idx] != "" or self.ap.dest[idx] != "": lines = lines + "Flying" if self.ap.orig[idx] != "": lines = lines + " from " + self.ap.orig[idx] if self.ap.dest[idx] != "": lines = lines + " to " + self.ap.dest[idx] # Show a/c info and highlight route of aircraft in radar window # and pan to a/c (to show route) return scr.showacinfo(acid,lines) # Waypoint: airport, navaid or fix else: wp = idxorwp.upper() # Reference position for finding nearest reflat = scr.ctrlat reflon = scr.ctrlon lines = "Info on "+wp+":\n" # First try airports (most used and shorter, hence faster list) iap = self.navdb.getaptidx(wp) if iap>=0: aptypes = ["large","medium","small"] lines = lines + self.navdb.aptname[iap]+"\n" \ + "is a "+ aptypes[max(-1,self.navdb.aptype[iap]-1)] \ +" airport at:\n" \ + latlon2txt(self.navdb.aptlat[iap], \ self.navdb.aptlon[iap]) + "\n" \ + "Elevation: " \ + str(int(round(self.navdb.aptelev[iap]/ft))) \ + " ft \n" # Show country name try: ico = self.navdb.cocode2.index(self.navdb.aptco[iap].upper()) lines = lines + "in "+self.navdb.coname[ico]+" ("+ \ self.navdb.aptco[iap]+")" except: ico = -1 lines = lines + "Country code: "+self.navdb.aptco[iap] try: rwytxt = str(self.navdb.rwythresholds[self.navdb.aptid[iap]].keys()) lines = lines + "\nRunways: " +rwytxt.strip("[]").replace("'","") except: pass # Not found as airport, try waypoints & navaids else: iwps = self.navdb.getwpindices(wp,reflat,reflon) if iwps[0]>=0: typetxt = "" desctxt = "" lastdesc = "XXXXXXXX" for i in iwps: # One line type text if typetxt == "": typetxt = typetxt+self.navdb.wptype[i] else: typetxt = typetxt+" and "+self.navdb.wptype[i] # Description: multi-line samedesc = self.navdb.wpdesc[i]==lastdesc if desctxt == "": desctxt = desctxt +self.navdb.wpdesc[i] lastdesc = self.navdb.wpdesc[i] elif not samedesc: desctxt = desctxt +"\n"+self.navdb.wpdesc[i] lastdesc = self.navdb.wpdesc[i] # Navaid: frequency if self.navdb.wptype[i] in ["VOR","DME","TACAN"] and not samedesc: desctxt = desctxt + " "+ str(self.navdb.wpfreq[i])+" MHz" elif self.navdb.wptype[i]=="NDB" and not samedesc: desctxt = desctxt+ " " + str(self.navdb.wpfreq[i])+" kHz" iwp = iwps[0] # Basic info lines = lines + wp +" is a "+ typetxt \ + " at\n"\ + latlon2txt(self.navdb.wplat[iwp], \ self.navdb.wplon[iwp]) # Navaids have description if len(desctxt)>0: lines = lines+ "\n" + desctxt # VOR give variation if self.navdb.wptype[iwp]=="VOR": lines = lines + "\nVariation: "+ \ str(self.navdb.wpvar[iwp])+" deg" # How many others? nother = self.navdb.wpid.count(wp)-len(iwps) if nother>0: verb = ["is ","are "][min(1,max(0,nother-1))] lines = lines +"\nThere "+verb + str(nother) +\ " other waypoint(s) also named " + wp else: return False,idxorwp+" not found as a/c, airport, navaid or waypoint" # Show what we found on airport and navaid/waypoint scr.echo(lines) return True
def test_crawl_arcode(self): rs = Area.crawl_area('제주도') self.assertEqual(2, len(rs))
from area import Area from coordinates import Coordinates print "----" print "| |" print "----" p = [Coordinates(0,0), Coordinates(0,2), Coordinates(2,2), Coordinates(2,0)] x = [Coordinates(0,0), Coordinates(0,1), Coordinates(0.5,2), Coordinates(1,1), Coordinates(2,0.5), Coordinates(2,3), Coordinates(-10,1)] f = Area(p) f.__start_point__() for i in x: print i.latitude, i.longitude, f.__das_is_in__(i) print "---------------------" print "|\/|" print "----" p = [Coordinates(0,0), Coordinates(0,2), Coordinates(2,0), Coordinates(4,2), Coordinates(4,0)] x = [Coordinates(0,0), Coordinates(0,1), Coordinates(0.5,2), Coordinates(1,1), Coordinates(2,0.5), Coordinates(2,3), Coordinates(-10,1)] f = Area(p) f.__start_point__() for i in x: print i.latitude, i.longitude, f.__das_is_in__(i)
from scrapper import Scrapper from ship import Ship from area import Area from coordinates import Coordinates bay=["33.52694833905606,44.61786288710962","33.52779437548921,44.6187406119569","33.52844095177134,44.61952376688691","33.52912847311098,44.6203916749758","33.52941621924846,44.62153677469976","33.52955130148957,44.62233144707166","33.5300525893401,44.6227438007253","33.53074849762842,44.62332258304048","33.53171789286472,44.62402774084964","33.5324194892887,44.62470767274025","33.53284911288601,44.62509717000224", "33.53319327158253,44.62545051188663", "33.53388568626423,44.6257351767263", "33.53436842166227,44.62606452934324", "33.53505441166816,44.62632008064779", "33.5353801786637,44.62659249116985", "33.53630376612985,44.62625791333705", "33.53648828981084,44.62599170149596", "33.53610642979442,44.62526522473693", "33.5357881089882,44.6248585430718", "33.53500799910345,44.62426344134919", "33.53465157533417,44.62368184867986", "33.53431369292202,44.62296420957523", "33.53382395865862,44.62231786828408", "33.53333558808044,44.6216463315828", "33.53246351873157,44.62075912758933", "33.53167225920291,44.61991668370528", "33.53115295169879,44.61933457914446", "33.53057732703983,44.61855221942759", "33.53004247447537,44.61794741478788", "33.52952835400872,44.61738465609927", "33.52893986428256,44.61685023094336", "33.52844685348632,44.61674350283417", "33.52770715079468,44.61675678646416","33.52693507427308,44.61711744970111","33.52694833905606,44.61786288710962"] Bay = [] for coord in bay : lon, lat = coord.split(",") Bay.append(Coordinates(float(lat), float(lon))) Field = Area(Bay) Field.__start_point__() caters = ["MOLODIZGNIY", "ADMIRAL LAZAREV", "SATURN", "ADMIRAL ISTOMIN", "V ADMIRAL KLOKACHEV", "NORD"] Caters = [] for c in caters: Caters.append(Ship(c)) Scrap = Scrapper() for cater in Caters : res = Scrap.scrape_ship(cater.name) if res == None: print cater.name, "Not found" else: v, cors, point = res print cater.name, "\t---\t", Field.__das_is_in__(point) print point print
def test_save(self): area = Area('서울특별시', '강북구', 11305) area.save(connection=self.conn) received_area = self.tables['area'].get_item(arcode=11305) self.assertEqual(area.sigunname, received_area['sigunname'])