Пример #1
0
 def test_car_is_stopped_at_initialization(self):
     car = Vehicle("Lotus", "Black")
     self.assertFalse(car.started)
Пример #2
0
        self.curr_controller = Search_Controller(self, self.drone)
        self.curr_controller.enter()

    def switch_state(self, new_controller):
        print("Here")
        rospy.loginfo("CONTROLLER TRANSITION: %s --> %s",
                      self.curr_controller.NAME, new_controller.NAME)
        if self.curr_controller is not None:
            self.curr_controller.exit()
        self.curr_controller = new_controller
        self.curr_controller.enter()

    def handle_track_message(self, msg):
        self.curr_controller.handle_track_message(msg)

    def run(self):
        """
    Spin the ROS event loop, running the controller on each iteration.
    """
        while not rospy.is_shutdown():
            self.curr_controller.run()
            self.control_loop_rate.sleep()

    def cleanup(self):
        pass


if __name__ == '__main__':
    drone = Vehicle()
    mission = Rescue_Mission(drone)
    mission.run()
Пример #3
0
def setup():
    size(640, 480)
    global target
    global brum
    brum = Vehicle()
    target = Target()
Пример #4
0
def generateVehicles(numvehicles):
    vehicles = []
    for i in range(numvehicles):
        vehicles.append(Vehicle(i))
    return vehicles
Пример #5
0
import kivy
kivy.require('1.10.0')  # replace with your current kivy version !

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen

import serial

from mainscreen import MainScreen
from graphscreen import GraphScreen
from vehicle import Vehicle

vehicles = []
vehicles.append(Vehicle(1, True, '+100', '+100', 100, 10, 12, 13))

#arduinoSerial = serial.Serial('dev/ttyACM0', timeout=1)

#Create screenmanager
sm = ScreenManager()
sm.add_widget(MainScreen(sm, name='Mainscreen'))
sm.add_widget(GraphScreen(sm, name='Graphscreen'))


class Coopvehicles(App):
    def build(self):
        return sm


if __name__ == '__main__':
    Coopvehicles().run()
Пример #6
0
 def vehicle(self, vin):
     return Vehicle(vin, self)
Пример #7
0
import libtcodpy as tcod

import random
from team import Team
from vehicle import Vehicle
import vehicle_bodies

ALL_TEAMS = [
    Team('Kasvot Vaxt', tcod.light_cyan, Vehicle(vehicle_bodies.v_bod_1)),
    Team('ViscDuds', tcod.purple, Vehicle(vehicle_bodies.v_bod_1)),
    Team('The Billiards', tcod.sea, Vehicle(vehicle_bodies.v_bod_1)),
    Team('Strange Dan Gustafvist', tcod.yellow,
         Vehicle(vehicle_bodies.v_bod_1)),
    Team('Italian Horse', tcod.red, Vehicle(vehicle_bodies.v_bod_1)),
    Team('The Unicorns', tcod.light_purple, Vehicle(vehicle_bodies.v_bod_1)),
    Team('Harold of the Boulders', tcod.gray, Vehicle(vehicle_bodies.v_bod_1)),
    Team('PrimeThem', tcod.sepia, Vehicle(vehicle_bodies.v_bod_1)),
    Team('Dreaded Blimp', tcod.turquoise, Vehicle(vehicle_bodies.v_bod_1)),
    Team('Has', tcod.white, Vehicle(vehicle_bodies.v_bod_1)),
]


def pick_season_teams(player_team):
    indexes = []
    while len(indexes) < 4:
        index = random.randint(0, len(ALL_TEAMS) - 1)
        if index not in indexes:
            indexes.append(index)

    teams = [
        ALL_TEAMS[indexes[0]], ALL_TEAMS[indexes[1]], player_team,
Пример #8
0
        ) and sys.argv[2].isdigit() and 3 <= int(sys.argv[2]) <= 50:
        vehicle = int(sys.argv[2])
    if (sys.argv[1] == "-t" or sys.argv[1] == "--totalduration"
        ) and sys.argv[2].isdigit() and 1 <= int(sys.argv[2]) <= 10:
        totalDuration = int(sys.argv[2])
    if len(sys.argv) == 5:
        if (sys.argv[3] == "-nv" or sys.argv[3] == "--vehicle"
            ) and sys.argv[4].isdigit() and 3 <= int(sys.argv[4]) <= 50:
            vehicle = int(sys.argv[4])
        if (sys.argv[3] == "-t" or sys.argv[3] == "--totalduration"
            ) and sys.argv[4].isdigit() and 1 <= int(sys.argv[4]) <= 10:
            totalDuration = int(sys.argv[4])

