Beispiel #1
0
    def score(xArr):
        axis = [
            math2d.pointOnLine(landmarkAsLine, xArr[0] % l),
            math2d.pointOnLine(landmarkAsLine, xArr[1] % l)
        ]
        score = 0.0
        for p1, p2 in zip(
                math2d.stepAlongLine(figureGeom, fLength / resolution),
                math2d.stepAlongLine(axis,
                                     math2d.length(axis) / resolution)):
            score += math2d.squaredist(p1, p2)

        return score
Beispiel #2
0
    def doCompute(self, drawer, landmark, figure, **args):
        (lowerLeft, lowerRight), (width, height) = math2d.boundingBox(landmark)
        scale = pow(pow(width, 2) + pow(height, 2), 0.5)

        scaleFactor = scale * 0.1

        polygon = math2d.boxToPolygon(
            (lowerLeft - scaleFactor, lowerRight - scaleFactor),
            (width + 2 * scaleFactor, height + 2 * scaleFactor))

        out = {}
        figureSteps = list(
            math2d.stepAlongLine(figure,
                                 math2d.length(figure) / 100.0))

        out["endPointsInLandmarkBoundingBox"] = 0
        for p in figureSteps[90:]:
            if math2d.isInteriorPoint(polygon, p):
                out["endPointsInLandmarkBoundingBox"] += 1
                drawer.drawPoint("endPointsInLandmarkBoundingBox", p)
        drawer.drawLine("endPointsInLandmarkBoundingBox",
                        math2d.polygonToLine(polygon))

        out["startPointsInLandmarkBoundingBox"] = 0
        for p in figureSteps[:10]:
            if math2d.isInteriorPoint(polygon, p):
                out["startPointsInLandmarkBoundingBox"] += 1
                drawer.drawPoint("startPointsInLandmarkBoundingBox", p)
        drawer.drawLine("startPointsInLandmarkBoundingBox",
                        math2d.polygonToLine(polygon))

        return out
Beispiel #3
0
    def doCompute(self, drawer, landmark, figure, **args):
        fPoints = list(
            math2d.stepAlongLine(figure,
                                 math2d.length(figure) / 100.0))
        gPoints = [math2d.closestPointOnPolygon(landmark, p) for p in fPoints]
        distances = math2d.squareDistances(fPoints, gPoints)
        #[math2d.squaredist(f1, g1) for f1, g1 in zip(fPoints, gPoints)]

        i, dist = math2d.argMin(distances)

        fPoint = fPoints[i]
        gPoint = math2d.closestPointOnPolygon(landmark, fPoint)

        axes = [fPoint, gPoint]

        m = {}

        drawer.drawSegment("angleFigureToPastAxes", fPoint, gPoint)
        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)
        if math2d.isDegenerate(axes):
            m['angleFigureToPastAxes'] = 0
        else:
            m['angleFigureToPastAxes'] = math2d.angleBetweenLines(
                axes, [figure[0], figure[-1]])
        drawer.distanceFeature(m, "pastAxesLength", "Axes Start", "Axes End",
                               axes[0], axes[1], scale)

        return m
Beispiel #4
0
    def doCompute(self, drawer, landmark, figure, **args):
        landmarkCentroid = math2d.centroid(landmark)
        d_f = math2d.length(figure) / 100
        steps = list(math2d.stepAlongLine(figure, d_f))
        slope, intercept, r_value, p_value, std_err = math2d.regression(
            steps[25:])
        axes = math2d.lineEquationToPoints(slope, intercept)

        axes = [
            math2d.closestPointOnSegmentLine(axes, figure[0]),
            math2d.closestPointOnSegmentLine(axes, figure[-1])
        ]

        #axes = [steps[5], steps[-1]]

        point = math2d.closestPointOnSegmentLine(axes, landmarkCentroid)
        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)
        m = {}
        drawer.distanceFeature(m, "axesToLandmarkCentroid",
                               "Point on Figure Line", "Landmark Centroid",
                               point, landmarkCentroid, scale)

        segmentStartToLandmark = [axes[0], landmarkCentroid]
        m["axesOrientation"] = math2d.angleBetweenSegments(
            segmentStartToLandmark, axes)
        drawer.drawLine("axesOrientation", segmentStartToLandmark)
        drawer.drawLine("axesOrientation", axes)
        drawer.drawPoint("axesOrientation", point, "Point on Figure Line")

        try:
            slope, intersept = math2d.lineEquation(axes)
        except:
            print "axes", axes
            raise
        intersectPoints = math2d.intersectPolygonAnalytic(
            landmark, slope, intersept)
        for p in intersectPoints:
            drawer.drawPoint("axesIntersectLandmark", p, "")
        if len(intersectPoints) == 0:
            m["axesIntersectLandmark"] = 0
            drawer.drawPoint("axesIntersectLandmark", landmarkCentroid,
                             "No intersect points.")
        else:
            m["axesIntersectLandmark"] = 1

        #intersectPoint =
        #m["axesToLandmark"] =
        return m
