示例#1
0
def _draw_classical_double_line(drawing: Drawing, x1_coord: int, y1_coord: int,
                                x2_coord: int, y2_coord: int) -> None:
    """Draw a double line between (x1_coord, y1_coord) and (x2_coord, y2_coord).

    :param drawing: Drawing that will be used to draw.
    :param x1_coord: x-coordinate of the first point.
    :param y1_coord: y-coordinate of the first point.
    :param x2_coord: x-coordinate of the second point.
    :param y2_coord: y-coordinate of the second point.
    :raise NotImplementedError: when x1_coord != x2_coord and
    y1_coord != y2_coord (i.e. when the line is neither horizontal
    nor vertical).
    """
    x_increment, y_increment = 0, 0
    if x1_coord == x2_coord:
        x_increment = _constants.DOUBLE_LINES_SEPARATION
    elif y1_coord == y2_coord:
        y_increment = _constants.DOUBLE_LINES_SEPARATION
    else:
        raise NotImplementedError("The drawn line should be either horizontal "
                                  "or vertical.")
    drawing.add(
        drawing.line(start=(x1_coord - x_increment, y1_coord - y_increment),
                     end=(x2_coord - x_increment, y2_coord - y_increment),
                     stroke=_constants.GATE_BORDER_COLOR,
                     stroke_width=_constants.STROKE_THICKNESS))
    drawing.add(
        drawing.line(start=(x1_coord + x_increment, y1_coord + y_increment),
                     end=(x2_coord + x_increment, y2_coord + y_increment),
                     stroke=_constants.GATE_BORDER_COLOR,
                     stroke_width=_constants.STROKE_THICKNESS))
示例#2
0
    def plot(self, x, y, scale, **extra):

        assert isinstance(scale, (int, float))
        assert isinstance(x, (int, float))
        assert isinstance(y, (int, float))

        svg = Drawing()
        g = svg.g()

        p1 = [x, y]
        p2 = [x + max(self.ticks) * scale, y]

        g.add(svg.line(start=p1, end=p2, stroke="black", stroke_width=1))

        for i, tick in enumerate(self.ticks):
            p1 = [x + tick * scale, y - 5]
            p2 = [x + tick * scale, y + 0.5]

            g.add(svg.line(start=p1, end=p2, stroke="black", stroke_width=1))

            g.add(
                svg.text(text="%s" % self.labels[i],
                         insert=[x + tick * scale, y + 10],
                         font_size=8,
                         font_family="Arial"))

        return g
示例#3
0
def _draw_cnot_cross(drawing: Drawing,
                     x_coord: float,
                     y_coord: float) -> None:
    # Draw the circle
    _draw_gate_circle(drawing, x_coord, y_coord)

    # Draw the cross
    drawing.add(drawing.line(start=(x_coord - _constants.GATE_SIZE/2, y_coord),
                             end=(x_coord + _constants.GATE_SIZE/2, y_coord),
                             stroke=_constants.GATE_BORDER_COLOR,
                             stroke_width=_constants.STROKE_THICKNESS))

    drawing.add(drawing.line(start=(x_coord, y_coord - _constants.GATE_SIZE/2),
                             end=(x_coord, y_coord + _constants.GATE_SIZE/2),
                             stroke=_constants.GATE_BORDER_COLOR,
                             stroke_width=_constants.STROKE_THICKNESS))
示例#4
0
def make_lines(layer, drawing: svgwrite.Drawing, inpts):
    usage = {k: 0 for k in inpts}
    conn = 9
    preferred_dist = 5
    used_pairs = set([])
    inpts.sort(key=lambda x: distance((page_width / 2, page_height / 2), x))
    while len([True for k in inpts if usage[k] < conn]) > 1:
        available = [k for k in inpts if usage[k] < conn]
        startpt = available[0]
        endpts = [
            k for k in available
            if k != startpt and (startpt, k) not in used_pairs
            and k[0] != startpt[0] and k[1] != startpt[1]
        ]
        if len(endpts) == 0:
            usage[startpt] += 1
            continue
        endpt = min(endpts,
                    key=lambda x: abs(preferred_dist - distance(x, startpt)))
        usage[startpt] += 1
        usage[endpt] += 1
        preferred_dist = preferred_dist
        used_pairs.add((endpt, startpt))
        used_pairs.add((startpt, endpt))
        if distance(startpt, endpt) < 100:
            layer.add(
                drawing.line(startpt,
                             endpt,
                             stroke=svgwrite.rgb(10, 10, 16, '%'),
                             stroke_width=5,
                             stroke_linecap='round',
                             stroke_opacity=1.0))
示例#5
0
def slice_file(image_position_patient_array,
               image_orientation_patient,
               output_path=None,
               input_path=None):
    print("Status: Loading File.")

    model = STLModel(input_path)
    stats = model.stats()

    print(stats)

    print("Status: Calculating Slices")

    v1 = Point3D(image_orientation_patient[0][0],
                 image_orientation_patient[0][1],
                 image_orientation_patient[0][2])
    v2 = Point3D(image_orientation_patient[1][0],
                 image_orientation_patient[1][1],
                 image_orientation_patient[1][2])
    org = Point3D(0, 0, 0)

    for i, slice_loc in enumerate(image_position_patient_array):
        slice_loc = Point3D(slice_loc[0], slice_loc[1], slice_loc[2])

        dwg = Drawing(output_path + str(i) + '.svg', profile='tiny')
        plane = Plane(v1 + slice_loc, v2 + slice_loc, org + slice_loc)
        x_axis = Line(org + slice_loc, v1 + slice_loc)
        y_axis = Line(org + slice_loc, v2 + slice_loc)
        pairs = model.slice_at_plane(plane, x_axis, y_axis)
        for pair in pairs:
            dwg.add(dwg.line(pair[0], pair[1], stroke=rgb(0, 0, 0, "%")))
        dwg.save()

    print("Status: Finished Outputting Slices")
