def rk4(f, h, n, x0, t0): t = [t0] for j in range(n - 1): t.append(t[j] + h) numCars = len(x0.lanes[0]) cars = [[[Car(pos=0, vel=0, c="b") for _ in range(len(x0.lanes[0]))] for _ in range(n)] for _ in range(len(x0.lanes))] for i, lane in enumerate(x0.lanes): cars[i][0] = lane # Iteration Loop for i in range(1, n): for lane in range(len(x0.lanes)): # Move leading car forward at constant speed leadingCar = cars[lane][i - 1][0] cars[lane][i][ 0].position = leadingCar.position + leadingCar.velocity * h cars[lane][i][0].velocity = leadingCar.velocity cars[lane][i][0].length = leadingCar.length # Move other cars forward using RK4 with IDM for j in range(1, numCars): c = cars[lane][i - 1][j] c1 = cars[lane][i - 1][j - 1] k1 = f(c, c1, t[i - 1]) tempC = map(add, [c.position, c.velocity], [h / 2.0 * el for el in k1]) c = Car(pos=tempC[0], vel=tempC[1], c=c.color) k2 = f(c, c1, t[i - 1] + h / 2.0) tempC = map(add, [c.position, c.velocity], [h / 2.0 * el for el in k2]) c = Car(pos=tempC[0], vel=tempC[1], c=c.color) k3 = f(c, c1, t[i - 1] + h / 2.0) tempC = map(add, [c.position, c.velocity], [h * el for el in k3]) c = Car(pos=tempC[0], vel=tempC[1], c=c.color) k4 = f(c, c1, t[i - 1] + h) k2 = [2.0 * el for el in k2] k3 = [2.0 * el for el in k3] step = [h / 6.0 * el for el in (map(sum, zip(k1, k2, k3, k4)))] temp = map(add, [ cars[lane][i - 1][j].position, cars[lane][i - 1][j].velocity ], step) cars[lane][i][j].position = temp[0] cars[lane][i][j].velocity = temp[1] return cars, t
def example(): car = Car("PBD-7541") car.canBeOnRoad("04-03-2018", "09:35") car.canBeOnRoad("05-03-2018", "08:07") car2 = Car("PBI-7055") car2.canBeOnRoad("05-03-2018", "08:07") car2.canBeOnRoad("07-03-2018", "17:45")
def create_vehicle(self, vehicle_type): if vehicle_type == "Машина": self.order_vehicle(vehicle_type) return Car() elif vehicle_type == "Велосипед": self.order_vehicle(vehicle_type) return Bike()
def __init__(self, num_cars, screen, center): pygame.sprite.Sprite.__init__(self) initial_vel = 200. self.center_of_circle = center self.radius = 200 self.cars = [ Car(KeyBoardController(), None, None, initial_position=self.center_of_circle + self.radius * np.array([ np.cos(2 * np.pi * i / num_cars), np.sin(2 * np.pi * i / num_cars) ]), initial_heading=2 * np.pi * i / (num_cars) + np.pi / 2, initial_velocity=initial_vel) for i in range(num_cars) ] for car in self.cars: car.steering_angle = 0.01 self.cars_viz = [ Vehicle_Visual(self.cars[i], screen, "green_car.png" if i == 0 else "red_car.png") for i in range(num_cars) ]
def test(self, **kwargs): func = kwargs['function'] if func == 'create_parking_lot': get_parking_lot(kwargs["slot_count"]) return elif func == 'assign_vehicle_slot': lot = get_parking_lot(3) ret = lot.assign_vehicle_slot( Car(kwargs["vehicle_reg_no"], kwargs["vehicle_color"])) elif func == 'release_vehicle': lot = get_parking_lot(3) ret = lot.release_vehicle(kwargs['slot_number']) elif func == 'slot_numbers_for_cars_with_colour': lot = get_parking_lot(3) ret = lot.slot_numbers_for_cars_with_colour( kwargs['vehicle_color']) print "success output:%s" % ret return elif func == 'slot_number_for_registration_number': lot = get_parking_lot(3) ret = lot.slot_number_for_registration_number( kwargs['vehicle_reg_no']) print "success output:%s" % ret return elif func == 'registration_numbers_for_cars_with_colour': lot = get_parking_lot(3) ret = lot.registration_numbers_for_cars_with_colour( kwargs['vehicle_color']) print "success output:%s" % ret return if ret != kwargs['Expected Answer']: print "Expected Answer is %s, got %s" % (kwargs['Expected Answer'], ret) else: print "success"
def create_vehicle(self, vehicle_type): if vehicle_type == "Car": self.order_vehicle(vehicle_type) return Car() elif vehicle_type == "Bike": self.order_vehicle(vehicle_type) return Bike()
def rk4(f, x, x1, t, h): try: k1 = f(x, x1, t) tempC = map(add, [x.position, x.velocity], [h / 2.0 * el for el in k1]) c = Car(pos=tempC[0], vel=tempC[1], c=x.color) k2 = f(c, x1, t + h / 2.0) tempC = map(add, [c.position, c.velocity], [h / 2.0 * el for el in k2]) c = Car(pos=tempC[0], vel=tempC[1], c=c.color) k3 = f(c, x1, t + h / 2.0) tempC = map(add, [c.position, c.velocity], [h * el for el in k3]) c = Car(pos=tempC[0], vel=tempC[1], c=c.color) k4 = f(c, x1, t + h) k2 = [2.0 * el for el in k2] k3 = [2.0 * el for el in k3] step = [h / 6.0 * el for el in (map(sum, zip(k1, k2, k3, k4)))] if step[1] >= -1 * bsafe: return step else: return [None, None] except: return [None, None]
def park(self, arg): reg_number = arg[0] color = arg[1] vehicle = Car() vehicle.set_registration(reg_number) vehicle.set_color(color) parking_slot_available = self.get_next_available() if parking_slot_available is False: print("Sorry, parking lot is full") else: is_parked = parking_slot_available.park_vehicle(vehicle) if is_parked: try: slot_popped = heapq.heappop(self.slots_available) v_color = slot_popped.parked_car.get_color() v_reg_number = slot_popped.parked_car.get_registration() v_slot = slot_popped.parking_slot_id try: self.slots_occupied["reg_numbers"][ v_reg_number] = slot_popped if v_color not in self.slots_occupied["colors"]: self.slots_occupied["colors"][v_color] = set() self.slots_occupied["colors"][v_color].add(slot_popped) self.slots_occupied["slots"][v_slot] = slot_popped except KeyError: print("Error in finding the values!") except Exception as e: print(e) print("Error in occupying slot!") print("Allocated slot number: {}".format(v_slot)) except IndexError: print("Error in parking")
def __init__(self, num_cars, screen, center): pygame.sprite.Sprite.__init__(self) initial_vel = np.array((200., 0)) self.center_of_circle = center self.radius = 200 desired_distance = self.radius * 2 * np.pi / num_cars self.cars = [ Car(CircularPlatoonController(npl.norm(initial_vel), desired_distance, self.center_of_circle, self.radius, None), None, None, initial_position=self.center_of_circle + self.radius * np.array([ np.cos(2 * np.pi * i / num_cars), np.sin(2 * np.pi * i / num_cars) ]), initial_heading=2 * np.pi * i / (num_cars) + np.pi / 2, initial_velocity=initial_vel) for i in range(num_cars) ] steering_angle = 0.01 for i in range(0, len(self.cars) - 1): car = self.cars[i] car.steering_angle = steering_angle car.controller.next_car = self.cars[i + 1] self.cars[-1].controller.next_car = self.cars[0] self.cars[-1].steering_angle = steering_angle self.cars_viz = [ Vehicle_Visual(self.cars[i], screen, "green_car.png" if i == 0 else "red_car.png") for i in range(num_cars) ]
def run_cmd(self, line): args = line.split(" ") cmd = args[0] if cmd == "create_parking_lot": self.lot = ParkingLot(args[1]) return "Created a parking lot with %s slots"%args[1] if not self.lot: raise Exception("Parking Lot is not created") if cmd == "park": return self.lot.assign_vehicle_slot(Car(args[1], args[2])) if cmd == "leave": return self.lot.release_vehicle(args[1]) if cmd == "status": return self.lot.get_status() if cmd == "registration_numbers_for_cars_with_colour": return self.lot.registration_numbers_for_cars_with_colour(args[1]) if cmd == "slot_number_for_registration_number": return self.lot.slot_number_for_registration_number(args[1]) if cmd == "slot_numbers_for_cars_with_colour": return self.lot.slot_numbers_for_cars_with_colour(args[1]) return "cmd %s is not valid"%cmd
class TestCar(TestCase): def setUp(self): self.car = Car("PBD-7541") def test_canBeOnRoad_weekend(self): self.assertTrue(self.car.canBeOnRoad("04-03-2018", "8:30")) self.assertTrue(self.car.canBeOnRoad("03-03-2018", "8:30")) def test_canBeOnRoad_weekday_morning(self): self.assertTrue(self.car.canBeOnRoad("05-03-2018", "9:45")) def test_canBeOnRoad_weekday_afternoon(self): self.assertTrue(self.car.canBeOnRoad("05-03-2018", "15:00")) def test_canBeOnRoad_weekday(self): self.assertTrue(self.car.canBeOnRoad("07-03-2018", "9:45")) def test_cannotBeOnRoad_weekday_morning(self): self.assertFalse(self.car.canBeOnRoad("05-03-2018", "08:45")) def test_cannotBeOnRoad_weekday_afternoon(self): self.assertFalse(self.car.canBeOnRoad("05-03-2018", "18:00")) def test_canBeOnRoad_invalid_date_time(self): self.assertRaises(ValueError, self.car.canBeOnRoad, "date", "time") def test_canBeOnRoad_invalid_date(self): self.assertRaises(ValueError, self.car.canBeOnRoad, "date", "8:30") def test_canBeOnRoad_invalid_time(self): self.assertRaises(FormatError, self.car.canBeOnRoad, "05-03-2018", "time") def test_canBeOnRoad_invalid_date_format(self): self.assertRaises(ValueError, self.car.canBeOnRoad, "03/03/2018", "8:30") def test_canBeOnRoad_invalid_time_format(self): self.assertRaises(FormatError, self.car.canBeOnRoad, "05-03-2018", "8h30")
def populate_west(self): if random.randint(0, 20) == 0: self.west.enqueue(Car())
def populate_north(self): if random.randint(0, 9) == 0: self.north.enqueue(Car())
time = 0 light = "green" while time < 3600: self.populate_north() self.populate_west() if time % 10 == 0: if light == "green": light = "red" else: light = "green" if light == "green": self.north.dequeue() time += 1 s = Simulation() s.north.enqueue(Car()) s.north.enqueue(Car()) s.north.enqueue(Car()) s.north.enqueue(Car()) s.north.enqueue(Car()) s.north.enqueue(Car()) s.north.enqueue(Car()) s.north.enqueue(Car()) s.north.enqueue(Car()) s.north.enqueue(Car()) print(s.north.size()) s.process_north() print(s.north.size())
background_perfect = pygame.Surface(screen.get_size()) background_perfect.fill((0, 0, 0)) dt = 0.1 # loop til done done = False clock = pygame.time.Clock() controller = KeyBoardController() center = np.array((screen_width / 2., screen_height / 2)) pm = 300 vel = 200 steering_angle = 0.007 car1 = Car(controller, None, None, initial_velocity=(vel, 0), initial_position=center + np.array([-pm, 0.])) car2 = Car(controller, None, None, initial_velocity=(vel, 0), initial_position=center + np.array([pm, 0.])) car3 = Car(controller, None, None, initial_velocity=(vel, 0), initial_position=center + np.array([0., -pm])) car4 = Car(controller, None, None,
def setUp(self): self.car = Car("PBD-7541")
cars[lane][i][j].position = temp[0] cars[lane][i][j].velocity = temp[1] return cars, t lanes = [] for lane in range(3): lanes.append([]) for pos in drange(0, 10000, 50): if pos == 0: v = v0 else: v = v0 + random.uniform(-10, 10) p = pos + random.uniform(0, 0) c = Car(pos=-1 * p, vel=v, c="blue") lanes[lane].append(c) lanes[0][0].velocity = 33.0 lanes[1][0].velocity = 33.0 lanes[2][0].velocity = 33.0 road = Road(lanes) data, t = rk4(IDM, delT, iterations, road, 0.0) ''' vs = [] for iteration in data[0]: velocities = [] for car in iteration: velocities.append(car.velocity) vs.append(sum(velocities)/float(len(iteration)))
def test_get_type_of_vehicle(): car_vehicle = Car("toyota", 1, "red", curr_time) assert car_vehicle.get_type() == "Car"
from Vehicle import Car """ Pico y placa predictor program that can be run on command line """ if __name__ == "__main__": plate = input("Enter plate number: ") date = input("Enter date: ") time = input("Enter time: ") car = Car(plate) car.canBeOnRoad(date, time)
def generate_trajectory(f, h, n, x0, t0): # SETUP num_lanes = len(x0) t = [t0] for j in range(n - 1): t.append(t[j] + h) cars = [[[Car(pos=0, vel=0, c="b") for _ in range(len(x0[0]))] for _ in range(n)] for _ in range(len(x0))] for i, lane in enumerate(x0): cars[i][0] = lane print "Generating Trajectory..." widgets = [ 'Percent Done: ', Percentage(), ' ', AnimatedMarker(), ' ', ETA() ] bar = ProgressBar(widgets=widgets, maxval=n).start() # Iteration Loop for i in range(1, n): bar.update(i) # DETERMINE WHICH CARS SWITCH laneChanges = [] for l, car in enumerate([el[i - 1][0] for el in cars]): cars[l][i][0].position = car.position cars[l][i][0].velocity = car.velocity for j in range(1, max_num_cars([el[i - 1] for el in cars])): for lane in range(num_lanes): if j < len(cars[lane][i - 1]): if j < len(cars[lane][i]): cars[lane][i][j].position = cars[lane][i - 1][j].position cars[lane][i][j].velocity = cars[lane][i - 1][j].velocity else: cars[lane][i].append( Car(pos=cars[lane][i - 1][j].position, vel=cars[lane][i - 1][j].velocity, c=cars[lane][i - 1][j].color)) c = cars[lane][i][j] c_leading = cars[lane][i][j - 1] nn = nearest_neighbor(cars, lane, i - 1, c) if nn != None: # Calculate Incentive anprime = rk4(f, nn[0], c, t[i - 1], h)[1] if anprime != None and anprime >= -1 * bsafe: acprime = rk4(f, c, cars[nn[2]][i - 1][nn[1] - 1], t[i - 1], h)[1] ac = rk4(f, c, c_leading, t[i], h)[1] an = rk4(f, cars[nn[2]][i - 1][nn[1]], cars[nn[2]][i - 1][nn[1] - 1], t[i - 1], h)[1] if acprime != None and ac != None and an != None: if j < len(cars[lane][i - 1]) - 1: c_following = cars[lane][i - 1][j + 1] aoprime = rk4(f, c_following, c_leading, t[i - 1], h)[1] ao = rk4(f, c_following, c, t[i], h)[1] else: aoprime = 0.0 ao = 0.0 if aoprime != None and ao != None: incentive = (acprime - ac) + polite * ( (anprime - an) + (aoprime - ao)) if incentive > ath: alreadyMovedTo = False for change in laneChanges: if change["car_to"] == nn[0]: alreadyMovedTo = True if alreadyMovedTo == False: laneChanges.append({ "lane_from": lane, "lane_to": nn[2], "car_to": nn[0], "car": c }) # Make changes for change in laneChanges: for k, CAR in enumerate(cars[change["lane_to"]][i]): if CAR == change["car_to"]: cars[change["lane_to"]][i].insert(k, change["car"]) for x, C in enumerate(cars[change["lane_from"]][i]): if C == change["car"]: del cars[change["lane_from"]][i][x] break # Removes Cars with pos = 0, vel = 0 for l, lane in enumerate([el[i] for el in cars]): cars[l][i] = [ c for c in cars[l][i] if c != Car(pos=0.0, vel=0.0, c=c.color) ] # MOVE CARS FORWARD for lane in range(num_lanes): numCars = len(cars[lane][i]) # Move leading car forward at constant speed leadingCar = cars[lane][i][0] cars[lane][i][ 0].position = leadingCar.position + leadingCar.velocity * h cars[lane][i][0].velocity = leadingCar.velocity cars[lane][i][0].length = leadingCar.length # Move other cars forward using RK4 with IDM for j in range(1, numCars): c = cars[lane][i][j] c_leading = cars[lane][i][j - 1] step = rk4(f, c, c_leading, t[i - 1], h) if step != [None, None]: if step[1] + cars[lane][i][j].velocity <= SL: if j < len(cars[lane][i]): cars[lane][i][j].position += step[0] cars[lane][i][j].velocity += step[1] else: p = cars[lane][i][j].position + step[0] v = cars[lane][i][j].velocity + step[1] cars[lane][i].append(Car(p, v, c.color)) bar.finish() return cars, t
from Vehicle import Vehicle from Vehicle import Car from Vehicle import Handicap from parkingSpace import parkingSpots car1 = Car(123) handicapped1 = Handicap(234) handicapped2 = Handicap(34) p = parkingSpots() p.park(car1) p.park(handicapped1) p.park(handicapped2)