Example #1
0
    def test_build_starts_ends(self):
        """Asserts start and end locations are correctly created"""

        vehicle_1 = Vehicle(capacity=0,
                            start='depot_1',
                            end='depot_1',
                            vehicle_id='vehicle_1')
        vehicle_2 = Vehicle(capacity=0,
                            start='depot_1',
                            end='depot_2',
                            vehicle_id='vehicle_2')
        depot_1 = Depot(depot_id='depot_1', location=Location(lat=0, lng=0))
        depot_2 = Depot(depot_id='depot_2', location=Location(lat=0, lng=0))
        vehicles = {
            vehicle_1.vehicle_id: vehicle_1,
            vehicle_2.vehicle_id: vehicle_2
        }
        depots = {depot_1.depot_id: depot_1, depot_2.depot_id: depot_2}
        starts, ends = ProblemBuilder._build_vehicles_starts_ends(
            vehicles, depots)
        self.assertTrue(starts, msg='Empty start locations.')
        self.assertTrue(ends, msg='Empty ends locations.')
        self.assertEqual(
            len(starts),
            len(vehicles),
            msg='Starts list differs from length to vehicles list.')
        self.assertEqual(len(starts),
                         len(ends),
                         msg='Starts list differs from length to ends list.')
        self.assertEqual(starts, [0, 0], msg='Starts list does not match.')
        self.assertEqual(ends, [0, 1], msg='Ends list does not match.')
Example #2
0
 def addVehicle(self, name, number, type, location):
     vehicle = Vehicle()
     vehicle.setVehicleName(name)
     vehicle.setVehicleNumber(number)
     vehicle.setVehicleType(type)
     vehicle.setLocation(location)
     VehicleService.vehicle_details[number] = vehicle
     return vehicle
Example #3
0
 def setUp(self) -> None:
     self.data = {
         "_id": "123",
         "make": "Test Vehicle",
         "vin_number": "5555",
         "owner_id": "0123456789",
     }
     self.vehicle = Vehicle(**self.data)
 def add_vehicle(self, *, category, make, model, register_number, gear_box):
     VehicleProxy.insert_vehicle(
         category=Vehicle.category_validator(category),
         make=Vehicle.make_validator(make),
         model=Vehicle.model_validator(model),
         register_number=Vehicle.register_number_validator(register_number),
         gear_box=Vehicle.gear_box_validator(gear_box),
         owner=self.id
     )
Example #5
0
def update_live_locations():

    # Delete existing data from vehicles
    Vehicle.query.delete()

    # Get live vehicles as json data
    json_data = requests.get(API_VEHICLES, headers=API_HEADER)
    vehicle_dict = json.loads(json_data.text)

    # Array of service objects
    vehicles = vehicle_dict["vehicles"]

    # Update the vehicle table's last_updated field
    vehicles_date = datetime.fromtimestamp(int(vehicle_dict["last_updated"]))
    update_table_date("vehicle", vehicles_date)

    # Create a vehicle instance of each vehicle.
    for vehicle in vehicles:
        new_vehicle = Vehicle()
        new_vehicle.vehicle_id = vehicle["vehicle_id"]
        new_vehicle.destination = vehicle["destination"]
        new_vehicle.speed = vehicle["speed"]
        new_vehicle.heading = vehicle["heading"]
        new_vehicle.latitude = vehicle["latitude"]
        new_vehicle.longitude = vehicle["longitude"]
        new_vehicle.service_name = vehicle["service_name"]

        db_session.add(new_vehicle)

    db_session.commit()
    db_session.flush()
def setup_vehicles(grid, num_vehicles):
    """
    Set up the vehicles on the grid. The number of vehicles N \\in [min_vehicles,max_ vehicles] and each vehicles drives
    a distance D \\in [min_roads_to_drive, max_roads_to_drive]
    :return: the array of vehicles
    """
    # The list of vehicles.
    vehicles = []

    # Make a random number of vehicles.
    for _ in range(num_vehicles):
        # Get a random intersection.
        x = random.randint(0, config.GRID_WIDTH - 1)
        y = random.randint(0, config.GRID_HEIGHT - 1)
        intersection = grid.intersections[x][y]

        # Determine the number of roads the vehicle has to drive.
        roads_to_drive = random.randint(config.VEHICLE_MIN_ROADS, config.VEHICLE_MAX_ROADS)

        # Choose a lane
        lane = intersection.get_random_lane()

        # Initialize the vehicle and it to the list.
        vehicle = Vehicle(roads_to_drive, intersection.incoming_roads[lane.direction], lane)
        vehicles.append(vehicle)

    return vehicles