示例#6
0
def _draw_line_between_qubits(drawing: Drawing,
                              bit_gate_rank: _types.BitRankType,
                              control_qubit: int, target_qubit: int,
                              bit_mapping: dict,
                              index_to_draw: int = None) -> None:
    """Draw a line between the two given qubits.

    :param drawing: Drawing that will be used to draw.
    :param bit_gate_rank: Structure used to keep track of the used and free
    places. See module docstring for more information.
    :param control_qubit: First qubit.
    :param target_qubit: Second qubit.
    :param bit_mapping: Unused at the moment.
    :param index_to_draw: If precised, force the line to be drawn at the given
    index. Else, the index is computed and the line drawn at the first free
    place possible.
    """
    if index_to_draw is None:
        index_to_draw, _ = _helpers.get_max_index(bit_gate_rank,
                                                  qubits=[control_qubit,
                                                          target_qubit])
    x_coord = _helpers.get_x_from_index(index_to_draw)
    y1_coord = _helpers.get_y_from_quantum_register(control_qubit, bit_mapping)
    y2_coord = _helpers.get_y_from_quantum_register(target_qubit, bit_mapping)
    drawing.add(drawing.line(start=(x_coord, y1_coord), end=(x_coord, y2_coord),
                             stroke=_constants.GATE_BORDER_COLOR,
                             stroke_width=_constants.STROKE_THICKNESS))
示例#7
0
def _draw_swap_cross(drawing: Drawing, x_coord: float, y_coord: float) -> None:
    start_bl_tr = tuple((x_coord - _constants.GATE_SIZE / 2,
                         y_coord - _constants.GATE_SIZE / 2))
    end_bl_tr = tuple((x_coord + _constants.GATE_SIZE / 2,
                       y_coord + _constants.GATE_SIZE / 2))
    # Draw the cross
    drawing.add(drawing.line(start=start_bl_tr, end=end_bl_tr,
                             stroke=_constants.GATE_BORDER_COLOR,
                             stroke_width=_constants.STROKE_THICKNESS))

    start_br_tl = tuple((x_coord + _constants.GATE_SIZE / 2,
                         y_coord - _constants.GATE_SIZE / 2))
    end_br_tl = tuple((x_coord - _constants.GATE_SIZE / 2,
                       y_coord + _constants.GATE_SIZE / 2))
    drawing.add(drawing.line(start=start_br_tl, end=end_br_tl,
                             stroke=_constants.GATE_BORDER_COLOR,
                             stroke_width=_constants.STROKE_THICKNESS))
def generate_frame(i, j, k):
    filename = str(i)+str(j)+str(k)+".svg"
    dwg = Drawing(filename, size=(300, 300))
    dwg.add(dwg.text('i = %d, j = %d, k %d' % (i, j, k), insert=(0.5, 20),
                     fill='red'))
    dwg.add(dwg.line((0, 0), (10, 0), stroke=rgb(10, 10, 16, '%')))
    dwg.save()
    pixel_width = 300
    return convert(pixel_width, filename)
示例#9
0
    def draw_svg(self, drawing: svgwrite.Drawing, g):

        glane = drawing.g()
        glane.attribs["class"] = "lane"

        cp1 = self.control_points[0]
        cp2 = self.control_points[-1]
        rel = relative_pose(cp1.as_SE2(), cp2.as_SE2())
        _, theta = geo.translation_angle_from_SE2(rel)

        delta = int(np.sign(theta))
        fill = {-1: "#577094", 0: "#709457", 1: "#947057"}[delta]

        points = self.lane_profile(points_per_segment=10)
        p = drawing.polygon(points=points, fill=fill, fill_opacity=0.5)

        glane.add(p)

        center_points = self.center_line_points(points_per_segment=10)
        center_points = [
            geo.translation_angle_from_SE2(_)[0] for _ in center_points
        ]
        p = drawing.polyline(
            points=center_points,
            stroke=fill,
            fill="none",
            stroke_dasharray="0.02",
            stroke_width=0.01,
        )
        glane.add(p)

        g.add(glane)

        for x in self.control_points:
            q = x.asmatrix2d().m
            p1, _ = geo.translation_angle_from_SE2(q)
            delta_arrow = np.array([self.width / 4, 0])
            p2 = SE2_apply_R2(q, delta_arrow)
            gp = drawing.g()
            gp.attribs["class"] = "control-point"
            l = drawing.line(
                start=p1.tolist(),
                end=p2.tolist(),
                stroke="black",
                stroke_width=self.width / 20.0,
            )
            gp.add(l)
            c = drawing.circle(
                center=p1.tolist(),
                r=self.width / 8,
                fill="white",
                stroke="black",
                stroke_width=self.width / 20.0,
            )
            gp.add(c)
            g.add(gp)
示例#10
0
def _draw_registers_names_and_lines(drawing: Drawing,
                                    circuit_width: int,
                                    json_circuit: str,
                                    show_clbits: bool) -> None:

    # First we draw the names of each register
    qubit_labels = json_circuit['header'].get('qubit_labels', [])
    clbit_labels = json_circuit['header'].get('clbit_labels', []) if show_clbits else []
    ## 1. Compute the font size that will be used to keep good dimensions
    font_size = _constants.REGISTER_NAME_FONT_SIZE
    for qubit_label in itertools.chain(qubit_labels, clbit_labels):
        qubit_text_name = "{}[{}]".format(*qubit_label)
        desired_width = (_constants.REGISTER_NAME_WIDTH
                         - _constants.REGISTER_NAME_LEFT_BORDER
                         - _constants.REGISTER_NAME_RIGHT_BORDER)
        adapted_font_size = _helpers.adapt_text_font_size(qubit_text_name,
                                                          desired_width,
                                                          _constants.MAX_REGISTER_NAME_HEIGHT)
        font_size = min(font_size, adapted_font_size)
    ## 2. Draw the bit names
    y_coord = _constants.VERTICAL_BORDER
    for bit_label in itertools.chain(qubit_labels, clbit_labels):
        qubit_text_name = "{}[{}]".format(*bit_label)
        drawing.add(
            drawing.text(
                qubit_text_name,
                insert=(_constants.REGISTER_NAME_WIDTH - _constants.REGISTER_NAME_RIGHT_BORDER,
                        y_coord + _constants.FONT_SIZE_CENTER_VERTICALLY_MULTIPLIER * font_size),
                text_anchor="end",
                font_size=font_size
            )
        )
        y_coord += _constants.REGISTER_LINES_VERTICAL_SPACING


    # Then we draw the register lines
    y_coord = _constants.VERTICAL_BORDER

    # Start with quantum registers
    quantum_register_number = json_circuit['header'].get('number_of_qubits', 0)
    for _ in range(quantum_register_number):
        drawing.add(drawing.line(start=(_constants.REGISTER_NAME_WIDTH, y_coord),
                                 end=(circuit_width, y_coord),
                                 stroke=_constants.GATE_BORDER_COLOR,
                                 stroke_width=_constants.STROKE_THICKNESS))
        y_coord += _constants.REGISTER_LINES_VERTICAL_SPACING

    # And see if we want to plot classical registers.
    if show_clbits:
        classical_register_number = json_circuit['header'].get('number_of_clbits', 0)
        for _ in range(classical_register_number):
            _draw_classical_double_line(drawing, _constants.REGISTER_NAME_WIDTH,
                                        y_coord, circuit_width, y_coord)
            y_coord += _constants.REGISTER_LINES_VERTICAL_SPACING
