Exemplo n.º 1
0
    def doCompute(self, drawer, situation):

        figureA = situation.agent("figure")
        landmarkA = situation.agent("landmark")

        figure = [(x, y) for x, y, theta in figureA.positions]
        landmark = [(x, y) for x, y, theta in landmarkA.positions]

        out = {}
        bborigin, (width, height) = math2d.boundingBox(figure)
        scale = pow(pow(width, 2) + pow(height, 2), 0.5)
        if scale == 0:
            bborigin, (width, height) = math2d.boundingBox(figure + landmark)
            scale = pow(pow(width, 2) + pow(height, 2), 0.5)

        pt = landmark[-1]

        dFigureStartToGround = math2d.dist(pt, figure[0])
        dFigureEndToGround = math2d.dist(pt, figure[-1])
        drawer.drawDistance("displacementFromGround", [pt, figure[0]])

        drawer.drawDistance("displacementFromGround", [pt, figure[-1]])

        out["endpointDist"] = math2d.dist(figure[-1], landmark[-1]) / scale
        out["startpointDist"] = math2d.dist(figure[0], landmark[0]) / scale

        out["displacementFromGround"] = (dFigureEndToGround -
                                         dFigureStartToGround) / scale
        return out
Exemplo n.º 2
0
    def nearestNeighbor(self, x_rand, tree):
        nodes = [n for n in tree.nodes()]

        x1, x2 = x_rand

        distances = [
            math2d.dist(p1, x1) + math2d.dist(p2, x2) for p1, p2 in nodes
        ]

        minI, min = math2d.argMin(distances)
        return nodes[minI]
Exemplo n.º 3
0
 def doCompute(self, drawer, situation):
     distances = []
     
     figure = situation.agent("figure")
     landmark = situation.agent("landmark")
     points = [(x, y) for x, y, theta in figure.positions + landmark.positions]
     (minX, minY), (scaleX, scaleY)  = math2d.boundingBox(points)
     
     scale = math.pow(scaleX**2 + scaleY**2, 0.5)
     
     for t in range(situation.startTime, situation.endTime, 100):
         fx, fy, ftheta = figure.location(t)
         lx, ly, ltheta = landmark.location(t)
         floc = fx, fy
         lloc = lx, ly
         distances.append(math2d.dist(floc, lloc))
         drawer.drawDistance("averageDistance", t, floc, lloc)
         drawer.drawDistance("stdDevOfDistance", t, floc, lloc)
         
     if len(distances) == 0:
         raise InsaneExample("Bad figure: " + `figure`)
     if scale == 0:
         scale = 0.000001
     return {"averageDistance":scipy.mean(distances) / scale,
             "stdDevOfDistance":scipy.std(distances) / scale
             }
Exemplo n.º 4
0
 def data(self, midx, role=Qt.DisplayRole):
     engineData = self.currentEngineData()
     col = midx.column()
     idx = midx.row()
     #idx = midx.row()
     metadata = self.m4du.metadataForMatrixKey(engineData.idxForKey(idx),
                                               wantArgs=False)
     if role != Qt.DisplayRole:
         return QVariant()
     if col == COL_SCORE:
         return QVariant("%e" % engineData.data(idx))
     elif col == COL_LANDMARK:
         return QVariant(metadata.groundName)
     elif col == COL_DIST_TO_ENDPOINTS:
         return QVariant(math2d.dist(metadata.sloc, metadata.eloc))
     elif col == COL_SLOC:
         return QVariant("(%.3f, %.3f)" % tuple(metadata.sloc))
     elif col == COL_ELOC:
         return QVariant("(%.3f, %.3f)" % tuple(metadata.eloc))
     elif col == COL_IDX_TUPLE:
         return QVariant( ` metadata.key `)
     elif col == COL_ROW_NUM:
         return QVariant(idx)
     else:
         raise ValueError("Bad id: %s" % col)
Exemplo n.º 5
0
 def pixels(self, dist):
     """
     Convert a distance in pixels to distance in the figure using
     the current data coordinates.
     """
     p1 = self.axes.transData.inverted().transform((0, 0))
     p2 = self.axes.transData.inverted().transform((0, dist))
     
     return math2d.dist(p1, p2)
Exemplo n.º 6
0
    def compute(self, situation, offset):
        a1 = situation.agent(self.a1)
        a2 = situation.agent(self.a2)

        x1, y1, theta1 = a1.location(offset)
        x2, y2, theta2 = a2.location(offset)

        #if math2d.length(situation.shortestPath((x1, y1), (x2, y2))) < 10:
        if math2d.dist((x1, y1), (x2, y2)) < 5:
            return True
        else:
            return False
