示例#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.')
    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)
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
示例#4
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
示例#5
0
 def setUp(self) -> None:
     self.data = {
         "_id": "123",
         "make": "Test Vehicle",
         "vin_number": "5555",
         "owner_id": "0123456789",
     }
     self.vehicle = Vehicle(**self.data)
示例#6
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)
    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)
 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)
示例#9
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)
示例#10
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)
示例#11
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
示例#12
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 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)
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)
示例#15
0
 def add_vehicle(number: str, vehicle_type: VehicleType):
     new_vehicle = Vehicle(number, vehicle_type)
     vehicles.append(new_vehicle)
     return new_vehicle
示例#16
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())])