示例#11
0
def slice_file(f=None, resolution=0.1):
    print("Status: Loading File.")

    model = STLModel(f)
    scale = 10
    stats = model.stats()

    sub_vertex = Vector3(stats['extents']['x']['lower'],
                         stats['extents']['y']['lower'],
                         stats['extents']['z']['lower'])
    add_vertex = Vector3(0.5, 0.5, 0.5)

    model.xmin = model.xmax = None
    model.ymin = model.ymax = None
    model.zmin = model.zmax = None

    print("Status: Scaling Triangles.")

    for triangle in model.triangles:
        triangle.vertices[0] -= sub_vertex
        triangle.vertices[1] -= sub_vertex
        triangle.vertices[2] -= sub_vertex

        # The lines above have no effect on the normal.

        triangle.vertices[0] = (triangle.vertices[0] * scale) + add_vertex
        triangle.vertices[1] = (triangle.vertices[1] * scale) + add_vertex
        triangle.vertices[2] = (triangle.vertices[2] * scale) + add_vertex

        # Recalculate the triangle normal

        u = model.triangles[0].vertices[1] - model.triangles[0].vertices[0]
        v = model.triangles[0].vertices[2] - model.triangles[0].vertices[0]

        triangle.n = Normal((u.y * v.z) - (u.z * v.y),
                            (u.z * v.x) - (u.x * v.z),
                            (u.x * v.y) - (u.y * v.x))
        model.update_extents(triangle)

    print("Status: Calculating Slices")

    interval = scale * resolution
    stats = model.stats()
    print(stats)

    for targetz in range(0, int(stats['extents']['z']['upper']),
                         int(interval)):
        dwg = Drawing('outputs/svg/' + str(targetz) + '.svg', profile='tiny')
        pairs = model.slice_at_z(targetz)
        for pair in pairs:
            dwg.add(dwg.line(pair[0], pair[1], stroke=rgb(0, 0, 0, "%")))
        dwg.save()

    print("Status: Finished Outputting Slices")
示例#12
0
def _draw_cnot_cross(drawing: Drawing, x_coord: float, y_coord: float) -> None:
    """Draw the cross of a CX gate with the circle around.

    :param drawing: Drawing that will be used to draw.
    :param x_coord: x-coordinate of the crossing point.
    :param y_coord: y-coordinate of the crossing point.
    """
    # Draw the circle
    _draw_gate_circle(drawing, x_coord, y_coord)

    # Draw the cross
    drawing.add(
        drawing.line(start=(x_coord - _constants.GATE_SIZE / 2, y_coord),
                     end=(x_coord + _constants.GATE_SIZE / 2, y_coord),
                     stroke=_constants.GATE_BORDER_COLOR,
                     stroke_width=_constants.STROKE_THICKNESS))

    drawing.add(
        drawing.line(start=(x_coord, y_coord - _constants.GATE_SIZE / 2),
                     end=(x_coord, y_coord + _constants.GATE_SIZE / 2),
                     stroke=_constants.GATE_BORDER_COLOR,
                     stroke_width=_constants.STROKE_THICKNESS))
示例#13
0
def display_svg():
    dwg = Drawing()
    hlines = dwg.add(dwg.g(id="hlines", stroke="green"))
    for y in range(20):
        hlines.add(
            dwg.line(start=(2 * cm, (2 + y) * cm),
                     end=(18 * cm, (2 + y) * cm)))
    vlines = dwg.add(dwg.g(id="vline", stroke="blue"))
    for x in range(17):
        vlines.add(
            dwg.line(start=((2 + x) * cm, 2 * cm),
                     end=((2 + x) * cm, 21 * cm)))
    shapes = dwg.add(dwg.g(id="shapes", fill="red"))

    # set presentation attributes at object creation as SVG-Attributes
    circle = dwg.circle(center=(15 * cm, 8 * cm),
                        r="2.5cm",
                        stroke="blue",
                        stroke_width=3)
    circle["class"] = "class1 class2"
    shapes.add(circle)

    # override the 'fill' attribute of the parent group 'shapes'
    shapes.add(
        dwg.rect(
            insert=(5 * cm, 5 * cm),
            size=(45 * mm, 45 * mm),
            fill="blue",
            stroke="red",
            stroke_width=3,
        ))

    # or set presentation attributes by helper functions of the Presentation-Mixin
    ellipse = shapes.add(
        dwg.ellipse(center=(10 * cm, 15 * cm), r=("5cm", "10mm")))
    ellipse.fill("green", opacity=0.5).stroke("black",
                                              width=5).dasharray([20, 20])

    return Response(dwg.tostring(), mimetype="image/svg+xml")
