コード例 #1
0
    def setUpClass(cls):
        print("setUpClass()")

        # Initialize airports
        cls.Logan = Airport()
        cls.JFK = Airport()
        cls.Logan.set_name("Logan")
        cls.JFK.set_name("JFK")

        # Initialize passengers
        cls.Ben = Passenger("Ben")
        cls.Julia = Passenger("Julia")
        cls.Jamie = Passenger("Jamie")

        # Initialize flights
        cls.flightLoganToJFK = Flight.airports_to_from(cls.Logan, cls.JFK)
        # Flight 1
        cls.flightLoganToJFK.set_flight_number("UA1161")
        cls.flightLoganToJFK.set_flight_date("04-27-2020")
        cls.flightLoganToJFK.set_flight_time("4:30pm")
        cls.flightLoganToJFK.set_airline("United Airlines")

        # Add flights to airport
        cls.Logan.add_flight(cls.flightLoganToJFK)
        cls.JFK.add_flight(cls.flightLoganToJFK)
コード例 #2
0
    def __init__(self):
        self.flight_number = 'Flight_number'
        self.airline = "Airline"

        self.passengers = []
        self.max_capacity = 0

        self.current_airport = Airport()
        self.destination_airport = Airport()
        self.flight_date = "flight_date"
        self.flight_time = "flight_time"
コード例 #3
0
def setup():
    global airportList
    airportList["Llyne"] = Airport("Llyne", 2)
    airportList["Tenby"] = Airport("Tenby", 2)
    airportList["Hythe"] = Airport("Hythe", 2)
    airportList["Pontheugh"] = Airport("Pontheugh", 6)
    airportList["Alderdyfi"] = Airport("Alderdyfi", 6)
    airportList["Stathmore"] = Airport("Stathmore", 6)
    airportList["Orilon"] = Airport("Orilon", 2)
    airportList["Hwen"] = Airport("Hwen", 2)
    airportList["Ecrin"] = Airport("Ecrin", 2)
    airportList["Erith"] = Airport("Erith", 2)
コード例 #4
0
def test_airport_take_off():
    airport = Airport()
    weather = Weather()
    allow(weather).weather_check.and_return('sunny')
    airport.land("plane")
    airport.take_off("plane")
    assert airport.hangar == []
コード例 #5
0
def update_information():
    print('UPDATING METAR INFORMATION')

    airports.clear()

    # NOAA Weather Data URL
    url2 = 'https://www.aviationweather.gov/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&hoursBeforeNow=2&mostRecentForEachStation=true&stationString=%s'

    identifiers = []
    for airport in settings.airports:
        ident = settings.airports[airport]

        identifiers.append(ident)
        airports.append(Airport(ident, airport))

    query_stirng = ','.join(identifiers)
    url2 = url2 % query_stirng

    dom = ET.fromstring(requests.get(url2).text)

    metars = dom.findall('./data/METAR')

    for m in metars:
        metar = m.find("raw_text").text
        station_id = m.find("station_id").text

        for airport in airports:
            if airport.get_station_info().icao == station_id:
                airport.set_metar(metar)
コード例 #6
0
    def get_airports_within_radius(self, lat, lon, radius):
        # Note: implementing a half-solution for getting a bounding box:
        # treat world as if it was flat. Getting a bounding box for coordinates
        # around the poles seems really difficult.
        # We'll interpret radius as degrees.
        west = max(-180, lon - radius)
        east = min(180, lon + radius)
        south = max(-90, lat - radius)
        north = min(90, lat + radius)

        box_center = ((west + east) / 2, (south + north) / 2)

        # Note: no need to sanitize input, the query will only read the db
        query = 'lon:[{} TO {}] AND lat:[{} TO {}]'.format(
            west, east, south, north)

        # No docs for this either, found by looking at source, searching for "search"
        # TODO: find out how pagination works, currently `rows` contains max 25 elements
        airports_query_result = self.db.get_search_result("view1",
                                                          "geo",
                                                          q=query)
        rows = airports_query_result.get("rows", [])

        airports = list(map(lambda x: Airport(x, box_center), rows))
        airports.sort(key=lambda airport: airport.distance)

        return airports
コード例 #7
0
 def test_stormy_weather(self):
     airport = Airport()
     plane = Mock()
     weather = Mock(stormy=True)
     airport.planes = [plane]
     self.assertEqual(airport.release_plane(plane, weather),
                      "Weather is Stormy")
