示例#1
0
 def __init__(self, gen):
     #generators       
     self.__gen = gen
     
     #points
     labels = self.__gen.get_lod_zero_lb()
     points = self.__gen.get_lod_zero_pt()
     
     self.__base_points = pt.PointSet(labels, points)
     self.__curr_points = pt.PointSet(labels, points)
      
     #dims will be used for LODs and imits
     dimspan = range(0, self.__base_points.dims() )
     all_dims = [ (did, did) for did in dimspan ]
     
     #LODs
     lod_objs = [0 for did in all_dims]
     
     self.__lod = mst.MdimStruct(lod_objs, all_dims)
     
     #Limits - start
     it_base = self.__base_points.get_labels().__iter__('ND')
     
     start_objs = deep( it_base.nd_index() )
     
     self.__curr_abs_start = mst.MdimStruct(start_objs, all_dims)
         
     #Limits - end
     it_base.set_last()
         
     end_objs = deep( it_base.nd_index() )
     
     self.__curr_abs_end = mst.MdimStruct(end_objs, all_dims)
             
     return
示例#2
0
    def __init__(self, objs, dims):

        self.__objs = deep(objs)

        self.__dims = deep(dims)

        return
def select_starting_tile():
    global TILEMAP, TILEPOSITIONS, IMAGE
    #p("selecting starting tile...")
    for id in TILES:
        if not debug and part2:
            id = "3643"  # <------------ hard coded solution for part 2
        start_tile = TILES[id]

        pp(id, "trying this tile as starting", True)
        for variation in tile_variations(start_tile):
            #p("--trying variation")
            TILEMAP = deep(TILEMAP_clear)
            TILEPOSITIONS = deep(TILEPOSITIONS_clear)
            TILEMAP[0][0] = id
            IMAGE[0][0] = variation
            TILEPOSITIONS[id] = [0, 0]
            #ppp(TILEMAP, "current tilemap")

            if iterate_tilemap():
                #p("Sucess iterating")
                return True
                break
            else:
                pass

    #p("Didn't work with ANY starting tile")
    return False
示例#4
0
 def testHeatVec(self):
     
     codmP2d = deep(self.codmP2d)
     domain = deep(self.dmP2d)
     
     sigvec = sp.cdmvec(codmP2d.fcval_at, domain)[1]
     
     vw.plot_heatvec(domain, sigvec, md = 'cartes')
     
     return
示例#5
0
    def replace(self, rhs, dst_dims, src_offs=0):

        new_objs = []
        new_dims = []

        #Before selected region
        lim = dst_dims[0]

        dst_did = 0
        while (dst_did < lim):

            curr_dst_dims = self.get_dims(dst_did)
            dst_fcid = self.get_objid(curr_dst_dims)

            new_dims.append(curr_dst_dims)
            new_objs.append(deep(self.__objs[dst_fcid]))

            dst_did += ((curr_dst_dims[1] + 1) - curr_dst_dims[0])

        lim = (dst_dims[1] + 1) - dst_dims[0] + src_offs

        #Selected region
        src_did = src_offs
        while (src_did < lim):

            curr_src_dims = rhs.get_dims(src_did)
            src_fcid = rhs.get_objid(curr_src_dims)

            curr_new_dims = (curr_src_dims[0] - src_offs + dst_dims[0],
                             curr_src_dims[1] - src_offs + dst_dims[0])

            new_dims.append(curr_new_dims)
            new_objs.append(deep(rhs.__objs[src_fcid]))

            src_did += ((curr_src_dims[1] + 1) - curr_src_dims[0])

        lim = self.last_did() + 1

        #After selected region
        dst_did = dst_dims[1] + 1
        while (dst_did < lim):

            curr_dst_dims = self.get_dims(dst_did)
            dst_fcid = self.get_objid(curr_dst_dims)

            new_dims.append(curr_dst_dims)
            new_objs.append(deep(self.__objs[dst_fcid]))

            dst_did += ((curr_dst_dims[1] + 1) - curr_dst_dims[0])

        #set new lists
        self.__dims = deep(new_dims)
        self.__objs = deep(new_objs)

        return
示例#6
0
 def measure_at(self, inds):
     
     bounds = deep(self.bounds)
     
     for end in bounds.get_end():
     
         bounds.set_curr(0, [0, end[1] + 1], end[0][0] )
     
     vol = self.volume
     
     res = deep( self.measure.measure_at(vol, bounds, inds) )
     
     return res
示例#7
0
    def __init__(self, labels, coeffs, bsgens):

        self.labels = deep(labels)

        #coefficients of base functions
        self.coeffs = deep(
            coeffs)  #Can be simple array, as product/replace etc.
        #is not supported for Signals.

        self.bsgens = deep(bsgens)  #Generator object that maps a base
        #function to a given multidim. label.

        return
示例#8
0
 def __init__(self, samps = None,
              bounds = None,
              volume = None,
              measure = None,
              is_eq = True,
              bandlims = None):
     
     #TODO: remove this member
     self.is_eq = is_eq
     
     if samps is None:
     
         self.samps = gd.Grid()
         self.bounds = gd.Grid()
     
     else:
     
         self.samps = samps
         self.bounds = bounds
     
     self.ns = self.samps.get_curr_cards()
     
     if volume is None:
         
         self.volume = vol.Volume()
     
     else:
         
         self.volume = volume
     
     if measure is None:
         
         self.measure = ms.Measure()
     
     else:
     
         self.measure = measure
          
     
     if bandlims is None:
         
         bounds = deep(self.bounds)
         
         self.bandlims = deep(bounds.get_lims() )
         
     else:
         
         self.bandlims = deep(bandlims)
         
     return
示例#9
0
 def volume_at(self, inds):
     
     bounds = self.bounds
     
     res = deep( self.volume.at(bounds, inds) )
     
     return res
示例#10
0
 def reactiveCallback(self, move):
     if self.state is 'Reactive':
         liftState = self.movement.lift
         self.movement = Movement()
         self.movement = deep(move)
         self.movement.mag = 1
         self.movement.lift = liftState
示例#11
0
 def ballCleanerCallback(self, move):
     if self.state is 'BallCleaner':
         liftState = self.movement.lift
         self.movement = Movement()
         self.movement = deep(move)
         self.movement.mag = 1
         self.movement.lift = liftState
示例#12
0
    def bound_points(self, par, new_bounds, lod, rpoints, loc_did):

        res_points = None

        res_points = deep(rpoints)

        return res_points
示例#13
0
 def visualServoCallback(self, move):
     if self.state is 'VisualServo':
         liftState = self.movement.lift
         self.movement = Movement()
         self.movement = deep(move)
         self.movement.mag = 1
         self.movement.lift = liftState
示例#14
0
 def mappingCallback(self, move):
     if self.state is 'Mapper':
         liftState = self.movement.lift
         self.movement = Movement()
         self.movement = deep(move)
         self.movement.mag = 1
         self.movement.lift = liftState