示例#14
0
def _draw_classical_double_line(drawing: Drawing,
                                x1_coord, y1_coord,
                                x2_coord, y2_coord) -> None:
    """Draw a double line between (x1_coord,y1_coord) and (x2_coord,y2_coord).

    Raises:
        NotImplementedError: when x1_coord!=x2_coord and y1_coord!=y2_coord (i.e. when the
                         line is neither horizontal nor vertical).
    """
    x_increment, y_increment = 0, 0
    if x1_coord == x2_coord:
        x_increment = _constants.DOUBLE_LINES_SEPARATION
    elif y1_coord == y2_coord:
        y_increment = _constants.DOUBLE_LINES_SEPARATION
    else:
        raise NotImplementedError("The drawed line should be either horizontal or vertical.")
    drawing.add(drawing.line(start=(x1_coord - x_increment, y1_coord - y_increment),
                             end=(x2_coord - x_increment, y2_coord - y_increment),
                             stroke=_constants.GATE_BORDER_COLOR,
                             stroke_width=_constants.STROKE_THICKNESS))
    drawing.add(drawing.line(start=(x1_coord + x_increment, y1_coord + y_increment),
                             end=(x2_coord + x_increment, y2_coord + y_increment),
                             stroke=_constants.GATE_BORDER_COLOR,
                             stroke_width=_constants.STROKE_THICKNESS))
示例#15
0
def make_lines2(layer, drawing: svgwrite.Drawing, inpts):
    tail = inpts

    while len(tail) > 1:
        head, *tail = tail

        minpt = min(tail, key=lambda x: distance(x, head))
        if not in_circle(circle_radius, mid_point(
                head, minpt)) and distance(minpt, head) < 15:
            layer.add(
                drawing.line(head,
                             minpt,
                             stroke=svgwrite.rgb(255, 10, 16, '%'),
                             stroke_width=8,
                             stroke_linecap='round'))
示例#16
0
def _draw_line_between_qubits(drawing: Drawing,
                              bit_gate_rank: BitRankType,
                              control_qubit: int,
                              target_qubit: int,
                              bit_mapping: dict,
                              index_to_draw: int = None) -> None:
    if index_to_draw is None:
        index_to_draw, _ = _helpers.get_max_index(bit_gate_rank,
                                                  qubits=[control_qubit, target_qubit])
    x_coord = _helpers.get_x_from_index(index_to_draw)
    y1_coord = _helpers.get_y_from_quantum_register(control_qubit, bit_mapping)
    y2_coord = _helpers.get_y_from_quantum_register(target_qubit, bit_mapping)
    drawing.add(drawing.line(start=(x_coord, y1_coord),
                             end=(x_coord, y2_coord),
                             stroke=_constants.GATE_BORDER_COLOR,
                             stroke_width=_constants.STROKE_THICKNESS))
示例#17
0
    def _draw_year(self, d: svgwrite.Drawing, size: XY, offset: XY, year: int):
        min_size = min(size.x, size.y)
        outer_radius = 0.5 * min_size - 6
        radius_range = ValueRange.from_pair(outer_radius / 4, outer_radius)
        center = offset + 0.5 * size

        if self._rings:
            self._draw_rings(d, center, radius_range)

        year_style = 'dominant-baseline: central; font-size:{}px; font-family:Arial;'.format(min_size * 4.0 / 80.0)
        month_style = 'font-size:{}px; font-family:Arial;'.format(min_size * 3.0 / 80.0)

        d.add(d.text('{}'.format(year), insert=center.tuple(), fill=self.poster.colors['text'], text_anchor="middle",
                     alignment_baseline="middle", style=year_style))
        df = 360.0 / (366 if calendar.isleap(year) else 365)
        day = 0
        date = datetime.date(year, 1, 1)
        while date.year == year:
            text_date = date.strftime("%Y-%m-%d")
            a1 = math.radians(day * df)
            a2 = math.radians((day + 1) * df)
            if date.day == 1:
                (_, last_day) = calendar.monthrange(date.year, date.month)
                a3 = math.radians((day + last_day - 1) * df)
                sin_a1, cos_a1 = math.sin(a1), math.cos(a1)
                sin_a3, cos_a3 = math.sin(a3), math.cos(a3)
                r1 = outer_radius + 1
                r2 = outer_radius + 6
                r3 = outer_radius + 2
                d.add(d.line(
                    start=(center + r1 * XY(sin_a1, -cos_a1)).tuple(),
                    end=(center + r2 * XY(sin_a1, -cos_a1)).tuple(),
                    stroke=self.poster.colors['text'],
                    stroke_width=0.3))
                path = d.path(d=('M', center.x + r3 * sin_a1, center.y - r3 * cos_a1), fill='none', stroke='none')
                path.push('a{},{} 0 0,1 {},{}'.format(r3, r3, r3 * (sin_a3 - sin_a1), r3 * (cos_a1 - cos_a3)))
                d.add(path)
                tpath = svgwrite.text.TextPath(path, date.strftime("%B"), startOffset=(0.5 * r3 * (a3 - a1)))
                text = d.text("", fill=self.poster.colors['text'], text_anchor="middle", style=month_style)
                text.add(tpath)
                d.add(text)
            if text_date in self.poster.tracks_by_date:
                self._draw_circle_segment(d, self.poster.tracks_by_date[text_date], a1, a2, radius_range, center)

            day += 1
            date += datetime.timedelta(1)
示例#18
0
    def add(self, svg: Drawing) -> None:

        a: np.array = to_grid(self.point1)
        b: np.array = to_grid(self.point2)
        n = (b - a) / np.linalg.norm((b - a))
        na = a + (n * self.radius)
        nb = b - (n * self.radius)
        line = svg.line(na, nb, stroke_width=0.5, fill="none", stroke="black")
        if not self.is_feasible:
            line.update({"stroke-dasharray": "1,1"})
        svg.add(line)

        v = svg.path(d=create_v(nb, n,
                                np.dot(rotation_matrix(-math.pi / 2.0), n)),
                     stroke_width=0.5,
                     fill="none",
                     stroke="black")
        if not self.is_feasible:
            v.update({"stroke-dasharray": "1,1"})
        svg.add(v)