Example #7
0
 def setUp(self) -> None:
     self.customer_data = {
         "_id": "123",
         "name": "Test Customer",
         "address": "Cairo",
         "phone": "0123456789",
         "date": "13-2-2021",
     }
     self.vehicle_data = {
         "_id": "123",
         "make": "Test Vehicle",
         "vin_number": "5555",
         "owner_id": "0123456789",
     }
     self.customer = Customer(**self.customer_data)
     self.vehicle = Vehicle(**self.vehicle_data)
    def generate_vehicle():
        fake = Faker()

        year = 2014
        make= ""
        model = ""
        qty = 1
        wide_load = True
        vehicle_type= ""
        vehicle = Vehicle(id, year, make, model, qty, wide_load, vehicle_type)
Example #9
0
def main():
    file_format = Arguments.get_format_of_file()
    try:
        if file_format == 'csv':
            first_argument = Arguments.get_first_file_name()
            second_argument = Arguments.get_second_file_name()

            csv_parser = CsvParser(first_argument, second_argument)

            customer_data = csv_parser.extract_customer_data()
            vehicle_data = csv_parser.extract_vehicle_data()

            customers = [Customer(**customer) for customer in customer_data]
            for customer in customers:
                vehicles = [
                    Vehicle(**vehicle) for vehicle in vehicle_data
                    if customer.id == vehicle.get('owner_id')
                ]
                customer.add_vehicles(vehicles)

                result = csv_parser.generate_json_file_structure(customer)
                csv_parser.save_data_as_json(result)

        elif file_format == 'xml':
            first_argument = Arguments.get_first_file_name()

            xml_parser = XmlParser(first_argument)

            customer_data = xml_parser.extract_customer_data()
            vehicle_data = xml_parser.extract_vehicle_data()

            current_customer = Customer(**customer_data)
            all_vehicles = [Vehicle(**vehicle) for vehicle in vehicle_data]
            current_customer.add_vehicles(all_vehicles)

            result = xml_parser.generate_json_file_structure(current_customer)
            xml_parser.save_data_as_json(result)
        else:
            raise NotImplemented('Not Implemented yet')
    except ParserException as e:
        logger.error(e)
    except Exception as e:
        logger.error(e)
Example #10
0
 def insert_invalid_null(self):
     new_vehicle = Vehicle()
     new_vehicle.vehicle_id = None  # Should not be null, so we expect and exception
     new_vehicle.service_name = "test"
     new_vehicle.destination = "test"
     new_vehicle.heading = 50
     new_vehicle.latitude = 4.00
     new_vehicle.longitude = 5.00
     new_vehicle.speed = 40
     db_session.add(new_vehicle)
     db_session.commit()
     db_session.flush()
Example #11
0
    def calculate_order(self):
        """Uses the temp values to find the values needed to calculate the
        price of the order."""
        start_date_Input = self.__temp_start_date
        end_date_Input = self.__temp_end_date
        extra_insurance = self.__temp_insurance

        # Creating a Vehicle instance to get the prices
        order_instance=Vehicle(0,0,0,0,self.__temp_type_of_vehicle,0,0,0)
        price_per_day = order_instance.get_price_per_day()
        if extra_insurance.lower() == "yes":
            extra_insurance_per_day = order_instance.get_insurance_per_day()
        else:
            extra_insurance_per_day = 0

        # Calculating the number of days and basic insurance price
        diffrence = end_date_Input - start_date_Input
        total_days = diffrence.days + 1
        basic_insurance_cost = int(price_per_day * 0.35)
        return price_per_day, basic_insurance_cost, extra_insurance_per_day, total_days
 def __init__(self, origin, destination, partnerReferenceId,
              desiredDeliveryDate, trailerType, vehicles,
              hasInOpVehicle: bool, availableDate, price, **kwargs):
     self.origin = Location(**origin)
     self.destination = Location(**destination)
     self.partnerReferenceId = partnerReferenceId
     self.desiredDeliveryDate = desiredDeliveryDate
     self.trailerType = trailerType
     self.vehicles = [Vehicle(**x) for x in vehicles]
     self.hasInOpVehicle = hasInOpVehicle
     self.availableDate = availableDate
     self.price = Price(**price)