コード例 #8
0
    def test_flight_creation(self):
        # Create a new airport - LAX
        self.LAX = Airport()
        self.LAX.set_name("LAX")

        # Check that the LAX airport currently has no flights
        LAXflights = self.LAX.get_flights()
        self.assertEqual(len(LAXflights), 0)

        # Create a new flight from LAX to Logan
        self.flightLAXToLogan = Flight.airports_to_from(self.LAX, self.Logan)
        self.flightLAXToLogan.set_flight_number("UA2274")
        self.flightLAXToLogan.set_flight_date("04-26-2020")
        self.flightLAXToLogan.set_flight_time("9:30pm")
        self.flightLAXToLogan.set_airline("United Airlines")

        # Add the new flight to LAX and Logan's flights
        self.Logan.add_flight(self.flightLAXToLogan)
        self.LAX.add_flight(self.flightLAXToLogan)

        # Check that the LAX airport now has this flight outgoing
        LAXflights = self.LAX.get_outgoing_flights()
        self.assertEqual(len(LAXflights), 1)
        self.assertEqual(LAXflights, [self.flightLAXToLogan])

        # Check that Logan airport now has this flight incoming
        Loganflights = self.Logan.get_incoming_flights()
        self.assertEqual(Loganflights, [self.flightLAXToLogan])

        # Remove flight in order to clean up for next test case
        self.Logan.remove_flight(self.flightLAXToLogan)
        self.LAX.remove_flight(self.flightLAXToLogan)
コード例 #9
0
 def test_docking_same_plane_twice_not_allowed(self):
   jfk = Airport()
   boeing = Plane("Boeing")
   jfk.dock(boeing)
   self.assertEqual(len(jfk.docked), 1)
   with self.assertRaises(ValueError):
     jfk.dock(boeing)
コード例 #10
0
    def test_conflicts(self):

        simulation = self.SimulationMock()
        # airport = Airport.create("simple")
        airport = Airport("test", self.SurfaceMock())

        a1 = Aircraft("A1", None, self.n1, State.stop)
        a2 = Aircraft("A2", None, self.n1, State.stop)
        a3 = Aircraft("A3", None, self.n2, State.stop)

        airport.aircrafts.append(a1)
        airport.aircrafts.append(a2)
        airport.aircrafts.append(a3)

        # Get only one conflict
        self.assertEqual(len(airport.conflicts[0]), 1)

        # Test if the conflict looks like what we expected
        conflict = airport.conflicts[0][0]
        self.assertTrue(conflict.locations[0] == self.n1)
        self.assertEqual(len(conflict.aircrafts), 2)
        self.assertTrue(a1 in conflict.aircrafts)
        self.assertTrue(a2 in conflict.aircrafts)

        # Add one far aircraft to the same spot
        a4 = Aircraft("A4", None, self.n1, State.stop)
        airport.aircrafts.append(a4)

        # Test if the third aircraft shown in conflict correctly
        self.assertEqual(len(airport.conflicts[0]), 3)
コード例 #11
0
def test_airport_capacity():
    airport = Airport()
    weather = Weather()
    allow(weather).weather_check.and_return('sunny')
    airport.land("plane")
    airport.land("plane")
    airport.land("plane")
    assert airport.land("plane") == "Hangar Capacity Reached!"
コード例 #12
0
 def test_airport_release_plane(self):
     airport = Airport()
     plane = Mock()
     weather = Mock()
     weather.stormy.return_value = False
     airport.land_plane(plane)
     airport.release_plane(plane, weather)
     self.assertEqual(airport.planes, [])
コード例 #13
0
 def test_airport_take_off_plane(self):
     airport = Airport()
     plane = Mock()
     weather = Mock()
     weather.stormy.return_value = False
     airport.planes = [plane]
     airport.release_plane(plane, weather)
     plane.take_off.assert_called_once_with()
コード例 #14
0
ファイル: test_airport.py プロジェクト: Nimor111/101-v5
 def setUp(self):
     self.airport = Airport()
     self.flight = Flight()
     self.flight2 = Flight(start_time=Date(day=29,
                                           month=11,
                                           year=2016,
                                           hour='17:30'),
                           from_dest="Vancouver",
                           to_dest="New York")
     self.terminal = Terminal()
     self.airport.add_terminal(self.terminal)