示例#15
0
def plotHeatMap(heat, color, axisOff, show, save, resize, resCo):
	#create copy of data
	heat = deep(heat)
	
	figure = plot.figure() #get window canvas
	figure.canvas.set_window_title('Heat Map') #set title
	
	#optional parameter
	#to remove padding
	if axisOff:
		ax = plot.Axes(figure, [0., 0., 1., 1.])
		ax.set_axis_off() #remove other axes
		figure.add_axes(ax) #add new, fake axis

	#interpolation nearest makes the heat map discrete without gradient
	if axisOff: plot.imshow(mat(heat), cmap = color, interpolation = 'nearest', aspect = 'normal')
	else: plot.imshow(mat(heat), cmap = color, interpolation = 'nearest') #normal aspect setting
	
	if show: plot.show() #show the stuff out to the screen
	if save: plot.savefig(getTestSave() + '/' + color + '.png')
	
	#calculate tuple to resize the grayscale image
	res = (len(heat[0]) * resCo, len(heat) * resCo)
	
	#if OpenCV image
	if resize == True:
		image = Image.open(getTestSave() + '/' + color + '.png') #open
		image = image.resize(res, Image.NEAREST) #resize image to scale
		image.save(getTestSave() + '/' + color + '.png') #resave to file
	
	#close plot
	plot.close()
示例#16
0
 def triangleCallback(self, move):
     if self.state is 'Triangle':
         liftState = self.movement.lift
         self.movement = Movement()
         self.movement = deep(move)
         self.movement.mag = 1
         self.movement.lift = liftState
示例#17
0
 def tangentBugCallback(self, move):
     if self.state is 'TangentBug':
         liftState = self.movement.lift
         self.movement = Movement()
         self.movement = deep(move)
         self.movement.mag = 1
         self.movement.lift = liftState
示例#18
0
    def add(self, rhs):

        res = None

        labels = deep(self.labels)

        coeffs = deep(self.coeffs)

        bsgens = deep(self.bsgens)

        for bsinds in labels:

            coeffs[bsinds] += rhs.coeffs[bsinds]

        res = Signal(labels, coeffs, bsgens)

        return res
示例#19
0
    def scmult(self, sc):

        res = None

        labels = deep(self.labels)

        coeffs = deep(self.coeffs)

        bsgens = deep(self.bsgens)

        for bsinds in labels:

            coeffs[bsinds] *= sc

        res = Signal(labels, coeffs, bsgens)

        return res
示例#20
0
def enumerate(sofar,remaining,count,total_list,fixed):
	if count == 0:
		new_tuple = tuple(deep(sofar))
		total_list.append(new_tuple)
		return  
	elif len(remaining) < count:
		return 
	else:
		rest = deep(remaining[:])
		for ind in range(len(remaining)):
			item = remaining[ind]
			rest.remove(item)
			sofar.append(item)
			new_count = count - 1
			enumerate(sofar,rest,new_count,total_list,fixed)
			sofar.remove(item)
	return total_list
示例#21
0
def gen_tree(griglia):
    griglia = NodoTris(griglia)
    for y in range(3):
        for x in range(3):
            if griglia.nome[y][x] == '' and casellevuote(griglia.nome,
                                                         0) % 2 != 0:
                griglia2 = deep(griglia.nome)
                griglia2[y][x] = 'o'
                griglia.lista_figli += [NodoTris(griglia2)]
            elif griglia.nome[y][x] == '' and casellevuote(griglia.nome,
                                                           0) % 2 == 0:
                griglia2 = deep(griglia.nome)
                griglia2[y][x] = 'x'
                griglia.lista_figli += [NodoTris(griglia2)]
    for k in griglia.lista_figli:
        k.lista_figli += [gen_tree(k.nome)]
    return griglia
示例#22
0
    def __init__(self, volmstr=None):

        if volmstr is None:

            volfcs = [cube]

            dims = [(0, 0)]

        else:

            volfcs = deep(volmstr._MdimStruct__objs)

            dims = deep(volmstr._MdimStruct__dims)

        self.__volstr = mst.MdimStruct(volfcs, dims)

        return
示例#23
0
    def __init__(self, measstr=None):

        if measstr is None:

            measfcs = [cube]

            fcsdims = [(0, 0)]

        else:

            measfcs = deep(measstr._MdimStruct__objs)

            fcsdims = deep(measstr._MdimStruct__dims)

        self.__measstr = mst.MdimStruct(measfcs, fcsdims)

        return
def rotate(tile, degrees):

    if degrees == 0:
        return tile

    newtile = deep(tile)
    width = len(tile)

    turns = degrees // 90
    for i in range(turns):
        for line in range(width):
            for pixel in range(width):
                #if degrees == 90:
                newtile[line][pixel] = tile[width - 1 - pixel][line]
        tile = deep(newtile)

    return newtile
示例#25
0
    def joystickCallback(self, preJoyData):
        joyData = deep(preJoyData)
        # Switcher reminder: (Variables to help with naming conventions)
        leftButton = joyData.buttons[4]
        rightButton = joyData.buttons[5]
        start = joyData.buttons[7]

        # Start Button Logic
        if start == 1 and not self.startButtonDepressed:
            self.startButtonDepressed = True
            self.debugPrint("Start Button Pressed")

            if self.liftOn:
                self.debugPrint("Turning Thruster Off")
                self.liftOn = False
                self.switcher.lift = False
            else:
                self.debugPrint("Turning Thruster On")
                self.liftOn = True
                self.switcher.lift = True

        elif start == 0 and self.startButtonDepressed:
            self.startButtonDepressed = False

        # Left Button Logic
        if leftButton == 1 and not self.leftButtonDepressed:
            self.leftButtonDepressed = True
            self.debugPrint("Left Button Pressed")

            # Cycle left (JOYSTICK, TRIANGLE, REACTIVE, MAPPING, TANGENTBUG)
            self.switchState = 4 if self.switchState - 1 < 0 else self.switchState - 1
            self.debugPrint("State is: " + str(self.switchState))
        elif leftButton == 0 and self.leftButtonDepressed:
            self.leftButtonDepressed = False

        # Right Button Logic
        if rightButton == 1 and not self.rightButtonDepressed:
            self.rightButtonDepressed = True
            self.debugPrint("Right Button Pressed")
            # Cycle right (Joystick ,triangle, reactive)
            self.switchState = 0 if self.switchState + 1 > 4 else self.switchState + 1
            self.debugPrint("State is: " + str(self.switchState))
        elif rightButton == 0 and self.rightButtonDepressed:
            self.rightButtonDepressed = False

        # Translational Control Passthrough
        self.movement.xR = joyData.axes[3]
        self.movement.yR = joyData.axes[4]
        self.movement.xL = joyData.axes[0]
        self.movement.yL = joyData.axes[1]
        self.movement.bumperL = joyData.axes[2]
        self.movement.bumperR = joyData.axes[5]

        # Note: Flipped on purpose
        self.movement.xButton = joyData.buttons[1]
        self.movement.bButton = joyData.buttons[2]
        self.switcher.state = self.switchState
示例#26
0
    def transform(self, trf_par):

        res = deep(self)

        res.__fix_params.lim = trf_par.lim

        res.__fix_params.card = trf_par.card

        return res
def flip(tile):

    newtile = deep(tile)
    width = len(tile)

    for line in range(width):
        for pixel in range(width):
            newtile[line][pixel] = tile[line][width - 1 - pixel]

    return newtile