Exemplo n.º 7
0
    def doCompute(self, drawer, situation):
        out = {}
        figurePath = situation.agent("figure").asPath()

        bborigin, (width, height) = math2d.boundingBox(figurePath)

        scale = pow(pow(width, 2) + pow(height, 2), 0.5)

        drawer.drawDistance("netDisplacement", 0, figurePath[0],
                            figurePath[-1])
        out["netDisplacement"] = math2d.dist(figurePath[0], figurePath[-1])
        return out
Exemplo n.º 8
0
    def compute(self, situation, offset):
        a1 = situation.agent(self.a1)

        dt = 100

        x1, y1, theta1 = a1.location(offset)
        x2, y2, theta2 = a1.location(offset + dt)

        if math2d.dist((x1, y1), (x2, y2)) != 0:
            return True
        else:
            return False
Exemplo n.º 9
0
def is_loc_visible_from_pose(loc_st, theta_st, loc_end, fov=None):
    """
    Returns true if loc is visible from start_loc, start_theta with the given field of view
    """
    abs_orient = atan2(loc_end[1] - loc_st[1], loc_end[0] - loc_st[0])

    if math2d.dist(loc_st, loc_end) < 0.00000001:
        return True
    elif (0 >= tklib_normalize_theta(theta_st - fov / 2.0 - abs_orient)
          and 0 <= tklib_normalize_theta(theta_st + fov / 2.0 - abs_orient)):
        return True
    else:
        return False
Exemplo n.º 10
0
    def plotPaths(self, results=None):

        self.resultsModel.setEntries(results)
        if results == None:
            if self.cached_results != None:
                results = self.cached_results
            else:
                raise ValueError("Passed no results, and no cached results.")
        else:
            self.cached_results = results
        for p in self.path_plots:
            p.remove()
        self.path_plots = []

        true_eloc_i = results[0].iCorrectElocs[0]
        topo_st, ang = self.m4du.viewpoints[true_eloc_i].split("_")
        true_eloc = self.m4du.tmap_locs[float(topo_st)]

        radius = self.radiusBox.value()
        plot = matplotlib.patches.Ellipse(true_eloc, radius*2, radius*2, 
                                          facecolor='none',
                                          linewidth=5)
        self.axes.add_patch(plot)
        self.path_plots.append(plot)

        random.seed(3)
        total = 0.0
        num_within_radius = 0.0
        
        for e in results:
            for path in e.paths:
                eloc_topo_st,  eloc_ang = path[-1].split("_")
                x, y = self.m4du.tmap_locs[float(eloc_topo_st)]
                x += random.uniform(-1, 1)
                y += random.uniform(-1, 1)
                p, = self.axes.plot([x], [y], "r^", markersize=15)
                self.path_plots.append(p)
                if math2d.dist((x, y), true_eloc) < radius:
                    num_within_radius += 1
                total += 1

                sloc_topo_st,  sloc_ang = path[0].split("_")
                x, y = self.m4du.tmap_locs[float(sloc_topo_st)]
                p, = self.axes.plot([x], [y], "g^", markersize=15)
                self.path_plots.append(p)


        self.fractionWithinCircleLabel.setText("%.3f" % (num_within_radius/total))
        self.figure.canvas.draw()        
                
Exemplo n.º 11
0
    def doCompute(self, drawer, landmark, figure, **args):
        boundary = math2d.computeBoundaryLine(landmark, figure)
        map = {}
        bborigin, (width, height) = math2d.boundingBox(figure)
        scale = pow(pow(width, 2) + pow(height, 2), 0.5)

        if scale == 0:
            bborigin, (width, height) = math2d.boundingBox(landmark)
            scale = pow(pow(width, 2) + pow(height, 2), 0.5)

        drawer.distanceFeature(map,
                               "distStartLandmarkBoundary",
                               "Boundary",
                               "Figure Start",
                               math2d.closestPointOnLine(boundary, figure[0]),
                               figure[0], scale)
        drawer.distanceFeature(map,
                               "distEndLandmarkBoundary",
                               "Boundary",
                               "Figure End",
                               math2d.closestPointOnLine(boundary, figure[-1]),
                               figure[-1], scale)

        map['averageDistStartEndLandmarkBoundary'] = na.mean([map['distStartLandmarkBoundary'],
                                                              map['distEndLandmarkBoundary']])
        drawer.drawLine('averageDistStartEndLandmarkBoundary', figure[-1],
                      math2d.closestPointOnLine(boundary, figure[-1]))

        drawer.distanceFeature(map,
                               "figureStartToEnd",
                               "Start",
                               "End",
                               figure[0],
                               figure[-1],
                               scale)

        map['figureLength'] = math2d.length(figure) / scale
        drawer.drawPoint('figureLength', figure[0])
        drawer.drawPoint('figureLength', figure[-1])

        if math2d.length(figure) == 0:
            map['figureLengthByCrow'] = 0
        else:
            map['figureLengthByCrow'] = math2d.dist(figure[0], figure[-1]) / math2d.length(figure)
        return map
