示例#1
0
文件: Tracker.py 项目: shl202/CSE252C
 def AddKernel(self, kname, feature):
     if kname == 'linear':
         self.kernels.append(Kernels.LinearKernel())
     elif kname == 'gaussian':
         self.kernels.append(Kernels.GaussianKernel(feature.params[0]))
     elif kname == 'intersection':
         self.kernels.append(Kernels.IntersectionKernel())
     elif kname == 'chi2':
         self.kernels.append(Kernels.Chi2Kernel())
示例#2
0
 def __init__( self, minPt, size, cell_size, kernel_size ):
     '''Constructor
     @param      minPt           A 2-tuple-like object of floats: the minimum x- and y-
                                 position of the grid.
     @param      size            A 2-tuple-like object of floats: the dimsions of the
                                 grid (width, height).
     @param      cell_size       A float; the length of the side of the square grid
                                 cells.
     @param      kernel_size     A float; the "size" of the kernel. '''
     QTGridContext.__init__( self, minPt, size, cell_size )
     self.show_kernel = True
     # TODO: Change this to support different types of kernels (when the GUI supports
     #       different types of kernels).
     # Setting the cell size to kernel size / 3 guarantees three samples per sigma
     self.kernel = Kernels.GaussianKernel( kernel_size, kernel_size / 3)
     self.kernel_data = self.kernel.computeSamples()
示例#3
0
    def execute(self):
        '''Perform the work of the task'''
        if (self.work):
            print 'Density analysis: %s' % (self.workName)
            print "\tAccessing scb file:", self.scbName
            frameSet = NPFrameSet(self.scbName)
            workPath = self.getWorkPath('density')
            tempFile = os.path.join(workPath, self.workName)
            grids = Crowd.GridFileSequence(tempFile)
            if (self.work & AnalysisTask.COMPUTE):
                print "\tComputing"
                kernel = Kernels.GaussianKernel(self.smoothParam,
                                                self.cellSize, False)
                domain = makeDomain(self.domainX, self.domainY, self.cellSize)
                sigDomain = makeDomain(self.domainX, self.domainY)
                signal = Signals.PedestrianSignal(
                    sigDomain
                )  # signal domain is the same as convolution domain

                s = time.clock()
                grids.convolveSignal(domain, kernel, signal, frameSet)
                print '\t\tdone in %.2f seconds' % (time.clock() - s)
            if (self.work & AnalysisTask.VIS):
                dataFile = grids.outFileName + ".density"
                if (not os.path.exists(dataFile)):
                    print "\tCan't visualize density - unable to locate file: %s" % dataFile
                    return
                imageName = os.path.join(workPath,
                                         '%s_density_' % self.workName)
                s = time.clock()
                reader = Crowd.GridFileSequenceReader(dataFile)
                try:
                    colorMap = COLOR_MAPS[self.colorMapName]
                except:
                    print '\tError loading color map: "%s", loading flame instead' % (
                        self.colorMapName)
                    colorMap = COLOR_MAPS['flame']
                print '\tCreating images'
                visualizeGFS(reader, colorMap, imageName, self.outImgType, 1.0,
                             None)
                print '\t\tdone in %.2f seconds' % (time.clock() - s)
示例#4
0
def main():
    """Test the functionality"""
    from math import pi, exp
    import os, sys
    import optparse
    parser = optparse.OptionParser()
    # analysis to perform
    parser.add_option( "-d", "--density", help="Evaluate density.",
                       action="store_true", dest='density', default=False )
    parser.add_option( "-s", "--speed", help="Evaluate speed.",
                       action="store_true", dest='speed', default=False )
    parser.add_option( "-o", "--omega", help="Evaluate omega.",
                       action="store_true", dest='omega', default=False )
    parser.add_option( "-p", "--progress", help="Evaluate progress.",
                       action="store_true", dest='progress', default=False )
    parser.add_option( "-k", "--koshak", help="Evaluate koshak regions.",
                       action="store_true", dest='koshak', default=False )
    parser.add_option( "-i", "--include", help="Include all states",
                       action="store_true", dest='includeAll', default=False )
    # analysis domain - start, frame count, frame step
    parser.add_option( "-r", "--range", help="A triple of numbers: start frame, max frame count, frame step",
                       nargs=3, action="store", dest='domain', type="int", default=(0, -1, 1) )
    options, args = parser.parse_args()

    # input source file
    srcFile = sys.argv[1]
    pygame.init()
    CELL_SIZE = 0.2
    MAX_AGENTS = -1
    MAX_FRAMES = -1
    FRAME_STEP = 1
    FRAME_WINDOW = 1
    START_FRAME = 0
    EXCLUDE_STATES = ()

    START_FRAME, MAX_FRAMES, FRAME_STEP = options.domain
    print "Command line:", START_FRAME, MAX_FRAMES, FRAME_STEP

    if ( True ):
        #increase the color bar specifications
        ColorMap.BAR_HEIGHT = 300
        ColorMap.BAR_WIDTH = 30
        ColorMap.FONT_SIZE = 20

    timeStep = 1.0
    outPath = '.'

    if ( True ):
        # This size doesn't work for 25k