示例#28
0
def preprocess(data, skip = True):
	#create copy of data
	data = deep(data)
	
	#store origin indices
	origins = {}
	
	for key, session in data.items():
		#no GPS found yet
		originIdx = None
		best = float('inf')
		
		#get GPS with lowest accuracy
		for idx in range(len(session)):
			if session[idx]['type'] == 'absolute':
				if not skip: continue #without GPS
				accuracy = session[idx]['accuracy']
				if originIdx is None or accuracy < best:
					best = accuracy
					originIdx = idx
		
		if originIdx is not None:
			left = transform(session[:originIdx+1][::-1])
			right = transform(session[originIdx:])
			
			session[originIdx]['x'] = session[originIdx]['east']
			session[originIdx]['y'] = session[originIdx]['north']
			
			#reassemble original session with fixes
			session = left[::-1] + [session[originIdx]] + right
			
			for idx in range(len(session)):
				#get rid of absolute type parameters
				if session[idx]['type'] == 'absolute':
					del session[idx]['north']
					del session[idx]['east']
					del session[idx]['zone']
					del session[idx]['accuracy']
					
				#get rid of parameters
				#that are now unnecessary
				del session[idx]['type']
				del session[idx]['time']
									
			#store origin index
			origins[key] = originIdx
		
		else: #originIdx None
			origins[key] = 0
		
		#put session back in place
		data[key] = session
	
	#output fixed
	return data, origins
示例#29
0
    def test_bsgen(self):

        dm_t = deep(self.dm_t)
        dm_f = deep(self.dm_f)

        dm_tt = dm_t.prod(dm_t)
        dm_ff = dm_f.prod(dm_f)

        symb_tt = deep(self.symb_tt)
        symb_ff = deep(self.symb_ff)

        crtab = deep(self.crtab)

        pdtab = crtab.product(crtab)

        inds = [1, 2]

        bsgen = pdtab.get_bsgen(symb_tt, symb_tt)
        bsfc = bsgen.gen(dm_tt, inds)

        vres = sp.cdmvec(bsfc.fcval_at, dm_tt)[1]
        vw.plot_heatvec(dm_tt, vres)

        bsgen = pdtab.get_bsgen(symb_tt, symb_ff)
        bsfc = bsgen.gen(dm_ff, inds)

        vres = sp.cdmvec(bsfc.fcval_at, dm_tt)[1]
        vw.plot_heatvec(dm_tt, vres)

        bsgen = pdtab.get_bsgen(symb_ff, symb_tt)
        bsfc = bsgen.gen(dm_tt, inds)

        vres = sp.cdmvec(bsfc.fcval_at, dm_ff)[1]
        vw.plot_heatvec(dm_ff, vres)

        bsgen = pdtab.get_bsgen(symb_ff, symb_ff)
        bsfc = bsgen.gen(dm_ff, inds)

        vres = sp.cdmvec(bsfc.fcval_at, dm_ff)[1]
        vw.plot_heatvec(dm_ff, vres)

        return
示例#30
0
    def transform(self, trf_par):

        res = deep(self)

        res.__fix_params.T = trf_par.T

        res.__fix_params.dt = trf_par.dt

        res.__fix_params.shf = trf_par.shf_t

        return res
示例#31
0
文件: parse.py 项目: WEB3-GForce/VOTE
def for_to_agn_stance(stance):
    new_stance = copy.deep(stance)
    opposite_issue = DBIssue.getById(stance.issue).opposite

    if opposite_issue is not None:
        new_stance.issue = opposite_issue

    else:
        new_stance.side = "CON" if new_stance.side == "PRO" else "PRO"

    return new_stance
示例#32
0
    def __init__(self, t, shf, band):

        self.T = band[0]

        self.t = deep(t)

        self.per = len(t)

        self.shf_t = shf[0]

        return
示例#33
0
    def get_dims(self, did):
        res = None
        for elm in self.__dims:

            if ( (did == elm[0] ) and (did == elm[1] ) ) or\
               ( (elm[0]<=did ) and (did <= elm[1] ) ):

                res = deep(elm)
                break

        return res
    def gyroCallback(self, gyro):
        currentAngle = deep(gyro.angle)

        #Initialize the target angle to the angle of the
        #hovercraft when it first turns on (prevents
        #spinning when the craft is launched)
        if self.first:
            self.movement.theta = currentAngle
            self.initialHeading = currentAngle
            self.previousAngle  = currentAngle
            self.first = False

        #Check to see if the magnitude is low.  If so,
        #set the target angle to the current angle (so if
        #the joy isn't depressed anymore, it stops moving).
        #Should be hard coded to 1 for any input that didn't
        #originate from the left joystick.
        if self.movement.mag < .5:
            self.movement.theta = self.previousAngle
        else:
            self.previousAngle = self.movement.theta

        targetAngle = self.movement.theta
        #Determine how the target angle should be affected given theta
        #(see Movement.msg for details)
        if self.movement.modType == 'Add':
            targetAngle = currentAngle + self.movement.theta
        elif self.movement.modType is 'Set':
            targetAngle = self.movement.theta
        elif self.movement.modType is 'Bound': #NOTE: CHECK THIS LOGIC
            targetAngle = self.movement.theta
	#print ("%s: %f, Current: %f\tTarget: %f"%(self.movement.modType, self.movement.theta, currentAngle, targetAngle))
        #Proportional and Derivative computations
        r = self.P*(targetAngle - currentAngle)
        r = r + self.D*((targetAngle - currentAngle)-self.previousError)
        self.previousError = targetAngle - currentAngle

        #Deadband
        if math.fabs(targetAngle - currentAngle) < 3:
            r = 0
        self.debugPrint("PosPID: Theta:{:6.2f} TargetAngle:{:6.2f}  GyroAngle:{:6.2f}  "
        "Diff: {:6.2f} ModType: {:10s} GyroRate: {:6.2f}".format(self.movement.theta, targetAngle,
                                                                 currentAngle, self.previousError,self.movement.modType,gyro.rate ))

        #Ship message off to VelocityPID
        move = Movement()
        pub = rospy.Publisher('/angularPositionOut',Movement)
        move.theta = r
        move.lift = self.movement.lift
        move.x = self.movement.x
        move.y = self.movement.y
        pub.publish(move)
示例#35
0
def sector(part_grid, inds):

    points = []

    tmp_inds = deep(inds)

    for did in range(0, len(inds)):
        #TODO: it could be made more efficient, if the first vertex point
        #in the bounding volume was accessed only once
        start = part_grid.point(tmp_inds)

        tmp_inds[did] += 1

        end = part_grid.point(tmp_inds)

        points.append(tuple((start, end)))

    return points
示例#36
0
def simpleThresholdMap(uw, min, max, coeff, tracks):
	#create data copy
	uw = deep(uw)
	
	#calculate threshold number of tracks
	#based on original number of tracks input
	sig = tracks * coeff #significant value

	for i in range(len(uw)):
		for j in range(len(uw[i])):
			if uw[i][j] == 0: uw[i][j] == 0
			elif uw[i][j] < min: uw[i][j] = 0
			elif uw[i][j] > max: uw[i][j] = 1
			elif uw[i][j] >= sig: uw[i][j] = 1
			elif uw[i][j] < sig: uw[i][j] = 0
			
	#output binary
	#based heatmap
	return uw
