예제 #1
0
 def i():
     first = input("Enter an equation for the first function: ")
     second = input("Enter an equation for the second function: ")
     from Intersection import Intersection
     f = Intersection(first, second)
     f.printFunction()
     return f
예제 #2
0
    def parse_input(self, filename):
        with open(filename, 'r') as file:
            solution = None
            cars = []
            streets = {}
            intersections = {}
            for i, line in enumerate(file.readlines()):
                if i == 0:
                    [D, I, S, V, F] = line.strip().split(' ')
                    solution = Solution(int(D), I, S, V, F)
                elif i <= int(S):
                    # processing streets
                    [start, end, name, length] = line.strip().split(' ')

                    if start not in intersections:
                        intersections[start] = Intersection(start)
                    if end not in intersections:
                        intersections[end] = Intersection(end)
                    street = Street(name, length, intersections[start],
                                    intersections[end])
                    streets[street.name] = street

                    intersections[end].add_incoming(street)
                    intersections[start].add_outgoing(street)

                else:
                    # processing cars
                    street_names = line.strip().split(' ')[1:]
                    car_streets = [
                        streets[street_name] for street_name in street_names
                    ]
                    cars.append(Car(car_streets))

        return solution, cars, streets, intersections
예제 #3
0
 def local_intersects(self, ray):
     # Incoming ray is now in object space already
     # the vector from the sphere's center, to the ray origin
     # remember: the sphere is centered at the world origin
     sphere_to_ray = ray.origin - Tuple4.Point(0, 0, 0)
     a = ray.direction.dot(ray.direction)
     b = 2 * ray.direction.dot(sphere_to_ray)
     c = sphere_to_ray.dot(sphere_to_ray) - 1
     discriminant = math.pow(b, 2) - 4 * a * c
     if discriminant < 0:
         return Intersections()
     t1 = (-b - math.sqrt(discriminant)) / (2 * a)
     t2 = (-b + math.sqrt(discriminant)) / (2 * a)
     # Intersections are a scalar and an object, so we don't need to
     # transform them back to world space
     return Intersections(Intersection(t1, self), Intersection(t2, self))
예제 #4
0
def create_environment():
	game = Intersection(length=length, prob = prob, keepalive = keepalive, wait_weight=wait_weight)

	idle = [1,0,0]
	waitNS = [0,1,0]
	waitEW = [0, 0,1]
	possible_actions = [idle, waitNS, waitEW]

	return game, possible_actions
def findIntersections(streamNetwork, numReaches):
    arcpy.AddMessage("Finding intersections...")

    intersections = []
    points = AVLPointsTree()
    reqReachLength = 50

    polylineCursor = arcpy.da.SearchCursor(streamNetwork, ["SHAPE@"])

    row = polylineCursor.next()
    currentStream = row[0]
    if currentStream.length > reqReachLength:
        points.addNode(currentStream.lastPoint, currentStream)

    previousStream = currentStream

    for i in range(numReaches - 1):
        """If the current stream has a point that """
        row = polylineCursor.next()
        currentStream = row[0]
        pointInTree = points.findPoint(currentStream.lastPoint)
        continuousStreams = pointsAreEqual(previousStream.lastPoint,
                                           currentStream.firstPoint, .01)
        if pointInTree is not None:
            if currentStream.length < reqReachLength and continuousStreams:  # If the stream is really short, we want to use the stream before it if possible, to get a better DA value
                intersections.append(
                    Intersection(currentStream.lastPoint, currentStream,
                                 pointInTree.stream))
            else:
                intersections.append(
                    Intersection(currentStream.lastPoint, currentStream,
                                 pointInTree.stream))
        else:
            if currentStream.length < reqReachLength and continuousStreams:
                points.addNode(currentStream.lastPoint, currentStream)
            else:
                points.addNode(currentStream.lastPoint, currentStream)

        previousStream = currentStream
    del row, polylineCursor
    arcpy.AddMessage("Intersections found")

    return intersections
예제 #6
0
 def local_intersects(self, ray):
     # Incoming ray is now in object space already
     # If the ray is parallel to the plane (y = 0), there
     # is no intersection
     if maths.equals(ray.direction.y, 0):
         return Intersections()
     else:
         # Otherwise, the ray is intersecting from above
         # or below
         t = -ray.origin.y / ray.direction.y
         return Intersections(Intersection(t, self))
예제 #7
0
    def color_at(self, r):
        """
        tieing up the intersect(), shade_hit(), and prepare_computations() functions for convenience's sake
        """
        # getting all the hits in total
        total_junctions = self.intersect_world(r)
        first = True
        if len(total_junctions) > 0:
            for hit in total_junctions:
                if hit['time'] >= 0 and first == True:
                    i = Intersection(hit['time'], hit['object'])
                    first = False

        if first == True or len(total_junctions) == 0:
            return color(0, 0, 0)

        comps = i.prepare_computations(r)

        # call shade_hit() to return the color at that specific point
        COL = self.shade_hit(comps)
        return COL