示例#19
0
        val = col.iloc[j]
        y = vertplace(j, col)
        if i == 0:
            txt = g.add(
                dwg.text(collabels.iloc[j] + tabpad + str(val),
                         insert=(collocs[i], h - y),
                         text_anchor='end',
                         font_size="%ipx" % fontsize))
        elif i == ncols - 1:
            txt = g.add(
                dwg.text(str(val) + tabpad + collabels.iloc[j],
                         insert=(collocs[i], h - y),
                         font_size="%ipx" % fontsize))
        else:
            txt = g.add(
                dwg.text(str(val),
                         insert=(collocs[i], h - y),
                         font_size="%ipx" % fontsize))

        ys[collabels.iloc[j]].append(y)

        if i > 0:
            line = g.add(
                dwg.line((collocs[i - 1] + textpad,
                          h - ys[collabels.iloc[j]][i - 1]),
                         (collocs[i] - textpad, h - ys[collabels.iloc[j]][i]),
                         stroke_width=1,
                         stroke='black'))

dwg.save()
示例#20
0
    def plot(self, svg: Drawing) -> None:

        recolor: Optional[str] = None

        if isinstance(self.color, list):
            linear_gradient: LinearGradient = svg.linearGradient(
                self.map_((0, self.max_y)),
                self.map_((0, 1)),
                gradientUnits="userSpaceOnUse",
            )
            for index, color in enumerate(self.color):
                linear_gradient.add_stop_color(
                    index / (len(self.color) - 1), color.hex
                )

            gradient: LinearGradient = svg.defs.add(linear_gradient)
            recolor = gradient.get_funciri()

        if isinstance(self.color, Color):
            recolor = self.color.hex

        svg.add(
            svg.rect(
                insert=(0, 0),
                size=("100%", "100%"),
                rx=None,
                ry=None,
                fill=self.background_color.hex,
            )
        )
        self.draw_grid(svg)
        last_text_y = 0

        for xs, ys, color, title in self.data:

            if recolor:
                color = recolor

            assert len(xs) == len(ys)

            xs_second: list[float] = [
                (x - self.min_x).total_seconds() for x in xs
            ]
            points = []

            for index, x in enumerate(xs_second):
                y = ys[index]
                mapped: np.ndarray = map_array(
                    np.array((x, y)),
                    np.array((self.min_x_second, self.max_y)),
                    np.array((self.max_x_second, self.min_y)),
                    self.canvas.workspace[0],
                    self.canvas.workspace[1],
                )
                points.append(mapped)
            previous_point: Optional[np.ndarray] = None

            for point in points:
                if previous_point is not None:
                    line: Line = svg.line(
                        (previous_point[0], previous_point[1]),
                        (point[0], point[1]),
                        stroke=self.background_color.hex,
                        stroke_width=6,
                    )
                    svg.add(line)
                    line: Line = svg.line(
                        (previous_point[0], previous_point[1]),
                        (point[0], point[1]),
                        stroke=color,
                        stroke_width=2,
                    )
                    svg.add(line)
                previous_point = point

            for point in points:
                svg.add(
                    svg.circle(
                        (point[0], point[1]),
                        5.5,
                        fill=self.background_color.hex,
                    )
                )
                svg.add(svg.circle((point[0], point[1]), 3.5, fill=color))

            title: str
            text_y = max(last_text_y + 20, point[1] + 6)
            self.text(svg, (point[0] + 15, text_y), title.upper(), color)
            last_text_y = text_y

        with Path(svg.filename).open("w+") as output_file:
            svg.write(output_file)
示例#21
0
for loc in locs:
    top_text.add(dwg.text(loc, (x - len(loc) * 4, y)))
    vertical_locs.append(x)
    x += delta_x

legend_text = dwg.add(
    dwg.g(font_size=main_font_size, style="font-family: arial;"))
legend_text.add(dwg.text('Phys', (x - 1500, y - 10), fill=color_phys))
legend_text.add(dwg.text('Scaled', (x - 1500, y + 20), fill=color_scaled))

v_lines = dwg.add(dwg.g(stroke_width=7.0, stroke=color_phys, fill='none'))
v_lines_scaled = dwg.add(
    dwg.g(stroke_width=7.0, stroke=color_scaled, fill='none'))

for loc in vertical_locs:
    v_lines.add(dwg.line(start=(loc, y + 15), end=(loc, 1300)))

extra_text = dwg.add(
    dwg.g(font_size=main_font_size - 3, style="font-family: arial;"))
extra_text.add(dwg.text('fwd mode', (150, 50)))
extra_text.add(dwg.text('unit conversion', (vertical_locs[3] + 15, 870)))