##        size = Vector2( 175.0, 120.0 )
##        minPt = Vector2( -75.0, -60.0 )
        # this size DOES work for 25k
        size = Vector2( 215.0, 160.0 )
        minPt = Vector2( -95.0, -80.0 )
        res = (int( size.x / CELL_SIZE ), int( size.y / CELL_SIZE ) )
        size = Vector2( res[0] * CELL_SIZE, res[1] * CELL_SIZE )
        timeStep = 0.05
        outPath = os.path.join( '/projects','tawaf','sim','jul2011','results' )
        path = os.path.join( outPath, '{0}.scb'.format( srcFile ) )
        print "Reading", path
        outPath = os.path.join( outPath, srcFile )
        if ( not options.includeAll ):
            EXCLUDE_STATES = (1, 2, 3, 4, 5, 6, 7, 8, 9)

    domain = AbstractGrid( minPt, size, res )
    print "Size:", size
    print "minPt:", minPt
    print "res:", res
    timeStep *= FRAME_STEP
    frameSet = FrameSet( path, START_FRAME, MAX_FRAMES, MAX_AGENTS, FRAME_STEP )
    print "Total frames:", frameSet.totalFrames()

    grids = GridFileSequence( os.path.join( outPath, 'junk' ), Vector2(0,3.2), Vector2(-6., 6.))
    colorMap = FlameMap()

    # output the parameters used to create the data
    # todo:

    R = 2.0
    R = 1.5

    def distFunc( dispX, dispY, radiusSqd ):
        """Constant distance function"""
        # This is the local density function provided by Helbing
        # using Gaussian, delta(in the equation) = radiusSqd
        return np.exp( -(dispX * dispX + dispY * dispY) / (2.0 * radiusSqd ) ) / ( 2.0 * np.pi * radiusSqd )

    dfunc = lambda x, y: distFunc( x, y, R * R )

    if ( options.density ):
        if ( not os.path.exists( os.path.join( outPath, 'dense' ) ) ):
            os.makedirs( os.path.join( outPath, 'dense' ) )

        print "\tComputing density with R = %f" % R
        s = time.clock()
        kernel = Kernels.GaussianKernel( R, CELL_SIZE, False )
        signal = Signals.PedestrianSignal( domain ) # signal domain is the same as convolution domain
        grids.convolveSignal( domain, kernel, signal, frameSet )
        print "\t\tTotal computation time: ", (time.clock() - s), "seconds"
        print "\tComputing density images",
        s = time.clock()
        imageName = os.path.join( outPath, 'dense', 'dense' )
        reader = GridFileSequenceReader( grids.outFileName + ".density"  )
        visualizeGFS( reader, colorMap, imageName, 'png', 1.0, grids.obstacles )
        print "Took", (time.clock() - s), "seconds"

    if ( options.speed ):
        if ( not os.path.exists( os.path.join( outPath, 'speed' ) ) ):
            os.makedirs( os.path.join( outPath, 'speed' ) )

        print "\tComputing speeds",
        s = time.clock()
        stats = grids.computeSpeeds( minPt, size, res, R, frameSet, timeStep, EXCLUDE_STATES, GridFileSequence.BLIT_SPEED )
        stats.write( os.path.join( outPath, 'speed', 'stat.txt' ) )
        stats.savePlot( os.path.join( outPath, 'speed', 'stat.png' ), 'Average speed per step' )
        print "Took", (time.clock() - s), "seconds"
        print "\tComputing speed images",
        s = time.clock()
        imageName = os.path.join( outPath, 'speed', 'speed' )
        # the limit: 0.5 means the color map is saturated from from minVal to 50% of the range
        reader = GridFileSequenceReader( grids.outFileName + ".speed"  )
        visualizeGFS( reader, colorMap, imageName, 'png', 0.75, grids.obstacles )
        print "Took", (time.clock() - s), "seconds"

    if ( options.omega ):
        if ( not os.path.exists( os.path.join( outPath, 'omega' ) ) ):
            os.makedirs( os.path.join( outPath, 'omega' ) )

        print "\tComputing omega",
        s = time.clock()
        stats = grids.computeAngularSpeeds( minPt, size, res, R, frameSet, timeStep, EXCLUDE_STATES, GridFileSequence.BLIT_SPEED, FRAME_WINDOW )
        stats.write( os.path.join( outPath, 'omega', 'stat.txt' ) )
        stats.savePlot( os.path.join( outPath, 'omega', 'stat.png'), 'Average radial velocity per step' )
        print "Took", (time.clock() - s), "seconds"
        print "\tComputing omega images",
        s = time.clock()
        imageName = os.path.join( outPath, 'omega', 'omega' )
        colorMap = RedBlueMap()

        reader = GridFileSequenceReader( grids.outFileName + ".omega"  )
        visualizeGFS( reader, colorMap, imageName, 'png', 1.0, grids.obstacles )

        print "Took", (time.clock() - s), "seconds"

    if ( options.progress ):
        if ( not os.path.exists( os.path.join( outPath, 'progress' ) ) ):
            os.makedirs( os.path.join( outPath, 'progress' ) )

        print "\tComputing progress",
        s = time.clock()
        stats = grids.computeProgress( minPt, size, res, R, frameSet, timeStep, EXCLUDE_STATES, FRAME_WINDOW )
        stats.write( os.path.join( outPath, 'progress', 'stat.txt' ) )
        stats.savePlot( os.path.join( outPath, 'progress', 'stat.png'), 'Average progress around Kaabah' )
        print "Took", (time.clock() - s), "seconds"
        print "\tComputing progress images",
        s = time.clock()
        imageName = os.path.join( outPath, 'progress', 'progress' )
        colorMap = FlameMap( (0.0, 1.0) )
        reader = GridFileSequenceReader( grids.outFileName + ".progress"  )
        visualizeGFS( reader, colorMap, imageName, 'png', 1.0, grids.obstacles )
        print "Took", (time.clock() - s), "seconds"

    if ( False ):
        if ( not os.path.exists( os.path.join( outPath, 'advec' ) ) ):
            os.makedirs( os.path.join( outPath, 'advec' ) )

        lines = [ Segment( Vector2(0.81592, 5.12050), Vector2( 0.96233, -5.27461) ) ]
        print "\tComputing advection",
        s = time.clock()
        grids.computeAdvecFlow( minPt, size, res, dfunc, 3.0, R, frameSet, lines )
        print "Took", (time.clock() - s), "seconds"
        print "\tComputing advection images",
        s = time.clock()
        imageName = os.path.join( outPath, 'advec', 'advec' )
        reader = GridFileSequenceReader( grids.outFileName + ".advec"  )
        visualizeGFS( reader, colorMap, imageName, 'png', 1.0, grids.obstacles )
        print "Took", (time.clock() - s), "seconds"

    if ( options.koshak ):
        if ( not os.path.exists( os.path.join( outPath, 'regionSpeed' ) ) ):
            os.makedirs( os.path.join( outPath, 'regionSpeed' ) )
        print "\tComputing region speeds"
        s = time.clock()
        vertices = ( Vector2( -0.551530, 0.792406 ),
                     Vector2( 3.736435, -58.246524 ),
                     Vector2( 42.376927, -56.160723 ),
                     Vector2( 5.681046, -6.353232 ),
                     Vector2( 92.823337, -4.904953 ),
                     Vector2( 5.376837, 6.823865 ),
                     Vector2( 92.526405, 9.199321 ),
                     Vector2( 88.517822, -48.850902 ),
                     Vector2( 6.416100, 53.293737 ),
                     Vector2( -5.906582, 6.230001 ),
                     Vector2( -6.203514, 53.739135 ),
                     Vector2( 62.833196, 57.896184 ),
                     Vector2( 93.268736, 43.643444 ),
                     Vector2( -41.686899, -61.322050 ),
                     Vector2( -74.794826, -25.838665 ),
                     Vector2( -75.388691, 49.582085 )
                     )
        vIDs = ( (0, 3, 4, 6, 5),
                 (5, 6, 12, 11, 8),
                 (5, 8, 10, 9, 0),
                 (0, 9, 10, 15, 14, 13),
                 (0, 13, 1),
                 (0, 1, 2, 3),
                 (3, 2, 7, 4)
                 )
        polygons = []

        for ids in vIDs:
            p = Polygon()
            p.closed = True
            for id in ids:
                p.vertices.append( vertices[id] )
            polygons.append( p )
        grids.computeRegionSpeed( frameSet, polygons, timeStep, EXCLUDE_STATES )
        print "Took", (time.clock() - s), "seconds"
        # output image
        imagePath = os.path.join( outPath, 'regionSpeed', 'region' )
        colorMap = TwoToneHSVMap( (0, 0.63, 0.96), (100, 0.53, 0.75 ) )
        regionSpeedImages( grids.outFileName + ".region", imagePath, polygons, colorMap, minPt, size, res )

    if ( False ):
        # flow lines
        if ( not os.path.exists( os.path.join( outPath, 'flow' ) ) ):
            os.makedirs( os.path.join( outPath, 'flow' ) )

        lines = ( Segment( Vector2( 4.56230, -7.71608 ), Vector2( 81.49586, -4.55443  ) ),
                  Segment( Vector2( 5.08924, 5.72094 ), Vector2( 82.28628, 8.61913  ) ),
                  Segment( Vector2( 3.50842, 8.09218 ), Vector2( 2.71800, 51.30145  ) ),
                  Segment( Vector2( -5.97654, 5.72094 ), Vector2( -8.87472, 51.56492  ) ),
                  Segment( Vector2( -6.50348, -7.18914 ), Vector2(  -40.75473, -53.56005 ) ),
                  Segment( Vector2( -1.23406, -6.92567 ), Vector2( 1.13718, -51.18881  ) ),
                  Segment( Vector2( 3.50842, -7.45261 ), Vector2( 44.08297, -45.65592 ) ) )
        flow = computeFlowLines( Vector2( 0, 0 ), lines, frameSet )
        flowFile = os.path.join( outPath, 'flow', 'flow.txt' )
        file = open( flowFile, 'w' )
        flow.write( file )
        file.close()

    if ( False ):
        # Traces
        print "Rendering traces"
        s = time.clock()
        grids.renderTraces( minPt, size, res, frameSet, 5, 5, 'data/trace11_' )
        print "Took", (time.clock() - s), "seconds"