예제 #8
0
파일: Sphere.py 프로젝트: chang02/graphics
 def getIntersection(self, ray):
     ocVector = ray.origin - self.center
     a = Vector.dot(ray.direction, ray.direction)
     b = Vector.dot(ocVector, ray.direction) * 2
     c = Vector.dot(ocVector, ocVector) - (self.radius * self.radius)
     discriminant = (b * b) - (4 * a * c)
     if discriminant < 0:
         return None
     else:
         t = (-b - math.sqrt(discriminant)) / (2.0 * a)
         t2 = (-b + math.sqrt(discriminant)) / (2.0 * a)
         if t > 0.0001:
             return Intersection(
                 ray.origin + ray.direction * t, t,
                 self.normal(ray.origin + ray.direction * t), self)
         elif t2 > 0.0001:
             return Intersection(
                 ray.origin + ray.direction * t2, t2,
                 self.normal(ray.origin + ray.direction * t2), self)
         else:
             return None
예제 #9
0
    def __init__(self):

        border = BoundaryLane()
        self.intersectionArray = N.array(
            ([Intersection(),
              Intersection()], [Intersection(), Intersection()]))

        #self.intersectionArray[0][0] = Intersection()
        #self.intersectionArray[0][1] = Intersection()
        #self.intersectionArray[1][0] = Intersection()
        #self.intersectionArray[1][1] = Intersection()

        #intersection top left
        self.intersectionArray[0,0].setAdjacents([border,border,self.intersectionArray[1,0].southLanes[1]\
                                                 ,self.intersectionArray[1,0].southLanes[0],\
                                                 self.intersectionArray[0,1].eastLanes[1],\
                                                 self.intersectionArray[0,1].eastLanes[0],border,border])
        #intersection top right
        self.intersectionArray[0,1].setAdjacents([border,border,self.intersectionArray[1,1].southLanes[1],\
                                                 self.intersectionArray[1,1].southLanes[0],border,border,\
                                                 self.intersectionArray[0,0].westLanes[1],\
                                                 self.intersectionArray[0,0].westLanes[1]])
        #intersection bottom left
        self.intersectionArray[1,0].setAdjacents([self.intersectionArray[0,0].northLanes[1]\
                                                 ,self.intersectionArray[0,0].northLanes[1],border,\
                                                 border,self.intersectionArray[1,1].eastLanes[1],\
                                                 self.intersectionArray[1,1].eastLanes[0],border,border])
        #intersection bottom right
        self.intersectionArray[1,1].setAdjacents([self.intersectionArray[0,1].northLanes[1],\
                                                 self.intersectionArray[0,1].northLanes[0],border,\
                                                 border,border,border,self.intersectionArray[1,0].westLanes[1],\
                                                 self.intersectionArray[1,0].westLanes[1]])
        """
        create four intersection objects and make
        clear which ones are adjacent to which.
        
        have each intersection adjacent to the 
        boundary.
        """
        self.timeWithinBoundary = []
예제 #10
0
def simulation(gui):
    # Initialize instance of intersection
    currIntersection = Intersection(length=40, wid=40, posX=490, posY=490)

    for i in range(0, len(carList)):
        carList[i].displayCar()

    elapsedTime = 0  # initialize time in seconds
    runSim = True  # bool to stop simulation

    # Begin simulation:
    while (runSim):

        # Remove processed cars from the intersection list
        # cleanList(carList, gui)

        # Check to see if we should end simulation
        if (elapsedTime > values.simluationTime):
            runSim = False  # if time condition is true runSim to false
        elapsedTime += values.timeInterval  # increment 100 mili second

        # Check if cars are in intersection range
        currIntersection.updateIntersectionQueues(carList, elapsedTime, gui)
        # Restore speeds
        currIntersection.restoreVelocities(carList)
        # Check for possible collisions
        Calculations.collisionDetection(currIntersection.queueX,
                                        currIntersection.queueY, gui)

        # Update the positions of the cars in the list
        for i in range(0, len(carList)):
            # THIRD update position
            carList[i].updatePosition(values.timeInterval)

        # Update the GUI positions
        gui.moveCars(carList, values.timeInterval)

        # Every seconds generate new cars
        '''
        if(elapsedTime % values.carGenerationModulo is 0):
            rndCar = randint(1, 2)
            if(rndCar == 1):
                # Generate one car
                newCar = randomCarGenerator(gui, False, 0)
                carList.append(newCar)
            elif(rndCar == 2):
                # Genereate two cars
                for i in range(1, 3):
                    newCar = randomCarGenerator(gui, True, i)
                    carList.append(newCar)
        '''
        if (elapsedTime % values.carGenerationModulo is 0):
            # Generate two cars
            for i in range(1, 3):
                newCar = randomCarGenerator(gui, True, i)
                carList.append(newCar)

        time.sleep(.01)

    print len(carList)