Exemplo n.º 12
0
def findSubsetOfFigure(landmark, figure):
    bestScore = None
    bestPath = figure
    d_f = math2d.length(figure)/100
    for subpath in math2d.slideWindowAlongPath(figure, 
                                               d_f,
                                               fractionSize=0.6):
        totalDist = 0.0
        count = 0
        for f1 in [x for x in math2d.stepAlongLine(figure, d_f)]:
            g1 = math2d.closestPointOnLine(math2d.polygonToLine(landmark), f1)
            totalDist += math2d.dist(f1, g1)
            count += 1
        mean = totalDist / count
        if bestScore == None or mean <= bestScore:
            bestScore = mean
            bestPath = subpath
    clippedFigure = bestPath
Exemplo n.º 13
0
    def drawArrow(self, line, narrowness=4, length=5):
        self.drawLine(line)

        p1 = self.mtp(line[0])
        p2 = self.mtp(line[-1])
        pixSeg = [p1, p2]

        startP = math2d.pointOnSegment(pixSeg, math2d.dist(p1, p2) - length)
        segment = math2d.perpendicular(pixSeg, startP)
        sa1 = [startP, segment[0]]
        sa2 = [startP, segment[-1]]
        
        a1 = math2d.pointOnSegment(sa1, narrowness)
        a2 = math2d.pointOnSegment(sa2, narrowness)
        a3 = p2

        self.p.drawLine(a1[0], a1[1], a3[0], a3[1])
        self.p.drawLine(a2[0], a2[1], a3[0], a3[1])
Exemplo n.º 14
0
def pack_get_srel_given_lmark_vpts_matrix(m4du):
    functions = []
    tmap, tmap_cnt, tmap_locs = m4du.clusters.get_topological_map()
    engineMap = m4du.sr_class.engineMap

    globals()["m4du"] = m4du

    #sorted(m4du.tmap.keys())
    tmap_keys = m4du.tmap_keys
    exampleCount = 0

    for j, tmapKey_j in enumerate(tmap_keys):
        sloc = m4du.tmap_locs[tmapKey_j]
        for k, tmapKey_k in enumerate(tmap_keys):
            eloc = m4du.tmap_locs[tmapKey_k]
            if math2d.dist(sloc, eloc) <= 20:
                desc = "viewpoint %d, %d" % (j, k)
                functions.append(
                    (desc, spatialRelationLoop, (sloc, eloc, j, k)))

    return functions
Exemplo n.º 15
0
    def updateTarget(self, timestamp):
        situation = self.agent.situation

        minDist = None
        minAgent = None
        hereX, hereY, hereTheta = self.agent.location(timestamp)
        for a in situation.agents:

            aX, aY, aTheta = a.location(timestamp)
            dist = math2d.dist((aX, aY), (hereX, hereY))
            if (minDist == None or dist < minDist) and a != self.agent:
                minDist = dist
                minAgent = a

        print "agent", minDist, minAgent
        if minDist != None and minDist < 4:
            if minDist < 1:
                return None
            else:
                x, y, theta = minAgent.location(timestamp)
                return x, y
        else:
            return None