示例#37
0
    def transform_pt(self, trf_par, dims):

        ptgens = deep(self.__ptgens)

        for gen in ptgens:

            obj = gen[1]

            curr_dims = gen[0]

            if curr_dims == dims:

                new_obj = obj.transform(trf_par)

        rptgen = mst.MdimStruct([new_obj], [dims])

        ptgens.replace(rptgen, dims, dims[0])

        return ptgens
    def createListOfGrids(self):
        b = 0
        exWrong = False
        oldGrid = list()
        Indikator = 0
        workerGrid = list()

        while True:
            workerGrid = self.getGridByName("pos")

            for rowIndex,row in enumerate(workerGrid):
                for nIndex,n in enumerate(row):
                    if type(n) is list and exWrong is False:
                        n = self.checkForColRow(workerGrid,nIndex,rowIndex,n)
                
                        try:
                            workerGrid[rowIndex][nIndex] = n[0]
                            workerGrid[rowIndex] = self.raoRow(workerGrid[rowIndex],n[0])
                            workerGrid = self.raoCol(workerGrid,nIndex,n[0])
                        except:
                            exWrong = True
                                        
            if workerGrid in oldGrid or exWrong:
                if b == 100000000:
                    print("Out of Run")
                    print(len(oldGrid))
                    break
                exWrong = False
            else:    
                oldGrid.append(deep(workerGrid))

                if v(workerGrid).shortValidator():
                    print("---------------------------------")
                    print(self.prettyPrintGrid(workerGrid,"Valid Result"))
                    print("Test Runs: " + str(b))
                    print("Grids: " + str(len(oldGrid)))
                    self.count = b
                    print("---------------------------------")
                    break
            
                b += 1
            Indikator += 1
示例#39
0
    def restrict(self, new_dims):

        tmp_objs = []
        tmp_dims = []

        did = new_dims[0]
        while (did < (new_dims[1] + 1)):

            dims_old = self.get_dims(did)

            ind = self.get_objid(dims_old)

            tmp_objs.append(deep(self.__objs[ind]))

            tmp_dims.append(
                (dims_old[0] - new_dims[0], dims_old[1] - new_dims[0]))

            did += ((dims_old[1] + 1) - dims_old[0])

        res = MdimStruct(tmp_objs, tmp_dims)

        return res
示例#40
0
    def __next__(self):

        res = None

        if 'fwd' == self.__direction:

            if self.__index < len(self.__mdimstruct._MdimStruct__dims):

                dims = self.__mdimstruct._MdimStruct__dims[self.__index]

                res = deep((dims, self.__mdimstruct.get_obj(dims)))

                self.__index += 1

            else:

                raise StopIteration

        elif 'bwd':
            #TODO
            pass

        return res
示例#41
0
def boxThresholdMap(uw, cf):
	#create data copy
	uw = deep(uw)

	#flatten heat map array using list comprehension
	weights = [item for list in uw for item in list]
	weights = sorted([i for i in weights if i != 0])
	
	#calculate appropriate statistics
	firstQuart = percentile(weights, .25)
	thirdQuart = percentile(weights, .75)
	interRange = thirdQuart - firstQuart
	outlier = firstQuart - cf * interRange
	
	for i in range(len(uw)):
		for j in range(len(uw[i])):
			if uw[i][j] == 0: uw[i][j] == 0
			elif uw[i][j] < outlier: uw[i][j] = 0
			else: uw[i][j] = 1 #turn pixel on
			
	#output binary
	#based heatmap
	return uw
示例#42
0
    def test_base_chg_unif(self):

        dm_t = deep(self.dm_t)
        dm_f = deep(self.dm_f)

        dm_tt = dm_t.prod(dm_t)
        dm_ff = dm_f.prod(dm_f)

        symb_tt = deep(self.symb_tt)
        symb_ff = deep(self.symb_ff)

        crtab = deep(self.crtab)

        pdtab = crtab.product(crtab)

        labels = deep(pdtab.bsubsp_labels)

        bsgen = pdtab.get_bsgen(symb_tt, symb_ff)

        coeffs = np.zeros(shape=(4, 4), dtype=np.complex64)

        coeffs[2, 2] = 0.7 + 1.2j

        sig_tt_ff = sp.Signal(labels, coeffs, bsgen)

        sig_ff_ff = pdtab.base_change(symb_tt, symb_ff, dm_ff, dm_tt,
                                      sig_tt_ff)

        vres = sp.sigvec(sig_ff_ff.fcval_at, dm_ff, dm_ff)[1]
        vw.plot_heatvec(dm_ff, vres)

        sig_tt_tt = pdtab.base_change(symb_ff, symb_tt, dm_ff, dm_ff,
                                      sig_ff_ff)

        vres = sp.sigvec(sig_tt_tt.fcval_at, dm_tt, dm_tt)[1]
        vw.plot_heatvec(dm_tt, vres)

        norm = op.vec_hsp_sc_prod(vres, vres, dm_tt)

        self.assertAlmostEqual(norm, (0.7 + 1.2j) * (0.7 - 1.2j), places=5)

        return