locs = [
    ('Problem.compute_totals()', None, []),
    ('_TotalJacInfo.compute_totals()', None, []),
    ('System.scaled_context_all()', ((0, 2), (0, 3), (0, 5), (0, 6)),
     ['stagger']),
    ('Group._linearize()', None, []),
    ('  ExplicitComponent._linearize()', None, []),
    ('  ExplicitComponent._unscaled_context()', ((0, 2), (0, 3), (0, 5),
                                                 (0, 6)), ['stagger']),
for loc in locs:
    top_text.add(dwg.text(loc, (x - len(loc) * 4, y)))
    vertical_locs.append(x)
    x += delta_x

legend_text = dwg.add(
    dwg.g(font_size=main_font_size, style="font-family: arial;"))
legend_text.add(dwg.text('Phys', (x - 300, y - 10), fill=color_phys))
legend_text.add(dwg.text('Scaled', (x - 300, y + 20), fill=color_scaled))

v_lines = dwg.add(dwg.g(stroke_width=7.0, stroke=color_phys, fill='none'))
v_lines_scaled = dwg.add(
    dwg.g(stroke_width=7.0, stroke=color_scaled, fill='none'))

for loc in vertical_locs:
    v_lines.add(dwg.line(start=(loc, y + 15), end=(loc, 1100)))

extra_text = dwg.add(
    dwg.g(font_size=main_font_size - 3, style="font-family: arial;"))
extra_text.add(dwg.text('Unit Conversion', (vertical_locs[0] + 10, 650)))

locs = [
    ('Problem.run_model()', None, []),
    ('Model.run_solve_nonlinear()', None, []),
    ('System.scaled_context_all()', ((0, 2), (0, 3)), []),
    ('System.solve_nonlinear()', None, []),
    ('NonlinearRunOnce.solve()', None, []),
    ('NonlinearRunOnce.gs_iter()', None, []),
    ('  Group._transfer()', None, []),
    ("  DefaultVector.scale('norm')", ((0, 1), ), []),
    ('  DefaultTransfer.transfer()', ((2, 1), ), []),
delta_x = 400
vertical_locs = []
for loc in locs:
    top_text.add(dwg.text(loc, (x - len(loc)*4, y)))
    vertical_locs.append(x)
    x += delta_x

legend_text = dwg.add(dwg.g(font_size=main_font_size, style="font-family: arial;"))
legend_text.add(dwg.text('Phys', (x-300, y-10), fill=color_phys))
legend_text.add(dwg.text('Scaled', (x-300, y+20), fill=color_scaled))

v_lines = dwg.add(dwg.g(stroke_width=7.0, stroke=color_phys, fill='none'))
v_lines_scaled = dwg.add(dwg.g(stroke_width=7.0, stroke=color_scaled, fill='none'))

for loc in vertical_locs:
    v_lines.add(dwg.line(start=(loc, y+15), end=(loc, 1100)))

extra_text = dwg.add(dwg.g(font_size=main_font_size - 3, style="font-family: arial;"))
extra_text.add(dwg.text('Unit Conversion', (vertical_locs[0] + 10, 650)))

locs = [('Problem.run_model()', None, []),
        ('Model.run_solve_nonlinear()', None, []),
        ('System.scaled_context_all()', ((0, 2), (0, 3)), []),
        ('System.solve_nonlinear()', None, []),
        ('NonlinearRunOnce.solve()', None, []),
        ('NonlinearRunOnce.gs_iter()', None, []),
        ('  Group._transfer()', None, []),
        ("  DefaultVector.scale('norm')", ((0, 1), ), []),
        ('  DefaultTransfer.transfer()', ((2, 1), ), []),
        ("  DefaultVector.scale('phys')", ((0, 1), ), []),
        ('  ExplicitComponent.solve_nonlinear()', None, []),
示例#24
0
def add_graphelement_to_svg_drawing(element: GraphElement,
                                    drawing: svgwrite.Drawing,
                                    filters: Dict[str, Filter]) -> None:
    args = {}
    for attr, value in element.attr.items():
        if attr.startswith('.svg_tag'):
            continue
        if attr.startswith('.svg_'):
            name = attr[5:]
            if name == 'filter':
                args[name] = filters[value].get_funciri()
            else:
                args[name] = value
    if '.svg_tag' in element.attr:
        tag = element.attr['.svg_tag']
        if tag == 'rect':
            x = float(element.attr['x'])
            y = -float(element.attr['y'])
            width = float(element.attr.get('.svg_width', 0.1))
            height = float(element.attr.get('.svg_height', 0.1))
            x = x - width / 2
            y = y - height / 2
            drawing.add(drawing.rect((x*mult, y*mult), (width*mult, height*mult),
                                     **args))
        elif tag == 'path':
            drawing.add(drawing.path(**args))
        elif tag == 'circle':
            x = float(element.attr['x'])
            y = -float(element.attr['y'])
            args.setdefault('r', '1cm')
            args.setdefault('stroke_width', '0.1mm')
            args.setdefault('stroke', 'black')
            args.setdefault('fill', 'none')
            drawing.add(drawing.circle(center=(x * mult, y * mult), **args))
        elif tag == 'image':
            x = float(element.attr['x'])
            y = -float(element.attr['y'])
            width = float(element.attr.pop('.svg_width', 5))
            height = float(element.attr.pop('.svg_height', 5))
            x = x - width / 2
            y = y - height / 2
            center = ((x + width / 2), (y + height / 2))
            args.setdefault('insert', (x * mult, y * mult))
            args.setdefault('size', (width * mult, height * mult))
            if '.svgx_rotate' in element.attr:
                rotation = float(element.attr['.svgx_rotate'])
                args.setdefault('transform',
                                f'translate({center[0]*mult}, {center[1]*mult}) '
                                f'rotate({-rotation}) '
                                f'translate({-center[0]*mult}, {-center[1]*mult})'
                                )
            drawing.add(getattr(drawing, element.attr['.svg_tag'])(**args))
        elif tag != 'None' and tag is not None:
            drawing.add(getattr(drawing, element.attr['.svg_tag'])(**args))
    elif isinstance(element, Vertex):
        if '.helper_node' in element.attr and element.attr['.helper_node']:
            return
        x = float(element.attr['x'])
        y = -float(element.attr['y'])
        args.setdefault('r', '0.4cm')
        args.setdefault('stroke_width', '1mm')
        args.setdefault('stroke', 'black')
        args.setdefault('fill', 'none')
        drawing.add(drawing.circle(center=(x*mult, y*mult), **args))
    elif isinstance(element, Edge):
        v1 = element.vertex1
        v2 = element.vertex2
        x1 = float(v1.attr['x'])
        y1 = -float(v1.attr['y'])
        x2 = float(v2.attr['x'])
        y2 = -float(v2.attr['y'])
        args.setdefault('stroke_width', '1mm')
        args.setdefault('stroke', 'black')
        drawing.add(drawing.line(start=(x1*mult, y1*mult), end=(x2*mult, y2*mult),
                                 **args))
    else:
        raise ValueError
示例#25
0
            return prevy - fontsize
        else:
            return curry
    else:
        return scale(val)

ys = {label: [] for label in labels}
for i in range(ncols):
    col = cols.iloc[:,i]
    
    sort = argsort(col)[::-1] # descending---top to bottom
    col = col[sort]
    collabels = labels[sort]

    for j in range(len(col)):
        val = col.iloc[j]
        y = vertplace(j, col)
        if i==0:
            txt = g.add(dwg.text(collabels.iloc[j]+tabpad+str(val), insert=(collocs[i], h - y), text_anchor='end', font_size="%ipx" % fontsize))
        elif i==ncols-1:
            txt = g.add(dwg.text(str(val)+tabpad+collabels.iloc[j], insert=(collocs[i], h - y), font_size="%ipx" % fontsize))
        else:
            txt = g.add(dwg.text(str(val), insert=(collocs[i], h - y), font_size="%ipx" % fontsize))

        ys[collabels.iloc[j]].append(y)

        if i > 0:
            line = g.add(dwg.line( (collocs[i-1]+textpad, h - ys[collabels.iloc[j]][i-1]), (collocs[i]-textpad, h - ys[collabels.iloc[j]][i]), stroke_width=1, stroke='black'))
    
dwg.save()
示例#26
0
    def plot(self, x, y, scale, break_width=10, **extra):

        svg = Drawing()

        break_length = 0
        fragments = self.get_fragments()
        g = svg.g()

        for i in range(len(fragments)):

            f = fragments[i]

            if i > 0:
                break_length += f.start - fragments[
                    i - 1].end - break_width / scale

            p1 = [x + (f.start - break_length) * scale, y]
            p2 = [x + (f.end - break_length) * scale, y]

            f.position = p1

            line1 = svg.line(start=p1, end=p2, **extra)

            line2 = svg.line(start=[p1[0], p1[1] - 5],
                             end=[p1[0], p1[1] + 5],
                             **extra)
            text2 = svg.text(text=f.start,
                             insert=(p1[0], p1[1] + 10),
                             font_size=8,
                             font_family="Arial",
                             transform='rotate(%s, %s, %s)' %
                             (90, p1[0], p1[1] + 10))
            line3 = svg.line(start=[p2[0], p1[1] - 5],
                             end=[p2[0], p1[1] + 5],
                             **extra)
            text3 = svg.text(text=f.end,
                             insert=(p2[0], p2[1] + 10),
                             font_size=8,
                             font_family="Arial",
                             transform='rotate(%s, %s, %s)' %
                             (90, p2[0], p1[1] + 10))
            g.add(line1)
            g.add(line2)
            g.add(text2)
            g.add(line3)
            g.add(text3)

        text1 = svg.text(text=self.name,
                         insert=(10, y),
                         font_size=10,
                         font_family="Arial")
        g.add(text1)
        text2 = svg.text(text="%s nt" % self.length,
                         insert=(x / 2.0 - 10, y + 12),
                         font_size=8,
                         font_family="Arial")
        g.add(text2)

        for e in self.features:
            if e.frag_genome:
                patch, text = e.plot(scale=scale)
                g.add(patch)
                g.add(text)

        return g
示例#27
0
        paths_to_add = [p for p in paths_to_add if p[0] != path_to_add[0]]
        start_location = paths[path_to_add[0]].start if path_to_add[0] else paths[
            path_to_add[1]].end
'''

if __name__ == "__main__":
    # make a graph of the next available grid
    num_grid = 8
    spacing = 30

    dwg = Drawing(join(OUTPUT_DIRECTORY, "next_available_grid.svg"),
                  (num_grid * spacing, num_grid * spacing))
    for x in range(num_grid):
        dwg.add(
            dwg.line(start=(0, x * spacing),
                     end=(num_grid * spacing, x * spacing),
                     stroke=rgb(10, 10, 16, '%')))
        dwg.add(
            dwg.line(start=(x * spacing, 0),
                     end=(x * spacing, num_grid * spacing),
                     stroke=rgb(10, 10, 16, '%')))
    start_point = [4, 4]

    dwg.add(
        dwg.rect(insert=(start_point[0] * spacing, start_point[1] * spacing),
                 size=(spacing, spacing),
                 fill=rgb(100, 100, 16, '%')))
    count = 0
    last_point = start_point
    for next_available in NextAvailableGrid(*start_point):
        dwg.add(
delta_x = 180
vertical_locs = []
for loc in locs:
    top_text.add(dwg.text(loc, (x - len(loc)*4, y)))
    vertical_locs.append(x)
    x += delta_x

legend_text = dwg.add(dwg.g(font_size=main_font_size, style="font-family: arial;"))
legend_text.add(dwg.text('Phys', (x-1500, y-10), fill=color_phys))
legend_text.add(dwg.text('Scaled', (x-1500, y+20), fill=color_scaled))

v_lines = dwg.add(dwg.g(stroke_width=7.0, stroke=color_phys, fill='none'))
v_lines_scaled = dwg.add(dwg.g(stroke_width=7.0, stroke=color_scaled, fill='none'))

for loc in vertical_locs:
    v_lines.add(dwg.line(start=(loc, y+15), end=(loc, 1200)))

extra_text = dwg.add(dwg.g(font_size=main_font_size - 3, style="font-family: arial;"))
extra_text.add(dwg.text('fwd', (vertical_locs[5] + 55, 820)))

locs = [('Problem.compute_totals()', None, []),
        ('_TotalJacInfo.compute_totals()', None, []),
        ('System.scaled_context_all()', ((0, 2), (0, 3), (0, 5), (0, 6)), ['stagger']),
        ('Group._linearize()', None, []),
        ('  ExplicitComponent._linearize()', None, []),
        ('  ExplicitComponent._unscaled_context()', ((0, 2), (0, 3), (0, 5), (0, 6)), ['stagger']),
        ('  Paraboloid.compute_partials()', ((4, 7), ), []),
        ('  ExplicitComponent._unscaled_context()', ((0, 2), (0, 3), (0, 5), (0, 6)), ['italic', 'stagger']),
        ('AssembledJacobian._update()', None, []),
        ('System.scaled_context_all()', ((0, 2), (0, 3), (0, 5), (0, 6)), ['italic', 'stagger']),
        ('DirectSolver._linearize()', None, []),
示例#29
0
    def _draw_year(self, dr: svgwrite.Drawing, g: svgwrite.container.Group,
                   size: XY, offset: XY, year: int) -> None:
        min_size = min(size.x, size.y)
        outer_radius = 0.5 * min_size - 6
        radius_range = ValueRange.from_pair(outer_radius / 4, outer_radius)
        center = offset + 0.5 * size

        if self._rings:
            self._draw_rings(dr, g, center, radius_range)

        year_style = f"dominant-baseline: central; font-size:{min_size * 4.0 / 80.0}px; font-family:Arial;"
        month_style = f"font-size:{min_size * 3.0 / 80.0}px; font-family:Arial;"

        g.add(
            dr.text(
                f"{year}",
                insert=center.tuple(),
                fill=self.poster.colors["text"],
                text_anchor="middle",
                alignment_baseline="middle",
                style=year_style,
            ))
        df = 360.0 / (366 if calendar.isleap(year) else 365)
        day = 0
        date = datetime.date(year, 1, 1)
        while date.year == year:
            text_date = date.strftime("%Y-%m-%d")
            a1 = math.radians(day * df)
            a2 = math.radians((day + 1) * df)
            if date.day == 1:
                (_, last_day) = calendar.monthrange(date.year, date.month)
                a3 = math.radians((day + last_day - 1) * df)
                sin_a1, cos_a1 = math.sin(a1), math.cos(a1)
                sin_a3, cos_a3 = math.sin(a3), math.cos(a3)
                r1 = outer_radius + 1
                r2 = outer_radius + 6
                r3 = outer_radius + 2
                g.add(
                    dr.line(
                        start=(center + r1 * XY(sin_a1, -cos_a1)).tuple(),
                        end=(center + r2 * XY(sin_a1, -cos_a1)).tuple(),
                        stroke=self.poster.colors["text"],
                        stroke_width=0.3,
                    ))
                path = dr.path(
                    d=("M", center.x + r3 * sin_a1, center.y - r3 * cos_a1),
                    fill="none",
                    stroke="none",
                )
                path.push(
                    f"a{r3},{r3} 0 0,1 {r3 * (sin_a3 - sin_a1)},{r3 * (cos_a1 - cos_a3)}"
                )
                g.add(path)
                tpath = svgwrite.text.TextPath(
                    path,
                    self.poster.month_name(date.month),
                    startOffset=(0.5 * r3 * (a3 - a1)))
                text = dr.text(
                    "",
                    fill=self.poster.colors["text"],
                    text_anchor="middle",
                    style=month_style,
                )
                text.add(tpath)
                g.add(text)
            if text_date in self.poster.tracks_by_date:
                self._draw_circle_segment(
                    dr,
                    g,
                    self.poster.tracks_by_date[text_date],
                    a1,
                    a2,
                    radius_range,
                    center,
                )

            day += 1
            date += datetime.timedelta(1)
示例#30
0
    def _create_group(self, drawing: Drawing, projection: np.ndarray,
                      viewport: Viewport, group: Group):
        """
        Render all the meshes contained in this group.

        The main consideration here is that we will consider the z-index of
        every object in this group.
        """
        default_style = group.style or {}
        shaders = [
            mesh.shader or (lambda face_index, winding: {})
            for mesh in group.meshes
        ]
        annotators = [
            mesh.annotator or (lambda face_index: None)
            for mesh in group.meshes
        ]

        # A combination of mesh and face indes
        mesh_faces: List[np.ndarray] = []

        for i, mesh in enumerate(group.meshes):
            faces = mesh.faces

            # Extend each point to a vec4, then transform to clip space.
            faces = np.dstack([faces, np.ones(faces.shape[:2])])
            faces = np.dot(faces, projection)

            # Reject trivially clipped polygons.
            xyz, w = faces[:, :, :3], faces[:, :, 3:]
            accepted = np.logical_and(np.greater(xyz, -w), np.less(xyz, +w))
            accepted = np.all(accepted,
                              2)  # vert is accepted if xyz are all inside
            accepted = np.any(accepted,
                              1)  # face is accepted if any vert is inside
            degenerate = np.less_equal(w, 0)[:, :,
                                             0]  # vert is bad if its w <= 0
            degenerate = np.any(degenerate,
                                1)  # face is bad if any of its verts are bad
            accepted = np.logical_and(accepted, np.logical_not(degenerate))
            faces = np.compress(accepted, faces, axis=0)

            # Apply perspective transformation.
            xyz, w = faces[:, :, :3], faces[:, :, 3:]
            faces = xyz / w
            mesh_faces.append(faces)

        # Sort faces from back to front.
        mesh_face_indices = self._sort_back_to_front(mesh_faces)

        # Apply viewport transform to X and Y.
        for faces in mesh_faces:
            faces[:, :, 0:1] = (1.0 + faces[:, :, 0:1]) * viewport.width / 2
            faces[:, :, 1:2] = (1.0 - faces[:, :, 1:2]) * viewport.height / 2
            faces[:, :, 0:1] += viewport.minx
            faces[:, :, 1:2] += viewport.miny

        # Compute the winding direction of each polygon.
        mesh_windings: List[np.ndarray] = []
        for faces in mesh_faces:
            windings = np.zeros(faces.shape[0])
            if faces.shape[1] >= 3:
                p0, p1, p2 = faces[:, 0, :], faces[:, 1, :], faces[:, 2, :]
                normals = np.cross(p2 - p0, p1 - p0)
                np.copyto(windings, normals[:, 2])
            mesh_windings.append(windings)

        group_ = drawing.g(**default_style)
        text_group_ = drawing.g(**default_style)

        # Finally draw the group
        for mesh_index, face_index in mesh_face_indices:
            face = mesh_faces[mesh_index][face_index]
            style = shaders[mesh_index](face_index,
                                        mesh_windings[mesh_index][face_index])
            if style is None:
                continue
            face = np.around(face[:, :2], self.precision)

            if len(face) == 1:
                group_.add(
                    drawing.circle(face[0], style.pop("radius", 0.005),
                                   **style))
            if len(face) == 2:
                group_.add(drawing.line(face[0], face[1], **style))
            else:
                group_.add(drawing.polygon(face, **style))

            annotation = annotators[mesh_index](face_index)
            if annotation is not None:
                centroid = face.mean(axis=0)
                text_group_.add(drawing.text(insert=centroid, **annotation))

        return [group_, text_group_]