Exemple #1
0
 def border_point(self, xt, yt):
     x1 = self.x + self.w / 2.0
     y1 = self.y + self.h / 2.0
     ac = np.array([x1, y1])
     bc = np.array([xt, yt])
     lines = []
     lines.append([[self.x, self.y], [self.x + self.w, self.y]])
     lines.append([[self.x + self.w, self.y],
                   [self.x + self.w, self.y + self.h]])
     lines.append([[self.x, self.y + self.h],
                   [self.x + self.w, self.y + self.h]])
     lines.append([[self.x, self.y], [self.x, self.y + self.h]])
     for e in lines:
         t1 = np.array(e[0])
         t2 = np.array(e[1])
         rez = intersection(ac, bc, t1, t2)
         if (rez != None):
             p, u, v = rez
             if u >= 0 and u <= 1 and v >= 0 and v <= 1:
                 tc = t1 + 0.5 * (t2 - t1)
                 x1 = p[0]
                 y1 = p[1]
                 #self.x1 = tc[0]
                 #self.y1 = tc[1]
                 return x1, y1
Exemple #2
0
def diffz_between(g, cornerid1, cornerid2):
    '''Returns set of DiffZ nodeids between cornerid1 and cornerid2. The DiffZ
    nodes actually tag the ZTag nodes that tag the corners.'''
    return intersection(
        g.at_last_step(cornerid1, ZTag, DiffZ),
        g.at_last_step(cornerid2, ZTag, DiffZ)
    )
Exemple #3
0
def cls_add_tag(cls, g, taggees):  # HACK
    taggees = list(as_iter(taggees))
    taggee_containers = intersection(
        *[g.member_of(ee) for ee in as_iter(taggees)])
    tag = g.make_node(cls, container=taggee_containers)
    for taggee in as_iter(taggees):
        g.add_edge(tag, tag_port_label, taggee, taggee_port_label)
    return tag
Exemple #4
0
def F_reg_pc(par, chd):
    """
    Regularization term(Parent-Child)
    """
    chd_area = area(chd)
    bbox_penalty = (chd_area - intersection(par, chd) + 1e-6) / \
                   (chd_area + 1e-6)
    return bbox_penalty.clamp(min=0)
Exemple #5
0
 def __call__(self, *args):
     subsets = [self.index[key] for key in enumerate(args)
                                if  key in self.index]
     if subsets:     # we are able to reduce the pool early
         facts = intersection(*sorted(subsets, key=len))
     else:
         facts = self.facts
     return conde(*[[eq(a, b) for a, b in zip(args, fact)]
                              for fact in facts])
Exemple #6
0
def F_reg_cc(chd_a, chd_b):
    """
    Regularization term(among childs)
    """
    margin = 0
    area_a = area(chd_a)
    area_b = area(chd_b)
    intersection_area = intersection(chd_a, chd_b)
    chds_penalty = F.relu((intersection_area + 1e-6) / (area_a + 1e-6) - margin) + \
                   F.relu((intersection_area + 1e-6) / (area_b + 1e-6) - margin)
    return chds_penalty
Exemple #7
0
 def is_match(self, g, tup):
     '''tup must have same length as self.port_labels.'''
     if len(tup) != len(self.port_labels):
         raise (ValueError(
             f'tuple {tup} and port_labels {self.port_labels} do not have the same length.'
         ))
     mate_sets = []
     for nodeid, port_label in zip(tup, self.port_labels):
         mate_sets.append(g.neighbors(nodeid, port_label=port_label))
     common_mates = intersection(*mate_sets)
     return len(common_mates) == 0
Exemple #8
0
        def f(s):
            args2 = reify(args, s)
            subsets = [self.index[key] for key in enumerate(args) if key in self.index]
            if subsets:  # we are able to reduce the pool early
                facts = intersection(*sorted(subsets, key=len))
            else:
                facts = self.facts
            varinds = [i for i, arg in enumerate(args2) if isvar(arg)]
            valinds = [i for i, arg in enumerate(args2) if not isvar(arg)]
            vars = index(args2, varinds)
            vals = index(args2, valinds)
            assert not any(var in s for var in vars)

            return (
                merge(dict(zip(vars, index(fact, varinds))), s) for fact in self.facts if vals == index(fact, valinds)
            )