Exemplo n.º 16
0
    def get_transition_matrix(self, direction="straight", p_self=1.0):
        T_mat = zeros([
            self.num_regions * self.num_viewpoints,
            self.num_regions * self.num_viewpoints
        ]) * 1.0
        print
        print "direction", direction
        if (direction == "straight"):
            new_tmap = self.get_topological_map_viewpoint(pi, 0)
        elif (direction == "back"):
            new_tmap = self.get_topological_map_viewpoint(pi, pi)
        elif (direction == "right"):
            new_tmap = self.get_topological_map_viewpoint(pi, -1.0 * pi / 2.0)
        elif (direction == "left"):
            new_tmap = self.get_topological_map_viewpoint(pi, +1.0 * pi / 2.0)
        elif (direction == "face"):
            new_tmap = self.get_topological_map_viewpoint(None, 0)
        else:
            raise ValueError("Unexpected direction: " + ` direction `)

        #for each of the viewpoints
        for i in range(len(self.viewpoints)):
            connections = new_tmap[self.viewpoints[i]]

            #find the areas connected and if they are reasonable
            for conn in connections:
                cconn = conn
                #connofconn = [conn]
                #connofconn.extend(new_tmap[conn])
                #for conn_i, cconn in enumerate(connofconn):

                #convert this into topo numbers
                topo_st, topo_st_ang = self.viewpoints[i].split("_")
                topo_end, topo_end_ang = cconn.split("_")

                if (cconn < 0 or self.viewpoints[i] == -1):
                    continue

                loc1 = self.tmap_locs[float(topo_st)]
                loc2 = self.tmap_locs[float(topo_end)]

                #for each of the to-node's orientations, check its relative angle to
                #          the from node's orientation and give it a relative probability
                #          accordingly
                start_num = self.vpt_to_num[self.viewpoints[i]]
                end_num = self.vpt_to_num[cconn]

                #make this dependent on how much we turn in total
                debug = False
                if (start_num == 18
                        or start_num == 16) and end_num == 42 and False:
                    print "***************", start_num, end_num
                    debug = True
                orient_diff, d_turn = get_total_turn_amount(
                    loc1[0],
                    loc1[1],
                    radians(float(topo_st_ang)),
                    loc2[0],
                    loc2[1],
                    radians(float(topo_end_ang)),
                    debug=debug)
                #going to end_num from i
                if (direction == 'straight'):
                    if debug:
                        print "val", max(-1.75 / pi * abs(orient_diff) + 1,
                                         0.0)
                    T_mat[end_num, start_num] = -abs(orient_diff)
                    T_mat[end_num, start_num] = sigmoid(T_mat[end_num,
                                                              start_num])
                elif (direction == 'back'):
                    diff_from_pi = tklib_normalize_theta(d_turn * orient_diff -
                                                         pi)
                    T_mat[end_num, start_num] = -abs(diff_from_pi)
                    T_mat[end_num, start_num] = sigmoid(T_mat[end_num,
                                                              start_num])
                    #T_mat[start_num][end_num] = max(-1.5/pi*abs(orient_diff)+1, 0.0)
                elif (direction == 'right' and d_turn < 0):
                    diff_from_neg_pi2 = tklib_normalize_theta(d_turn *
                                                              orient_diff +
                                                              (pi / 2.0))
                    T_mat[end_num, start_num] = -abs(diff_from_neg_pi2)
                    T_mat[end_num, start_num] = sigmoid(T_mat[end_num,
                                                              start_num])
                    #T_mat[start_num][end_num] = max(-1.5/pi*abs(diff_from_neg_pi2)+1, 0.0)
                elif (direction == 'left' and d_turn > 0):
                    diff_from_pi2 = tklib_normalize_theta(d_turn *
                                                          orient_diff -
                                                          (pi / 2.0))
                    T_mat[end_num, start_num] = -abs(diff_from_pi2)
                    T_mat[end_num, start_num] = sigmoid(T_mat[end_num,
                                                              start_num])
                elif direction == "face":
                    if math2d.dist(loc1, loc2) < 0.01:
                        T_mat[end_num, start_num] = p_self
                    else:
                        T_mat[end_num, start_num] = 0
                assert 0 <= T_mat[end_num, start_num] <= 1, T_mat[end_num,
                                                                  start_num]

                #T_mat[start_num][end_num] = max(-1.5/pi*abs(diff_from_pi2)+1, 0.0)
                #if(not conn == cconn):
                #    T_mat[end_num,start_num] = T_mat[end_num,start_num]*0.3

            #connect self transitions
            topo_st, topo_st_ang = self.viewpoints[i].split("_")
            if (direction == "straight"):
                T_mat[i, i] = p_self
            elif (direction == "right"):
                newang = mod(
                    int(float(topo_st_ang)) -
                    int(float(self.get_viewpoint_diff())), 360.0) * 1.0
                T_mat[self.vpt_to_num[str(topo_st) + "_" + str(newang)],
                      i] = p_self
            elif (direction == "left"):
                newang = mod(
                    int(float(topo_st_ang)) +
                    int(float(self.get_viewpoint_diff())), 360.0) * 1.0
                T_mat[self.vpt_to_num[str(topo_st) + "_" + str(newang)],
                      i] = p_self
            elif (direction == "back"):
                newang = mod(int(float(topo_st_ang)) + 180, 360) * 1.0
                T_mat[self.vpt_to_num[str(topo_st) + "_" + str(newang)],
                      i] = p_self
        return T_mat
