class Tower: __flightClearance = False flightList = ["0001a", '0001b', '0001c', '0001d', '0001e'] flightNum = "" __fuelCheck = False # Testing airplane codes are correct and adding them to a list of correct codes. # Codes can be added also. def __init__(self): self.anAirplane = Aircraft() def currentFlightList(self): for plane in self.flightList: print(plane) def updateFlightList(self, flightNum): # testing new flight codes are of correct format while True: if len(flightNum) == 5: if flightNum not in self.flightList: print("Flight code", flightNum, "does not appear to be on our system.") self.add_to_system = input("Do you wish to be added to the updated system?") else: print("Flight code", flightNum, " is in our system.") break if self.add_to_system == "y": self.flightList.append(flightNum) self.currentFlightList() break else: print("Flight number not added to system.") break # Checks flight codes are correct. def checkFlightList(self): print("") while True: for plane in self.flightList: print(plane) check = input("Flight list check correct?") if check == "y": print("Flight list authorization complete.") break else: removeFlight = input("Enter flight number that you wish to remove:") if removeFlight in self.flightList: self.flightList.remove(removeFlight) print("Flight number", removeFlight, "was deleted from flight list system.") else: print("Invalid flight number entered.") print("Please enter a authorized flight code.") def requestFlightCheck(self): self.anAirplane.flightNum = input("Enter flight number: ") if len(self.anAirplane.flightNum) == 5: if self.anAirplane.flightNum not in self.flightList: print("Flight code", self.anAirplane.flightNum, "does not appear to be on our system.") self.add_to_system = input("Do you wish to be added to the updated system?") if self.add_to_system == "y": self.flightList.append(self.anAirplane.flightNum) self.currentFlightList() else: print("Flight number not added to system.") else: # Create anAirplane object and grant clearance print("Flight code", self.anAirplane.flightNum, "is in our system.") #check fuel self.anAirplane.fuelCheck() if self.__fuelCheck == False: print("Refueling in process .. ") self.anAirplane.addFuel(15000) self.anAirplane.__flightClearance = self.anAirplane.fuelCheck() self.anAirplane.preFlightCheck() else: self.anAirplane.__flightClearance = self.anAirplane.fuelCheck() self.anAirplane.preFlightCheck()
def read_aircraft(self, aircraft_csv): """ method to read aircraft data from csv file into dictionary """ # open filename, read into 'f' using utf-8 with open(os.path.join("input", aircraft_csv), "rt", encoding="utf8") as f: # assign read data to reader reader = csv.reader(f) # loop through data line-by-line for line in reader: # create an instance/object of Airport for each line aircraft = Aircraft(line[0], line[1], line[2]) # assign line values to airport variables aircraft.code = line[0] aircraft.units = line[1] aircraft.range = line[2] # assign 'code' value as dictionary key for aircraft object self.aircraft_dict[aircraft.code] = aircraft return self.aircraft_dict
def __init__(self, myAirportList, myAircraft, atlas): self.route = [ atlas.getAirport(myAirportList[0]), atlas.getAirport(myAirportList[1]), atlas.getAirport(myAirportList[2]), atlas.getAirport(myAirportList[3]), atlas.getAirport(myAirportList[4]) ] self.aircraft = Aircraft(myAircraft)
def createAircraft(self, code): """ Create a unique aircraft for every route""" aircraftList = [] print('\ncreating', len(self.itinerary.allRoutes), 'Aircraft') print('For Route:', self.itinerary.toString(), 'with aircraft', self.itinerary.aircraftType) aircraftAtlas = Aircraft.AircraftAtlas() flightRadius = aircraftAtlas.getAircraft(code)[2] for route in self.itinerary.allRoutes: aircraftList.append(Aircraft.Aircraft(code, flightRadius, route)) return aircraftList
def test_aircraft(self): a = Aircraft("777") self.assertTrue(a.fuelLevel==0) self.assertTrue(a.range==15610) a.refuel(2000) self.assertTrue(a.fuelLevel==2000) b = Aircraft("A330") b.refuel_to_full(1) self.assertTrue(b.fuelLevel==13430) b.flight_distance(430) self.assertTrue(b.fuelLevel==13000)
def test_aircraft_buyFuel(self): simpleRoute = Route(['DUB', 'LHR', 'EIN'], self.airportAtlas) testAircraft = Aircraft('747', 1000, simpleRoute) fuelBought = testAircraft.buyFuel(testAircraft.route.currentAirport, 1000) self.assertEqual(fuelBought, 1000) fuelBought = testAircraft.buyFuel(testAircraft.route.currentAirport, 1500) self.assertEqual(fuelBought, 1000) fuelBought = testAircraft.buyFuel(testAircraft.route.currentAirport, 800) self.assertEqual(fuelBought, 800)
def __init__(self, plane1, plane2): # Two aircraft self.plane1 = Aircraft(plane1.getXPos(), plane1.getYPos(), plane1.getXFinal(), plane1.getYFinal()) self.plane2 = Aircraft(plane2.getXPos(), plane2.getYPos(), plane2.getXFinal(), plane2.getYFinal()) self.safetyMonitor = SafetyMonitor() # External safety monitor self.graph = Graph(plane1, plane2) # Empty graph self.last1X = True # Plane1 last moved in the x-direction self.last2X = True # Plane2 last moved in the x-direction
def __init__(self): random.seed() self.modelHelperFunctions = Model self.timeDelta = 1.0 #sec self.numberParticles = 1000 self.world = np.array([-3000,3000, #x dims -3000,3000, #y dims 0,200]) #z dims self.transmitters = np.array([tra.Transmitter()]) self.transmitters[-1].state.x = 0 #set the x location of the transmitter self.transmitters[-1].state.y = 0 #set the x location of the transmitter self.transmitters[-1].state.z = 2.35 #the z location of the transmitter [meters off the ground] self.transmitters[-1].state.id = len(self.transmitters)-1 self.transmitters = np.hstack((self.transmitters,np.array([tra.Transmitter()]))) self.transmitters[-1].state.x = 500 #set the x location of the transmitter self.transmitters[-1].state.y = -100 #set the x location of the transmitter self.transmitters[-1].state.z = 4. #the z location of the transmitter [meters off the ground] self.transmitters[-1].state.id = len(self.transmitters)-1 self.transmitters = np.hstack((self.transmitters,np.array([tra.Transmitter()]))) self.transmitters[-1].state.x = 1000 #set the x location of the transmitter self.transmitters[-1].state.y = 1500 #set the x location of the transmitter self.transmitters[-1].state.z = 3. #the z location of the transmitter [meters off the ground] self.transmitters[-1].state.id = len(self.transmitters)-1 self.aircrafts = np.array([air.Aircraft(len(self.transmitters))]) for aircraft in self.aircrafts: aircraft.state.x = -100#random.uniform(300, 900) #randomise the x location of the aircraft aircraft.state.y = 1400#random.uniform(300, 900) #randomise the y location of the aircraft aircraft.state.z = random.uniform(50, 120) #randomise the z location of the aircraft self.particles = [] for i in range(self.numberParticles): self.particles.append(par.Particle(len(self.transmitters))) self.particles[-1].state.x = random.uniform(self.world[0], self.world[1]) #randomise the x location of the particle self.particles[-1].state.y = random.uniform(self.world[2], self.world[3]) #randomise the y location of the particle self.particles[-1].state.z = random.uniform(self.world[4], self.world[5]) #randomise the z location of the particle self.particles[-1].state.groundSpeed = self.aircrafts[0].state.groundSpeed #randomise ground speed of the particle, heading is assumed to be known self.particles[-1].state.yaw = self.aircrafts[0].state.yaw #randomise ground speed of the particle, heading is assumed to be known
def __init__(self, csvFile): """ Reads a csv file to create a dictionary of aircraft objects. It is assumed that the code of an aircraft is contained in the first row of the csv and that the aircraft fuel capacity in litres is in the fifth row of the csv. """ self.Table = {} with open(csvFile) as csvFile: csvOpen = csv.reader(csvFile, delimiter=',') count = 0 for row in csvOpen: if count != 0: aircraft = Aircraft.Aircraft(row[0], row[4]) self.Table[row[0]] = aircraft count += 1
def __init__(self, sim_conditions): self.time_step = 0.01 self.sim_conditions = sim_conditions aircraft_conditions = { "Velocity": self.sim_conditions.get("Velocity"), "Thrust": self.sim_conditions.get("Thrust"), "Flight Path": self.sim_conditions.get("Flight Path"), "Time Step": self.time_step } self.plane = Aircraft.Aircraft(aircraft_conditions) self.steps = math.ceil( self.sim_conditions.get("Run Time") / self.time_step) self.t_ret = np.array([]) self.gamma_ret = np.array([]) self.alpha_ret = np.array([]) self.ub_ret = np.array([]) self.wb_ret = np.array([]) self.theta_ret = np.array([]) self.delta_ret = np.array([]) self.altitude_ret = np.array([])
def buildAircraft(plane): """Builds objects for each of the aircraft - with attributes model, manufacturer, and range. Returns a dictionary of this""" aircraftDict = {} with open('aircraft.csv', newline='', encoding="utf8") as airplane_file: # opens the csv file reader = csv.reader(airplane_file) # reads the cotents to a variable next(reader, None) # returns none at the end of the file for airplane in reader: # iterates through the reader if airplane[0] == plane: if airplane[2] == "imperial": airRange = int(airplane[4]) * 1.609 else: airRange = airplane[4] aircraftDict[airplane[0]] = Aircraft.Aircraft( airplane[0], airplane[3], airRange) if len(aircraftDict) == 0: return False else: return aircraftDict
def __init__(self): self.modelHelperFunctions = Model self.timeDelta = 1.0 #sec self.numberParticles = 1000 self.world = [ 0, 1500, #x dims 0, 0, #y dims 0, 200 ] #z dims aircraft = air.Aircraft() aircraft.state.x = random.uniform( 1000, 1500) #randomise the x location of the aircraft aircraft.state.z = random.uniform( 50, 120) #randomise the z location of the aircraft self.aircrafts = [aircraft] transmitter = tra.Transmitter() transmitter.state.x = 1 #set the x location of the transmitter transmitter.state.z = 2.35 #the z location of the transmitter [meters off the ground] self.transmitters = [transmitter] self.particles = [] for i in range(self.numberParticles): self.particles.append(par.Particle()) self.particles[-1].state.x = random.uniform( self.world[0], self.world[1]) #randomise the x location of the particle self.particles[-1].state.y = random.uniform( self.world[2], self.world[3]) #randomise the y location of the particle self.particles[-1].state.z = random.uniform( self.world[4], self.world[5]) #randomise the z location of the particle #self.particles[-1].state.groundSpeed = random.uniform(-10, -100) #randomise ground speed of the particle, heading is assumed to be known self.particles[-1].state.groundSpeed = self.aircrafts[ 0].state.groundSpeed #randomise ground speed of the particle, heading is assumed to be known
def set_callsign(self, cs): self.callsign = cs = cs.strip().upper() self.radio_callsign = Aircraft.get_radio_callsign(cs)
def test1(self): code = 'MD11' units = 'metric' range = 20272 a1 = Aircraft(code, units, range) self.assertTrue(a1.get_range() == 20272)
def __init__(self, conf, exc_file = ""): self.conf = conf self.exercise_file = exc_file logging.info("Loading exercise "+exc_file) e=Exercise(exc_file) # Find the FIR mentioned by the exercise file fir_list = FIR.load_firs(os.path.dirname(exc_file)) try: fir = [fir for fir in fir_list if fir.name==e.fir][0] except: logging.critical("Unable to load FIR file for "+str(exc_file)) raise return self.fir = fir Aircraft.fir = fir # Rather than passing globals Route.fir = fir TLPV.fir = fir self.sector = e.sector # TODO wind and qnh should be properties of the atmosphere object # and should be variables dependent on location and height in the case of wind self.wind = [e.wind_knots, e.wind_azimuth] # We have set somewhere else a fixed seed so that squawks are reproducible # but we want the qnh to be different in each exercise, so we use getstate and setstate st = random.getstate() random.seed() self.qnh = random.gauss(1013.2, 8) self.qnh_var = random.gauss(0, QNH_STD_VAR) # Variation in mB per second. # Should not be much more than 1mB per 10minutes random.setstate(st) # Initializes time self.cont = True # Marks when the main loop should exit t = datetime.datetime.today() self.t = t.replace(t.year, t.month, t.day, int(e.start_time[0:2]), int(e.start_time[3:5]), 0, 0) self.last_update = self.t - datetime.timedelta(seconds=5) # Copy the datetimeobject fact_t = self.fact_t = 1.0 self.paused = False self.tlpv = tlpv = TLPV.TLPV(exc_file) # Create the aircraft for each of the flights in the exercise self.flights = [] logging.debug("Loading aircraft") for ef in e.flights.values(): # Exercise flights # TODO Because the current exercise format cannot distiguish between # overflights and departures first we create them all as overflights eto = datetime.datetime.today() eto = eto.replace(hour=int(ef.eto[:2]), minute=int(ef.eto[2:4]), second=int(ef.eto[4:6])) logging.debug("Loading %s"%ef.callsign) try: a = Aircraft.Aircraft(ef.callsign, ef.type, ef.adep, ef.ades, float(ef.cfl), float(ef.rfl), ef.route, next_wp = ef.fix, next_wp_eto = eto, wake_hint = ef.wtc) except: logging.warning("Unable to load "+ef.callsign, exc_info=True) continue a.lvl = int(ef.firstlevel) # TODO We need to know which of the flights are true departures. We assume that # if the aircraft departs from an airfield local to the FIR, # the EOBT is the estimate to the first point in the route # We substitute the overflight (created using next_wp_eto) with a departure # (created using an EOBT) if a.adep in fir.aerodromes.keys(): eobt = a.route[0].eto a = Aircraft.Aircraft(a.callsign, a.type, a.adep, a.ades, a.cfl, a.rfl, a.route, eobt = eobt, wake_hint=a.wake_hint) if not fir.auto_departures[self.sector] \ and a.adep in fir.release_required_ads[self.sector]: a.auto_depart = False self.flights.append(a) # Creates new flight plans from the loaded aircraft if a.eobt: ecl = a.rfl # If it's a departure else: ecl = a.cfl fp = tlpv.create_fp(ef.callsign, ef.type, ef.adep, ef.ades, float(ef.rfl), ecl, a.route, eobt = a.eobt, next_wp = a.next_wp, next_wp_eto = a.next_wp_eto) a.squawk = fp.squawk # Set the aircraft's transponder to what the flight plan says a.fs_print_t = fp.fs_print_t fp.wake = ef.wtc # Keep the WTC in the exercise file, even if wrong fp.filed_tas = int(ef.tas) tlpv.start() self.protocol_factory=GTA_Protocol_Factory(self, fir.file, self.sector, self.flights) self.pseudopilots = [] # List of connected pseudopilot clients self.controllers = [] # List of connected controller clients
from Aircraft import * from tower import * myAirplane = Aircraft() myAirplane.addFuel(500) myAirplane.printStatus() myAirplane.takeOff() print("---") dublinTower = Tower() dublinTower.requestFlightCheck()
class Itinerary: route = [] permutationlist = [] distancesDict = {} costDict = {} refuelCostDict = {} def __init__(self, myAirportList, myAircraft, atlas): self.route = [atlas.getAirport(myAirportList[0]), atlas.getAirport(myAirportList[1]), atlas.getAirport(myAirportList[2]),atlas.getAirport(myAirportList[3]), atlas.getAirport(myAirportList[4])] self.aircraft = Aircraft(myAircraft) def permutateRoute(self): permutations = list(itertools.permutations([self.route[1], self.route[2], self.route[3], self.route[4]])) for route in permutations: self.permutationlist.append(((self.route[0],) + route + (self.route[0],))) return self.permutationlist def getCosts(self, atlas): for route in self.permutationlist: totCost = 0 for i in range(len(route)-1): rate = float(route[i+1].country.rateFrom()) cost = atlas.getDistBetween(route[i].code, route[i+1].code)*rate totCost += cost self.costDict[route] = round(totCost,2) return self.costDict def getLowestCostRoute(self): return min(self.costDict, key=self.costDict.get) def getDistances(self, atlas): for route in self.permutationlist: totDistance = 0 for i in range(len(route)-1): dist = atlas.getDistBetween(route[i].code, route[i+1].code) totDistance += dist self.distancesDict[route]=round(totDistance,2) return self.distancesDict def getLowestDistRoute(self): return min(self.distancesDict, key=self.distancesDict.get) def getRefuelCosts(self, atlas): for route in self.permutationlist: self.aircraft.addFuel(self.aircraft.MIN_FUEL) totCost = self.aircraft.MIN_FUEL for i in range(len(route)-1): if atlas.getDistBetween(route[i].code, route[i+1].code) <= self.aircraft.getRange(): if self.aircraft.fuel < (atlas.getDistBetween(route[i].code, route[i+1].code))*1.1: rate = float(route[i].country.rateFrom()) cost = ((atlas.getDistBetween(route[i].code, route[i+1].code))*1.1-self.aircraft.fuel)*rate totCost += cost self.aircraft.addFuel(((atlas.getDistBetween(route[i].code, route[i+1].code))*1.1)-self.aircraft.fuel) self.aircraft.fly(atlas.getDistBetween(route[i].code, route[i+1].code)) else: self.aircraft.fly(atlas.getDistBetween(route[i].code, route[i+1].code)) else: totCost = 99999999999.99 self.refuelCostDict[route] = round(totCost, 2) return self.refuelCostDict def getRefuelCostRoute(self): if self.refuelCostDict.get(min(self.refuelCostDict, key=self.refuelCostDict.get)) > 9999999999.99: return "ERROR" else: return min(self.refuelCostDict, key=self.refuelCostDict.get) def costMinCalculator(self): return self.costDict.get(min(self.costDict, key=self.costDict.get)) def distMinCalculator(self): return self.distancesDict.get(min(self.distancesDict, key=self.distancesDict.get)) def refuelMinCalculator(self): if self.refuelCostDict.get(min(self.refuelCostDict, key=self.refuelCostDict.get)) > 9999999999.99: return "Plane range too short for this route" else: return self.refuelCostDict.get(min(self.refuelCostDict, key=self.refuelCostDict.get))
def __init__(self, plane): self.plane = Aircraft(plane.getXPos(), plane.getYPos(), plane.getXFinal(), plane.getYFinal()) self.graph = Graph(plane) # Empty graph
def main(airport, er, currency, aircraft): newEr = ExchangeRate(currency, er) newAtlas = AirportAtlas(airport) newAirplaneList = Aircraft(aircraft) newAirplane = Airplane("12345") user_input = 0 country_search = 0 while user_input != 6: print("Please select and option: ") print("[1] Get list of airports in a particular country") print("[2] Get the aiport code of a specific airport") print( "[3] Get distance between 2 aiports (using their relevant aiport codes" ) print("[4] Get fuel cost of a journey between 2 aiports") print("[5] Get fuel price for a specific route") print("[6] Exit") print() user_input = int(input(" 1, 2, 3, 4 or 5\n")) if user_input == 1: country = input( "Please enter the country for which you want a list of airports\n" ) country_search = input( "If you would like to restrict search results to aiports starting with a specific letter, please enter letter now or press enter to skip this option" ) found_country = False found_letter = False if country_search != "": for i in newAtlas._atlas: if newAtlas._atlas[i].country == country: found_country = True if newAtlas._atlas[i].name[0] == country_search.upper( ): found_letter = True print(newAtlas._atlas[i].name) if not found_country: found_letter = True print( "Sorry we could not find a record of the country you entered\n" ) if not found_letter: print( "No airport could be found beginning withe letter '%s'" % country_search.upper()) again = repeat() if again: user_input = 0 else: user_input = 5 else: for i in newAtlas._atlas: if newAtlas._atlas[i].country == country: found = True print(newAtlas._atlas[i].name) if not found: print( "Sorry we could not find a record of the country you entered\n" ) again = repeat() if again: user_input = 0 else: user_input = 5 elif user_input == 2: name = input( "Please enter the airport for which you want a code\n") print() found = False for i in newAtlas._atlas: if newAtlas._atlas[i].name == name: print(newAtlas._atlas[i].code) found = True if not found: print( "We're sorry but we could not find an airport with the name", name, "in our database") print() print( "Please try and use the services provided to find the exact name of the airport in our database if you wish" ) again = repeat() if again: user_input = 0 else: user_input = 5 elif user_input == 3: code1 = input( "Please enter airport code of the original airport\n") code2 = input("Please enter airport code of destination airport\n") found1 = False found2 = False for i in newAtlas._atlas: if newAtlas._atlas[i].code == code1: found1 = True elif newAtlas._atlas[i].code == code2: found2 = True if found1 and found2: distance = newAtlas.getDistance(code1, code2) print("Distance between 2 airports:", distance, "km") elif not found1 and found2: print("Sorry but we could not find", code1, "in our records") elif not found2 and found1: print("Sorry but we could not find", code2, "in our records") else: print("Sorry we could not find either", code1, "or", code2, "in our records") again = repeat() if again: user_input = 0 else: user_input = 5 elif user_input == 4: code1 = input( "Please enter the airport code of the first airport\n") code2 = input( "Please enter the airport code of the destination aiport\n") airplane = input( "Please enter the code of the aircraft for the journey") newAircraft = AircraftList.createNewAircraft(airplane) if not newAircraft: again = repeat() else: found1 = False found2 = False for i in newAtlas._atlas: if newAtlas._atlas[i].code == code1: found1 = True elif newAtlas._atlas[i].code == code2: found2 = True if found1 and found2: distance = newAtlas.getDistance(code1, code2) a_range = newAircraft.getRange() if a_range >= distance: cost = newAtlas.getPrice(newEr, code1, code2, newAirplane) for i in newAtlas._atlas: if newAtlas._atlas[i].code == code1: country = newAtlas._atlas[i].country print("Fuel cost between 2 airports:", cost, "EUR") else: print( "Aircraft selected does not have the range for this journey" ) elif not found1 and found2: print("Sorry but we could not find", code1, "in our records") elif not found2 and found1: print("Sorry but we could not find", code2, "in our records") else: print("Sorry we could not find either", code1, "or", code2, "in our records") again = repeat() if again: user_input = 0 else: user_input = 5 elif user_input == 5: airport_list = [] count = 1 airport = "first" while airport != "": airport = input("Please enter airport code #" + str(count) + " or hit enter to submit") if airport != "": airport_list.append(airport) print(airport_list) i = 0 total = 0 while i < len(airport_list) - 1: found1 = False found2 = False for j in newAtlas._atlas: if newAtlas._atlas[j].code == airport_list[i]: found1 = True elif newAtlas._atlas[j].code == airport_list[i + 1]: found2 = True if found1 and found2: cost = newAtlas.getPrice(newEr, airport_list[i], airport_list[i + 1], newAirplane) total += cost elif not found1: print("Sorry we could not find a airport with the code", airport_list[i], "in our database") break else: print("Sorry we could not find a airport with the code", airport_list[i + 1], "in our database") break i += 1 if found1 and found2: for i in newAtlas._atlas: if newAtlas._atlas[i].code == airport_list[0]: country = newAtlas._atlas[i].country currency = newEr._currencyInfo[country] print("total cost:", total, currency) again = repeat() if again: user_input = 0 else: user_input = 5 elif user_input == 6: exit() else: print( "Sorry that was not a valid option, would you like to try again?" ) user_input = input("y/n?\n") if user_input == "n": user_input = 6
def test_aircraft_calculateOptimumFuel_valid(self): simpleRoute = Route(['DUB', 'LHR', 'EIN'], self.airportAtlas) testAircraft = Aircraft('747', 1000, simpleRoute) testAircraft.completeRoute() testAircraft.calculateOptimumFuel() self.assertEqual(len(testAircraft.fuelBought), 4)
class SimpleController: def __init__(self, plane): self.plane = Aircraft(plane.getXPos(), plane.getYPos(), plane.getXFinal(), plane.getYFinal()) self.graph = Graph(plane) # Empty graph def run(self): # Move until x = xf if self.plane.xDistance() != 0: self.setX() self.plane.advance() # Move until y = yf elif self.plane.yDistance() != 0: self.setY() self.plane.advance() self.graph.addPoint(self.plane.getXPos(), self.plane.getYPos()) # Set x-direction of plane def setX(self): if self.plane.getXFinal() - self.plane.getXPos() > 0: self.plane.setAngle(0) elif self.plane.getXFinal() - self.plane.getXPos() < 0: self.plane.setAngle(180) # Set y-direction of plane def setY(self): if self.plane.getYFinal() - self.plane.getYPos() > 0: self.plane.setAngle(90) elif self.plane.getYFinal() - self.plane.getYPos() < 0: self.plane.setAngle(270) # Return true if plane has reached destination def success(self): return self.plane.xDistance() == 0 and self.plane.yDistance() == 0 # Show plot of run def showPlot(self): self.graph.createSimplePlot()
class CompleteController: def __init__(self, plane1, plane2): # Two aircraft self.plane1 = Aircraft(plane1.getXPos(), plane1.getYPos(), plane1.getXFinal(), plane1.getYFinal()) self.plane2 = Aircraft(plane2.getXPos(), plane2.getYPos(), plane2.getXFinal(), plane2.getYFinal()) self.safetyMonitor = SafetyMonitor() # External safety monitor self.graph = Graph(plane1, plane2) # Empty graph self.last1X = True # Plane1 last moved in the x-direction self.last2X = True # Plane2 last moved in the x-direction # Main algorithm def run(self): # Aircraft in communication zone if self.communicationZone(): # Neither plane's final destination is in other's communication zone if not self.plane1Check() and not self.plane2Check(): if self.plane1.xDistance() != 0 and self.plane2.yDistance( ) != 0: self.setXAngle1() self.setYAngle2() elif self.plane1.yDistance() != 0 and self.plane2.xDistance( ) != 0: self.setYAngle1() self.setXAngle2() elif self.plane1.yDistance() != 0 and self.plane2.yDistance( ) != 0: # Head-on, y-direction self.setXAngle2() # Plane 2 moves out of the way elif self.plane1.xDistance() != 0 and self.plane2.xDistance( ) != 0: # Head on, x-direction self.setYAngle2() # Plane 2 moves out of the way self.plane1.advance() self.plane2.advance() # Plane2's final destination is in plane1's communication zone elif not self.plane1Check() and self.plane2Check(): if self.plane2.angle == 0 or self.plane2.angle == 180: # X-direction self.setYAngle1() else: # Y-direction self.setXAngle1() self.runPlane2() # Plane2 continues, plane1 moves self.plane1.advance() # Plane1's final destination is in plane2's communication zone elif self.plane1Check() and not self.plane2Check(): if self.plane1.angle == 0 or self.plane1.angle == 180: # X-direction self.setYAngle2() else: # Y-direction self.setXAngle2() self.runPlane1() # Plane1, continues, plane2 moves self.plane2.advance() # Aircraft cannot communicate, run normally else: if self.plane1.xDistance() != 0 or self.plane1.yDistance() != 0: self.runPlane1() if self.plane2.xDistance() != 0 or self.plane2.yDistance() != 0: self.runPlane2() # Send output to safety monitor, add points to graph self.safetyMonitor.error(self.plane1, self.plane2) self.graph.addPoints(self.plane1.getXPos(), self.plane1.getYPos(), self.plane2.getXPos(), self.plane2.getYPos()) self.showPlot() # Set angle in x-direction for plane1 def setXAngle1(self): if self.plane1.getXPos() - self.plane1.getXFinal( ) > 0 or self.plane1.angle == 180: self.plane1.setAngle(180) # Left else: self.plane1.setAngle(0) # Right # Sets angle in y-direction for plane1 def setYAngle1(self): if self.plane1.getYPos() - self.plane1.getYFinal( ) > 0 or self.plane1.angle == 270: self.plane1.setAngle(270) # Down else: self.plane1.setAngle(90) # Up # Sets angle in x-direction for plane2 def setXAngle2(self): if self.plane2.getXPos() - self.plane2.getXFinal( ) > 0 or self.plane2.angle == 180: self.plane2.setAngle(180) # Left else: self.plane2.setAngle(0) # Right # Sets angle in y-direction for plane2 def setYAngle2(self): if self.plane2.getYPos() - self.plane2.getYFinal( ) > 0 or self.plane2.angle == 270: self.plane2.setAngle(270) # Down else: self.plane2.setAngle(90) # Up # Runs plane1 normally def runPlane1(self): if self.plane1.xDistance() != 0: self.setXAngle1() if not self.last1X or self.plane1.yDistance() == 0: self.plane1.advance() # Move in x-direction self.last1X = not self.last1X if self.plane1.yDistance() != 0: self.setYAngle1() if self.last1X or self.plane1.xDistance() == 0: self.plane1.advance() # Move in y-direction # Runs plane2 normally def runPlane2(self): if self.plane2.xDistance() != 0: self.setXAngle2() if not self.last2X or self.plane2.yDistance() == 0: self.plane2.advance() # Move in x-direction if self.plane2.yDistance() != 0: self.setYAngle2() if self.last2X or self.plane2.xDistance() == 0: self.plane2.advance() # Move in y-direction self.last2X = not self.last2X # Determines if one plane is at its final destination def finalDestinations(self): return (self.plane1.xDistance() == 0 and self.plane1.yDistance() == 0) and \ (self.plane2.xDistance() == 0 and self.plane2.yDistance() == 0) # Check if planes are within a 2km square of each other def communicationZone(self): return abs(self.plane1.getXPos() - self.plane2.getXPos()) <= 2 and abs( self.plane1.getYPos() - self.plane2.getYPos()) <= 2 # Check if plane1's final position is within plane2's communication zone def plane1Check(self): return abs(self.plane1.getXFinal() - self.plane2.getXPos( )) <= 2 and abs(self.plane1.getYFinal() - self.plane2.getYPos()) <= 2 # Check if plane2's final position is within plane1's communication zone def plane2Check(self): return abs(self.plane2.getXFinal() - self.plane1.getXPos( )) <= 2 and abs(self.plane2.getYFinal() - self.plane1.getYPos()) <= 2 # Show plot of run def showPlot(self): self.graph.createCompletePlot() def checkSafety(self): return self.safetyMonitor.safety()
def test_aircraft_flyNextStage_out_of_range(self): simpleRoute = Route(['DUB', 'LHR', 'EIN'], self.airportAtlas) testAircraft = Aircraft('747', 50, simpleRoute) self.assertEqual(testAircraft.route.currentAirport.code, 'DUB') testAircraft.flyNextStage() self.assertEqual(testAircraft.route.isPossible, False)
def test_aircraft_constructor(self): simpleRoute = Route(['DUB', 'LHR', 'EIN'], self.airportAtlas) testAircraft = Aircraft('747', 1000, simpleRoute) self.assertEqual(testAircraft.code, '747') self.assertEqual(testAircraft.flightRadius, 1000)
def __init__(self, myAirportList, myAircraft, atlas): self.route = [atlas.getAirport(myAirportList[0]), atlas.getAirport(myAirportList[1]), atlas.getAirport(myAirportList[2]),atlas.getAirport(myAirportList[3]), atlas.getAirport(myAirportList[4])] self.aircraft = Aircraft(myAircraft)
def compute(array): """ Function to carry out all necessary calculations for the most efficient route """ global feasible feasible = True aircraft = Aircraft(str(array[-1])) # creates an aircraft object based on the value of the last item in the input array print("List of desired destinations",Color.BLUE,array,Color.END) # prints the input array airports = [] # an empty array to store every airport object for i in range(len(array)-1): airport = Airport(array[i]) # creates an airport object for each element in the input array, except for the last element (the aircraft) airports.append([airport.code,airport.lat,airport.lng,airport.currency,float(airport.rate)]) distances = [] # an array to store the distances for each possible trip for i in airports: for j in airports: if i!=j: distance = round(distanceBetweenAirports(i[1],i[2],j[1],j[2])) adj_cost = float(i[4])*distance distances.append([i[0],j[0],distance,round(adj_cost)]) itinerary = Graph() # creating a new graph object for i in airports: itinerary.add_vertex(i[0]) # each airport is a node for i in distances: itinerary.add_edge(i[0], i[1], round(i[-1])) # each distance (considering the currency cost) is an edge (rounding the weight of the edges) shortest_paths = [] # an array to store the shortest path from each node to every other node for i in airports: for j in airports: if i!=j: shortest_paths.append(sp(itinerary,i[0],j[0])) # sp is shortest path using dijkstra's algo for i in range(len(shortest_paths)): cost = 0 for j in range(len(shortest_paths[i])-1): cost += itinerary.weights[shortest_paths[i][j],shortest_paths[i][j+1]] shortest_paths[i].append(cost) tracker = [] # an array to store all visited airports origin = shortest_paths[0][0] # the origin airport is added to the tracker tracker.append(origin) graph = [] dist = [] def routing_algorithm(current): """ Function to find the nearest reachable airport that has not yet been added to the tracker """ options = [] # an array to hold each viable route for i in range(len(shortest_paths)): if distances[i][2] > aircraft.range: # checks if plane can fly that far continue elif shortest_paths[i][-2] in tracker: #checks if airport has been visited continue elif shortest_paths[i][0] != current: # checks that we're considering current airport as start off continue else: options.append(shortest_paths[i]) if options: options = sorted(options, key=lambda x: x[-1]) # sorts the options by distance next = options[0][-2] else: next = tracker[-1] tracker.append(next) # adds the next airport to the visited list return next def print_itinerary(): """ Prints the itinerary """ for i in range(len(airports)-1): next = routing_algorithm(tracker[i]) for i in range(len(tracker)): for j in range(i+1,len(tracker)): if tracker[i] == tracker[j]: print() print(Color.RED+"One or more of your destinations could not be reached.\nHere is the best possible route under these circumstances:"+Color.END) tracker.pop(j) global feasible feasible = False return "" print(print_itinerary()) tracker.append(origin) print("Optimal path", Color.BLUE,tracker,Color.END) print() print(Color.RED+"Trip Breakdown for each leg:"+Color.END) total_cost = 0 for j in range(len(tracker)-1): for i in distances: if i[0]==tracker[j] and i[1]==tracker[j+1]: print(i[0],"->",i[1],"Distance:",i[2],"Cost:",i[3]) new = (i[0],i[1]) graph.append(new) dist.append(i[3]) total_cost += i[3] print() print("The total cost of this journey is:",Color.RED,total_cost,Color.END) print() edges = dist if feasible: yes = (Color.RED,'I', u'\u2764',"", u'\u2708',Color.END) print("This route IS feasible",*yes) with open(output_file, 'a', newline='') as a: writer = csv.writer(a) writer.writerow([array,tracker,total_cost]) return graph, edges else: no = (Color.RED+u'\u2718'+Color.END) print(Color.RED+"PLEASE NOTE:"+Color.END) print("This route IS NOT feasible",no) with open(output_file, 'a', newline='') as w: writer = csv.writer(w) writer.writerow([array,"","NOT FEASIBLE"]) return None, None
def __init__(self, I, aircraft_profile_df): self.Aircrafts = {} self.I = I for i in I: self.Aircrafts[i] = Aircraft(i, aircraft_profile_df.loc[i]['Type'])
class Itinerary: route = [] permutationlist = [] distancesDict = {} costDict = {} refuelCostDict = {} def __init__(self, myAirportList, myAircraft, atlas): self.route = [ atlas.getAirport(myAirportList[0]), atlas.getAirport(myAirportList[1]), atlas.getAirport(myAirportList[2]), atlas.getAirport(myAirportList[3]), atlas.getAirport(myAirportList[4]) ] self.aircraft = Aircraft(myAircraft) def permutateRoute(self): permutations = list( itertools.permutations( [self.route[1], self.route[2], self.route[3], self.route[4]])) for route in permutations: self.permutationlist.append( ((self.route[0], ) + route + (self.route[0], ))) return self.permutationlist def getCosts(self, atlas): for route in self.permutationlist: totCost = 0 for i in range(len(route) - 1): rate = float(route[i + 1].country.rateFrom()) cost = atlas.getDistBetween(route[i].code, route[i + 1].code) * rate totCost += cost self.costDict[route] = round(totCost, 2) return self.costDict def getLowestCostRoute(self): return min(self.costDict, key=self.costDict.get) def getDistances(self, atlas): for route in self.permutationlist: totDistance = 0 for i in range(len(route) - 1): dist = atlas.getDistBetween(route[i].code, route[i + 1].code) totDistance += dist self.distancesDict[route] = round(totDistance, 2) return self.distancesDict def getLowestDistRoute(self): return min(self.distancesDict, key=self.distancesDict.get) def getRefuelCosts(self, atlas): for route in self.permutationlist: self.aircraft.addFuel(self.aircraft.MIN_FUEL) totCost = self.aircraft.MIN_FUEL for i in range(len(route) - 1): if atlas.getDistBetween( route[i].code, route[i + 1].code) <= self.aircraft.getRange(): if self.aircraft.fuel < (atlas.getDistBetween( route[i].code, route[i + 1].code)) * 1.1: rate = float(route[i].country.rateFrom()) cost = ((atlas.getDistBetween( route[i].code, route[i + 1].code)) * 1.1 - self.aircraft.fuel) * rate totCost += cost self.aircraft.addFuel(((atlas.getDistBetween( route[i].code, route[i + 1].code)) * 1.1) - self.aircraft.fuel) self.aircraft.fly( atlas.getDistBetween(route[i].code, route[i + 1].code)) else: self.aircraft.fly( atlas.getDistBetween(route[i].code, route[i + 1].code)) else: totCost = 99999999999.99 self.refuelCostDict[route] = round(totCost, 2) return self.refuelCostDict def getRefuelCostRoute(self): if self.refuelCostDict.get( min(self.refuelCostDict, key=self.refuelCostDict.get)) > 9999999999.99: return "ERROR" else: return min(self.refuelCostDict, key=self.refuelCostDict.get) def costMinCalculator(self): return self.costDict.get(min(self.costDict, key=self.costDict.get)) def distMinCalculator(self): return self.distancesDict.get( min(self.distancesDict, key=self.distancesDict.get)) def refuelMinCalculator(self): if self.refuelCostDict.get( min(self.refuelCostDict, key=self.refuelCostDict.get)) > 9999999999.99: return "Plane range too short for this route" else: return self.refuelCostDict.get( min(self.refuelCostDict, key=self.refuelCostDict.get))
def test_aircraft_completeRoute_valid(self): simpleRoute = Route(['DUB', 'LHR', 'EIN'], self.airportAtlas) testAircraft = Aircraft('747', 1000, simpleRoute) self.assertEqual(testAircraft.route.currentAirport.code, 'DUB') testAircraft.completeRoute() self.assertEqual(testAircraft.route.currentAirport.code, 'DUB')
def __init__(self): self.anAirplane = Aircraft()