예제 #11
0
    def __init__(self):
        AlgorithmProvider.__init__(self)
        self.alglist = [SumLines(), PointsInPolygon(),
                        PointsInPolygonWeighted(), PointsInPolygonUnique(),
                        BasicStatisticsStrings(), BasicStatisticsNumbers(),
                        NearestNeighbourAnalysis(), MeanCoords(),
                        LinesIntersection(), UniqueValues(), PointDistance(),
                        ReprojectLayer(), ExportGeometryInfo(), Centroids(),
                        Delaunay(), VoronoiPolygons(), SimplifyGeometries(),
                        DensifyGeometries(), DensifyGeometriesInterval(),
                        MultipartToSingleparts(), SinglePartsToMultiparts(),
                        PolygonsToLines(), LinesToPolygons(), ExtractNodes(),
                        Eliminate(), ConvexHull(), FixedDistanceBuffer(),
                        VariableDistanceBuffer(), Dissolve(), Difference(),
                        Intersection(), Union(), Clip(), ExtentFromLayer(),
                        RandomSelection(), RandomSelectionWithinSubsets(),
                        SelectByLocation(), RandomExtract(),
                        RandomExtractWithinSubsets(), ExtractByLocation(),
                        SpatialJoin(), RegularPoints(), SymetricalDifference(),
                        VectorSplit(), VectorGrid(), DeleteColumn(),
                        DeleteDuplicateGeometries(), TextToFloat(),
                        ExtractByAttribute(), SelectByAttribute(), Grid(),
                        Gridify(), HubDistance(), HubLines(), Merge(),
                        GeometryConvert(), AddTableField(), FieldsCalculator(),
                        SaveSelectedFeatures(), JoinAttributes(),
                        AutoincrementalField(), Explode(), FieldsPyculator(),
                        EquivalentNumField(), PointsLayerFromTable(),
                        StatisticsByCategories(), ConcaveHull(), Polygonize(),
                        RasterLayerStatistics(), PointsDisplacement(),
                        ZonalStatistics(), PointsFromPolygons(),
                        PointsFromLines(), RandomPointsExtent(),
                        RandomPointsLayer(), RandomPointsPolygonsFixed(),
                        RandomPointsPolygonsVariable(),
                        RandomPointsAlongLines(), PointsToPaths(),
                        PostGISExecuteSQL(), ImportIntoPostGIS(),
                        SetVectorStyle(), SetRasterStyle(),
                        SelectByExpression(), HypsometricCurves(),
                        # ------ raster ------
                        # CreateConstantRaster(),
                        # ------ graphics ------
                        # VectorLayerHistogram(), VectorLayerScatterplot(),
                        # RasterLayerHistogram(), MeanAndStdDevPlot(),
                        # BarPlot(), PolarPlot()
                       ]

        folder = os.path.join(os.path.dirname(__file__), 'scripts')
        scripts = ScriptUtils.loadFromFolder(folder)
        for script in scripts:
            script.allowEdit = False
        self.alglist.extend(scripts)
        for alg in self.alglist:
            alg._icon = self._icon
예제 #12
0
 def StartGameBoard(self):
     for i in range(rows):
         objectRow = []
         row = []
         row2 = []
         for j in range(cols):
             x = int(i * boxWidth + (boxWidth/2))
             y = int(j * boxWidth + (boxWidth/2))
             intersection = Intersection(x, y, boxWidth, stoneRadius)
             objectRow.append(intersection)
             row.append(0)
             row2.append(1)
         self.objectGameBoard.append(objectRow)
예제 #13
0
def main():
    d = CarDespawner()
    s1 = CarSpawner(0.5, [d])
    s2 = CarSpawner(0.5, [d])
    inter = Intersection()
    lane1 = Lane(5, s1, None, inter, Direction.SOUTH)
    lane2 = Lane(5, s2, None, inter, Direction.WEST)
    lane3 = Lane(5, inter, Direction.NORTH, d, None)

    for i in range(100):
        d.update()
        lane1.update()
        lane2.update()
        lane3.update()
        inter.update()
        s1.update()
        s2.update()
        print(lane3, end=" ||| ")
        print(inter, end=" ||| ")
        print(lane1)
        print(" " * 51, end="")
        print(lane2)
        print("-" * 100)
예제 #14
0
 def getIntersection(self, ray):
     dot = Vector.dot(self.normal, ray.direction)
     if abs(dot) < 0.0001:
         return None
     else:
         difference = self.point - ray.origin
         t = Vector.dot(difference, self.normal) / dot
         if t > 0.0001:
             point = ray.origin + ray.direction * t
             if self.minxyz.x <= point.x <= self.maxxyz.x and self.minxyz.y <= point.y <= self.maxxyz.y and self.minxyz.z <= point.z <= self.maxxyz.z:
                 return Intersection(point, t, self.normal, self)
             else:
                 return None
         else:
             return None