Exemplo n.º 17
0
    def describe(self):
        figure = self.player_locs[self.figure_start:]
        if math2d.sorta_eq(math2d.length(figure), 0):
            return

        if (self.last_describe_loc != None
                and math2d.dist(self.last_describe_loc, figure[-1]) < 1):
            return

        landmark_i = self.pick_landmark(figure)
        if landmark_i == None:
            return

        object_name = self.m4du.obj_names[landmark_i]

        ground = self.m4du.createGroundFromPolygon(landmark_i)
        self.describe_window.generate(geometry={
            "figure": figure,
            "ground": ground
        })

        #verb_choices = [e.engine.name()
        #                for e in self.describe_window.verbResultModel._data
        #                if e.p_true > 0.7]
        verb_choices = ["straight"]
        print "choices", verb_choices
        if "straight" in verb_choices or True:
            verb_name = "straight"
        else:
            if len(verb_choices) == 0:
                return
            else:
                verb = self.describe_window.verbResultModel.get(0)
                verb_name = verb.engine.name()
        verb_str = random.choice(verb_forms[verb_name])

        print "object name", object_name, landmark_i
        object_str = random.choice(object_forms[object_name])

        sr_choices = []
        for e in self.describe_window.srResultModel._data:
            if e.p_true > 0.7:
                sr_choices.append(e)

        if len(sr_choices) == 0:
            return
        engine_names = [e.engine.name() for e in sr_choices]

        if "through" in engine_names:
            sr = sr_choices[engine_names.index("through")]
        else:
            sr = random.choice(sr_choices)

        next_segment = "%s %s the %s." % (
            verb_str,
            sr.engine.name(),
            object_str,
        )
        connectors = ["Next", "Then", "", "After that"]
        connector = random.choice(connectors)
        if len(self.segments) >= 1 and connector != "":
            next_segment = "%s %s" % (connector, next_segment)
        else:
            next_segment = next_segment.capitalize()

        self.segments.append(next_segment)

        self.descriptionLabel.setText(" ".join(self.segments))
        bar = self.labelScrollArea.verticalScrollBar()
        #bar.setSliderPosition(bar.maximum() + 100)

        self.last_describe_time = datetime.now()

        self.last_describe_loc = figure[-1]
        self.figure_start = len(figure) - 1
        self.plot_landmark(landmark_i)
Exemplo n.º 18
0
    def doCompute(self, drawer, landmark, figure, **args):
        line = self._lineFunction(landmark, figure)
        for x in self.names():
            drawer.drawLine(x, line)
        if line == None:
            raise InsaneExample("Couldn't get line: %s %s" %
                                (landmark, figure))
        else:
            steps = 100
            figure = math2d.trimLine(figure, line[0], line[-1])
            if len(figure) <= 1:
                print "degenerate figure", figure, landmark
                raise InsaneExample("Figure was too short: %s" % figure)
            d_f = math2d.length(figure) / float(steps)
            fpoints = [x for x in math2d.stepAlongLine(figure, d_f)]
            distances = [
                math2d.dist(f1, math2d.closestPointOnLine(line, f1))
                for f1 in fpoints
            ]
            start, stop = math2d.smallestWindow(distances,
                                                int(len(distances) * 0.75))

            distances = []
            maxDist = 0.0
            maxp1 = None
            maxp2 = None
            bborigin, (width, height) = math2d.boundingBox(figure)
            scaleFactor = pow(pow(width, 2) + pow(height, 2), 0.5)
            for f1 in fpoints[start:stop]:
                g1 = math2d.closestPointOnLine(line, f1)
                drawer.drawSegment("averageDistToAxes", f1, g1)
                drawer.drawSegment("stdDevToAxes", f1, g1)
                d = math2d.dist(f1, g1)
                distances.append(d / scaleFactor)
                if d > maxDist:
                    maxDist = d
                    maxp1 = f1
                    maxp2 = g1

            if len(distances) == 0:
                map = {}
                centroid = math2d.centroid(landmark)
                for x in self.names():
                    drawer.drawText(x, centroid, "Couldn't find axes.")
                    map[x] = -1
                return map

            mean = math2d.mean(distances)
            stdDev = math2d.stdDeviation(distances)

            whitenedMean = math2d.mean([x - mean for x in distances])
            drawer.drawSegment("peakDistToAxes", maxp1, maxp2)
            f1 = math2d.closestPointOnLine(figure, line[0])
            f2 = math2d.closestPointOnLine(figure, line[-1])

            distF1F2 = math2d.distBetweenPointsAlongLine(figure, f1, f2)
            if distF1F2 != 0:
                x = math.fabs(distF1F2 / math2d.length(line))
                relativeLength = min(x, 1.0 / x)
                #relativeLength = 1.0/x
                #x = math2d.length(line) / math2d.length(figure)
                #relativeLength = min(x, 1.0/x)
            else:
                relativeLength = -1

            drawer.drawPoint("relativeLength", f1)
            drawer.drawPoint("relativeLength", f2)
            drawer.drawLine("relativeLength", line)

            return {
                "averageDistToAxes": mean,
                "whitenedAverageDist": whitenedMean,
                "peakDistToAxes": maxDist / scaleFactor,
                "stdDevToAxes": stdDev,
                "relativeLength": relativeLength
            }