Example #13
0
    def generate_listing():
        origin = vars(Location("Townsend", "54175", "WI"))
        destination = vars(Location("Beverly Hills", "90210", "CA"))
        partner_reference_id = "multi-car"
        trailer_type = "OPEN"
        vehicles = [
            vars(Vehicle("5", 2008, "nissan", "altima", 1, False, "CAR")),
            vars(Vehicle("6", 2014, "toyota", "camry", 1, True, "CAR"))
        ]
        has_in_op_vehicle = False
        available_date = "2021-12-31"
        desired_delivery_date = "2021-12-31"
        cod = vars(Cod("1600", "CHECK", "DELIVERY"))
        bla = vars(Price(cod, "1600"))
        price = {'cod': cod, 'total': '1600'}
        price_two = json.loads(
            json.dumps(Price(cod, "1600"), default=lambda o: o.__dict__))

        return Listing(origin, destination, partner_reference_id,
                       desired_delivery_date, trailer_type, vehicles,
                       has_in_op_vehicle, available_date, price)
Example #14
0
 def generateRouteFile(cls, nodeList, edgeList, carNum, carTypeNum, fileName):
     adjacentMatrix = RoadEdge.generateAdjacentMatrix(nodeList, edgeList)
     routesList = RoadRoute.generateRoutes(adjacentMatrix)
     vehicleTypeList = VehicleType.getARandomCarTypeList(carTypeNum)
     Vehicle.generateCarList(carNum, routesList, vehicleTypeList, cls.TotalTimeStep)
     carTypeList = VehicleType.getARandomCarTypeList(cls.CarTypeNum)
     carList= Vehicle.generateCarList(carNum, routesList, carTypeList, cls.TotalTimeStep)
     
     
     with open(fileName, "w") as routes:
         routes.write("<routes>\n")
         for item in carTypeList:
             routes.write(str(item) + "\n")
         
         for item in routesList:
             routes.write(str(item) + "\n")
         
         for item in carList:
             routes.write(str(item) + "\n")
         routes.write("</routes>")
     
     print("Route File generated successfully")
    def list_saved_repair_hours_and_get_hour(self):
        repair_hours = self.client.get_saved_repair_hours()
        repair_hours_with_vehicles = [[
            pos + 1, v[1], v[2], v[3],
            str(Vehicle.make_vehicle(v[4:10]))
        ] for pos, v in enumerate(repair_hours)]
        self._print(
            repair_hours_with_vehicles,
            headers=['id', 'Date', 'Hour', 'Bill', 'Vehicle'],
        )

        hour_idx = self._read('Hour id:\n>>>')
        self.validate_id(hour_idx, len(repair_hours))
        return repair_hours[int(hour_idx) - 1]
 def update_vehicle(self, *, vehicle_id, category, make, model, register_number, gear_box):
     VehicleProxy.update_vehicle(
         Vehicle.category_validator(category),
         Vehicle.make_validator(make),
         Vehicle.model_validator(model),
         Vehicle.register_number_validator(register_number),
         Vehicle.gear_box_validator(gear_box),
         Vehicle.id_validator(vehicle_id)
     )
Example #17
0
    def test_successful_insert(self):
        # Create sample vehicle and insert it into our test database
        new_vehicle = Vehicle()
        new_vehicle.vehicle_id = 5
        new_vehicle.service_name = "test"
        new_vehicle.destination = "test"
        new_vehicle.heading = 50
        new_vehicle.latitude = 4.00
        new_vehicle.longitude = 5.00
        new_vehicle.speed = 40
        db_session.add(new_vehicle)
        db_session.commit()
        db_session.flush()

        vehicles = Vehicle.query.all()
        self.assertEqual(len(vehicles), 1)
        test_vehicle = vehicles[0]
        self.assertEqual(test_vehicle.service_name, "test")