예제 #15
0
    def run(self, net_data, args, exp_replay, neural_network, eps, rl_stats):
        ###for batch vehicle data, faster than API calls
        data_constants = [
            traci.constants.VAR_SPEED, traci.constants.VAR_POSITION,
            traci.constants.VAR_LANE_ID, traci.constants.VAR_LANE_INDEX
        ]
        self.vehicles = Vehicles(self.conn, data_constants, net_data,
                                 self.sim_len, args.demand, args.scale)

        ###create some intersections
        intersections = [
            Intersection(_id, args.tsc, self.conn, args, net_data['tsc'][_id],
                         exp_replay[_id], neural_network[_id], eps,
                         rl_stats[_id], self.vehicles.get_edge_delay)
            for _id in self.conn.trafficlight.getIDList()
        ]

        print('start running sumo sim on port ' + str(self.port))
        while self.t < self.sim_len:
            ###loop thru tsc intersections
            ###run and pass v_data
            lane_vehicles = self.vehicles.run()
            for i in intersections:
                i.run(lane_vehicles)
            self.step()

        if args.mode == 'train':
            ###write travel time mean to csv for graphing after training
            self.write_csv(
                str(eps) + '.csv',
                np.mean([
                    self.vehicles.travel_times[v]
                    for v in self.vehicles.travel_times
                ]))
        '''
        if eps < 0.1:
        #    #print('--- SIM FINISHED -- '+str(eps)+' average tt '+str(np.mean([self.vehicles.travel_times[v] for v in self.vehicles.travel_times])) +' std tt '+str(np.std([self.vehicles.travel_times[v] for v in self.vehicles.travel_times]))   )
            self.write_csv('hpresults.csv', np.mean([self.vehicles.travel_times[v] for v in self.vehicles.travel_times]) )

        '''
        #self.write_csv(str(eps)+'.csv', np.sum([i.tsc.rewards for i in intersections]) )
        #print('-------______TT -------------')
        #print(np.mean([self.vehicles.travel_times[v] for v in self.vehicles.travel_times]))

        print('finished running sumo sim on port ' + str(self.port))
        self.cleanup()
def simulation(gui):
    # Initialize instance of intersection
    currIntersection = Intersection(length=40,
                                    wid=40,
                                    posX=490,
                                    posY=490,
                                    gui=gui)
    generate_physical_test_cars(gui)

    elapsedTime = 0  # initialize time in seconds
    runSim = True  # bool to stop simulation

    # Begin simulation:
    while (runSim):

        # Remove processed cars rom the intersection list
        # cleanList(carList, gui, currIntersection)

        # Check to see if we should end simulation
        if (elapsedTime > values.simluationTime):
            runSim = False  # if time condition is true runSim to false
        elapsedTime += values.timeInterval  # increment 100 mili second

        # Update the intersection containers and values
        update_intersection(currIntersection, elapsedTime)

        # Check if this is a conventional simulation
        if (values.conventionalSimFlag):
            run_conventional(currIntersection, gui)

        # Check if this is an optimized simulation
        else:
            run_optimized(currIntersection, gui, values.carList)

        # Update the positions of the cars
        update_positions(gui)

        # Sleep the while loop with custom spinlock.
        now = time.time()
        while (time.time() - now <= (0.01)):
            pass

    generate_statistics()
예제 #17
0
    def __init__(self):
        AlgorithmProvider.__init__(self)
        self._icon = QIcon(os.path.join(pluginPath, 'images', 'qgis.png'))

        self.alglist = [
            SumLines(),
            PointsInPolygon(),
            PointsInPolygonWeighted(),
            PointsInPolygonUnique(),
            BasicStatisticsStrings(),
            BasicStatisticsNumbers(),
            NearestNeighbourAnalysis(),
            MeanCoords(),
            LinesIntersection(),
            UniqueValues(),
            PointDistance(),
            ReprojectLayer(),
            ExportGeometryInfo(),
            Centroids(),
            Delaunay(),
            VoronoiPolygons(),
            SimplifyGeometries(),
            DensifyGeometries(),
            DensifyGeometriesInterval(),
            MultipartToSingleparts(),
            SinglePartsToMultiparts(),
            PolygonsToLines(),
            LinesToPolygons(),
            ExtractNodes(),
            Eliminate(),
            ConvexHull(),
            FixedDistanceBuffer(),
            VariableDistanceBuffer(),
            Dissolve(),
            Difference(),
            Intersection(),
            Union(),
            Clip(),
            ExtentFromLayer(),
            RandomSelection(),
            RandomSelectionWithinSubsets(),
            SelectByLocation(),
            RandomExtract(),
            DeleteHoles(),
            RandomExtractWithinSubsets(),
            ExtractByLocation(),
            SpatialJoin(),
            RegularPoints(),
            SymmetricalDifference(),
            VectorSplit(),
            VectorGrid(),
            DeleteColumn(),
            DeleteDuplicateGeometries(),
            TextToFloat(),
            ExtractByAttribute(),
            SelectByAttribute(),
            Grid(),
            Gridify(),
            HubDistance(),
            HubLines(),
            Merge(),
            GeometryConvert(),
            AddTableField(),
            FieldsCalculator(),
            SaveSelectedFeatures(),
            JoinAttributes(),
            AutoincrementalField(),
            Explode(),
            FieldsPyculator(),
            EquivalentNumField(),
            PointsLayerFromTable(),
            StatisticsByCategories(),
            ConcaveHull(),
            RasterLayerStatistics(),
            PointsDisplacement(),
            ZonalStatistics(),
            PointsFromPolygons(),
            PointsFromLines(),
            RandomPointsExtent(),
            RandomPointsLayer(),
            RandomPointsPolygonsFixed(),
            RandomPointsPolygonsVariable(),
            RandomPointsAlongLines(),
            PointsToPaths(),
            PostGISExecuteSQL(),
            ImportIntoPostGIS(),
            SetVectorStyle(),
            SetRasterStyle(),
            SelectByExpression(),
            HypsometricCurves(),
            SplitLinesWithLines(),
            CreateConstantRaster(),
            FieldsMapper(),
            SelectByAttributeSum(),
            Datasources2Vrt(),
            CheckValidity(),
            OrientedMinimumBoundingBox(),
            Smooth(),
            ReverseLineDirection()
        ]

        if hasMatplotlib:
            from VectorLayerHistogram import VectorLayerHistogram
            from RasterLayerHistogram import RasterLayerHistogram
            from VectorLayerScatterplot import VectorLayerScatterplot
            from MeanAndStdDevPlot import MeanAndStdDevPlot
            from BarPlot import BarPlot
            from PolarPlot import PolarPlot

            self.alglist.extend([
                VectorLayerHistogram(),
                RasterLayerHistogram(),
                VectorLayerScatterplot(),
                MeanAndStdDevPlot(),
                BarPlot(),
                PolarPlot(),
            ])

        if hasShapely:
            from Polygonize import Polygonize
            self.alglist.extend([Polygonize()])

        if QGis.QGIS_VERSION_INT >= 21400:
            from ExecuteSQL import ExecuteSQL
            self.alglist.extend([ExecuteSQL()])

        folder = os.path.join(os.path.dirname(__file__), 'scripts')
        scripts = ScriptUtils.loadFromFolder(folder)
        for script in scripts:
            script.allowEdit = False
        self.alglist.extend(scripts)
        for alg in self.alglist:
            alg._icon = self._icon