Exemplo n.º 19
0
    def doCompute(self, drawer, landmark, figure, **args):
        major, minor = computeAxes(landmark, figure)

        if (major, minor) == (None, None):
            centroid = math2d.centroid(landmark)
            for x in self.names():
                drawer.drawText(x, centroid, "Couldn't find axes.")
            return None
        else:
            map = {}
            origin = math2d.intersectSegment(major, minor)

            centroid = math2d.centroid(landmark)
            bborigin, (width, height) = math2d.boundingBox(landmark + figure)
            scale = pow(pow(width, 2) + pow(height, 2), 0.5)
            drawer.distanceFeature(map, "centroidToAxesOrigin", "Centroid",
                                   "Axes Origin", centroid, origin, scale)
            drawer.drawAxes("centroidToAxesOrigin", (major, minor))

            sampledFig = [
                x for x in math2d.stepAlongLine(figure,
                                                math2d.length(figure) / 100)
            ]
            figureCentroid = math2d.centerOfMass(sampledFig)
            drawer.distanceFeature(map, "figureCenterOfMassToAxesOrigin",
                                   "Figure Center of Mass", "Axes Origin",
                                   figureCentroid, origin, scale)
            drawer.drawAxes("figureCenterOfMassToAxesOrigin", (major, minor))

            drawer.distanceFeature(map, "figureCenterOfMassToLandmarkCentroid",
                                   "Figure Center of Mass", "Centroid",
                                   figureCentroid, centroid, scale)

            drawer.distanceFeature(
                map, "axesStartToLandmark", "Landmark", "Start of minor axis",
                math2d.closestPointOnPolygon(landmark, minor[0]), minor[0],
                scale)
            drawer.drawAxes("axesStartToLandmark", (major, minor))

            drawer.distanceFeature(
                map, "axesEndToLandmark", "Landmark", "End of minor axis",
                math2d.closestPointOnPolygon(landmark, minor[-1]), minor[-1],
                scale)

            drawer.drawAxes("axesEndToLandmark", (major, minor))

            map['axesToLandmarkSum'] = map['axesEndToLandmark'] + map[
                'axesStartToLandmark']
            drawer.drawAxes("axesToLandmarkSum", (major, minor))

            map['figureLengthByCrow'] = math2d.ratioLengthByCrow(figure)
            drawer.drawDistance("figureLengthByCrow", figure[0], figure[-1],
                                "Start", "End")

            m1 = minor[0]
            f1 = figure[0]
            m2 = minor[-1]
            f2 = figure[-1]
            d1 = math2d.dist(m1, f1) + math2d.dist(m2, f2)
            d2 = math2d.dist(m1, f2) + math2d.dist(m2, f1)
            if (math.fabs(d1 - d2) > math2d.threshold and d1 > d2):
                f1 = figure[-1]
                f2 = figure[0]

            drawer.distanceFeature(map, "axesStartToFigureStart", "Axes Start",
                                   "Figure start", m1, f1, scale)

            drawer.distanceFeature(map, "axesEndToFigureEnd", "Axes End",
                                   "Figure End", m2, f2, scale)

            map['axesToFigureSum'] = map['axesEndToFigureEnd'] + map[
                'axesStartToFigureStart']
            drawer.drawDistance('axesToFigureSum', m2, f2, 'Axes End',
                                'Figure End')
            # from Rao at Winston's group meeting 12-9-2008
            map['distAlongLandmarkBtwnAxes'] = \
                math2d.distBetweenPointsAlongPolygon(landmark,
                                                     minor[0], minor[-1]) / math2d.perimeter(landmark)
            drawer.drawAxes("distAlongLandmarkBtwnAxes", (major, minor))
            drawer.drawPoint("distAlongLandmarkBtwnAxes", figure[0], "",
                             Qt.green, 30)
            drawer.drawPoint("distAlongLandmarkBtwnAxes", figure[-1], "",
                             Qt.red, 30)

            map['ratioFigureToAxes'] = \
                math2d.dist(figure[0], figure[-1]) / math2d.length(minor)
            drawer.drawAxes("ratioFigureToAxes", (major, minor))

            drawer.drawDistance("ratioFigureToAxes", figure[0], figure[-1],
                                "Figure Start", "Figure End")
            drawer.drawDistance("ratioFigureToAxes", minor[0], minor[-1],
                                "Minor Start", "Minor End")


            map['ratioLengthFigureToAxes'] = \
                math2d.length(figure) / math2d.length(minor)
            drawer.drawAxes("ratioLengthFigureToAxes", (major, minor))

            return map