コード例 #15
0
def initialize_airports(airport_names):
    airports = []

    # create airport objects
    for i in range(len(airport_names)):
        airports.append(Airport())

    # add names to objects
    for airport in airports:
        airport.set_name(airport_names[0])
        airport_names.remove(airport_names[0])

    return airports
コード例 #16
0
    def load_data(filename):
        airports = {}
        with open(os.path.join("", "clean_files", filename),
                  "rt",
                  encoding="utf8") as f:

            reader = csv.reader(f)

            for row in reader:
                airport_code = row[4]
                # remove cr
                airports[airport_code] =\
                    Airport(row[4], row[5], row[6], row[7], row[3], row[1], row[2], row[9], row[8])
        return airports
コード例 #17
0
    def input(self, csv_path):
        """Takes csv input from command-line and checks for errors"""
        # test_routes_csv = csv.reader(io.open(
        #     csv_path.csv_file_path, "r", encoding=csv_path.encoding), delimiter=",", quotechar='"')

        inputFile = open(csv_path.csv_file_path, 'r', encoding='utf-8')
        fileReader = csv.reader(inputFile, delimiter=',')
        finalCsv = []
        aircrafts = []
        aircraftRange = []
        for row in fileReader:
            self.__csv_data = []
            # print("ROW:::", row)
            #finding duplicate values
            D = [k for k, v in Counter(row).items() if v > 1]
            if len(D) != 0:
                print("There are duplicate values")
                #dont append row to csv_data

            _airdict = Airport()
            parsedAirportDict = _airdict.parseAirport('airport.csv')
            parsedAircraft = _airdict.Aircraft('aircraft.csv')
            # print(parsedAircraft)
            #Checking for incorrect IATA codes
            dests = row[:-1]
            # print(dests)
            if len(dests) <= 1:
                print("Need to enter a minimum of 2 aircodes", '\n')
            else:
                for i in dests:
                    if i in list(parsedAirportDict.keys()):
                        self.__csv_data.append(i)
                    else:
                        print("Incorrect IATA entered", '\n')

            #Presuming Aircraft code will always be last item in csv file
            aircraft_code = row[-1]
            #print(aircraft_code)

            if aircraft_code in list(parsedAircraft.keys()):
                print("Aircraft range for", aircraft_code, "is:",
                      parsedAircraft.get(aircraft_code))
                #self.__csv_data.append(parsedAircraft.get(aircraft_code))
            else:
                print("Warning, please specify aircraft model")
            aircrafts.append(aircraft_code)
            aircraftRange.append(parsedAircraft.get(aircraft_code))
            finalCsv.append(self.__csv_data)
        return finalCsv, aircrafts, aircraftRange
コード例 #18
0
 def test_airport_bounded_insert(self):
     print("Running test_airport_bounded_insert")
     airport = Airport(100)
     airport.bounded_insert(1080, "TOP")
     airport.bounded_insert(700, "TIP")
     airport.bounded_insert(1300, "RIC")
     airport.bounded_insert(500, "KRO")
     airport.bounded_insert(900, "LLE")
     airport.bounded_insert(1180, "DDD")
     self.assertEqual(str(airport),
                      "500/KRO 700/TIP 900/LLE 1080/TOP 1180/DDD 1300/RIC")
     airport.bounded_insert(990, "THU")
     self.assertEqual(
         str(airport),
         "500/KRO 700/TIP 900/LLE 1080/TOP 1180/DDD 1300/RIC 1400/THU")
コード例 #19
0
    def get(self, departure=True):

        for airport_name in self.airport_codes:

            print(f'Collecting information for airport {airport_name}...')

            airport = Airport(airport_name, departure=departure)

            if not airport.is_created():
                _ = airport.flights()

            flights = Flights(airport_name, departure=departure)
            flights.statuses()

            time.sleep(4.7)
コード例 #20
0
ファイル: application.py プロジェクト: CaptainZoid/PAir
def create_airports(log: List[List[str]]) -> List[Airport]:
    """ Return a list of Airports with all applicable data, based
    on the input dataset stored in the <log>.

    Precondition:
    - The <log> list contains the input data in the correct format.
    >>> a = import_data('data/airports.csv', 'data/segments.csv',
    'data/customers.csv', 'data/trips.csv')
    >>> create_airports(a[0])
    []
    """
    final = []
    for line in log:
        final.append(
            Airport(line[0], line[1], (float(line[2]), float(line[3]))))
    return final