예제 #18
0
def _intersection(self, name1, t, name2):
    setattr(world, name1, Intersection(float(t), getattr(world, name2)))
예제 #19
0
    # w = world()
    # w.set_light(point_light(point(0, 0, -10), color(1, 1, 1)))
    # s1 = sphere()
    # w.add_object(s1)
    # s2 = sphere(transform_within=translation(0, 0, 10))
    # w.add_object(s2)
    # r = ray(point(0, 0, 5), vector(0, 0, 1))
    # i = Intersection(4, s2)
    # comps = i.prepare_computations(r)
    # c = w.shade_hit(comps)
    # print(c.red, c.green, c.blue)

    r = ray(point(0, 0, -5), vector(0, 0, 1))
    shape = sphere()
    shape.transform_within = translation(0, 0, 1)
    i = Intersection(5, shape)
    comps = i.prepare_computations(r)
    print(comps['over_point'].val[2] < -EPSILON / 2)
    print(comps['point'].val[2] > comps['over_point'].val[2])

#     w = default_world()
#     p = point(10, -10, 10)
#     result = w.is_shadowed(p)
#     print(result)
# w.set_light(point_light(point(0, 0.25, 0), color(1, 1, 1)))
# r = ray(point(0, 0, 0), vector(0, 0, 1))
# i = Intersection(0.5, w.items[1])
# comps = i.prepare_computations(r)
# c = w.shade_hit(comps)
# print(c)
예제 #20
0
def main():

    pygame.init()
    # setup
    with open("colors.json") as f:
        text = f.read()
        colors = json.loads(text)

    wWidth = 800
    wHeight = 800
    w = pygame.display.set_mode((wWidth, wHeight))

    width = 30

    streetH = Street((0, wHeight // 2), (wWidth, wHeight // 2), 4, 2, 1,
                     wWidth // 2)
    streetV = Street((wWidth // 2, 0), (wWidth // 2, wHeight), 3, 3, 1,
                     wHeight // 2)

    intersection = Intersection(streetH, streetV)

    cars = []
    carsWaiting = []  # cars that aren't past the intersection yet

    waitTime = 10
    time = 0
    timeAbsolute = 0
    carDensity = 1.2
    running = True
    simulating = True  #whether we're in th options menu or not
    typing = False  #whether we're typing or not
    intersection.changeToCycle(intersection.hgreenCycle)
    vProb = 0.5
    densityLightAlgorithm = True
    options = Options(streetH.numPos, streetH.numNeg, streetH.numLeftOnly,
                      streetV.numPos, streetV.numNeg, streetV.numLeftOnly,
                      carDensity, 10 / waitTime, vProb, densityLightAlgorithm)
    carsPassed = 0
    carsPassedQueue = deque([0] * 500)
    flowRate = 0
    avgFlowRate = 0

    carRects = []
    while running:
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                return

            if e.type == pygame.KEYDOWN:
                if typing:
                    if e.key == pygame.K_RETURN:
                        typing = False
                        options.typing = False
                    elif e.key == pygame.K_BACKSPACE:
                        options.index[options.currentIndex] = options.index[
                            options.currentIndex][:-1]
                    else:
                        if options.currentIndex < 6:
                            if options.index[options.currentIndex] == '':
                                options.index[
                                    options.currentIndex] += e.unicode
                        else:
                            options.index[options.currentIndex] += e.unicode
                else:
                    if e.key == pygame.K_ESCAPE:
                        if not simulating:
                            waitTime = int(round(10 / float(options.index[7])))
                            carDensity = np.math.log(
                                float(options.index[6]) + 1) + 1
                        simulating = not simulating
                    if e.key == pygame.K_r:
                        streetH = Street((0, wHeight // 2),
                                         (wWidth, wHeight // 2),
                                         int(options.index[0]),
                                         int(options.index[1]),
                                         int(options.index[2]), wWidth // 2)
                        streetV = Street((wWidth // 2, 0),
                                         (wWidth // 2, wHeight),
                                         int(options.index[3]),
                                         int(options.index[4]),
                                         int(options.index[5]), wHeight // 2)
                        intersection = Intersection(streetH, streetV)
                        waitTime = int(round(10 / float(options.index[7])))
                        carDensity = float(options.index[6])
                        cars = []
                        time = 0
                        timeAbsolute = 0
                        carsPassed = 0
                        carsPassedQueue = deque([0] * 500)
                        simulating = True

            if not simulating:
                if e.type == pygame.MOUSEBUTTONDOWN:
                    for box in options.inputBoxes:
                        if box.collidepoint(e.pos):
                            if options.inputBoxes.index(box) == 9:
                                densityLightAlgorithm = not densityLightAlgorithm
                                options.index[9] = densityLightAlgorithm
                            else:
                                typing = True
                                options.typing = True
                                options.currentBox = box
                                options.currentIndex = options.inputBoxes.index(
                                    box)
                                options.flashTimer = 0

        if time > intersection.totalCycleLength:
            time = 0
        intersection.changeCycle(time)

        time += 1
        if timeAbsolute != 0:
            timeAbsolute += 1

        if simulating:

            if time > intersection.totalCycleLength:
                time = 0
            intersection.changeCycle(time)
            time += 1

            if np.random.rand() > 1 / carDensity:
                vProb = float(options.index[8])
                street = np.random.choice((streetV, streetH),
                                          p=(vProb, 1 - vProb))
                carLane = street.lanes[np.random.randint(0, len(street.lanes))]
                carColor = np.random.choice(Car.COLORS)
                car = Car(carLane,
                          intersection,
                          carColor,
                          desiredSpeed=np.random.normal(1.35, 0.1))
                if not car.hitBox.collidelistall(
                        carRects
                ):  # Making sure the cars don't overlap when spawned
                    cars.append(car)
                    carLane.cars.append(car)
                    carsWaiting.append(car)

            w.fill(colors["green"])
            for l in streetH.lanes:
                l.draw(w)
            for l in streetV.lanes:
                l.draw(w)

            streetH.drawLines(w)
            streetV.drawLines(w)

            intersection.draw(w)
            carRects = []
            for car in cars:
                carRects.append(car.rect)

            for i, car in enumerate(cars):
                if not car.isTurningLeft:
                    collisionIdxs = car.hitBox.collidelistall(carRects)
                    if collisionIdxs != [i]:
                        collisionIdxs.remove(i)
                        if len(collisionIdxs) > 1:
                            # TODO: better way to handle this?
                            #print("multiple collisions detected")
                            cheese = 0
                        else:
                            if car.speed != 0:
                                car.speed = cars[collisionIdxs[0]].speed * 0.7

            for c in cars:
                c.move(carRects)
                c.draw(w, showHitbox=False)

                if c.distance >= c.lane.length + 10 * c.LENGTH:
                    if c in c.lane.cars:
                        c.lane.cars.remove(c)
                    cars.remove(c)
                    carsPassed += 1
                    if timeAbsolute == 0:
                        timeAbsolute += 1

                if c.rect.colliderect(intersection.rect):
                    if c in c.lane.cars:
                        c.lane.cars.remove(c)
                    if c in carsWaiting:
                        carsWaiting.remove(c)

            numCarsInGreen = 0
            numGreenLanes = 0
            for light in intersection.lights:
                light[0].draw(w)
                if light[0].color == "green":
                    numGreenLanes += 1
                    numCarsInGreen += len(light[0].lane.cars)

            # if the density algorithm is on, and the density of cars with green ahead is less than 20% the density of cars
            # waiting overall, and there are at least 6 cars, and it's been green for at least 2 seconds, then switch
            if densityLightAlgorithm and numCarsInGreen * (
                    streetH.numLanes + streetV.numLanes
            ) < 0.2 * numGreenLanes * len(carsWaiting) and len(
                    cars
            ) >= 6 and time - intersection.trafficFlow[
                    intersection.cycleNumber - 1][1] * constants.SECOND > 200:
                time = intersection.abruptChangeCycle()

            carsPassedQueue.appendleft(carsPassed)
            flowRate = carsPassed - carsPassedQueue.pop()
            avgFlowRate = 500 * carsPassed / (timeAbsolute + 1)
            if timeAbsolute < 100:
                Options.text(w, "Flow Rate: n/a", 20, 20, 20)
                Options.text(w, "Average Flow Rate: n/a", 20, 70, 20)
            else:
                Options.text(w, "Current Flow Rate: " + str(flowRate), 20, 20,
                             20)
                Options.text(
                    w, "Average Flow Rate: " + str(round(avgFlowRate, 1)), 20,
                    70, 20)

            Options.text(w, "ESC for options", 550, 20, 20)
            Options.text(w, "R to reset", 550, 70, 20)

            pygame.display.flip()
            pygame.time.wait(waitTime)

        else:
            options.draw(w)

            pygame.display.flip()
            pygame.time.wait(waitTime)
예제 #21
0
def intersect(blank, tool):
    from Intersection import Intersection
    return Intersection(blank, tool)
예제 #22
0
파일: classic.py 프로젝트: piratos/ITS
ln, ls, le, lw = Lane("north"), Lane("south"), Lane("east"), Lane("west")
lanes = [le, lw, ln, ls]
lanes = {
    "east": le,
    "west": lw,
    "north": ln,
    "south": ls,
}
#initiate variables
lane_data = {
    "east": 0,
    "west": 0,
    "north": 0,
    "south": 0,
}
inter = Intersection("Intersection 1")
inter.attach(lanes)
lights = {
    (0, 30): "rrrrggggrrrrgggg",
    (30, 60): "ggggrrrrggggrrrr",
}


def run():
    global lanes, vec_sum, lane_data, intersection, lights
    traci.init(PORT)
    step = 0
    data_count = inter.cycle
    while step < MAX_STEP:
        traci.simulationStep()
        data = dict(
예제 #23
0
파일: tlsrun.py 프로젝트: piratos/ITS
    show(p)


########################################################
table = PrettyTable(["Step", "from_east", "from_west", "from_north", "from_south"])
lane_table = PrettyTable(["Lane", "Q length", "Awt"])
lanevar_table = PrettyTable(["Lane", "Tin", "Tout"])
data = {"east": 0, "west": 0, "north": 0, "south": 0}

# initiate lanes' objects
ln, ls, le, lw = Lane("north"), Lane("south"), Lane("east"), Lane("west")
lanes = [le, lw, ln, ls]
lanes = {"east": le, "west": lw, "north": ln, "south": ls}
# initiate variables
lane_data = {"east": 0, "west": 0, "north": 0, "south": 0}
inter = Intersection("Intersection 1")
inter.attach(lanes)
lights = {(0, 30): "rrrrggggrrrrgggg", (30, 60): "ggggrrrrggggrrrr"}


def run():
    global lanes, vec_sum, lane_data, intersection, lights
    traci.init(PORT)
    step = 0
    data_count = inter.cycle
    while step < MAX_STEP:
        traci.simulationStep()
        data = dict(
            zip(
                [key for key in ["east", "west", "north", "south"]],
                [value for value in [numberv(i) for i in lanes_id()]],
예제 #24
0
import math

#keep track of time
ts = time.time()

#make the toward lanes and the away lanes
toward = []
for i in range(7):
    toward.append(Lane(10,1))

away = []
for i in range(4):
    away.append(Lane(10,-1))

#make the intersection
I = Intersection(toward, away)

#store the networks' througputs and wait times
#gets cleared every epoch
throughs = []
waits = []

#stores average throughs and waits for all the generations
avg_throughs = []
avg_waits = []

#stores the best throughput and the best wait time for all the generations
best_throughs = []
best_waits = []

#store the best neural networks
예제 #25
0
def main():
    #CHANGE THESE FLAGS TO CONTROL THE EXPERIMENT

    VIZ = False  # Set to True for visualization
    USE_ROUNDABOUT = True  # Set to True to use roundabout
    PAUSE = 0.1  # time (in sec) between each update, if VIZ is True
    MAX_TIME = 1000000
    SEED = 0
    SPAWN_PROB = 0.1

    row, col = 2, 2
    stat = Stats()

    # grid of intersection/roundabout
    if USE_ROUNDABOUT:
        matrix = [[Roundabout(1) for j in range(col)] for i in range(row)]
    else:
        matrix = [[Intersection() for j in range(col)] for i in range(row)]

    despawns = [CarDespawner(stat) for i in range(row * 4)]
    spawns = [CarSpawner(stat, SPAWN_PROB, despawns) for i in range(col * 4)]

    # connect lanes
    baseLaneLen = 10
    lanes = []

    # spawn/despawn lanes first
    lanes.append(
        Lane(baseLaneLen, spawns[0], None, matrix[0][0], Direction.NORTH))
    lanes.append(
        Lane(baseLaneLen, spawns[1], None, matrix[0][1], Direction.NORTH))
    lanes.append(
        Lane(baseLaneLen, spawns[2], None, matrix[0][1], Direction.EAST))
    lanes.append(
        Lane(baseLaneLen, spawns[3], None, matrix[1][1], Direction.EAST))
    lanes.append(
        Lane(baseLaneLen, spawns[4], None, matrix[1][1], Direction.SOUTH))
    lanes.append(
        Lane(baseLaneLen, spawns[5], None, matrix[1][0], Direction.SOUTH))
    lanes.append(
        Lane(baseLaneLen, spawns[6], None, matrix[1][0], Direction.WEST))
    lanes.append(
        Lane(baseLaneLen, spawns[7], None, matrix[0][0], Direction.WEST))

    lanes.append(
        Lane(baseLaneLen, matrix[0][0], Direction.NORTH, despawns[0], None))
    lanes.append(
        Lane(baseLaneLen, matrix[0][1], Direction.NORTH, despawns[1], None))
    lanes.append(
        Lane(baseLaneLen, matrix[0][1], Direction.EAST, despawns[2], None))
    lanes.append(
        Lane(baseLaneLen, matrix[1][1], Direction.EAST, despawns[3], None))
    lanes.append(
        Lane(baseLaneLen, matrix[1][1], Direction.SOUTH, despawns[4], None))
    lanes.append(
        Lane(baseLaneLen, matrix[1][0], Direction.SOUTH, despawns[5], None))
    lanes.append(
        Lane(baseLaneLen, matrix[1][0], Direction.WEST, despawns[6], None))
    lanes.append(
        Lane(baseLaneLen, matrix[0][0], Direction.WEST, despawns[7], None))

    # always order endpoints as northern node, southern node OR
    #                           western node, eastern node
    connect(lanes, matrix, baseLaneLen, 0, 0, 0, 1)
    connect(lanes, matrix, baseLaneLen, 0, 0, 1, 0)
    connect(lanes, matrix, baseLaneLen, 0, 1, 1, 1)
    connect(lanes, matrix, baseLaneLen, 1, 0, 1, 1)

    if VIZ:
        root = Tk()
        viz = Viz(matrix, lanes, baseLaneLen, root)

    random.seed(SEED)
    for x in range(MAX_TIME):
        for i in range(len(matrix)):
            for j in range(len(matrix[0])):
                if matrix[i][j]:
                    matrix[i][j].update()

        for lane in lanes:
            lane.update()

        for spawn in spawns:
            spawn.update()

        stat.cur_time += 1

        # Then update viz
        if VIZ:
            viz.update()
            time.sleep(PAUSE)

    print(len(stat.car_times))
    print(sum(stat.car_times) / len(stat.car_times))
    print(stat.n_rejected)

    # Close window to terminate
    if VIZ:
        root.mainloop()
예제 #26
0
from Intersection import Intersection
from GUI import GUI

length = 5
prob = 0.5
keepalive = -1
wait_weight = 0.5

state_size = 2 * (length + 2)
action_size = 3

if __name__ == '__main__':
    game = Intersection(length=length,
                        prob=prob,
                        keepalive=keepalive,
                        wait_weight=wait_weight)
    window = GUI(50)

    window.update(game.getState())

    while not game.gameEnd():
        text = raw_input("Input (0 is for nothing, 1 is for NS, 2 is for EW: ")
        stepReward = 0
        if (int(text) == 0):
            stepReward = game.step(0, 0)
        elif (int(text) == 1):
            stepReward = game.step(1, 0)
        else:
            stepReward = game.step(0, 1)

        print("Step Reward: ", stepReward)
def simulation(gui):
    # Initialize instance of intersection
    currIntersection_1 = Intersection(length=40,
                                      wid=40,
                                      posX=490,
                                      posY=200,
                                      gui=gui)
    currIntersection_2 = Intersection(length=40,
                                      wid=40,
                                      posX=1020,
                                      posY=500,
                                      gui=gui)
    currIntersection_3 = Intersection(length=40,
                                      wid=40,
                                      posX=1020,
                                      posY=200,
                                      gui=gui)
    currIntersection_4 = Intersection(length=40,
                                      wid=40,
                                      posX=490,
                                      posY=500,
                                      gui=gui)
    IntersectionList.append(currIntersection_1)
    IntersectionList.append(currIntersection_2)
    IntersectionList.append(currIntersection_3)
    IntersectionList.append(currIntersection_4)

    for i in range(len(IntersectionList)):
        gui.drawIndicationLines(IntersectionList[i])

    elapsedTime = 0  # initialize time in seconds
    runSim = True  # bool to stop simulation

    # Begin simulation:
    while (runSim):

        gui.update()

        # Determine what kind of simulation we're running
        if (gui.CheckVar.get() == 1):
            values.conventionalSimFlag = True
        else:
            values.conventionalSimFlag = False

        # Remove processed cars from the intersection list
        for i in range(len(IntersectionList)):
            cleanList(carList, gui, IntersectionList[i])

        # Check to see if we should end simulation
        """
        if(elapsedTime > values.simluationTime):
            runSim = False
        """                              # if time condition is true runSim to false
        elapsedTime += values.timeInterval  # increment 100 mili second

        # Update the intersection containers and values
        for i in range(len(IntersectionList)):
            update_intersection(IntersectionList[i], elapsedTime)

        # Check if this is a conventional simulation
        if (values.conventionalSimFlag):
            for i in range(len(IntersectionList)):
                # thread.start_new_thread(run_conventional, (IntersectionList[i], gui))
                run_conventional(IntersectionList[i], gui)
                # interThread = IntersectionThread.interThread(IntersectionList[i],)

        # Check if this is an optimized simulation
        else:
            interThreads = []
            for i in range(len(IntersectionList)):
                # run_opt = thread.__init__(run_optimized, (IntersectionList[i], gui, carList))
                # run_opt.start()
                # interThreads.append(run_opt)
                # interThread = IntersectionThread.InterThread(IntersectionList[i], gui, carList)
                # interThread.start()
                # interThreads.append(interThread)
                run_optimized(IntersectionList[i], gui, carList)
            '''
            for i in range(len(interThreads)):
                interThreads[i].join()
            '''

            # interThreads.clear()

        # Update the positions of the cars
        update_positions(gui)

        # Generate new cars
        generate_cars(gui, elapsedTime)

        # Call server communications
        # server_send_packet()

        # Sleep the while loop
        time.sleep(.01)

    generate_statistics()