Exemplo n.º 20
0
def makeTable(data, engine, tagLayer, useFarAway=False):
    table = orange.ExampleTable(engine.domain())
    if engine.name() in skipMap:
        skipList = skipMap[engine.name()]
    else:
        skipList = []

    labeledCount = 0
    negativeCount = 0
    farAwayCount = 0
    for engineName, landmarkName, geometry in data:

        #geometry["landmark"] = createLandmarkPt(math2d.centroid(geometry["landmark"]))

        if not (engineName in skipList):  # or True:

            try:
                geometry["landmark"] = geometry["ground"]
                ex = engine.makeExample(**geometry)
            except preposition.InsaneExample:
                continue
            except:
                print "dc", engineName
                print "dc", geometry
                print "dc", landmarkName
                raise
            if engineName == engine.name():
                if engineName == "down" and False:
                    print "doing down differently"
                    if landmarkName == "hallway":
                        cls = "True"
                        labeledCount += 1
                    else:
                        continue
                        #cls = "False"
                        #negativeCount -= 1
                else:
                    cls = "True"
                    labeledCount += 1
            else:
                cls = "False"
                negativeCount += 1
            ex['class'] = cls
            ex['sourceEngineName'] = engineName
            ex['engineName'] = engine.name()
            ex['landmarkName'] = landmarkName
            ex['farAway'] = False
            table.append(ex)
    if useFarAway and engine.name() != "through" and engine.name() != "down":
        for name, landmark in tagLayer:
            centroid1 = math2d.centroid(landmark)
            for engineName, landmarkName, geometry in data:
                if engineName == engine.name():
                    centroid2 = math2d.centroid(geometry["landmark"])
                    d1 = math2d.dist(centroid1, centroid2)
                    d2 = math2d.length(geometry["figure"])
                    if d1 > d2:
                        ex = engine.makeExample(figure=geometry["figure"],
                                                landmark=landmark)
                        ex['class'] = "False"
                        ex['landmarkName'] = landmarkName
                        ex['sourceEngineName'] = engineName
                        ex['engineName'] = engine.name()
                        ex['farAway'] = True
                        table.append(ex)
                        farAwayCount += 1
                        if farAwayCount >= 100:
                            break
    for ex in table:
        ex['drawMap'] = None
        #ex['geometry'] = None

    print "counts"
    print labeledCount, "labeled examples."
    print negativeCount, "negative examples."
    print farAwayCount, "far away examples."

    return table
Exemplo n.º 21
0
    def get_vertical_transition_matrix(self, direction="stay", p_self=1.0):

        assert direction in ["stay", "up", "down"]

        T_mat = zeros([
            self.num_regions * self.num_viewpoints,
            self.num_regions * self.num_viewpoints
        ]) * 1.0
        new_tmap = self.get_topological_map_viewpoint(None, 0)

        print "verticaldirection", direction
        print "vpt", 18, [
            self.vpt_to_num[x] for x in new_tmap[self.viewpoints[18]]
        ]

        #for each of the viewpoints
        for i in range(len(self.viewpoints)):
            connections = new_tmap[self.viewpoints[i]]

            #find the areas connected and if they are reasonable
            for conn in connections:
                cconn = conn
                #connofconn = [conn]
                #connofconn.extend(new_tmap[conn])
                #for conn_i, cconn in enumerate(connofconn):

                #convert this into topo numbers
                topo_st, topo_st_ang = self.viewpoints[i].split("_")
                topo_end, topo_end_ang = cconn.split("_")

                if (cconn < 0 or self.viewpoints[i] == -1):
                    continue

                x1, y1, z1 = self.tmap_locs_3d[float(topo_st)]
                x2, y2, z2 = self.tmap_locs_3d[float(topo_end)]

                #for each of the to-node's orientations, check its relative angle to
                #          the from node's orientation and give it a relative probability
                #          accordingly
                start_num = self.vpt_to_num[self.viewpoints[i]]
                end_num = self.vpt_to_num[cconn]

                #going to end_num from i
                if direction == 'stay':
                    if z1 == z2:
                        val = 1.0
                    else:
                        val = 1e-6
                elif direction == 'up':
                    if z1 < z2:
                        val = 1.0
                    elif z1 == z2:
                        val = 0.2
                    else:
                        val = 1e-6

                    if math2d.dist((x1, y1), (x2, y2)) > 0.5:
                        val = 0.9 * val
                elif direction == 'down':
                    if z2 < z1:
                        val = 1.0
                    elif z1 == z2:
                        val = 0.2
                    else:
                        val = 1e-6
                    if math2d.dist((x1, y1), (x2, y2)) > 0.5:
                        val = 0.9 * val
                else:
                    raise ValueError("Bad direction: " + ` direction `)

                T_mat[end_num, start_num] = val

            #connect self transitions
            topo_st, topo_st_ang = self.viewpoints[i].split("_")
            if (direction == "stay"):
                T_mat[i, i] = p_self

        return T_mat