コード例 #21
0
 def test_in_order_traversal(self):
     print("Running test_in_order_traversal")
     airport = Airport(100)
     a1 = airport.bounded_insert(2000, "TOP")
     a2 = airport.bounded_insert(1000, "TIP")
     a3 = airport.bounded_insert(2500, "RIC")
     a4 = airport.bounded_insert(500, "KRO")
     a5 = airport.bounded_insert(1800, "LLE")
     order = airport.in_order_traversal()
     ground_truth = [a4, a2, a5, a1, a3]
     for element in order:
         # Check if there are still elements that could be processed
         self.assertTrue(len(ground_truth) > 0)
         gt = ground_truth.pop(0)
         self.assertEqual(element, gt)
     # All elements should have been processed.
     self.assertTrue(len(ground_truth) == 0)
コード例 #22
0
   def read_airports_from_csv(cls, csv_filename):
       """
       Read airports from specified csv file
       """
       airports_df = pd.read_csv(csv_filename)
       airports = []
       
       for row in airports_df.itertuples(index=False, name="Airport"):
           airports.append(
               Airport(
                   row.icao,
                   row.latitude,
                   row.longitude,
                   row.city
               )
           )
 
       return airports
コード例 #23
0
    def get_nearby_airports(self):
        '''
        Defines the coordinates of the given city.
        Searches for nearby airports using API_location
        Saves result of the research in  dynamic array

        airports_nearby: array of Airport objects - airports
                         found using API_location
        '''
        geolocator = Nominatim(user_agent="airport finder")
        location = geolocator.geocode(self._cityname)
        self._location = API_location(location.latitude, location.longitude,
                                      50, 10)

        for airport in self._location['items']:
            name = airport['name']
            icao = airport['icao']
            location = airport['location']
            self._airports_nearby.append(Airport(name, location, icao))
コード例 #24
0
def main():
    """creates an instance of Airport and tests all the functions
    """

    airport = Airport('Vancouver Regional Airport', 4)
    cap = CapacityObserver(airport)
    air = AirplaneObserver(airport)
    airport.attatch_observer(air)
    airport.attatch_observer(cap)
    airport.land_airplane('A0001')
    airport.land_airplane('A0002')
    airport.land_airplane('B0011')
    airport.land_airplane('B0012')
    airport.set_max_capacity(15)
    print('%s current maximum capacity is %s' %
          (airport.get_airport_name(), airport.get_max_capacity()))
    airport.set_max_capacity(8)
    airport.depart_airplane('B0012')
    airport.depart_airplane('B0011')
    airport.depart_airplane('A0002')
    airport.depart_airplane('A0001')
    print(str(airport))
コード例 #25
0
    def get_routes_available(self):
        '''
        Searches for avaliable routes and average 
        number of daily flights  from the chosen airport
        (ICAO identifier)in these directions using API_destination
        If any of the parameters (name, location, average flights)
        is absent, the route is skipped

        routes_available: array of Airport objects - directions
                          available for travelling                        
        '''
        self._destinations = API_destination(self._icao)

        for route in self._destinations['routes']:
            try:
                location = route['destination']['location']
                name = route['destination']['name']
                average_flights = route['averageDailyFlights']
                self._routes_available.append(
                    Airport(name, location, average_fligths=average_flights))
            except KeyError:
                pass
コード例 #26
0
    def storeAirpotsDB(self):
        airports_list = []
        airports = self.getAirportsFromUrl()

        for airport in airports:
            iata = airports[airport]['iata']

            try:
                session.query(Airport).filter_by(iata=iata).one()
            except NoResultFound:
                city_name = airports[airport]['city']

                try:
                    city = session.query(City).filter_by(name=city_name).one()
                except NoResultFound:
                    try:
                        state_cod = airports[airport]['state'].strip()
                        try:
                            state = session.query(State).filter_by(cod=state_cod).one()
                        except NoResultFound:
                            raise ValueError('State does not match any record in the database!')

                    except Exception as error:
                        print('Error: ' + repr(error))
                        return 0

                    else:
                        city = City(name=city_name, state_id=state.state_id)
                        session.add(city)
                        session.commit()

                coord = "SRID=4674;POINT(%s %s)" % (airports[airport]["lat"], airports[airport]["lon"])
                airport = Airport(iata=iata, city=city.city_id, geom=coord)
                airports_list.append(airport)
                session.add(airport)
                session.commit()

        return airports_list