Exemple #9
0
 def make(cls, g, operandids):
     '''If any Operators remain that haven't been tried on the operandids
     (node ids), returns a ConsumeOperands Action to build a full
     arithmetic operation on the operandids, linking them to a new
     Operator, whose class is chosen randomly, which links to a result
     Block. Otherwise returns None.'''
     operandids = list(operandids)
     consumers = intersection(
         *[g.neighbors(o, port_label='consumer') for o in operandids]
     )
     consumer_classes = set([g.class_of(c) for c in consumers])
     untried_classes = all_operator_classes.difference(consumer_classes)
     #print('MAKE', consumers, consumer_classes, untried_classes)
     if untried_classes:
         return ConsumeOperands(operandids, choice(list(untried_classes)))
     else:
         return None
Exemple #10
0
 def on_blocked(self) -> Actions:
     '''Actions to perform when this node is Blocked.'''
     agents = self.g.neighbors(self, 'agents')
     agents_problems = union(*(self.g.neighbors(agent, 'problem')
                               for agent in agents))
     tags_with_agent, tags_without_agent = [], []
     for tag in self.g.tags_of(self, 'Blocked'):
         if tag in agents_problems:
             tags_with_agent.append(tag)
         else:
             tags_without_agent.append(tag)
     if tags_without_agent:
         return BuildAgent(self, choice(tags_without_agent))
     else:
         return BoostFromTo(
             intersection(
                 agents,
                 self.g.neighbors(tags_with_agent,
                                  neighbor_label='problem')))
Exemple #11
0
def make_list_2 ():

    cwd = os.getcwd()
    ext = os.path.splitext(cwd)[1]
    if ext == ".pbm":
        pbms = glob.glob("problem.*.tex")
        if pbms:
            langs = []
            for p in pbms:
                langs.append(p.replace("problem.", "").replace(".tex", ""))
        else:
            langs = util.intersection(glob.glob("*"), languages)
        print(cwd + " " + " ".join(sorted(langs)))

    else:
        for path in sorted(glob.glob("*")):
            if os.path.isdir(path):
                os.chdir(path)
                make_list_2()
                os.chdir(cwd)
Exemple #12
0
def make_srclst_2 ():
    global ctr

    cwd = os.getcwd()
    ext = os.path.splitext(cwd)[1]
    if ext == ".pbm":
        ctr+=1
        pbms = glob.glob("problem.*.tex")
        if pbms:
            langs = []
            for p in pbms:
                langs.append(p.replace("problem.", "").replace(".tex", ""))
        else:
            langs = util.intersection(glob.glob("*"), languages)
        for l in langs:
            print "P%04d_%s" % (ctr, l), cwd, l
    else:
        for path in sorted(glob.glob("*")):
            if os.path.isdir(path):
                os.chdir(path)
                make_srclst_2()
                os.chdir(cwd)
Exemple #13
0
def line_between(g, cornerid1, cornerid2):
    '''Returns id of Line node between cornerid1 and cornerid2.'''
    return first(intersection(
        g.neighbors(cornerid1, neighbor_class=Line),
        g.neighbors(cornerid2, neighbor_class=Line)
    ))