Example #18
0
def read_entities(
    input_dir: str
) -> Tuple[Dict[str, Rider], Dict[str, Vehicle], Dict[str, Depot], Params]:
    """Method to parse the Riders, Vehicles and Depots from JSON to Dict"""

    riders_file = RIDERS_FILE.format(input_dir=input_dir)
    with open(riders_file) as f:
        logging.info(f'Read riders from {riders_file}.')
        riders_dicts = json.load(f)
    riders = {
        r_dict['rider_id']: Rider.from_dict(r_dict)
        for r_dict in riders_dicts
    }
    logging.info(f'Successfully parsed {len(riders)} riders.')

    vehicles_file = VEHICLES_FILE.format(input_dir=input_dir)
    with open(vehicles_file) as f:
        vehicles_dicts = json.load(f)
        logging.info(f'Read vehicles from {vehicles_file}.')
    vehicles = {
        v_dict['vehicle_id']: Vehicle.from_dict(v_dict)
        for v_dict in vehicles_dicts
    }
    logging.info(f'Successfully parsed {len(vehicles)} vehicles.')

    depots_file = DEPOTS_FILE.format(input_dir=input_dir)
    with open(depots_file) as f:
        depots_dicts = json.load(f)
        logging.info(f'Read depots from {depots_file}.')
    depots = {
        d_dict['depot_id']: Depot.from_dict(d_dict)
        for d_dict in depots_dicts
    }
    logging.info(f'Successfully parsed {len(depots)} depots.')

    params_file = PARAMS_FILE.format(input_dir=input_dir)
    with open(params_file) as f:
        logging.info(f'Read params from {params_file}.')
        params_dict = json.load(f)
    params = Params.from_dict(params_dict)
    logging.info(f'Successfully parsed {len(params_dict)} params.')

    return riders, vehicles, depots, params
Example #19
0
    def _assert_vehicle_fields(self, vehicle_dict: Dict[str, Any]):
        """Auxiliary method to assert fields in the Vehicle are correct"""

        vehicle = Vehicle.from_dict(vehicle_dict)
        self.assertEqual(
            vehicle.capacity,
            vehicle_dict['capacity'],
            msg='The Vehicle is instantiated with incorrect capacity.')
        self.assertEqual(
            vehicle.start,
            vehicle_dict['start'],
            msg='The Vehicle is instantiated with incorrect start Depot.')
        self.assertEqual(
            vehicle.end,
            vehicle_dict['end'],
            msg='The Vehicle is instantiated with incorrect end Depot.')
        self.assertEqual(
            vehicle.vehicle_id,
            vehicle_dict['vehicle_id'],
            msg='The Vehicle is instantiated with incorrect vehicle_id.')
Example #20
0
 def get_vehicle_list(self):
     """Reads in all vehicles from the file and returns a list of Vehicle instances"""
     if self.__vehicle_list == []:
         with open(self.VEHICLE_FILE, "r") as vehicle_file:
             csv_reader = csv.DictReader(vehicle_file, delimiter=";")
             for line in csv_reader:
                 # the column for dates rented needs to be split into a list before
                 # the data is converted to a Vehicle instance
                 try:
                     dates = line["dates rented"].split(",")
                 except AttributeError:
                     dates = []
                 if line["licence"] != None:
                     vehicle = Vehicle(line["licence"], line["make"],
                                       line["model"], line["year"],
                                       line["type"], line["seats"],
                                       line["fuel"], line["transmission"],
                                       dates)
                     self.__vehicle_list.append(vehicle)
     return self.__vehicle_list
Example #21
0
class TestTransaction(unittest.TestCase):
    def setUp(self) -> None:
        self.customer_data = {
            "_id": "123",
            "name": "Test Customer",
            "address": "Cairo",
            "phone": "0123456789",
            "date": "13-2-2021",
        }
        self.vehicle_data = {
            "_id": "123",
            "make": "Test Vehicle",
            "vin_number": "5555",
            "owner_id": "0123456789",
        }
        self.customer = Customer(**self.customer_data)
        self.vehicle = Vehicle(**self.vehicle_data)

    def test_transaction_to_json(self):
        expected = {
            "date":
            "13-2-2021",
            "customer": {
                "id": "123",
                "name": "Test Customer",
                "address": "Cairo",
                "phone": "0123456789",
            },
            "vehicle": [{
                "id": "123",
                "make": "Test Vehicle",
                "vin_number": "5555",
            }]
        }
        result = {
            "date": self.customer.date,
            "customer": self.customer.to_json(),
            "vehicle": [self.vehicle.to_json()]
        }

        self.assertDictEqual(result, expected)
Example #22
0
class TestVehicle(unittest.TestCase):
    def setUp(self) -> None:
        self.data = {
            "_id": "123",
            "make": "Test Vehicle",
            "vin_number": "5555",
            "owner_id": "0123456789",
        }
        self.vehicle = Vehicle(**self.data)

    def test_create_vehicle(self):
        self.assertEqual(self.vehicle.id, "123")
        self.assertEqual(self.vehicle.make, "Test Vehicle")
        self.assertEqual(self.vehicle.vin_number, "5555")
        self.assertEqual(self.vehicle.owner_id, "0123456789")

    def test_vehicle_to_json(self):
        expected = {
            "id": "123",
            "make": "Test Vehicle",
            "vin_number": "5555",
        }
        result = self.vehicle.to_json()
        self.assertDictEqual(result, expected)