#Default duration and vehicles
totalDuration = 5
vehicle = 50

if __name__ == "__main__":

    sys.argv = [sys.argv[0]]

    print(f"{vehicle} vehicles")

    print(f"{totalDuration} * 10000 steps")

    myAgent = Vehicle('sumo/network.net.xml', vehicle)

    myAgent.qlearning(totalDuration)

    myAgent.close_simulation()
Пример #9
0
 def add_one(self):
     self.vehicles.append(Vehicle(mouse_x, mouse_y))
Пример #10
0
        ride_lines = file_contents[1:]
        for r, line in enumerate(ride_lines):
            l = line.split(' ')
            ride = Ride(
                int(l[0]),  # x_start
                int(l[1]),  # y_start
                int(l[2]),  # x_end
                int(l[3]),  # y_end
                int(l[4]),  # start
                int(l[5]),  # finish
                r)  # id
            rides.append(ride)

        for car in range(0, info.cars):
            cars.append(Vehicle(0, 0, 0))

        rides = Mathss.sortRidesByStart(rides)

        for i, car in enumerate(cars):
            cars[i].rides.append(rides[0])
            cars[i].avail_at += Mathss.calculate_distance(
                cars[i].pos_x, cars[i].pos_y, rides[0].x_start,
                rides[0].y_start) + rides[0].distance
            cars[i].completed_rides.append(rides[0])
            cars[i].pos_x = rides[0].x_end
            cars[i].pos_x = rides[0].y_end
            del rides[0]

        while len(rides) > 0:
            cars = Mathss.sortCarsByAvailibilityToNextRide(cars, rides[0])
Пример #11
0
from vehicle import Vehicle
from car import Car

vehicle1 = Vehicle('Black', 'Ford', 10, 2)
vehicle1.vehicle_plug()
vehicle1.to_fuel(25)
vehicle1.vehicle_plug()
vehicle2 = Vehicle('Silver', 'FIAT', 15, 3)
vehicle2.vehicle_plug()
vehicle2.to_fuel(65)
vehicle2.vehicle_plug()
car1 = Car('Red', 'Honda', 50)
car1.vehicle_plug()
car1.to_fuel(51)
car1.vehicle_plug()
Пример #12
0
 def test_initialization(self):
     car = Vehicle("Ferrari", "red")
     self.assertEqual(car.brand, "Ferrari")
     self.assertEqual(car.color, "red")
Пример #13
0
 def test_car_can_be_stopped(self):
     car = Vehicle("Lotus", "Black")
     car.start()
     car.stop()
     self.assertFalse(car.started)
Пример #14
0
 def test_car_can_be_started(self):
     car = Vehicle("Lotus", "Black")
     car.start()  # Calling an instance method that you need to implement
     self.assertTrue(car.started)
	def test_subsequent_years_tax_for_alternative_fuel_if_over_40k(self):
		vehicle = Vehicle(206, "ALTERNATIVE FUEL", self.FIRST_OF_APRIL_2017, 50000)
		self.assertEqual(440, self.tax_calculator.calculate_tax(vehicle))
Пример #16
0
 def __init__(self):
     self.num_of_vehs = 1
     self.origin = Vector(width / 2, height / 2)
     self.vehicles = [Vehicle()] * self.num_of_vehs
     self.debug = False
Пример #17
0
import sys
from collections import deque
from vehicle import Vehicle
from Queue import PriorityQueue
import webbrowser, os

GOAL_VEHICLE = Vehicle('X', 4, 2, 'H')