Exemple #14
0
def find_page(img):
    """This function uses a Hough line transform to detect the four sides of a
    piece of paper in the image, applies an inverse warp transformation to
    correct for perspective distortion, returning the corrected image.
    """
    rows, cols = img.shape[:2]

    img2 = cv2.GaussianBlur(img, (params.BLUR_RADIUS, params.BLUR_RADIUS), 0)

    """
    util.show('Blurred', img2)
    """

    # use Canny edge deduction to obtain an edge map
    edge_map_bw = cv2.Canny(img2, params.CANNY_THRESHOLD_LOW, params.CANNY_THRESHOLD_HIGH)

    """
    util.show('Edges', edge_map_bw)
    """

    # use the probablistic Hough transform
    lines = cv2.HoughLinesP(
        edge_map_bw,
        params.HOUGH_DISTANCE_RESOLUTION,
        params.HOUGH_ANGLE_RESOLUTION,
        params.HOUGH_THRESHOLD,
        minLineLength=params.HOUGH_MIN_LINE_LENGTH,
        maxLineGap=params.HOUGH_MAX_LINE_GAP,
    )

    if lines is None:
        util.debug("detected no image outlines")
        return
    else:
        lines = lines[0].tolist()
        util.debug("detected %d image outlines: %s" % (len(lines), str(lines)))

    edge_map_color = cv2.cvtColor(edge_map_bw, cv2.COLOR_GRAY2BGR)

    while True:
        for a in lines:
            """
            util.debug('current line: %s' % str(a))
            """
            too_similar = False

            for b in lines:
                if a == b:
                    continue

                t = util.angle(a, b)
                d = util.distance(a, b)

                """
                util.debug('other line: %s (angle: %f)' % (str(b), t))
                """

                if d < params.DISTANCE_THRESHOLD and t < params.ANGLE_THRESHOLD:
                    too_similar = True
                    break

            if too_similar:
                """
                util.debug('removing %s' % str(a))
                """
                lines.remove(a)
                break

        if not too_similar:
            break

    util.debug("kept %d image outlines: %s" % (len(lines), str(lines)))

    for x1, y1, x2, y2 in lines:
        cv2.line(edge_map_color, (x1, y1), (x2, y2), util.RED, params.LINE_THICKNESS)

    """
    util.show('Lines', edge_map_color)
    """

    if len(lines) != 4:
        return None

    corners = set()
    for a in lines:
        for b in lines:
            if a == b:
                continue

            i = util.intersection(a, b)
            if i[0] >= 0 and i[0] < cols and i[1] >= 0 and i[1] < cols:
                corners.add(i)

    # take the most extreme four corners to be the corners of the page

    asc_by_x = lambda seq: sorted(seq, cmp=lambda a, b: int(a[0] - b[0]))
    asc_by_y = lambda seq: sorted(seq, cmp=lambda a, b: int(a[1] - b[1]))
    dsc_by_x = lambda seq: sorted(seq, cmp=lambda a, b: int(b[0] - a[0]))
    dsc_by_y = lambda seq: sorted(seq, cmp=lambda a, b: int(b[1] - a[1]))

    ul = asc_by_y(asc_by_x(corners))[0]
    corners.remove(ul)
    ur = asc_by_y(dsc_by_x(corners))[0]
    corners.remove(ur)
    ll = dsc_by_y(asc_by_x(corners))[0]
    corners.remove(ll)
    lr = dsc_by_y(dsc_by_x(corners))[0]
    corners.remove(lr)

    for x, y in [ul, ur, ll, lr]:
        cv2.circle(edge_map_color, (x, y), 3, util.GREEN, -1)

    """
    util.show('Lines & corners', edge_map_color)
    """

    # use these four corners to construct a transformation matrix

    # for the height/width of the new image, we use a bounding box
    rows2 = max(ll[1], lr[1]) - min(ul[1], ur[1])
    cols2 = max(ur[0], lr[0]) - min(ul[0], ll[0])

    """
    print("source: ", numpy.array([ul, ur, ll, lr]).astype('float32'))
    print("dest: ", numpy.array(
                [
                    [0, 0],
                    [cols2 - 1, 0],
                    [cols2 - 1, rows2 - 1],
                    [0, rows2 - 1]
                ]
            ).astype('float32'))
    """

    m = cv2.getPerspectiveTransform(
        numpy.array([ul, ur, ll, lr]).astype("float32"),
        numpy.array([[0, 0], [cols2 - 1, 0], [cols2 - 1, rows2 - 1], [0, rows2 - 1]]).astype("float32"),
    )

    corrected = cv2.warpPerspective(img, m, (cols2, rows2))

    """
    util.show('Corrected', corrected)
    """

    return corrected
        LMaj = u.line(pH, pT)
        pMaj = (pH, pT)
        pMin = (pW1, pW2)
        # if u.longer((pW1, pW2), (pH, pT)):
        #     LMaj = u.line(pW1, pW2)
        #     pMaj = (pW1, pW2)
        #     pMin = (pH, pT)

        # Find the equations of the long and short edges of the bounding box
        le = (u.linePointSlope(LMaj, pMin[0]), 
            u.linePointSlope(LMaj, pMin[1]))
        se = (u.linePointSlopeInverted(LMaj, pMaj[0]), 
            u.linePointSlopeInverted(LMaj, pMaj[1]))

        # Find the vertices of the bounding box from the lines
        v = (u.intersection(le[0], se[0]), 
            u.intersection(le[0], se[1]), 
            u.intersection(le[1], se[0]), 
            u.intersection(le[1], se[1]))

        # Show the raw vertices without epsilon
        if SHOW:
            plt.scatter(np.array(v)[:,0], np.array(v)[:,1])

        # Calculate the diagonal lines of the bounding box
        diags = (u.line(v[0], v[3]), u.line(v[1], v[2]))

        # Calculate the center, width, height, and angle of the bounding box
        c = u.intersection(diags[0], diags[1])      # Find the center by looking at the intersection
        w = u.length(v[0], v[1]) + EPSILON          # Find the width
        h = u.length(v[0], v[2]) + EPSILON          # Find the height