Exemplo n.º 22
0
 def distanceFeature(self, valueMap, key, p1Desc, p2Desc, start, end, scale):
     valueMap[key] = math2d.dist(start, end) / float(scale)
     self.drawDistance(key, start, end, p1Desc, p2Desc)
Exemplo n.º 23
0
    def nearestNeighbor(self, x_rand, tree):
        nodes = [n for n in tree.nodes()]
        distances = [math2d.dist(n, x_rand) for n in nodes]

        minI, min = math2d.argMin(distances)
        return nodes[minI]
Exemplo n.º 24
0
    def get_topological_map_viewpoint(self, fov, turn_amount):
        tmap_new = {}

        #iterate through all the viewpoints
        for i in range(len(self.viewpoints)):
            #get the start location
            tf, tfor = self.viewpoints[i].split("_")
            tf = float(tf)
            loc_st = self.tmap_locs[tf]
            st_orient = float(tfor) * pi / 180.0

            tmap_new[self.viewpoints[i]] = []

            #iterate through all the viewpoints
            for j in range(len(self.viewpoints)):

                #get the end location
                tt, ttor = self.viewpoints[j].split("_")
                tt = float(tt)
                loc_end = self.tmap_locs[tt]
                end_orient = float(ttor) * pi / 180.0

                #absolute difference in orientation
                abs_orient = atan2(loc_end[1] - loc_st[1],
                                   loc_end[0] - loc_st[0])

                #if we're connected and we're in the fov
                if i == 40 and j == 42 and True:
                    print i, j
                    print "vp1", self.viewpoints[i]
                    print "vp2", self.viewpoints[j]
                    print "l1", loc_st, "=>", loc_end

                    print
                    print "tt", tt in self.tmap[tf]
                    if fov != None:
                        print "fov/2.0", math.degrees(fov / 2.0)
                        print "c1", (0 >= tklib_normalize_theta(
                            st_orient - fov / 2.0 - abs_orient + turn_amount))
                        print "c2", (0 <= tklib_normalize_theta(
                            st_orient + fov / 2.0 - abs_orient + turn_amount))
                        print "c1 angle", math.degrees(st_orient - fov / 2.0 -
                                                       abs_orient +
                                                       turn_amount)
                        print "c2 angle", math.degrees(st_orient + fov / 2.0 -
                                                       abs_orient +
                                                       turn_amount)
                        print "normalized"
                        print "c1 angle", tklib_normalize_theta(
                            math.degrees(st_orient - fov / 2.0 - abs_orient +
                                         turn_amount))
                        print "c2 angle", tklib_normalize_theta(
                            math.degrees(st_orient + fov / 2.0 - abs_orient +
                                         turn_amount))
                    else:
                        print "fov is None"
                    print
                    print "st_orient", math.degrees(st_orient)

                    print "abs_orient", abs_orient
                    print "turn_amount", turn_amount

                    print

                if tt in self.tmap[tf]:
                    append = False
                    if fov == None:
                        append = True
                    elif (0 >= tklib_normalize_theta(st_orient - fov / 2.0 -
                                                     abs_orient + turn_amount)
                          and 0 <=
                          tklib_normalize_theta(st_orient + fov / 2.0 -
                                                abs_orient + turn_amount)):
                        append = True
                    elif math2d.dist(loc_st, loc_end) < 0.00001:
                        append = True
                    if append:
                        tmap_new[self.viewpoints[i]].append(self.viewpoints[j])
        return tmap_new