class RushHour(object):
    """A configuration of a single Rush Hour board."""
    def __init__(self, vehicles):
        """Create a new Rush Hour board.
        
        Arguments:
            vehicles: a set of Vehicle objects.
        """
        self.vehicles = vehicles

    def __hash__(self):
        return hash(self.__repr__())

    def __eq__(self, other):
        return self.vehicles == other.vehicles

    def __ne__(self, other):
        return not self.__eq__(other)

    def __repr__(self):
        s = '-' * 8 + '\n'
        for line in self.get_board():
Пример #18
0
 def test_vehicle_1(self):
    vehicle_1 = Vehicle(4, 35, 2, True)
    self.assertEqual(vehicle_1.wheels, 4)
    self.assertEqual(vehicle_1.fuel, 35)
    self.assertEqual(vehicle_1.doors, 2)
    self.assertEqual(vehicle_1.roof, True)
Пример #19
0
 def vehicles(self):
     payload = self.read_json_path('vehicles')
     v = []
     for p in payload:
         v.append(Vehicle(p['vin'], self, p))
     return v
Пример #20
0
    load_controller.wait_for_topics(5)

    load_controller.computeSystemStates()

    print("* Attitude control *")
    load_controller.position_active = False
    load_controller.attitude_active = True
    load_controller.load_active = False

    print(f'=== number_of_vehicles ==={number_of_vehicles}')
    
    # Arm quadrotors and set mode to offboard
    quad_list = []
    for i in range(number_of_vehicles):
        print(f"[{i}] Start vehicle object...")
        quad = Vehicle(ID=i, vehicle_cfg=cfg[i])
        
        # quad.wait_for_topics(10)
        quad.thread.start()
        quad_list.append(quad)

    rospy.sleep(100.0)

    print("* Load control *")
    load_controller.t0 = rospy.get_time()
    load_controller.k = 0
    load_controller.t_prev = -0.01
    load_controller.position_active = False
    load_controller.attitude_active = False
    load_controller.load_active = True