with open('./src/paths/simulated_waypoints.json') as f:
    waypoints = json.load(f)
    waypoints_x = waypoints['waypoints_x']
    waypoints_y = waypoints['waypoints_y']

path = Path(waypoints_x=waypoints_x, waypoints_y=waypoints_y)

wheelbase = 1
max_velocity = 10
max_steering_angle = math.pi

initial_state = np.array([0, 0, math.pi / 2])

vehicle = Vehicle(
    wheelbase=wheelbase, initial_state=initial_state, dt=dt,
    max_velocity=max_velocity, max_steering_angle=max_steering_angle)

vehicle_x = np.append(initial_state[0], np.zeros(simulation_steps - 1))
vehicle_y = np.append(initial_state[1], np.zeros(simulation_steps - 1))
steering_angles = np.zeros(simulation_steps)

spatial_bicycle_model = SpatialBicycleModel(
    path.as_array_with_curvature(), vehicle.state)

mpc = MPC(
    Q=Q, R=R, Qn=Qn, prediction_horizon=prediction_horizon,
    steering_angle_min=np.radians(-16),
    steering_angle_max=np.radians(16),
    wheelbase=wheelbase)
mpc.setup_optimization_problem(spatial_bicycle_model)
 def delete_vehicle(self, vehicle_id):
     VehicleProxy.delete_vehicle(Vehicle.id_validator(vehicle_id))
Example #25
0
    def dispatch(self, cmd):
        """
        Executes the command.
        :param cmd: command to be executed.
        """
        response = Response()
        cmd_key, parsed_cmd = parse(cmd)

        if cmd_key and parsed_cmd:
            if cmd_key != Command.CREATE and self.parking_service.parking_lot is None:
                logger.error("No parking lot found, please create a parking lot first.")
                response = Response(success=False, error=ErrorConstant.NO_PARKING_LOT_FOUND,
                                    message="Parking lot must be created first")
                return response

            if cmd_key == Command.CREATE:
                size = int(parsed_cmd.get('size', 0))
                self.parking_service.create_parking_lot(size)
                logger.info("Created a parking lot with {} slots".format(size))
                response = Response(data={'size': size}, message="Parking lot created successfully.")

            elif cmd_key == Command.PARK:
                reg_num = parsed_cmd.get('reg_num')
                color = parsed_cmd.get('color')

                # Create vehicle.
                vehicle = Vehicle.create(Car, reg_num, color)

                # Park the vehicle.
                response = self.parking_service.park(vehicle)
                if response.success:
                    logger.info("Allocated slot number: {}".format(response.data['slot_num']))
                else:
                    if response.error == ErrorConstant.PARKING_LOT_OVERFLOW:
                        logger.info("Sorry, parking lot is full")

            elif cmd_key == Command.LEAVE:
                slot_num = int(parsed_cmd.get('slot_num'))

                # Vehicle is leaving the slot.
                response = self.parking_service.leave(SmallSlot(int(slot_num)))
                if response.success:
                    logger.info("Slot number {} is free".format(slot_num))

            elif cmd_key == Command.STATUS:
                logger.info("Slot No.\tRegistration No.\tColour")
                for slot_num, reg_num, col in self.parking_service.status():
                    logger.info('{}\t\t\t{}\t\t{}'.format(slot_num, reg_num, col))

            elif cmd_key == Command.REG_NUMS_BY_COLOR:
                color = parsed_cmd.get('color')

                # Will be better to print reg_num one-by-one, as it will save the space.
                reg_nums = [reg_num for reg_num in self.parking_service.registration_numbers_by_color(color)]
                logger.info(', '.join(reg_nums))
                response = Response(data={'reg_nums': reg_nums})

            elif cmd_key == Command.SLOT_NUMS_BY_COLOR:
                color = parsed_cmd.get('color')

                # Will be better to print slot_num one-by-one, as it will save the space.
                slot_nums = [str(slot_num) for slot_num in self.parking_service.slot_numbers_by_color(color)]
                logger.info(', '.join(slot_nums))
                response = Response(data={'slot_nums': slot_nums})

            elif cmd_key == Command.SLOT_NUM_BY_REG_NUM:
                reg_num = parsed_cmd.get('reg_num')
                slot_num = self.parking_service.slot_number_by_registration_number(reg_num)
                logger.info(str(slot_num or 'Not found'))
                response = Response(success=slot_num is not None, data={'slot_num': slot_num})

            else:
                logger.error("Invalid command: {}".format(cmd))
                response = Response(success=False, error=ErrorConstant.INVALID_COMMAND)

        else:
            logger.error("Invalid command: {}".format(cmd))
            response = Response(success=False, error=ErrorConstant.INVALID_COMMAND)

        return response
 def get_personal_vehicles(self):
     return [Vehicle.make_vehicle(vrow)
             for vrow in VehicleProxy.get_vehicles_for_client(self.id)]