Beispiel #5
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
Beispiel #6
0
    def doCompute(self, drawer, landmark, figure, **args):
        figureSteps = list(
            math2d.stepAlongLine(figure,
                                 math2d.length(figure) / 100.0))
        points = [
            math2d.closestPointOnPolygon(landmark, p) for p in figureSteps
        ]
        interiorPoints = math2d.interiorPoints(landmark, figureSteps)
        landmarkCentroid = math2d.centroid(landmark)
        distances = [math2d.squaredist(p, (0, 0)) for p in points]
        bborigin, (width,
                   height) = math2d.boundingBox(na.append(landmark, figure, 0))
        scale = pow(pow(width, 2) + pow(height, 2), 0.5)
        out = {}
        i, dist = math2d.argMin(distances)
        drawer.distanceFeature(out, "minimumDistanceToLandmark",
                               "Closest point on landmark", "Figure End",
                               figureSteps[i], points[i], scale)

        for p in interiorPoints:
            drawer.drawPoint("numInteriorPoints", p)
        if len(interiorPoints) == 0:
            drawer.drawText("numInteriorPoints", landmarkCentroid,
                            "No interior points.")
            #if out["numInteriorPoints"] > 0:
            #out["numInteriorPoints"] = 1

        out["numInteriorPoints"] = len(interiorPoints)
        if math2d.isInteriorPoint(landmark, figureSteps[i]):
            out["minimumDistanceToLandmark"] = 0
        if math2d.isInteriorPoint(landmark, figure[-1]):
            out["distFigureEndToLandmark"] = 0

        differences = [d1 - d2 for d1, d2 in zip(distances, distances[1:])]
        differences = [d / d if d != 0 else 0 for d in differences]
        if len(differences) == 0:
            out["averageDistanceDifference"] = 0
        else:
            out["averageDistanceDifference"] = math2d.mean(differences)
        for p1, p2 in zip(points, points[1:]):
            drawer.drawLine("averageDistanceDifference", [p1, p2])

        return out
Beispiel #7
0
 def averageParallel(self, drawer, landmark, figure):
     total = 0.0
     count = 0.0
     d_f = math2d.length(figure)/100
     steps = list(math2d.stepAlongLine(figure, d_f))
     for f1, f2 in zip(steps, steps[1:]):
         g1 = math2d.closestPointOnLine(math2d.polygonToLine(landmark), f1)
         g2 = math2d.closestPointOnLine(math2d.polygonToLine(landmark), f2)
         drawer.drawLine('averageParallel', [f1,g1])
         try:
             angle = math2d.angleBetweenLines([f1, f2], [g1, g2])
         except math2d.VerticalSegmentError:
             continue
         total += angle
         count += 1
         
     if count == 0:
         return math.pi/4
     else:
         return total / count
Beispiel #8
0
def plot_markers_evenly(X,
                        Y,
                        thelabel,
                        marker,
                        color,
                        linewidth,
                        markerSep=5,
                        markersize=140,
                        linestyle="-"):
    """
    This function plots 
    """

    line, = plot(X, Y, color + linestyle, label="_nolegend_", linewidth=2.5)
    line.set_marker("None")

    import math2d

    markers = [p for p in math2d.stepAlongLine(line.get_xydata(), markerSep)]

    X = [x for x, y in markers]
    Y = [y for x, y in markers]
    try:
        points = scatter(X,
                         Y,
                         s=markersize,
                         color=color,
                         marker=marker,
                         label=thelabel,
                         facecolor="white",
                         zorder=10)
    except:
        print "color", color
        print "marker", marker
        raise

    return line
Beispiel #9
0
    def doCompute(self, drawer, ground, figure, **args):
        steps = 100
        fPoints = list(
            math2d.stepAlongLine(figure,
                                 math2d.length(figure) / 100))

        gPoints = [math2d.closestPointOnPolygon(ground, p) for p in fPoints]
        distances = [
            math2d.squaredist(f1, g1) for f1, g1 in zip(fPoints, gPoints)
        ]

        i, minDist = math2d.argMin(distances)
        bborigin, (width, height) = math2d.boundingBox(ground + figure)
        scale = pow(pow(width, 2) + pow(height, 2), 0.5)
        featureMap = {}
        drawer.distanceFeature(self, featureMap, "minimumDistanceToGround",
                               "Figure", "Ground", fPoints[i], gPoints[i],
                               scale)

        for f1, g1 in zip(fPoints, gPoints):
            self.drawSegment("averageDistanceToGround", f1, g1)
        featureMap["averageDistanceToGround"] = math2d.mean(distances) / scale

        return featureMap
Beispiel #10
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
    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
            }