Пример #21
0
def annotate_img_vehicle(img,
                         clf,
                         X_scaler,
                         vehicles=vehicle_list,
                         heatmap_cache=heatmap_cache,
                         l1_size=param['l1_sliding_window_size'],
                         l2_size=param['l2_sliding_window_size'],
                         thresh=param['thresh'],
                         smooth=param['smooth']):
    win_l1 = slide_window(img,
                          xy_window=(l1_size, l1_size),
                          xy_overlap=(param['overlap'], param['overlap']))
    win_l2 = slide_window(img,
                          xy_window=(l2_size, l2_size),
                          xy_overlap=(param['overlap'], param['overlap']))

    on_win_l1 = search_windows_naive(img, win_l1, clf, X_scaler)
    on_win_l2 = search_windows_naive(img, win_l2, clf, X_scaler)

    all_on_windows = on_win_l1 + on_win_l2

    print('num on_windows: ', len(all_on_windows))
    heatmap = np.zeros_like(img[:, :, 0]).astype(np.uint8)
    heatmap = add_heat(heatmap, all_on_windows)

    heatmap_cache.append(heatmap)
    # checking new cars using a higher threshold to be more sure about a car
    heatmap_high_confidence = apply_threshold(sum(heatmap_cache), 2 * thresh)
    heatmap_high_confidence = np.clip(heatmap_high_confidence, 0, 255)
    heatmap_high_confidence = cv2.GaussianBlur(heatmap_high_confidence,
                                               (smooth, smooth), 0)
    bbox_list_high_confidence = get_labeled_bboxes(
        label(heatmap_high_confidence))

    print('alive vehicles: ', len(vehicles))
    for bbox in bbox_list_high_confidence:
        bbox_center = [(bbox[0][0] + bbox[1][0]) // 2,
                       (bbox[0][1] + bbox[1][1]) // 2]

        # first car creation
        if len(vehicles) == 0:
            vehicles.append(Vehicle(bbox))
            print('create first car {}'.format(vehicles[-1].id))
        # there are cars already, check if this bbox belongs to any of them
        else:
            exist_flag = 0
            for car in vehicles:
                # print('bbox - car {} distance: {}'.format(car.id, pdist(np.vstack((car.center, bbox_center)))[0]))
                if pdist(np.vstack(
                    (car.center, bbox_center)))[0] < max(car.size):
                    exist_flag = 1
                    break
                    # print('this bbox belongs to existing vehicles')
            if exist_flag == 0:
                vehicles.append(Vehicle(bbox))
                print('Found new car {}'.format(vehicles[-1].id))

    # updating cars
    heatmap_low_confidence = apply_threshold(sum(heatmap_cache), thresh)
    bbox_list_low_confidence = get_labeled_bboxes(
        label(heatmap_low_confidence))

    for car in vehicles:
        car.update(bbox_list_low_confidence)

    # first, check if car is alive, if not drop it from vehicle list
    n_cars_prev = len(vehicles)
    vehicles = [car for car in vehicles if car.alive is True]
    n_cars_current = len(vehicles)
    print('dropping {} non-alive cars'.format(n_cars_prev - n_cars_current))

    # second, merge cars which are too close to each other
    remove_idxes = []
    for i in range(len(vehicles)):
        ref_car = vehicles[i]
        for j in range(i + 1, len(vehicles)):
            current_car = vehicles[j]
            if pdist(np.vstack((ref_car.center, current_car.center)))[0] < 16:
                remove_idxes.append(i)
                current_car.center = list_list_mean(current_car.center,
                                                    ref_car.center)
                current_car.vel = list_list_mean(current_car.vel, ref_car.vel)

    print('merging cars nearby.')
    n_cars_current = len(vehicles)
    print('remove idx: ', remove_idxes)
    vehicles = [
        car for idx, car in enumerate(vehicles) if idx not in remove_idxes
    ]
    n_cars_merged = len(vehicles)
    print('dropping {} nearby cars'.format(n_cars_current - n_cars_merged))

    bbox_draw = []

    # draw bbox for each car
    for car in vehicles:
        bbox_draw.append(car.get_bbox())

    img_out = draw_boxes(img, bbox_draw)

    return img_out
Пример #22
0
pickup_time = [delivery_times['min'] - 30 * 60, delivery_times['max']]
pickup_dur = 3  #time to pick up order
dropoff_dur = 3  #time to drop off order
num_drivers = 3
car_capacity = 10  #max number of orders a car can hold
car_start = [-71.061033, 42.358157]  #starting vehicle location

#set variables
buffers = [10, 20, 30]
cases = ['A', 'B', 'C']

#number of repetitions
N = 20

#define vehicles and shipments for routes
vehicles = [Vehicle(j, car_capacity, car_start) for j in range(num_drivers)]

unopt_distances = []
for repetition in range(8, N):
    time.sleep(60)  #avoid maxing out API token quota
    shipment_cases = {}

    for i in range(8, number_of_orders):
        #get random restaurant, delivery address, and time for order
        restaurant_loc, customer_loc, order_time, time_formatted = get_random_orders(
        )

        shipment_id = 2 * i
        pickup_step = Shipment_step(shipment_id, restaurant_loc, pickup_dur,
                                    pickup_time)
        dropoff = Stop(customer_loc, order_time)
Пример #23
0
    def setup_vehicle_pools(self):

        self.left_pool = []
        self.right_pool = []

        vehicle_id = 0
        direct_flag = 1
        lane_ID = 0
        acceleration = np.array([0.0, 0.0])
        speed = np.array([0.0, 0.0])
        position = np.array([0.0, 0.0])
        position[1] = ((-1)**(direct_flag))*(self.LANE_WIDTH*0.5 + \
        lane_ID*self.LANE_WIDTH)
        speed[0] = self.speed_headway_random.speed_random.rvs()
        vehicle = Vehicle(vehicle_id, direct_flag, lane_ID, position, speed,
                          acceleration)
        vehicle.setup_communication_terminal(True)  # the source
        vehicle.communication_terminal.receive([vehicle_id])
        self.current_message_carrier.append(vehicle)
        self.propagation_distance = vehicle.position[0]
        # the right pool
        lane_pool = []

        while position[0] < (self.ROAD_LENGTH - self.VEHICLE_LENGTH):
            lane_pool.append(vehicle)
            self.right_vehicle_count[lane_ID] += 1
            vehicle_id += 1
            acceleration = np.array([0.0, 0.0])
            speed = np.array([0.0, 0.0])
            speed[0] = self.speed_headway_random.speed_random.rvs()
            position = np.array([position[0], 0.0])
            position[1] = ((-1)**(direct_flag))*(self.LANE_WIDTH*0.5 + \
            lane_ID*self.LANE_WIDTH)
            position[0] = position[
                0] + self.VEHICLE_LENGTH + self.speed_headway_random.headway_random.rvs(
                )
            vehicle = Vehicle(vehicle_id, direct_flag, lane_ID, position,
                              speed, acceleration)
            vehicle.setup_communication_terminal(False)

        self.right_pool.append(lane_pool)

        for lane_ID in range(self.LANE_NUM_PER_DIRECT - 1):

            vehicle_id = 0
            acceleration = np.array([0.0, 0.0])
            speed = np.array([0.0, 0.0])
            position = np.array([0.0, 0.0])
            position[1] = ((-1)**(direct_flag))*(self.LANE_WIDTH*0.5 + \
            (lane_ID + 1)*self.LANE_WIDTH)
            speed[0] = self.speed_headway_random.speed_random.rvs()
            vehicle = Vehicle(vehicle_id, direct_flag, (lane_ID + 1), position,
                              speed, acceleration)
            vehicle.setup_communication_terminal(False)

            lane_pool = []

            while position[0] < (self.ROAD_LENGTH - self.VEHICLE_LENGTH):
                lane_pool.append(vehicle)
                self.right_vehicle_count[1 + lane_ID] += 1
                vehicle_id += 1
                acceleration = np.array([0.0, 0.0])
                speed = np.array([0.0, 0.0])
                speed[0] = self.speed_headway_random.speed_random.rvs()
                position = np.array([position[0], 0.0])
                position[1] = ((-1)**(direct_flag))*(self.LANE_WIDTH*0.5 + \
                (lane_ID+1)*self.LANE_WIDTH)
                position[0] = position[
                    0] + self.VEHICLE_LENGTH + self.speed_headway_random.headway_random.rvs(
                    )
                vehicle = Vehicle(vehicle_id, direct_flag, lane_ID, position,
                                  speed, acceleration)
                vehicle.setup_communication_terminal(False)

            self.right_pool.append(lane_pool)
        print "successfully set up the right vehicle pool!"

        # the left pool
        direct_flag = 2
        for lane_ID in range(self.LANE_NUM_PER_DIRECT):

            vehicle_id = 0
            acceleration = np.array([0.0, 0.0])
            speed = np.array([0.0, 0.0])
            position = np.array([0.0, 0.0])
            position[1] = ((-1)**(direct_flag))*(self.LANE_WIDTH*0.5 + \
            (lane_ID)*self.LANE_WIDTH)
            position[0] = self.ROAD_LENGTH - position[0]
            speed[0] = (-1) * self.speed_headway_random.speed_random.rvs()
            vehicle = Vehicle(vehicle_id, direct_flag, (lane_ID + 1), position,
                              speed, acceleration)
            vehicle.setup_communication_terminal(False)

            lane_pool = []

            while position[0] > (self.VEHICLE_LENGTH):
                lane_pool.append(vehicle)
                self.left_vehicle_count[lane_ID] += 1
                vehicle_id += 1
                acceleration = np.array([0.0, 0.0])
                speed = np.array([0.0, 0.0])
                speed[0] = (-1) * self.speed_headway_random.speed_random.rvs()
                position = np.array([position[0], 0.0])
                position[1] = ((-1)**(direct_flag))*(self.LANE_WIDTH*0.5 + \
                (lane_ID)*self.LANE_WIDTH)
                position[0] = position[0] + (
                    -1) * (self.VEHICLE_LENGTH +
                           self.speed_headway_random.headway_random.rvs())
                vehicle = Vehicle(vehicle_id, direct_flag, lane_ID, position,
                                  speed, acceleration)
                vehicle.setup_communication_terminal(False)

            self.left_pool.append(lane_pool)

        print "successfully set up the left vehicle pool!"
        self.infected_ratio = 1.0*len(self.current_message_carrier)/(1.0*sum([len(self.right_pool[lane_ID]) for lane_ID in range(self.LANE_NUM_PER_DIRECT)]) \
        +1.0*sum([len(self.left_pool[lane_ID]) for lane_ID in range(self.LANE_NUM_PER_DIRECT)]))
Пример #24
0
from vehicle import Vehicle
import time

vehicle = Vehicle()
for i in xrange(600, 1000, 1):
    pwm = i / 100.0
    print '{}'.format(pwm)
    vehicle.set_steering(pwm)
    time.sleep(0.01)

for i in xrange(1000, 600, -1):
    pwm = i / 100.0
    print '{}'.format(pwm)
    vehicle.set_steering(pwm)
    time.sleep(0.01)
 def __init__(self, c, m, o, n, b, s):
     self.vehicle = Vehicle(c, m, o, n, b, s)
	def test_subsequent_years_tax_for_petrol_if_over_40k(self):
		vehicle = Vehicle(206, "PETROL", self.FIRST_OF_APRIL_2017, 50000)
		self.assertEqual(450, self.tax_calculator.calculate_tax(vehicle))
Пример #27
0
def main():

    try:

        jsonDictionary = getVehicleInfo(
        )  # this returns a dictionary with the keys as indicies 0-n and values are vehicle objects
        # with keys vID, vLatitude, vLongitude, fleetID, and vState
        count = 0
        isRunning = True

        try:
            while jsonDictionary[str(count)] != None:
                vehicleObj = jsonDictionary[str(count)]
                vID = vehicleObj["vID"]
                vLat = vehicleObj["vLatitude"]
                vLong = vehicleObj["vLongitude"]
                fleetID = vehicleObj["fleetID"]
                vState = vehicleObj["vState"]
                vLatFloat = float(vLat)
                vLongFloat = float(vLong)
                v1 = Vehicle(ID=vID,
                             latitude=vLatFloat,
                             longitude=vLongFloat,
                             status=vState)  # create new vehicles
                print("New Vehicle created with id ", str(vID))

                if fm.doesIDExist(
                        fleetID
                ):  # if the fleet id is already in the fleet manager
                    fleet = fm.getFleetByID(fleetID)
                    fleet.add(v1)  # add the vehicle to the existing fleet
                    print("Vehicle added to fleet with fleetID: ",
                          str(fleetID))
                else:
                    newFleet = Fleet(
                        fleetID
                    )  # otherwise create a new fleet w/ that fleetID
                    fm.add(newFleet)
                    newFleet.add(v1)
                    print("New fleet created for vehicle with fleetID: ",
                          str(fleetID))

                v1.start()

                count += 1
        except KeyError as e:
            print("Key could not be found.")

        answer = 0
        print("All Vehicles instantiated")
        while isRunning:
            validAnswer = False
            print("What would you like to do?\n1. Exit ")
            try:
                answer = int(input())
                if answer == 1:
                    validAnswer = True
                else:
                    print("Please select '1' if you would like to exit")
            except ValueError as e:
                print("Error: " + str(e))
            if validAnswer:
                isRunning = False
                killAllThreads(fm)
    # the except catches all keyboard exceptions and shuts down the threads
    except KeyboardInterrupt as e:
        isRunning = False
        killAllThreads(fm)
        print("\n^C received,...")
    finally:
        print("Shutting down the vehicle sim...")
	def test_subsequent_years_tax_for_electric_if_over_40k(self):
		vehicle = Vehicle(206, 'ELECTRIC', self.FIRST_OF_APRIL_2017, 50000)
		self.assertEqual(310, self.tax_calculator.calculate_tax(vehicle))
Пример #29
0
 def setUp(self):
     self.rider = Rider(0, 2, 10, (1, 1), (4, 4), 2)
     self.next_rider = Rider(0, 9, 15, (2, 2), (3, 3), 2)
     self.vehicle = Vehicle(0, 2)
Пример #30
0
 def vehicle_is_abstract_class(self):
     with self.assertRaises(TypeError) as exc:
         Vehicle(20, 5)