def automatic_shift_creation(latitude, longitude):
    # create the new shift
    new_shift = Shift(location_lat=latitude, location_long=longitude)
    db.session.add(new_shift)
    # instantiate the new shift. We need to get the ID to stamp our vehicles
    db.session.commit()
    # query for 20 nearest not in use/not fully charged vehicles
    target_data = db.session.execute(
        """SELECT *,
      SQRT(
        POW(69.1 * (location_lat - :lat), 2) +
        POW(69.1 * (location_long - :long) * COS(location_lat / 57.3), 2)
      ) AS distance
      FROM vehicle
      WHERE battery_level != 100.0
      AND shift_id IS NULL
      AND in_use = 'False'
      ORDER BY distance LIMIT 20""", {
            'lat': latitude,
            'long': longitude
        })

    vehicles = []
    for v in target_data:
        vehicles.append(
            Vehicle(
                id=v.id,
                license_plate=v.license_plate,
                battery_level=v.battery_level,
                in_use=v.in_use,
                model=v.model,
                location_lat=v.location_lat,
                location_long=v.location_long,
                shift_id=new_shift.id,
                created_at=v.created_at,
            ))

    path = PathFinder(vehicles, new_shift).initial_route[1:len(vehicles) + 1]
    # pathing logic for vehicles goes HERE
    # currently employing nearest neighbor heuristic, need to hook up the Two_opt solution for further accuracy
    # then iterate through the newly sorted/pathed vehicles

    # not enough time to implement two_opt confidently. Will do further research and go over during onsite, currently just using Nearest Neighbor
    if len(path) > 0:
        for i in range(0, len(path)):
            # set the Vehicle.next_id to be the next vehicle
            current_vehicle_index = path[i] - 1
            if i < len(path) - 1:
                db.session.query(Vehicle).filter(
                    Vehicle.id == vehicles[current_vehicle_index].id).update({
                        'next_id':
                        vehicles[path[i + 1] - 1].id,
                        'shift_id':
                        new_shift.id
                    })
            else:
                db.session.query(Vehicle).filter(
                    Vehicle.id == vehicles[current_vehicle_index].id).update(
                        {'shift_id': new_shift.id})
        # create the shift_index row
        new_link = ShiftIndex(shift_id=new_shift.id,
                              next_vehicle_id=vehicles[path[0]].id)
        db.session.add(new_link)

    # # commit all changes
    db.session.commit()
    return ShiftSchema().dump(new_shift)
Example #28
0
 def vehicle_animation(self, id: str, secs: float) -> Vehicle:
     if id in self.vehicles:
         v = self.vehicles[id]
         return Vehicle(id, v.path_id, [Vehicle.Target(v.mileage + v.average_speed * secs, datetime.utcnow().timestamp())])
Example #29
0
 def add_vehicle(number: str, vehicle_type: VehicleType):
     new_vehicle = Vehicle(number, vehicle_type)
     vehicles.append(new_vehicle)
     return new_vehicle
    def parse_to_objects(self, content):
        """Parse the game board file into the corresponding models."""
        vehicles = {}

        for row_index, line in enumerate(content):
            for column_index, letter in enumerate(line):

                if letter != '.' and letter != 'r':
                    if letter not in vehicles:
                        vehicle = Vehicle(name=letter)
                        vehicle.set_start_location(column_index, row_index)
                        vehicles[letter] = vehicle
                    else:
                        vehicle = vehicles[letter]
                        vehicle.set_end_location(column_index, row_index)

                if letter == 'r':
                    if letter not in vehicles:
                        vehicle = Vehicle(name=letter, main_vehicle=True)
                        vehicle.set_start_location(column_index, row_index)
                        vehicles[letter] = vehicle
                    else:
                        vehicle = vehicles[letter]
                        vehicle.set_end_location(column_index, row_index)

        board_width = len(content[0])
        board_height = len(content)
        self.game_board = GameBoard(board_height, board_width)

        for key, vehicle in sorted(vehicles.items()):
            locations = vehicle.get_occupied_locations()
            self.game_board.add_vehicle(vehicle, locations)