Exemple #16
0
def find_page(img):
    """This function uses a Hough line transform to detect the four sides of a
    piece of paper in the image, applies an inverse warp transformation to
    correct for perspective distortion, returning the corrected image.
    """
    rows, cols = img.shape[:2]

    img2 = cv2.GaussianBlur(img, (params.BLUR_RADIUS, params.BLUR_RADIUS), 0)
    """
    util.show('Blurred', img2)
    """

    # use Canny edge deduction to obtain an edge map
    edge_map_bw = cv2.Canny(img2, params.CANNY_THRESHOLD_LOW,
                            params.CANNY_THRESHOLD_HIGH)
    """
    util.show('Edges', edge_map_bw)
    """

    # use the probablistic Hough transform
    lines = cv2.HoughLinesP(edge_map_bw,
                            params.HOUGH_DISTANCE_RESOLUTION,
                            params.HOUGH_ANGLE_RESOLUTION,
                            params.HOUGH_THRESHOLD,
                            minLineLength=params.HOUGH_MIN_LINE_LENGTH,
                            maxLineGap=params.HOUGH_MAX_LINE_GAP)

    if lines is None:
        util.debug('detected no image outlines')
        return
    else:
        lines = lines[0].tolist()
        util.debug('detected %d image outlines: %s' % (len(lines), str(lines)))

    edge_map_color = cv2.cvtColor(edge_map_bw, cv2.COLOR_GRAY2BGR)

    while True:
        for a in lines:
            """
            util.debug('current line: %s' % str(a))
            """
            too_similar = False

            for b in lines:
                if a == b:
                    continue

                t = util.angle(a, b)
                d = util.distance(a, b)
                """
                util.debug('other line: %s (angle: %f)' % (str(b), t))
                """

                if d < params.DISTANCE_THRESHOLD and t < params.ANGLE_THRESHOLD:
                    too_similar = True
                    break

            if too_similar:
                """
                util.debug('removing %s' % str(a))
                """
                lines.remove(a)
                break

        if not too_similar:
            break

    util.debug('kept %d image outlines: %s' % (len(lines), str(lines)))

    for x1, y1, x2, y2 in lines:
        cv2.line(edge_map_color, (x1, y1), (x2, y2), util.RED,
                 params.LINE_THICKNESS)
    """
    util.show('Lines', edge_map_color)
    """

    if len(lines) != 4:
        return None

    corners = set()
    for a in lines:
        for b in lines:
            if a == b:
                continue

            i = util.intersection(a, b)
            if i[0] >= 0 and i[0] < cols and i[1] >= 0 and i[1] < cols:
                corners.add(i)

    # take the most extreme four corners to be the corners of the page

    asc_by_x = lambda seq: sorted(seq, cmp=lambda a, b: int(a[0] - b[0]))
    asc_by_y = lambda seq: sorted(seq, cmp=lambda a, b: int(a[1] - b[1]))
    dsc_by_x = lambda seq: sorted(seq, cmp=lambda a, b: int(b[0] - a[0]))
    dsc_by_y = lambda seq: sorted(seq, cmp=lambda a, b: int(b[1] - a[1]))

    ul = asc_by_y(asc_by_x(corners))[0]
    corners.remove(ul)
    ur = asc_by_y(dsc_by_x(corners))[0]
    corners.remove(ur)
    ll = dsc_by_y(asc_by_x(corners))[0]
    corners.remove(ll)
    lr = dsc_by_y(dsc_by_x(corners))[0]
    corners.remove(lr)

    for x, y in [ul, ur, ll, lr]:
        cv2.circle(edge_map_color, (x, y), 3, util.GREEN, -1)
    """
    util.show('Lines & corners', edge_map_color)
    """

    # use these four corners to construct a transformation matrix

    # for the height/width of the new image, we use a bounding box
    rows2 = max(ll[1], lr[1]) - min(ul[1], ur[1])
    cols2 = max(ur[0], lr[0]) - min(ul[0], ll[0])
    """
    print("source: ", numpy.array([ul, ur, ll, lr]).astype('float32'))
    print("dest: ", numpy.array(
                [
                    [0, 0],
                    [cols2 - 1, 0],
                    [cols2 - 1, rows2 - 1],
                    [0, rows2 - 1]
                ]
            ).astype('float32'))
    """

    m = cv2.getPerspectiveTransform(
        numpy.array([ul, ur, ll, lr]).astype('float32'),
        numpy.array([[0, 0], [cols2 - 1, 0], [cols2 - 1, rows2 - 1],
                     [0, rows2 - 1]]).astype('float32'))

    corrected = cv2.warpPerspective(img, m, (cols2, rows2))
    """
    util.show('Corrected', corrected)
    """

    return corrected