示例#5
0
PATH = 'ktest'
if ( not os.path.exists( PATH ) ):
    os.makedirs( PATH )

cMap = BlackBodyMap()
CELL_SIZE = 0.03125 #0.05
smoothParam = 1.5

REFLECT = True
obst, bb = obstacles.readObstacles( '/projects/crowd/fund_diag/paper/pre_density/experiment/Inputs/Corridor_onewayDB/c240_obstacles.xml')
obstSet = ObstacleHandler.ObjectHandler( obst )
##kernel = Kernels.UniformKernel( smoothParam, CELL_SIZE, REFLECT )
##kernel = Kernels.TriangleKernel( smoothParam / 1.1, CELL_SIZE, REFLECT )
##kernel = Kernels.BiweightKernel( smoothParam / 1.2, CELL_SIZE, REFLECT )
kernel = Kernels.GaussianKernel( smoothParam / 3.0, CELL_SIZE, REFLECT )
##kernel = Kernels.Plaue11Kernel( smoothParam, CELL_SIZE, REFLECT, obstSet )
      
def syntheticPedestrians( SIZE ):
    '''Produce a set of fake pedestrian trajectories.

    @param      SIZE        The size of the origin-centered simulation domain.
    @returns    An Nx2xM numpy array with N pedestrians over M frames and
                    The number of steps in the trajectory.
    '''
    STEP_COUNT = 15
    traj = np.empty( (3, 2, STEP_COUNT ), dtype=np.float32 )
    # ped 1 - moves bottom left to top center
    start = -SIZE * 0.5 + 0.1
    end = 0
    x = np.linspace( start, end, STEP_COUNT )