コード例 #27
0
    def __init__(self, airports_dat_file, routes_dat_file, delim):
        # construct index = dictionary> airport_name:index
        self.sym_tab_IATA = {}
        self.sym_tab_ICAO = {}
        self.air_dat = []
        
        with open(airports_dat_file) as file:
            line = file.readline()       # the header
            line = file.readline().split(delim)
            index = 0
            print("processing vertices...")
            while len(line) != 1:
                # unpack values
                air_id, name, city, country, iata, icao, lat, lng, alt, res =  line[0:10]

                name, city, country, iata, icao = name.strip("\""),  city.strip("\""), country.strip("\""), iata.strip("\""), icao.strip("\"")
                #print(air_id, "|", name, "|",city, "|", country, "|", iata, "|", icao, "|", lat,  "|",lng,  "|",alt,  "|",res)                
                
                try:
                    air_id, lat, lng, alt = int(air_id), float(lat), float(lng), float(alt)
                except Exception as ex:
                #if isinstance(lat, str):
                    lat, lng, alt = lng, alt, float(res)
                
                airport = Airport(name, country, lat, lng, alt, iata, icao)
                if iata is not '\\N' and iata not in self.sym_tab_IATA.keys() and icao is not '\\N' and icao not in self.sym_tab_ICAO.keys():
                    self.sym_tab_IATA[iata] = index
                    self.sym_tab_ICAO[icao] = index
                    self.air_dat.append(airport)
                    index += 1                
                elif iata is not '\\N' and iata not in self.sym_tab_IATA.keys():
                    self.sym_tab_IATA[iata] = index
                    self.air_dat.append(airport)
                    index += 1 
                elif icao is not '\\N' and icao not in self.sym_tab_ICAO.keys():
                    self.sym_tab_ICAO[icao] = index
                    self.air_dat.append(airport)
                    index += 1
                # don't add if both IATA and ICAO are None
                line = file.readline().split(',')

        # count of vertices in the symbol graph
        self.v = len(self.air_dat)    
        
        # construct inverted index for IATA code
        self.key_iata = {}
        for index in self.sym_tab_IATA.keys():
            self.key_iata[self.sym_tab_IATA[index]] = index
        print("iata",self.key_iata)

        # construct inverted index for ICAO code
        self.key_icao = {}
        for index in self.sym_tab_ICAO.keys():
            self.key_icao[self.sym_tab_ICAO[index]] = index

        graph = DirGraph(self.v)
        with open(routes_dat_file) as file:
            line = file.readline()      # the header
            line = file.readline().split(delim)
            print("processing edges...")
            while len(line) != 1:
                # unpack values
                src, src_id, dst, dst_id = line[2:6]
                #print(src, src_id, dst, dst_id)
                # both IATA
                src, dst = self.get_index(src), self.get_index(dst)
                if src != -1 and dst != -1:
                    graph.add_route(src, dst)
                line = file.readline().split(',')
        print(self.get_code(6477))
        #print(graph)
        print("preprocessing done...")
コード例 #28
0
ファイル: main.py プロジェクト: eheimlich/airline_simulation
def main():
    a = Airport("JFK", "JFK", 100, 40.63980103, -73.77890015)
コード例 #29
0
    def __make_widgets(self):
        """ Adds the Label and Close Button """
        airport = self.airport
        label = Label(self, text=airport.name)
        label.config(relief=GROOVE)
        label.pack(side=LEFT, fill=X, expand=YES)
        button = Button(self, text='X', command=self.nuke)
        button.pack(side=RIGHT, fill=X, expand=NO)

    def packMe(self):
        """ Adds the frame to the parent frame """
        self.pack(side=TOP, fill=X, expand=NO)
        self.isPacked = True

    def nuke(self):
        """ Deletes the DestFrame object and the selected airport """
        self.pack_forget()
        self.isPacked = False


if __name__ == '__main__':
    from tkinter import Tk
    from airport import Airport
    from currency import Currency
    root = Tk()
    fake_currency = Currency('EUR', 'Euro', 1, 1)
    dummyAirport = Airport('Dublin', 'Dublin', '', '', '', 5, 5, fake_currency)
    dest_frame = DestFrame(dummyAirport)
    dest_frame.packMe()
    root.mainloop()
コード例 #30
0
 def test_airport_capacity(self):
     airport = Airport()
     self.assertEqual(airport.capacity, 20)