Exemple #17
0
    def renderAsJson(self, filename):
        bb = self.schedule.GetStopBoundingBox()
        longitude = (bb[1] + bb[3]) / 2.
        zone = (int((longitude + 180)/6) % 60) + 1
        utm17 = pyproj.Proj(proj='utm', zone=zone, ellps='WGS84')
        features = []

        for edge in self.graph.edges:
            if not self.graph.edges[edge]['junction']:
                A, B = edge
                A, B = fullEdge(A)
                currentEdge = self.graph.edges[edge]
                #self.graph.edges[edge]['offsets'] = {}
                self.graph.node[A]['points'] = {}
                self.graph.node[B]['points'] = {}
                centreGeom = currentEdge['geom'].simplify(self.totalThickness / 2.)
                __, self.graph.node[A]['dir'] = getDirection(centreGeom, True)
                __, self.graph.node[B]['dir'] = getDirection(centreGeom, False)
                #offset = -self.graph.edges[edge]['width'] / 2.
                for route in currentEdge['sequence']:
                    route_color = self.schedule.GetRoute(route).route_color
                    #offset += self._getTotalThickness(edge, route) / 2.
                    offset = currentEdge['offsets'][route]
                    geom = centreGeom.parallel_offset(offset, 'left')
                    #self.graph.edges[edge]['offsets'][route] = offset
                    if offset >= 0:
                        self.graph.node[A]['points'][route] = geom.coords[0]
                        self.graph.node[B]['points'][route] = geom.coords[-1]
                    else:
                        self.graph.node[A]['points'][route] = geom.coords[-1]
                        self.graph.node[B]['points'][route] = geom.coords[0]
                    #offset += self._getTotalThickness(edge, route) / 2.
                    coord_list = [list(utm17(inverse=True, *c))
                                  for c in geom.coords]
                    features.append({"type": "Feature",
                                     "properties": {
                                            'stroke-width': self._getLineThickness(edge, route),
                                            'stroke': '#' + route_color,
                                            'stroke-opacity': 1,
                                            'route': route,
                                            'sides': str(self.graph.edges[edge]['sides'].items())
                                        },
                                     "geometry": {
                                        "type": "LineString",
                                        "coordinates": coord_list
                                     }})
        for edge in self.graph.edges:
            if self.graph.edges[edge]['junction']:
                A, B = edge
                currentEdge = self.graph.edges[edge]
                edgeA = self.graph.edges[fullEdge(A)]
                edgeB = self.graph.edges[fullEdge(B)]
                seqA = list(edgeA['sequence'])
                seqB = list(edgeB['sequence'])
                if firstNode(A) == firstNode(B):
                    seqB.reverse()
                # __, dA = getDirection(edgeA['geom'], firstNode(A))
                # __, dB = getDirection(edgeB['geom'], firstNode(B))
                dA = self.graph.node[A]['dir']
                dB = self.graph.node[B]['dir']
                # if self.maxAngle > currentEdge['angle']:
                #
                #
                #     continue
                sinAB = np.cross(dA, dB)
                cosAB = np.dot(dA, dB)
                angle = np.arctan2(abs(sinAB), cosAB)
                right = sinAB > 0
                if right and firstNode(A) or not right and not firstNode(A):
                    seqA.reverse()
                    seqB.reverse()
                routesA = [r for r in seqA if r in currentEdge['routes']]
                routesB = [r for r in seqB if r in currentEdge['routes']]
                routes = [r for r in currentEdge['routes']
                          if r in routesA and r in routesB]
                if not routes:
                    continue
                offsetA0 = edgeA['offsets'][routesA[0]]
                offsetB0 = edgeB['offsets'][routesB[0]]

                # lastRadius = self.minRadius - self._getTotalThickness(edge, routeIndexes[0][1]) / 2.
                # delta = 0
                radii = {}
                for r in routes:
                    offsetA = abs(offsetA0 - edgeA['offsets'][r])
                    offsetB = abs(offsetB0 - edgeB['offsets'][r])
                    radii[r] = self.minRadius + min(offsetA, offsetB)
                # for i, r in sorted(routeIndexes):
                #     thickness = self._getTotalThickness(edge, r)
                #     if i != lastIndex:
                #         lastRadius += delta
                #         delta = 0
                #     radii[r] = lastRadius + thickness / 2.
                #     delta += thickness
                #     lastIndex = i
                for route in self.graph.edges[edge]['routes']:
                    route_color = self.schedule.GetRoute(route).route_color
                    if route not in edgeA['sequence'] or route not in edgeB['sequence']:
                        continue
                    ptA = np.array(self.graph.node[A]['points'][route])
                    ptB = np.array(self.graph.node[B]['points'][route])
                    # offsetA = edgeA['offsets'][route]
                    # offsetB = edgeB['offsets'][route]
                    # if firstNode(A):
                    #     ptA = edgeA['geom'].interpolate(0, normalized=True)
                    #     dirA = getDirection(edgeA['geom'], 0)
                    # else:
                    #     ptA = edgeA['geom'].interpolate(1, normalized=True)
                    #     dirA = getDirection(edgeA['geom'], 1)
                    # if firstNode(B):
                    #     ptB = edgeB['geom'].interpolate(0, normalized=True)
                    #     dirB = getDirection(edgeB['geom'], 0)
                    # else:
                    #     ptB = edgeB['geom'].interpolate(1, normalized=True)
                    #     dirB = getDirection(edgeB['geom'], 1)
                    # ptA = Point(ptA.x - dirA[1] * offsetA, ptA.y + dirA[0] * offsetA)
                    # ptB = Point(ptB.x - dirB[1] * offsetB, ptB.y + dirB[0] * offsetB)
                    radius = radii[route]
                    corner = intersection(ptA, dA, ptB, dB)
                    setback = radius / np.tan(angle/2)
                    delta = abs(setback-radius)/radius
                    filler = ''
                    if np.sin(self.maxAngle) > np.sin(angle) or delta > 1:
                        # hack for now with straight line
                        dAB = ptB - ptA
                        dAB /= np.linalg.norm(dAB)
                        dAR = np.array([dA[1], -dA[0]])
                        dBR = np.array([dB[1], -dB[0]])
                        crossAAB = np.cross(dA, dAB)
                        crossBAB = np.cross(dB, dAB)
                        dotAAB = np.dot(dA, dAB)
                        dotBAB = np.dot(dB, dAB)
                        offsetsA = [o
                                    for (r, o) in edgeA['offsets'].items()
                                    if r in routes]
                        offsetsB = [o
                                    for (r, o) in edgeB['offsets'].items()
                                    if r in routes]
                        if crossAAB < 0:  # left
                            if firstNode(A):
                                offsetA0 = min(offsetsA)
                            else:
                                offsetA0 = max(offsetsA)
                        else:  # right
                            if firstNode(A):
                                offsetA0 = max(offsetsA)
                            else:
                                offsetA0 = min(offsetsA)
                            dAR = -dAR
                        if crossBAB > 0:  # left
                            if firstNode(B):
                                offsetB0 = min(offsetsB)
                            else:
                                offsetB0 = max(offsetsB)
                        else:  # right
                            if firstNode(B):
                                offsetB0 = max(offsetsB)
                            else:
                                offsetB0 = min(offsetsB)
                            dBR = - dBR

                        radiusA = self.minRadius + abs(offsetA0 - edgeA['offsets'][route])
                        radiusB = self.minRadius + abs(offsetB0 - edgeB['offsets'][route])
                        centreA = ptA + dAR * radiusA
                        angleA = np.arctan2(-dAR[1], -dAR[0])
                        centreB = ptB + dBR * radiusB
                        angleB = np.arctan2(-dBR[1], -dBR[0])

                        l = np.linalg.norm(centreA - centreB)
                        #if radius + radius <= l:
                        __, dC = getDirection(LineString([centreA, centreB]))
                        angleC = np.arctan2(dC[1], dC[0])
                        if (crossAAB > 0 and crossBAB > 0) or (crossAAB < 0 and crossBAB < 0):
                            thetaB = np.arccos((radiusA-radiusB)/l)
                            thetaA = thetaB
                        elif radiusA + radiusB <= l:
                            thetaA = np.arccos((radiusA+radiusB)/l)
                            thetaB = np.pi - thetaA
                        else:
                            thetaA = 0
                            thetaB = np.pi
                        if crossAAB > 0:  # left
                            angleAC = angleC + thetaA
                        else:
                            angleAC = angleC - thetaA
                        if crossBAB < 0:  # left
                            angleBC = angleC - thetaB
                        else:
                            angleBC = angleC + thetaB
                        while angleAC - angleA > np.pi:
                            angleAC -= 2 * np.pi
                        while angleA - angleAC > np.pi:
                            angleAC += 2 * np.pi
                        while angleBC - angleB > np.pi:
                            angleBC -= 2 * np.pi
                        while angleB - angleBC > np.pi:
                            angleBC += 2 * np.pi
                        pts = [centreA + radiusA * np.array([np.cos(a), np.sin(a)]) for a in np.linspace(angleA, angleAC, 5)]
                        pts += [centreB + radiusB * np.array([np.cos(a), np.sin(a)]) for a in np.linspace(angleBC, angleB, 5)]
                        pts.insert(0, ptA)
                        pts.append(ptB)
                        filler = str((angleA, angleAC, angleBC, angleB, crossAAB, crossBAB, dotAAB, dotBAB, angleC, thetaA, thetaB, radiusA, radiusB))
                        # else:
                        #     pts = [ptA, ptB]

                        # coord_list = [list(utm17(*ptA, inverse=True)),
                        #               list(utm17(*ptB, inverse=True))]
                    else:
                        # radius = radii[route]
                        # corner = intersection(ptA, dA, ptB, dB)
                        # setback = radius / np.tan(angle/2)
                        endA = corner + dA * setback
                        if right:
                            # if firstNode(A):
                            #     setback = radius / np.tan(currentEdge['angle']/2)
                            # else:
                            #     setback = radius * np.tan(currentEdge['angle']/2)
                            # endA = corner + dA * setback
                            dAR = np.array([-dA[1], dA[0]])
                            dBR = np.array([dB[1], -dB[0]])
                            angleA = np.arctan2(-dAR[1], -dAR[0])
                            angleB = np.arctan2(-dBR[1], -dBR[0])
                            if angleB > angleA:
                                angleB -= 2. * np.pi
                        else:
                            # if firstNode(A):
                            #     setback = radius * np.tan(currentEdge['angle']/2)
                            # else:
                            #     setback = radius / np.tan(currentEdge['angle']/2)
                            # endA = corner + dA * setback
                            dAR = np.array([dA[1], -dA[0]])
                            dBR = np.array([-dB[1], dB[0]])
                            angleA = np.arctan2(-dAR[1], -dAR[0])
                            angleB = np.arctan2(-dBR[1], -dBR[0])
                            if angleB < angleA:
                                angleB += 2. * np.pi
                        centre = endA + radius * dAR
                        steps = int(abs(angleA - angleB)*4)  # for now, point at least every .25 radians
                        angles = np.linspace(angleA, angleB, steps + 2)
                        pts = [centre + [radius*np.cos(a), radius*np.sin(a)]
                               for a in angles]
                        pts.append(ptB)
                        pts.insert(0, ptA)
                    coord_list = [list(utm17(*pt, inverse=True))
                                  for pt in pts if pt[0] < 1e29]
                    thickness = min(self._getLineThickness(edgeA, route),
                                    self._getLineThickness(edgeB, route))
                    features.append({"type": "Feature",
                                     "properties": {
                                            'stroke-width': thickness,
                                            'stroke': '#' + route_color,
                                            'stroke-opacity': 1,
                                            'angles': filler
                                            # 'setback': min(setback, 1e30),
                                            # 'radius': radii[route]
                                        },
                                     "geometry": {
                                        "type": "LineString",
                                        "coordinates": coord_list
                                     }})


        data = {"type": "FeatureCollection",
                "features": features}
        with open(filename, 'w') as fp:
            json.dump(data, fp)
Exemple #18
0
 def is_already_consumed(self, g):
     consumers = intersection(
         *[g.neighbors(o, port_label='consumer') for o in self.operandids]
     )
     consumer_classes = set([g.class_of(c) for c in consumers])
     return self.operator_class in consumer_classes