示例#43
0
def plotCompare(oldData, newData, origins, bound, show):
	#create copy of data
	oldData = deep(oldData)
	newData = deep(newData)
	origins = deep(origins)
	
	#GPS data by old and new coords
	gpsData, gpsDataNew = {}, {}
	
	#rescale old data to origin
	for key, session in oldData.items():
		x = oldData[key][origins[key]]['x']
		y = oldData[key][origins[key]]['y']
				
		#dictionary with GPS XY points
		gpsData[key] = {'x' : [], 'y' : []}
		
		for idx in range(len(session)):
			oldData[key][idx]['x'] -= x
			oldData[key][idx]['y'] -= y
			
			if oldData[key][idx]['type'] == 'absolute':
				gpsData[key]['x'].append(oldData[key][idx]['x'])
				gpsData[key]['y'].append(oldData[key][idx]['y'])	
				
		#pre-compute arrays of X and Y to avoid wasteful looping
		oldData[key][0]['x'] = [i['x'] for i in oldData[key]]
		oldData[key][0]['y'] = [i['y'] for i in oldData[key]]

	#rescale new data to origin
	for key, session in newData.items():
		x = newData[key][origins[key]]['x']
		y = newData[key][origins[key]]['y']
				
		#dictionary with GPS XY points
		gpsDataNew[key] = {'x' : [], 'y' : []}
		
		for idx in range(len(session)):
			newData[key][idx]['x'] -= x
			newData[key][idx]['y'] -= y
			
			if oldData[key][idx]['type'] == 'absolute':
				gpsDataNew[key]['x'].append(newData[key][idx]['x'])
				gpsDataNew[key]['y'].append(newData[key][idx]['y'])	
			
		#pre-compute arrays of X and Y to avoid wasteful looping
		newData[key][0]['x'] = [i['x'] for i in newData[key]]
		newData[key][0]['y'] = [i['y'] for i in newData[key]]
		
	#draw plots for every session key
	for key in sorted(oldData.keys()):
		#instantiate two different subplots that share the XY axes
		f, (new, old) = plot.subplots(2, sharex = True, sharey = True)
		
		old.plot(oldData[key][0]['x'], oldData[key][0]['y'], 'bo')
		new.plot(newData[key][0]['x'], newData[key][0]['y'], 'go')
		old.plot(gpsData[key]['x'], gpsData[key]['y'], 'yo')
		new.plot(gpsDataNew[key]['x'], gpsDataNew[key]['y'], 'ro')
		old.plot(gpsDataNew[key]['x'], gpsDataNew[key]['y'], 'ro')
		
		#these are temporary arrays used for axis scaling
		x = oldData[key][0]['x'] + newData[key][0]['x']
		y = oldData[key][0]['y'] + newData[key][0]['y']
		
		#find max point values for X and Y
		rawMaxX = max([i for i in x])
		rawMaxY = max([i for i in y])
		
		#find max point values for X and Y
		rawMinX = min([i for i in x])
		rawMinY = min([i for i in y])
		
		#find scaled X and Y to define plotting ranges
		maxX = bound * math.ceil(rawMaxX / bound)
		maxY = bound * math.ceil(rawMaxY / bound)
		
		if maxX == 0:
			maxX += bound

		if maxY == 0:
			maxY += bound
		
		maxX += bound/2
		maxY += bound/2
		
		#scale minima based on maxima margin
		minX = rawMinX - (maxX - rawMaxX)
		minY = rawMinY - (maxY - rawMaxY)
		
		#set up gridlines with color and appropriate width
		old.grid(color = '#9932cc', linestyle = ':', linewidth = 1)
		new.grid(color = '#9932cc', linestyle = ':', linewidth = 1)
		
		#define axes for both old and new
		old.axis([minX, maxX, minY, maxY])
		new.axis([minX, maxX, minY, maxY])
		
	if show: plot.show()
	plot.close() #done
    def interpretJoystick(self,preMove):
        '''
        move = deep(preMove)
        publisher = rospy.Publisher('/angleIntegratorOut',Movement)
        xAxisL = move.xL
        yAxisL = move.yL
        xAxisR = move.xR
        yAxisR = move.yR
        xButton = move.xButton
        bButton = move.bButton
        leftBumperMag = move.bumperL
        rightBumperMag= move.bumperR

        #X/B button toggle logic
        if bButton == 1 and not self.bButtonDepressed:
            self.bButtonDepressed = True
            self.buttonTargetAngle += 90
        elif xButton == 1 and not self.xButtonDepressed:
            self.xButtonDepressed = True
            self.buttonTargetAngle += -90
        if bButton == 0 and self.bButtonDepressed:
            self.bButtonDepressed = False
        if xButton == 0 and self.xButtonDepressed:
            self.xButtonDepressed = False


        #Bumper logic (rotational spin using shoulders)
        #Right overrides left
        bumperMag = 0
        if rightBumperMag != 1:
            bumperMag = (1 - rightBumperMag)
        elif leftBumperMag != 1:
            bumperMag = (1 - leftBumperMag)


        #Get the arctangent of xAxis/yAxis to get the angle in radians.
        #Convert it to degrees and make it so that it goes from 0-360 starting
        #at the positive y axis (to match with the front of the hovercraft).
        #Uses extreme deadzone to makesure accidental rotations don't happen.
        magnitudeThreshold = 1
        magnitude = math.sqrt(xAxisL**2 + yAxisL**2)
        rotationalAngle = 0
        if magnitude >= magnitudeThreshold:
            rotationalAngle = round(math.atan2(xAxisL,yAxisL)*(180.0/3.141593),4)
            if (rotationalAngle > 0):
                rotationalAngle = rotationalAngle - 360
            rotationalAngle = math.fabs(rotationalAngle)

        magnitudeThreshold = 1
        magnitude = math.sqrt(xAxisL**2 + yAxisL**2)
        rotationalAngle = xAxisL*10


        #Ships off the message to the arbitrator
        #Joystick overrides button target commands
        moveOut = Movement()
        moveOut.theta =0
        moveOut.modType = 'Bound'

        #Joystick Logic
        if magnitude >= magnitudeThreshold:
            #Reset button  upon hitting the joystick
            self.buttonTargetAngle = 0
            moveOut.theta = rotationalAngle
            moveOut.modType = 'Add'

        #Trigger absolute rotation if trigger/bumper is held down
        #print moveOut.theta
        if rightBumperMag != 1:
            #print "Right Trigger"
            self.rightBumperAngle = rightBumperMag
            self.buttonTargetAngle = 0
            moveOut.theta = -.1 if self.rightBumperAngle < 0 else 0
            moveOut.modType = 'Add'
            magnitude = 1
        else:
            self.rightBumperAngle = 0

        if leftBumperMag != 1:
            self.buttonTargetAngle = 0
            self.leftBumperAngle = leftBumperMag
            moveOut.theta = .1 if self.leftBumperAngle < 0 else 0
            moveOut.modType = 'Add'
            magnitude = 1
        else:
            self.leftBumperAngle = 0

        #For 90 degree button rotations

        if math.fabs(self.buttonTargetAngle) > 0:
            magnitude = 1
            moveOut.theta = self.buttonTargetAngle
            moveOut.modType = 'Add'
        '''
        move = deep(preMove)
        publisher = rospy.Publisher('/angleIntegratorOut',Movement)
        xAxisL = move.xL
        yAxisL = move.yL
        xAxisR = move.xR
        yAxisR = move.yR
        xButton = move.xButton
        bButton = move.bButton
        leftBumperMag = move.bumperL
        rightBumperMag= move.bumperR

        moveOut = Movement()
        moveOut.x = xAxisR
        moveOut.y = yAxisR
        moveOut.mag = math.fabs(xAxisL)

        if moveOut.mag > .5:
            if xAxisL < -.2:
                theta = -30
            elif xAxisL > .2:
                theta = 30
            else:
                theta = 0

            moveOut.theta = theta
            moveOut.modType = 'Add'
        else:
            moveOut.theta = 0
            moveOut.modType = 'Add'
        publisher.publish(moveOut)
        '''
示例#45
0
        deck2.append(card2)
        deck2.append(card1)
        pp("Player 2 wins this round", "Result")
    return deck1, deck2


def score(deck):
    score = 0
    multiplier = len(deck)
    for i, card in enumerate(deck):
        score += card * (multiplier - i)
    return score


turns = 0
deck1part1, deck2part1 = deep(deck1), deep(deck2)

if not part2:
    while len(deck1part1) > 0 and len(deck2part1) > 0:

        turns += 1
        pp(turns, "Turn")
        deck1part1, deck2part1 = turn(deck1part1, deck2part1)
        #pp(deck1part1), pp(deck2part1)

    if len(deck1part1) == 0:
        winner = "Player 2"
        winner_score = score(deck2part1)
    else:
        winner = "Player 1"
        winner_score = score(deck1part1)
 def arbitratorCallback(self, move):
     self.movement = deep(move)
示例#47
0
 def manualJoyControl(self, move):
     if self.state is 'Manual':
         liftState = self.movement.lift
         self.movement = Movement()
         self.movement = deep(move)
         self.movement.lift = liftState
示例#48
0
def cleanData(data, rotate, head = None):
	#create copy of data
	data = deep(data)
	
	#store data with
	#labels and GPS
	newData = {}
	
	#rotations
	rotCos = 0
	rotSin = 0
	
	#rot set or not
	rotSet = False
	
	for key, session in data.items():
		session = sorted(session, key = timeSort) #sort events by time
		newData[key] = []
		
		#relatives
		relIdx = 0
		relId2 = 1
		
		while session[relIdx]['type'] != 'relative':
			relIdx += 1 #loop through until found
			relId2 += 1 #use to find second reltv
			
		while session[relId2]['type'] != 'relative':
			relId2 += 1 #loop through until found
			
		xValue = session[relIdx]['absX']
		yValue = session[relIdx]['absY']
		stride = session[relIdx]['stride']
		time = session[relIdx]['time']
		label = session[relIdx]['start']
		
		#auto-rotate if rotation is not set
		if (head is None) and (not rotSet):
			#get heading of the first step
			head = session[relId2]['heading']
		
		#calculate rot trig values
		if (not rotSet) and (rotate):
			#figure out rotation matrix values
			rotCos = math.cos(math.radians(head))
			rotSin = math.sin(math.radians(head))
			
			#unset rotSet
			rotSet = True
				
		newData[key].append({
			'type' : 'relative',
			'x' : xValue,
			'y' : yValue,
			'stride' : stride,
			'label' : label,
			'time' : time
		})
		
		for idx in range(1, len(session)):
			if idx == relIdx:
				continue
			
			if session[idx]['type'] == 'label':
				if len(newData[key]) > 1: #don't overwrite start location
					newData[key][-1]['label'] = session[idx]['content']
			
			elif session[idx]['type'] == 'absolute':
				#change type as an identifier
				newData[key][-1]['type'] = 'absolute'
				
				latitude = session[idx]['latitude']
				longitude = session[idx]['longitude']
				northing, easting, zone = toUTM(latitude, longitude)
				
				newData[key][-1]['north'] = northing #cartesian y-axis
				newData[key][-1]['east'] = easting #cartesian x-axis
				newData[key][-1]['zone'] = zone #UTM validity zone
				newData[key][-1]['accuracy'] = session[idx]['accuracy']
				
			elif session[idx]['type'] == 'relative':
				xValue = session[idx]['absX']
				yValue = session[idx]['absY']
				stride = session[idx]['stride']
				time = session[idx]['time'] 
						
				newData[key].append({
					'type' : 'relative',
					'x' : xValue,
					'y' : yValue,
					'stride' : stride,
					'time' : time
				})
				
				#rotates
				if rotate:
					newData[key][-1]['x'] = xValue * rotCos - yValue * rotSin
					newData[key][-1]['y'] = xValue * rotSin + yValue * rotCos
	
	#output organized
	return newData
 def positionPIDCallback(self, move):
     self.movePass = deep(move)
    def interpretJoystick(self,preMove):
        move = deep(preMove)
        publisher = rospy.Publisher('/angleIntegratorOut',Movement)
        xAxisL = move.xL
        yAxisL = move.yL
        xAxisR = move.xR
        yAxisR = move.yR
        xButton = move.xButton
        bButton = move.bButton
        leftBumperMag = move.bumperL
        rightBumperMag= move.bumperR

        #X/B button toggle logic
        if bButton == 1 and not self.bButtonDepressed:
            self.bButtonDepressed = True
            self.buttonTargetAngle += 90
        elif xButton == 1 and not self.xButtonDepressed:
            self.xButtonDepressed = True
            self.buttonTargetAngle += -90
        if bButton == 0 and self.bButtonDepressed:
            self.bButtonDepressed = False
        if xButton == 0 and self.xButtonDepressed:
            self.xButtonDepressed = False

        #Bumper logic (rotational spin using shoulders)
        #Right overrides left
        bumperMag = 0
        if rightBumperMag != 1:
            bumperMag = (1 - rightBumperMag)
        elif leftBumperMag != 1:
            bumperMag = (1 - leftBumperMag)

        #Get the arctangent of xAxis/yAxis to get the angle in radians.
        #Convert it to degrees and make it so that it goes from 0-360 starting
        #at the positive y axis (to match with the front of the hovercraft).
        #Uses extreme deadzone to makesure accidental rotations don't happen.
        magnitudeThreshold = 1
        magnitude = math.sqrt(xAxisL**2 + yAxisL**2)
        rotationalAngle = 0
        if magnitude >= magnitudeThreshold:
            rotationalAngle = round(math.atan2(xAxisL,yAxisL)*(180.0/3.141593),4)
            if (rotationalAngle > 0):
                rotationalAngle = rotationalAngle - 360
            rotationalAngle = math.fabs(rotationalAngle)

        #Ships off the message to the arbitrator
        #Joystick overrides button target commands
        moveOut = Movement()
        moveOut.modType = 'Bound'

        #Joystick Logic
        if magnitude >= magnitudeThreshold:
            #Reset button  upon hitting the joystick
            self.buttonTargetAngle = 0
            moveOut.theta = rotationalAngle
            moveOut.modType = 'Bound'

        #Trigger absolute rotation if trigger/bumper is held down
        if rightBumperMag != 1:
            self.rightBumperAngle = self.rightBumperAngle + (rightBumperMag * 100)
            self.buttonTargetAngle = 0
            moveOut.theta = self.rightBumperAngle
            moveOut.modType = 'Add'
            magnitude = 1
        else:
            self.rightBumperAngle = 0

        if leftBumperMag != 1:
            self.buttonTargetAngle = 0
            self.leftBumperAngle = self.leftBumperAngle + (leftBumperMag * 100)
            moveOut.theta = -1 * self.leftBumperAngle
            moveOut.modType = 'Add'
            magnitude = 1
        else:
            self.leftBumperAngle = 0

        #For 90 degree button rotations
        if math.fabs(self.buttonTargetAngle) > 0:
            magnitude = 1
            moveOut.theta = self.buttonTargetAngle
            moveOut.modType = 'Add'

        moveOut.x = xAxisR
        moveOut.y = yAxisR
        moveOut.mag = magnitude

        publisher.publish(moveOut)

        #Prints all information related to the integrator if need be
        if (self.debug == 1):
            print("xL: %6.2f  yL: %6.2f  Angle: %6.2f  Magnitude:%6.2f  "
                  "xR: %6.2f  yR: %6.2f Theta: %6.2f Button Target: %6.2f"
                  "rB: %6.2f  lB: %6.2f rM: %6.2f  lM: %6.2f " % (xAxisL,yAxisL,rotationalAngle,magnitude,xAxisR,yAxisR,moveOut.theta, self.buttonTargetAngle, self.rightBumperAngle, self.leftBumperAngle, rightBumperMag, leftBumperMag))
示例#51
0
def transform(steps):
	#create copy of data
	steps = deep(steps)
	
	#coordinate frame
	origin = steps[0]
	originIdx = 0

	#get origin rel and abs XY-coordinates
	originRel = (origin['x'], origin['y'])
	originAbs = (origin['east'], origin['north'])
	originZone = origin['zone'] #zone check
	
	#set current accuracy
	currentAcc = origin['accuracy']
	
	#transform relative to absolute
	for idx in range(len(steps)):
		steps[idx]['x'] += originAbs[0] - originRel[0]
		steps[idx]['y'] += originAbs[1] - originRel[1]
		
	for idx in range(1, len(steps)):
		if steps[idx]['type'] == 'absolute':
			reading = (steps[idx]['east'], steps[idx]['north'])
			footfall = (steps[idx]['x'], steps[idx]['y'])
			
			#get new reading accuracy
			newAcc = steps[idx]['accuracy']
			
			#discard if reading overlaps with previous reading
			if (distance(originAbs, reading) <= currentAcc + newAcc):
				continue
			
			#same thing, but with footfall and its corresponding GPS
			if (distance(footfall, reading) <= currentAcc + newAcc):
				continue
			
			#check if zones match, or continue
			if originZone != steps[idx]['zone']:
				continue
			
			#calculate linear matrix transformation for footfalls
			initialPoints = mat([list(originAbs), list(footfall)]).T
			finalPoints = mat([list(originAbs), list(reading)]).T
			
			try:
				#see if we can find a transformation matrix
				transform = finalPoints * initialPoints.I
				
			#this fires if initialPoints is singular
			except numpy.linalg.linalg.LinAlgError:
				#we could not
				continue
			
			#apply transformation to each point
			#that is located between readings
			for pos in range(originIdx, idx + 1):
				oldPt = (steps[pos]['x'], steps[pos]['y'])
				oldVec = mat([[oldPt[0], oldPt[1]]]).T
				newVec = transform * oldVec
				
				newPt = newVec.ravel().tolist()[0]
				(steps[pos]['x'], steps[pos]['y']) = newPt
			
			#calculate translation vector for reading
			footfallVec = mat([list(footfall)]).T
			readingVec = mat([list(reading)]).T
			translate = readingVec - footfallVec
			
			#apply translation to each point
			#that is subsequent to new reading
			for pos in range(idx + 1, len(steps)):
				oldPt = (steps[pos]['x'], steps[pos]['y'])
				oldVec = mat([[oldPt[0], oldPt[1]]]).T
				newVec = oldVec + translate
				
				newPt = newVec.ravel().tolist()[0]
				(steps[pos]['x'], steps[pos]['y']) = newPt
			
			#all of the stuff we did at the beginning
			#since the first point was the first origin anchor
			
			origin = steps[idx]
			originIdx = idx
			
			originRel = (origin['x'], origin['y'])
			originAbs = (origin['east'], origin['north'])
			
			#see discussion for why this changes
			currentAcc = origin['accuracy']
			
	#return all but
	#first origin point
	return steps[1:]
示例#52
0
def plotSuper(data, bound, show, save):
	#create copy of data
	data = deep(data)
	
	figure = plot.figure() #get the window canvas
	figure.canvas.set_window_title('Superimposed Paths')
	
	#keep track of seen points
	#we don't want duped labels
	seenLabels, x, y = [], [], []
	
	for step in data:
		x.append(step['x'])
		y.append(step['y'])
		
		#plot point and corresponding label
		plot.plot(x[-1], y[-1], 'go')
		
		if 'label' in step:
			if step['label'] not in seenLabels:
				#store label temporarily
				label = step['label']
				
				#set style of annotation box. this should be nice but unobtrusive
				box = dict(boxstyle = 'round, pad = 0.4', fc = 'cyan', alpha = 1.0)
				plot.annotate(label, xy = (x[-1], y[-1]), bbox = box) #add label to plot
				
				#append label to seen labels
				seenLabels.append(label)

	#find max point values for X and Y
	rawMaxX = max([i for i in x])
	rawMaxY = max([i for i in y])
	
	#find max point values for X and Y
	rawMinX = min([i for i in x])
	rawMinY = min([i for i in y])
	
	#find scaled X and Y to define plotting ranges
	maxX = bound * math.ceil(rawMaxX / bound)
	maxY = bound * math.ceil(rawMaxY / bound)
	
	if maxX == 0:
		maxX += bound

	if maxY == 0:
		maxY += bound
	
	maxX += bound/2
	maxY += bound/2
	
	#scale minima based on maxima margin
	minX = rawMinX - (maxX - rawMaxX)
	minY = rawMinY - (maxY - rawMaxY)
	
	#set up gridlines with color and appropriate width
	plot.grid(color = '#9932cc', linestyle = ':', linewidth = 1)
	plot.axis([minX, maxX, minY, maxY]) #define axis
	
	if show: plot.show() #show the stuff out to the screen
	if save: plot.savefig(getTestSave() + '/' + 'super.png')
	
	#close plot
	plot.close()
示例#53
0
				sub = types[i][-1]
				
				#identify points as corner types or not
				if sub == 'e': corr = ['s', 'e', 's']
				elif sub == 's': corr = ['s', 's', 's']
				elif sub == 'i': corr = ['s', 'i', 's']
				elif sub == 't': corr = ['t', 't', 't']
				
				#if we are drawing a filled type edge with no exts
				if I and II and III and IV and not exts: continue
				
				paths.append(edges[i])
				corns.append(corr)

#copy paths and corners
orgPaths = deep(paths)
orgCorns = deep(corns)	
	
idx = 0	#fake for loop
while idx < len(orgPaths):

	found = True #init
	while found == True:
		found = False
		lastlen = 0
		
		#try to stitch the point groups together
		for i in range(len(orgPaths)-1, idx, -1):
			#needs the algo extension
			if orgCorns[i][0] == 't':
			
示例#54
0
def makeHeatMap(data, steps, pixel, alpha, function, frame):
	#floor pixel to one meter
	#to avoid bugs that occur
	if pixel > 1: pixel = 1

	#create copy of data
	data = deep(data)
	steps = deep(steps)
	
	#make scaling coefficient
	coeff = round(1/pixel)
	
	minX, maxX = steps[0]['x'], steps[0]['x']
	minY, maxY = steps[0]['y'], steps[0]['y']
	
	#find min and max vals of X and Y
	#accounting for radius expansion
	for element in steps:
		#calculate the personal comfort radius
		#see TODO note above about this formula
		radius = element['stride'] * alpha * coeff
		
		if element['x'] - radius < minX: minX = element['x'] - radius
		if element['x'] + radius > maxX: maxX = element['x'] + radius
		
		if element['y'] - radius < minY: minY = element['y'] - radius
		if element['y'] + radius > maxY: maxY = element['y'] + radius
	
	#calculate XY ranges
	xRange = maxX - minX
	yRange = maxY - minY
	
	#rescale everything positive
	for key, session in data.items():
		for idx in range(len(session)):
			data[key][idx]['x'] -= minX
			data[key][idx]['y'] -= minY
	
	#then scale X and Y ranges appropriately
	xRange, yRange = xRange * coeff, yRange * coeff
	xRange, yRange = math.ceil(xRange), math.ceil(yRange)
	
	#heatmap arrays
	heatmap = []
	weighted = []
	labels = []
	
	#debug runtime issues
	#print(xRange, yRange)
	
	#initialize zero matrix
	for i in range(xRange):
		heatmap.append([])
		weighted.append([])
		labels.append([])
		for j in range(yRange):
			heatmap[-1].append(0)
			weighted[-1].append(0)
			labels[-1].append(None)
	
	for key, session in data.items():
		#track seen pixels
		seenPixels = []
		
		for step in session:
			x = step['x'] * coeff
			y = step['y'] * coeff
			
			#preserve labels
			mapX = round(x)
			mapY = round(y)
			
			#calculate personal comfort radius
			#see TODO note above about this line
			radius = step['stride'] * alpha * coeff
			
			#make bounding box to find pixels
			#used in for loop, see below
			boundMinX = math.floor(x - radius)
			boundMaxX = math.ceil(x + radius)
			boundMinY = math.floor(y - radius)
			boundMaxY = math.ceil(y + radius)
			
			#only add label to array if label not set already
			if 'label' in step and labels[mapX][mapY] is None:
				labels[mapX][mapY] = step['label']
				
			for i in range(boundMinX, boundMaxX + 1):
				for j in range(boundMinY, boundMaxY + 1):
					if distance((x, y), (i, j)) <= radius:
						if i in range(xRange) and j in range(yRange):
							#weight only if not weighted
							if (i, j) not in seenPixels:
								heatmap[i][j] += 1
								seenPixels.append((i, j))
							
							#calculate weighted function of heatmap
							weighted[i][j] = function(heatmap[i][j])
	
	#rotate array CCW so it is oriented north
	weighted = mat(weighted).T[::-1].tolist()
	heatmap = mat(heatmap).T[::-1].tolist()
	labels = mat(labels).T[::-1].tolist()
	
	#add a frame of zero-weighted pixels on the top
	vertFrame = [[0] * len(weighted[0])] * frame
	weighted = mat(vertFrame + weighted + vertFrame).T.tolist()
	
	#do the same thing for our unweighted matrix
	vertFrame = [[0] * len(heatmap[0])] * frame
	heatmap = mat(vertFrame + heatmap + vertFrame).T.tolist()
	
	#do the same thing for our matrix of labels
	vertFrame = [[None] * len(labels[0])] * frame
	
	labels = mat(vertFrame + labels + vertFrame).T.tolist()
	#add a frame of zero-weighted pixels on the side
	sideFrame = [[0] * len(weighted[0])] * frame
	weighted = mat(sideFrame + weighted + sideFrame).T.tolist()
	
	#do the same thing for our unweighted matrix
	sideFrame = [[0] * len(heatmap[0])] * frame
	heatmap = mat(sideFrame + heatmap + sideFrame).T.tolist()
	
	#do the same thing for our matrix of labels
	sideFrame = [[None] * len(labels[0])] * frame
	labels = mat(sideFrame + labels + sideFrame).T.tolist()
	
	#output weights with unweighted
	return weighted, heatmap, labels
    def fireThrusters(self, move):
        theta = deep(move.theta)
        x = deep(move.x)
        y = deep(move.y)

        #Translation
        coef=0.75
        if y > .1:
            self.thrust.thruster2 = y
            self.thrust.thruster3 = y
        elif y < -.1:
            self.thrust.thruster1 = -y
        else:
            self.thrust.thruster1 = 0
            self.thrust.thruster2 = 0
            self.thrust.thruster3 = 0
        '''
        tr1x=0
        tr2x=0
        tr3x=0
        tr1y=0
        tr2y=0
        tr3y=0

        if -x>0:
            tr2x=1/0.866*(-x)*coef
            tr1x=0.5/0.866*(-x)*coef
        if -x<0:
            tr3x=1/0.866*x*coef
            tr1x=0.5/0.866*x*coef
        if y>0:
            tr2y=1*y*coef
            tr3y=1*y*coef
        if y<0:
            tr1y=1*(-y)*coef

        self.thrust.thruster1=tr1x+tr1y
        self.thrust.thruster2=tr2x+tr2y
        self.thrust.thruster3=tr3x+tr3y
        '''


        if theta >0:
            #Turn on 4
            self.thrust.thruster5 = 0
            self.thrust.thruster4 = math.fabs(theta)/100.0
            self.thrust.thruster4 = self.thrust.thruster4 if self.thrust.thruster4 < .7 else .7
        elif theta<0:
            #Turn on 5
            self.thrust.thruster4 = 0
            self.thrust.thruster5 = math.fabs(theta)/100.0
            self.thrust.thruster5 = self.thrust.thruster5 if self.thrust.thruster5 < .7 else .7
        elif theta==0:
            #Turn off thrusters if theta is 0
            self.thrust.thruster4 =0
            self.thrust.thruster5 =0

        if (self.debug == 1):
            print ("Thruster 1:%6.2f Thruster 2:%6.2f Thruster 3:%6.2f\nTheta:%6.2f  Thruster 4:%6.2f  Thruster 5:%6.2f Lift:%6.2f\nX: %6.2f Y: %6.2f" %
                   (self.thrust.thruster1, self.thrust.thruster2, self.thrust.thruster3, theta, self.thrust.thruster4, self.thrust.thruster5, self.thrust.lift,x, y))

        #Kill the thrusters if no lift is present
        if move.lift == False:
            self.thrust.thruster1 = 0
            self.thrust.thruster2 = 0
            self.thrust.thruster3 = 0
            self.thrust.thruster4 = 0
            self.thrust.thruster5 = 0
            self.thrust.lift = 0
        else:
            self.thrust.lift = self.liftPower

        pub = rospy.Publisher('/hovercraft/Thruster', Thruster)

        #if self.thrust.thruster1 > 0 or self.thrust.thruster2 > 0 or self.thrust.thruster3 > 0 or self.thrust.thruster4 > 0 or self.thrust.thruster5 > 0:
        #   print self.thrust

        pub.publish(self.thrust)
示例#56
0
def superimpose(data, label, split):
	#create copy of data
	data = deep(data)

	#list of compiled steps
	compiledData = []
	
	#dic of compiled sessions
	compiledSessions = {}
	
	for key, session in data.items():
		refX = 0 #reference x-coordinate
		refY = 0 #reference y-coordinate
		
		for idx in range(len(session)):
			if 'label' in session[idx]:
				if session[idx]['label'] == label:
					refX = session[idx]['x']
					refY = session[idx]['y']
					break #for efficiency sake
					
		for idx in range(len(session)):
			session[idx]['x'] -= refX
			session[idx]['y'] -= refY
			
		#append falls to split with first
		newSplitSession = [session[0]]
		
		#add intermediary extrapolations
		for idx in range(1, len(session)):
			dx = (session[idx]['x'] - session[idx-1]['x'])
			dy = (session[idx]['y'] - session[idx-1]['y'])
			
			#avoid zero
			if dx == 0:
			
				#define fake dy split length 
				splitLength = dy / (split + 1)
			
				#calculate the extrapolations
				for i in range(1, split + 1):
					newSplitSession.append({
						'x' : session[idx-1]['x'], #value constant
						'y' : session[idx-1]['y'] + i * splitLength,
						'stride' : session[idx]['stride'], #use old
					})
					
				#errors
				continue
			
			#define slope
			slope = dy/dx
			
			#define split length using dx
			splitLength = dx / (split + 1)
			
			#calculate the extrapolations
			for i in range(1, split + 1):
				newSplitSession.append({
					'x' : session[idx-1]['x'] + i * splitLength,
					'y' : session[idx-1]['y'] + slope * i * splitLength,
					'stride' : session[idx]['stride'], #use old stride
				})
				
			#finally add actual step to session
			newSplitSession.append(session[idx])
			
		#add steps to compiled list of steps
		for idx in range(len(newSplitSession)):
			compiledData.append(newSplitSession[idx])
			
		#add session to compiled session list
		compiledSessions[key] = newSplitSession
			
	#our final lists of steps and sessions
	return compiledData, compiledSessions