示例#1
0
 def __init__(self, width=None, height=None):
     """
     Compositor creator function
     """
     # Main SVG initialization
     self.__mainSVG = None
     if ((height != None) and (width != None)):
         self.__mainSVG = st.SVGFigure(width, height)
     else:
         self.__mainSVG = st.SVGFigure()
     self.__SVGS = {}
示例#2
0
def test_create_svg_figure():
    svg_fig = transform.SVGFigure()
    assert "svg" in svg_fig.to_str().decode("ascii")

    svg_fig = transform.SVGFigure(Unit("2px"), Unit("2px"))
    assert "svg" in svg_fig.to_str().decode("ascii")

    svg_fig = transform.SVGFigure(2, 3)
    assert "svg" in svg_fig.to_str().decode("ascii")

    svg_fig = transform.SVGFigure("2", "3")
    assert "svg" in svg_fig.to_str().decode("ascii")
示例#3
0
def main(args):
    fig = sg.SVGFigure("22cm", "25cm")
    fig1 = sg.fromfile(args.gene_counts)
    fig2 = sg.fromfile(args.mpc_dist)
    fig3 = sg.fromfile(args.fg_roc)
    fig4 = sg.fromfile(args.clinvar_roc)

    plot1 = fig1.getroot()
    plot2 = fig2.getroot()
    plot3 = fig3.getroot()
    plot4 = fig4.getroot()

    plot1.moveto(0, 20, scale=0.75)
    plot2.moveto(400, 0, scale=0.75)
    plot3.moveto(0, 390, scale=0.7)
    plot4.moveto(410, 390, scale=0.7)

    # add text labels
    txt1 = sg.TextElement(25, 20, "a", size=12, weight="bold")
    txt2 = sg.TextElement(400, 20, "b", size=12, weight="bold")

    txt3 = sg.TextElement(25, 390, "c", size=12, weight="bold")
    txt4 = sg.TextElement(400, 390, "d", size=12, weight="bold")

    fig.append([plot1, plot2, plot3, plot4])
    fig.append([txt1, txt2, txt3, txt4])
    fig.save(args.out)
示例#4
0
def plot_depth(save_path=None):

    plot_depth_abs(save_path + "_abs.svg")
    plot_depth_diff(save_path + "_diff.svg")

    fig = sg.SVGFigure("8.38cm", "13.2cm")

    abs_fig = sg.fromfile(save_path + "_abs.svg")
    abs_plot = abs_fig.getroot()

    diff_fig = sg.fromfile(save_path + "_diff.svg")
    diff_plot = diff_fig.getroot()

    abs_plot.moveto(3.319, 11, scale=1.25)
    diff_plot.moveto(0, 247, scale=1.25)

    text = functools.partial(sg.TextElement,
                             size=12,
                             weight="bold",
                             font="freesans")

    A = text(11.6, 24, "A")
    B = text(11.6, 241, "B")

    fig.append([abs_plot, diff_plot])
    fig.append(A)
    fig.append(B)

    fig.save(save_path + ".svg")

    figutils.figutils.svg_to_pdf(svg_path=save_path + ".svg",
                                 pdf_path=save_path + ".pdf")
示例#5
0
def combine_figs(*labeled_figs, unit="px"):
    """Combines the given figures horizontally."""
    # Assumes all figures have the same height and use the same size units
    plots = []
    labels = []
    cur_offset = 0
    for fig, label in labeled_figs:
        plot = fig.getroot()
        plot.moveto(cur_offset, 0)
        plots.append(plot)

        width = int(fig.width.strip(unit))
        left_label_offset = 0.0125 * width
        top_label_offset = 0.0375 * width
        font_size = 0.03 * width

        text = sg.TextElement(left_label_offset + cur_offset,
                              top_label_offset, label, size=font_size)
        labels.append(text)

        cur_offset += width

    height = labeled_figs[0][0].height

    combined_fig = sg.SVGFigure(cur_offset, height)
    combined_fig.append(plots)
    combined_fig.append(labels)

    return combined_fig
示例#6
0
 def write(self):
     label = click.style('Cards Processed', fg='yellow')
     with click.progressbar(self.data, label=label, show_eta=True) as data:
         for card in data:
             self.layout = sg.fromfile(self.getLayout())
             output_file = os.path.join(self.dir,
                                        '%05d.svg' % card['number'])
             numbers = []
             for k in card['card'].keys():
                 numbers = numbers + card['card'][k]
             w, h = self.layout.get_size()
             c = sg.SVGFigure(w, h)
             c.append(self.layout)
             fillables = self.getFillables()
             for i in range(len(numbers)):
                 fillable = fillables[i]
                 number = numbers[i]
                 txt = sg.TextElement(
                     fillable['x'] +
                     (fillable['width'] -
                      Writer.FONT_SIZE * Writer.H_FACTOR) / 2,
                     fillable['y'] +
                     (fillable['height'] +
                      Writer.FONT_SIZE * Writer.V_FACTOR) / 2,
                     "%02d" % number,
                     size=Writer.FONT_SIZE,
                     weight="bold",
                     font="Helvetica")
                 c.append(txt)
             c.save(output_file)
     print click.style('\nCards written to %s' % self.dir, fg='blue') + '\n'
示例#7
0
def put_list_of_figs_to_svg_fig(FIGS, CAP_SIZE=14,\
                                fig_name="fig.svg", visualize=True,\
                                transparent=True):
    """ take a list of figures and make a """

    label = list(string.ascii_uppercase)[:len(FIGS)]

    fig = sg.SVGFigure("21cm", "29.7cm")  # A4 figure

    PLOT_LIST, LABEL_LIST = [], []
    for i in range(len(FIGS)):
        ff = 'f.svg'
        FIGS[i].savefig(ff, format='svg', transparent=transparent)
        fig1 = sg.fromfile(ff)
        plot = fig1.getroot()
        plot.moveto(10. * i, 10. * i, scale=1.)
        PLOT_LIST.append(plot)
        txt = sg.TextElement(10.*i, 10.*i, label[i%26],\
                             size=CAP_SIZE, weight="bold")
        LABEL_LIST.append(txt)

    fig.append(PLOT_LIST)
    fig.append(LABEL_LIST)
    fig.save(fig_name)
    if visualize:
        os.system('eog ' + fig_name)
    os.system('rm f.svg')
示例#8
0
def draw_logo(file_path_or_matrix,
              out_path,
              unit_width,
              unit_height,
              revcomp=False,
              words=100,
              mode='KDIC'):
    if os.path.isfile(file_path_or_matrix):
        if file_path_or_matrix.endswith('.pcm'):
            mode = 'KDIC'
        elif file_path_or_matrix.endswith('.ppm'):
            mode = 'freq'
        else:
            raise ValueError(file_path_or_matrix,
                             ' should ends with ".pcm" or ".ppm"')
        lines = []
        with open(file_path_or_matrix) as f:
            for line in f:
                if line.startswith('>'):
                    continue
                try:
                    lines.append(list(map(float,
                                          line.strip('\n').split('\t'))))
                except ValueError:
                    lines.append(list(map(float, line.strip('\n').split(' '))))
    else:
        lines = file_path_or_matrix
    m, heights = get_heights(lines, mode=mode, words=words)
    get_revcomp = {
        'A': 'T',
        'T': 'A',
        'C': 'G',
        'G': 'C',
    }
    if os.path.isdir(out_path):
        if os.path.isfile(file_path_or_matrix):
            out_path = os.path.join(
                out_path, '{}{}.svg'.format(
                    os.path.splitext(os.path.basename(file_path_or_matrix))[0],
                    '_revcomp' if revcomp else ''))
        else:
            out_path = os.path.join(
                out_path, 'matrix{}.svg'.format('_revcomp' if revcomp else ''))

    fig = transform.SVGFigure("{}".format(m * unit_width),
                              "{}".format(unit_height))

    for pos, pack in enumerate(heights[::-1] if revcomp else heights):
        current_height = 0
        for letter, height in renorm(pack):
            # Draw letter with offset of pos*unit_width, current_height*unit_height and height of height*unit_height
            place_letter_on_svg(
                fig,
                get_letter_svg_by_name(
                    get_revcomp[letter] if revcomp else letter), unit_width,
                pos * unit_width, (1 - current_height - height) * unit_height,
                height * unit_height)
            current_height += height

    fig.save(out_path)
def plot_cross_relationship(all_results,
                            graph_loc,
                            prediction_loc,
                            size=4.6,
                            dpi=300,
                            ext='pdf',
                            plot_dir=None):
    assert ext in ['pdf', 'svg'], 'Must use svg or pdf'
    tmp_dir = '/tmp/'
    plot_corr_heatmap(all_results, size=size / 3, plot_dir=tmp_dir, ext='svg')
    plot_glasso_edge_strength(all_results,
                              graph_loc,
                              size / 4,
                              plot_dir=tmp_dir,
                              ext='svg')
    plot_cross_within_prediction(prediction_loc,
                                 size / 4,
                                 plot_dir=tmp_dir,
                                 ext='svg')

    fig1 = sg.fromfile('/tmp/data_correlations.svg')
    fig2 = sg.fromfile('/tmp/cross_prediction.svg')
    fig3 = sg.fromfile('/tmp/glasso_edge_strength.svg')
    width = float(fig1.get_size()[0][:-2])
    height = float(fig2.get_size()[1][:-2])
    fig = sg.SVGFigure(width * 2.5, height)
    fig.root.set("viewbox", "0 0 %s %s" % (width * 2, height))
    plot1 = fig1.getroot()
    plot2 = fig2.getroot()
    plot3 = fig3.getroot()
    # move plots
    plot2.moveto(width, 0)
    plot3.moveto(width * 1.8, 0)
    fig.append([plot1, plot2, plot3])
    # add text
    txt1 = sg.TextElement(0, height * .1, "A", size=size * 1.5, weight="bold")
    txt2 = sg.TextElement(width * 1.05,
                          height * .1,
                          "B",
                          size=size * 1.5,
                          weight="bold")
    txt3 = sg.TextElement(width * 1.85,
                          height * .1,
                          "C",
                          size=size * 1.5,
                          weight="bold")
    fig.append([txt1, txt2, txt3])
    # save
    svg_file = path.join(plot_dir, 'cross_relationship.svg')
    fig.save(svg_file)
    if ext == 'pdf':
        pdf_file = path.join(plot_dir, 'cross_relationship.pdf')
        a = subprocess.Popen('cairosvg %s -o %s' % (svg_file, pdf_file),
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
    # remove temp files
    remove('/tmp/data_correlations.svg')
    remove('/tmp/glasso_edge_strength.svg')
    remove('/tmp/cross_prediction.svg')
示例#10
0
def plot_point_bar_figure(figure_one_path, figure_two_path):
    """
    Combines the pointplot and bargraph together using svg magic
    Arguments:
        figure_one_path - The pointplot figure
        figure_two_path - The barplot figure
    """

    fig = sg.SVGFigure("1280", "960")
    fig.append([
        etree.Element("rect", {
            "width": "100%",
            "height": "100%",
            "fill": "white"
        })
    ])

    fig1 = sg.fromfile(figure_one_path)
    plot1 = fig1.getroot()
    plot1.moveto(22, 25, scale=1.35)

    fig2 = sg.fromfile(figure_two_path)
    plot2 = fig2.getroot()
    plot2.moveto(662, 0, scale=1.35)

    fig.append([plot1, plot2])

    text_A = sg.TextElement(10, 30, "A", size=18, weight="bold")
    text_B = sg.TextElement(640, 30, "B", size=18, weight="bold")

    fig.append([text_A, text_B])

    return fig
示例#11
0
def main(args):
    fig = sg.SVGFigure("50cm", "50cm")
    fig1 = sg.fromfile(args.panel_one)
    fig2 = sg.fromfile(args.uc)
    fig3 = sg.fromfile(args.panel_two)
    fig4 = sg.fromfile(args.clinvar)
    fig5 = sg.fromfile(args.denovo)

    plot1 = fig1.getroot()
    plot2 = fig2.getroot()
    plot3 = fig3.getroot()
    plot4 = fig4.getroot()
    plot5 = fig5.getroot()

    plot1.moveto(0, 0, scale=0.75)
    plot2.moveto(0, 150, scale=0.75)
    plot3.moveto(0, 300, scale=0.75)
    plot4.moveto(0, 450, scale=0.75)
    plot5.moveto(0, 600, scale=0.75)

    # add text labels
    txt1 = sg.TextElement(25, 20, "panel one", size=12, weight="bold")
    txt2 = sg.TextElement(25, 150, "uc", size=12, weight="bold")
    txt3 = sg.TextElement(25, 300, "panel two", size=12, weight="bold")
    txt4 = sg.TextElement(25, 450, "clinvar", size=12, weight="bold")
    txt5 = sg.TextElement(25, 600, "denovo db", size=12, weight="bold")

    fig.append([plot1, plot2, plot3, plot4, plot5])
    fig.append([txt1, txt2, txt3, txt4, txt5])
    fig.save(args.out)
示例#12
0
    def save(self, fname):
        """Save figure to SVG file.

        Parameters
        ----------
        fname : str
            Full path to file.
        """
        element = _transform.SVGFigure(self.width, self.height)
        element.append(self)
        element.save(os.path.join(CONFIG['figure.save_path'], fname))
示例#13
0
 def dumps(self):
     # the default .tostr() function fails to return the same text .dump() would return
     element = _transform.SVGFigure(self.width, self.height)
     element.append(self)
     out = etree.tostring(element.root, xml_declaration=True,
                          standalone=True,
                          pretty_print=True)
     # but even this doesn't make it. The encoding must be changed to UTF-8 (otherwise svgexport fails)
     out = out.replace("version='1.0'", 'version="1.0"')
     out = out.replace("encoding='ASCII'", 'encoding="UTF-8"')
     return out
示例#14
0
def test_svg_figure_writes_width_height_and_view_box():
    svg_fig = transform.SVGFigure(Unit("400mm"), Unit("300mm"))

    with NamedTemporaryFile() as f1:
        svg_fig.save(f1.name)
        with open(f1.name) as f2:
            written_content = f2.read()

    assert 'width="400.0mm"' in written_content
    assert 'height="300.0mm"' in written_content
    assert 'viewBox="0 0 400.0 300.0"' in written_content
示例#15
0
def makeSVG(output,sc=0.435,W2=680/2 ,H1=300):
    #create new SVG figure
    fig = sg.SVGFigure("19.05cm", "22.86cm")
    
    # load matpotlib-generated figures
    figA2 = sg.fromfile(output+os.sep+'FigureB_histXY.svg')
    figA1= sg.fromfile(output+os.sep+'FigureA_histXY.svg')
    figB4 = sg.fromfile(output+os.sep+'angle_hist.svg')
    figB=[]
    for n in [u'ext__Bacteria_Rad25_1_3', u'ext__IngredientC_1_1', u'ext__snake']:
        fig2 = sg.fromfile(output+os.sep+n+"_histXY_labels.svg")
        figB.append(fig2) 
        
    figB.append(figB4)    
    
#    W2 = 680/2    
#    H1 = 350
    # get the plot objects
    plot1 = figA1.getroot()
    plot1.moveto(5, 0, scale=sc)
    plot2 = figA2.getroot()
    plot2.moveto(W2, 0, scale=sc)
    
    plot3 = figB[0].getroot()
    plot3.moveto(5, H1, scale=sc)
    plot4 = figB[1].getroot()
    plot4.moveto(W2, H1, scale=sc)
    
    plot5 = figB[2].getroot()
    plot5.moveto(5, H1*2, scale=sc)
    plot6 = figB[3].getroot()
    plot6.moveto(W2, H1*2, scale=sc)
    
    # add text labels
    txt1 = sg.TextElement(25,20, "A.1", size=12, weight="bold")
    txt2 = sg.TextElement(W2+5,20, "A.2", size=12, weight="bold")
    
    txt3 = sg.TextElement(25,20+H1, "B.1", size=12, weight="bold")
    txt4 = sg.TextElement(W2+5,20+H1, "B.2", size=12, weight="bold")
    
    txt5 = sg.TextElement(25,20+H1*2, "B.3", size=12, weight="bold")
    txt6 = sg.TextElement(W2+5,20+H1*2, "B.4", size=12, weight="bold")
    
    # append plots and labels to figure
    fig.append([plot1, plot2])
    fig.append([plot3, plot4])
    fig.append([plot5, plot6])
    fig.append([txt1, txt2])
    fig.append([txt3, txt4])
    fig.append([txt5, txt6])
    
    # save generated SVG files
    fig.save(output+os.sep+"fig_final.svg")
示例#16
0
def main():
    svgs = files_to_svg_dict(
        ["A.svg", "B.svg", "C.svg", "D.svg", "E.svg", "F.svg"])
    rescale(svgs)
    change_positions(svgs)
    full_width = sum([svgs[i].width for i in ['A', 'E']])
    full_height = sum([svgs[i].height for i in ['A', 'B', 'C', 'D']])
    fig = sg.SVGFigure(full_width, full_height)
    text = letter_annotations(svgs)
    fig.append([s.data for s in svgs.values()])
    fig.append(text)
    fig.save("combined.svg")
示例#17
0
def combine_svg_verbose(in_brainmask, in_segmentation, in_artmask, in_headmask,
                        in_airmask, in_bgplot):
    import os.path as op
    import svgutils.transform as svgt
    import svgutils.compose as svgc
    import numpy as np

    hspace = 10
    wspace = 10
    #create new SVG figure
    in_mosaics = [
        in_brainmask, in_segmentation, in_artmask, in_headmask, in_airmask
    ]
    figs = [svgt.fromfile(f) for f in in_mosaics]

    roots = [f.getroot() for f in figs]
    nfigs = len(figs)

    sizes = [(int(f.width[:-2]), int(f.height[:-2])) for f in figs]
    maxsize = np.max(sizes, axis=0)
    minsize = np.min(sizes, axis=0)

    bgfile = svgt.fromfile(in_bgplot)
    bgscale = (maxsize[1] * 2 + hspace) / int(bgfile.height[:-2])
    bgsize = (int(bgfile.width[:-2]), int(bgfile.height[:-2]))
    bgfileroot = bgfile.getroot()

    totalsize = (minsize[0] + hspace + int(bgsize[0] * bgscale),
                 nfigs * maxsize[1] + (nfigs - 1) * hspace)
    fig = svgt.SVGFigure(
        svgc.Unit(totalsize[0]).to('cm'),
        svgc.Unit(totalsize[1]).to('cm'))

    yoffset = 0
    for i, r in enumerate(roots):
        xoffset = 0
        if sizes[i][0] == maxsize[0]:
            xoffset = int(0.5 * (totalsize[0] - sizes[i][0]))
        r.moveto(xoffset, yoffset)
        yoffset += maxsize[1] + hspace

    bgfileroot.moveto(minsize[0] + wspace,
                      3 * (maxsize[1] + hspace),
                      scale=bgscale)

    fig.append(roots + [bgfileroot])
    out_file = op.abspath('fig_final.svg')
    fig.save(out_file)
    return out_file
示例#18
0
def north_arrow(img_file_in: Path,
                img_file_out: Path = None,
                rotation_angle=0):
    if img_file_out is None:
        img_file_out = img_file_in.parent / f"{img_file_in.name[:-4]}_north_arrow.svg"

    arrow_fig_path = Path(__file__).parent.parent / "north_arrow.svg"

    # load matpotlib-generated figures
    fig1 = sg.fromfile(str(img_file_in))
    fig2 = sg.fromfile(str(arrow_fig_path))

    #create new SVG figure
    fig = sg.SVGFigure(fig1.get_size())

    w, h = get_fig_size(fig1)

    # get the plot objects
    plot1 = fig1.getroot()
    plot2 = fig2.getroot()

    print(fig2.get_size())
    x_label = 0.9 * w
    y_label = 0.8 * h

    kx = 0.5 * 0.05
    ky = 0.05
    plot2.scale_xy(x=kx, y=ky)

    w_fig2, h_fig2 = get_fig_size(fig2)
    plot2.moveto(x_label - w_fig2 * kx / 2, y_label)

    print(fig2.get_size())

    n_text = sg.TextElement(0.9 * w,
                            0.8 * h,
                            "N",
                            size=12,
                            weight="bold",
                            anchor="middle")

    fig.append([plot1, plot2])
    fig.append([
        n_text,
    ])

    fig.set_size(fig1.get_size())

    fig.save(str(img_file_out))
def plot_resp_amp_rois(save_path=None, loc_mask=True):

    conf = ul_sens_fmri.config.get_conf()
    conf.ana = ul_sens_analysis.config.get_conf()

    if loc_mask:

        # subjects x va x img x pres (U,L) x src (A, B)
        amp_data = np.load(
            os.path.join(conf.ana.base_group_dir,
                         "ul_sens_group_amp_data.npy"))

    else:

        # subjects x va x img x pres (U,L) x src (A, B)
        amp_data = np.load(
            os.path.join(conf.ana.base_group_dir,
                         "ul_sens_group_amp_ret_roi_data.npy"))

    # average over images
    amp_data = np.mean(amp_data, axis=2)

    for i_va in xrange(len(conf.ana.roi_names)):

        plot_amps_visual_area(save_path + "_" + str(i_va) + ".svg",
                              amp_data[:, i_va, ...], conf.ana.roi_names[i_va])

    fig = sg.SVGFigure("13.7cm", "3.56cm")

    v1_fig = sg.fromfile(save_path + "_0.svg")
    v1_plot = v1_fig.getroot()
    v1_plot.moveto(0, 0, scale=1.25)

    v2_fig = sg.fromfile(save_path + "_1.svg")
    v2_plot = v2_fig.getroot()
    v2_plot.moveto(170, 0, scale=1.25)

    v3_fig = sg.fromfile(save_path + "_2.svg")
    v3_plot = v3_fig.getroot()
    v3_plot.moveto(170 * 2, 0, scale=1.25)

    fig.append([v1_plot, v2_plot, v3_plot])

    fig.save(save_path + ".svg")

    figutils.svg_to_pdf(svg_path=save_path + ".svg",
                        pdf_path=save_path + ".pdf")
def plot_point_bar_figure(figure_one_path, figure_two_path):
    """
    Combines the pointplot and bargraph together using svg magic
    Arguments:
        figure_one_path - The pointplot figure
        figure_two_path - The barplot figure
    """
    fig1 = sg.fromfile(figure_one_path)
    fig2 = sg.fromfile(figure_two_path)

    fig1_width_size = np.round(float(fig1.root.attrib["width"][:-2]) * 1.33, 0)
    fig1_height_size = np.round(
        float(fig1.root.attrib["height"][:-2]) * 1.33, 0)

    fig2_width_size = np.round(float(fig2.root.attrib["width"][:-2]) * 1.33, 0)
    fig2_height_size = np.round(
        float(fig2.root.attrib["height"][:-2]) * 1.33, 0)

    fig = sg.SVGFigure(
        Unit((fig1_width_size + fig2_width_size) - 360),
        Unit(min(fig1_height_size, fig2_height_size) - 50),
    )

    fig.append([
        etree.Element("rect", {
            "width": "100%",
            "height": "100%",
            "fill": "white"
        })
    ])

    plot1 = fig1.getroot()
    plot1.moveto(10, 30)

    plot2 = fig2.getroot()
    plot2.moveto(fig1_width_size - 160, 12)

    text_A = sg.TextElement(10, 30, "A", size=18, weight="bold")
    text_B = sg.TextElement(fig1_width_size - 160,
                            30,
                            "B",
                            size=18,
                            weight="bold")

    fig.append([plot1, plot2, text_A, text_B])

    return fig
示例#21
0
    def output_qr(self):
        '''Combine plots into single SVG'''
        try:
            self._create_plots_qr()
        except AttributeError as e:  # We never got data to encode, and never produced a qrcode. Nothing to ouput.
            return None

        fig = sg.SVGFigure(self.qr_size * self.scale_factor,
                           self.qr_size * self.scale_factor)

        try:  # Logo and background are set
            self._create_plots_logo()
            fig.append([self.plot_qr, self.plot_background, self.plot_logo
                        ])  # Order Matters. First is lowest z-index.
        except AttributeError as e:  # We never got a logo svg, just ouput a qr code.
            fig.append(self.plot_qr)  # Just a qr code
        return fig.to_str()  # Can only save to a file or be cast into a string
示例#22
0
def register_sketches(skname1, sk1, skname2, sk2, mp1=1, mp2=1):
    def parse_line(elem):
        return ((float(elem.get('x1')), float(elem.get('y1'))),
                (float(elem.get('x2')), float(elem.get('y2'))))

    print _get_MP(skname1, sk1, mp1)

    # Get mounting points guide lines
    up1 = parse_line(sk1.find_id('MP_' + skname1 + '_' + str(mp1) + '_u').root)
    rg1 = parse_line(sk1.find_id('MP_' + skname1 + '_' + str(mp1) + '_r').root)
    up2 = parse_line(sk2.find_id('MP_' + skname2 + '_' + str(mp2) + '_u').root)
    rg2 = parse_line(sk2.find_id('MP_' + skname2 + '_' + str(mp2) + '_r').root)

    # Compute scales to make the two figures match in size
    fig1scale = geomutils.line_len(up1)
    fig2scale = geomutils.line_len(up2)
    midscale = (fig1scale + fig2scale) / 2.  # The average of the two scales
    fig1_normscale = fig1scale / midscale
    fig2_normscale = fig2scale / midscale
    print '--scales-->', fig1scale, fig2scale
    print '--normscales-->', fig1_normscale, fig2_normscale

    # 2D displacement of the second figure
    displacement = (up1[0][0] * fig2_normscale - up2[0][0] * fig1_normscale,
                    up1[0][1] * fig2_normscale - up2[0][1] * fig1_normscale)

    # Get the plot objects
    plot1 = sk1.getroot()
    plot2 = sk2.getroot()
    plot1.moveto(0, 0, scale=fig2_normscale)
    plot2.moveto(0 + displacement[0],
                 0 + displacement[1],
                 scale=fig1_normscale)

    # Rotation
    plot1.rotate(-90 - geomutils.line_angle(up1), up1[0][0], up1[0][1])
    plot2.rotate(-90 - geomutils.line_angle(up2), up2[0][0], up2[0][1])

    # TODO: Flip if needed

    # Create new SVG figure
    fig = sg.SVGFigure("1500px", "1500px")  # FIXME: hardcoded size

    # Append plots and labels to figure
    fig.append([plot1, plot2])
    return fig
示例#23
0
    def generate_figures(self, fname, highlight=None):

        _image_len = self.width / self.row
        self.__subimages = [(s,
                             moldraw(s,
                                     size=(_image_len, _image_len),
                                     highlight_atoms=highlight))
                            for s in self.__smiles]

        _fig = sg.SVGFigure(str(self.width), str(self.height))
        _subfigs = [
            sg.fromfile(ff[1]) for ff in self.__subimages if ff[1] is not None
        ]
        _labels = range(len(_subfigs))
        _plots = [ff.getroot() for ff in _subfigs]

        _x_coord = 0
        _y_coord = 0
        _final_coords = []

        for sf in _plots:
            if _x_coord + (self.width % self.row) == self.width:
                _x_coord = 0
                _y_coord += 1.25 * _image_len
                sf.moveto(_x_coord, _y_coord, scale=1.0)
                _final_coords.append((_x_coord, _y_coord))
                _x_coord += _image_len
            else:
                sf.moveto(_x_coord, _y_coord, scale=1.0)
                _final_coords.append((_x_coord, _y_coord))
                _x_coord += _image_len

        _txt = [
            sg.TextElement(loc[0] + _image_len / 2,
                           loc[1] + 1.1 * _image_len,
                           str(n + 1),
                           size=36,
                           weight='bold',
                           font='Arial')
            for loc, n in zip(_final_coords, _labels)
        ]

        _fig.append(_plots)
        _fig.append(_txt)
        _fig.save(fname)
    def draw(self):
        import svgutils.transform as sg
        import sys

        fig = sg.SVGFigure(self.width, self.height)
        n = self.height * self.width * self.density / 2500
        random.shuffle(f)
        x = f[:int(n)]
        fig1 = sg.fromfile(x[0])
        fig2 = sg.fromfile(x[1])

        plot1 = fig1.getroot()
        plot2 = fig2.getroot()
        plot2.moveto(50, 50, scale=0.5)

        fig.append([plot1, plot2])

        fig.save("fig_final.svg")
示例#25
0
def transform(setup, infile, outfile, checkfile=None):
    width = f"{setup.bot_width}"
    height = f"{setup.bot_height}"
    fig = sg.SVGFigure(width=width, height=height)
    print(f"Width: {setup.bot_width}")
    print(f"Fig: {fig}")
    fig.root.set('height', height)
    fig.root.set('width', width)
    svg = sg.fromfile(infile)
    drawing = svg.getroot()
    scale, x, y = get_placement(setup, svg)

    drawing.moveto(x, y, scale)
    fig.append([drawing])
    fig.save(outfile)

    if checkfile:
        label_setup(fig, setup, text=False)
        fig.save(checkfile)
示例#26
0
    def saveSVG(self, drawing, filename=None, path=None):
        # compute canvas size
        [xMin, yMin, width, height], strokeWidth = drawing.getViewBox()

        # create SVG
        svg = sg.SVGFigure(str(width) + "mm", str(height) + "mm")
        svg.root.set("viewBox", "%s %s %s %s" % (xMin, yMin, width, height))
        svgLines = []
        for line in drawing.polylines:
            # custom path creation
            points = " ".join(
                map(lambda x: "{:.3f},{:.3f}".format(x[0], -x[1]),
                    line.getPoints()))
            linedata = etree.Element(
                sg.SVG + "polyline", {
                    "points": points,
                    "stroke-width": str(strokeWidth),
                    "stroke-linecap": "square",
                    "stroke": line.color,
                    "fill": "none"
                })
            svgLines.append(sg.FigureElement(linedata))
        g = sg.GroupElement(svgLines, {'id': "root"})
        svg.append(g)

        # save generated SVG files
        if not (path):
            path = self.rootPath
        if not (filename):
            filename = drawing.filename

        filename = re.sub(
            r"[^(a-zA-Z0-9\-_)]+", "_", filename
        )  # make sure that only safe characters are used for filename
        mkpath(path)
        filepath = os.path.join(path, filename) + ".svg"
        drawing.filename = filename
        drawing.path = path
        drawing.url = self.pathToURL(filepath)
        logging.info("drawing.path: " + drawing.path)
        logging.info("drawing.url: " + drawing.url)
        svg.save(filepath)
示例#27
0
def compose_svg_figure(figure_spec, filename, size, display=False):
    """Compose a figure from multiple SVG components.

    Parameters
    ----------
    figure_spec : dict
        Structure describing subfigures to compose (see below).
    filename : str
        File name to save composed SVG
    size : tuple
        Size of final SVG document like ("16cm", "10cm")
    display : bool
        If True, display the complete SVG in Jupyter notebook.

    Each item in *figure_spec* is a dict containing::

        {
            'figure': <matplotlib Figure>,
            'pos': (x, y),
            'scale': 1.0,
            'label': 'A',
            'label_opts': {'size': 16, 'weight': 'bold'},
        }
    """
    import svgutils.transform as svg

    fig = svg.SVGFigure(*size)

    for item in figure_spec:
        subfig = svg.from_mpl(item['figure'], savefig_kw={'bbox_inches':'tight', 'pad_inches':0})
        root = subfig.getroot()
        root.moveto(item['pos'][0], item['pos'][1], scale=item.get('scale', 1.0))
        label = svg.TextElement(item['pos'][0], item['pos'][1], item['label'], **item.get('label_opts', {}))
        fig.append([root, label])

    fig.save(filename)

    if display:
        from IPython.display import SVG, display
        display(SVG(filename=filename))
示例#28
0
def plot_dist(save_path=None):

    plot_dist_abs(save_path + "_abs.svg")
    plot_dist_diff(save_path + "_diff.svg")

    fig = sg.SVGFigure("8.38cm", "17.5cm")

    abs_fig = sg.fromfile(save_path + "_abs.svg")
    abs_plot = abs_fig.getroot()

    diff_fig = sg.fromfile(save_path + "_diff.svg")
    diff_plot = diff_fig.getroot()

    map_fig = sg.fromfile(
        os.path.join("/home/damien/science/papers/current/ns_patches/figures",
                     "dist/dist_map.svg"))
    map_plot = map_fig.getroot()

    map_plot.moveto(41, 14, scale=1)
    abs_plot.moveto(0, 160.0, scale=1.25)
    diff_plot.moveto(0, 395.08, scale=1.25)

    text = functools.partial(sg.TextElement,
                             size=12,
                             weight="bold",
                             font="freesans")

    A = text(11.6, 13, "A")
    B = text(11.6, 162, "B")
    C = text(11.6, 390, "C")

    fig.append([abs_plot, diff_plot, map_plot])
    fig.append(A)
    fig.append(B)
    fig.append(C)

    fig.save(save_path + ".svg")

    figutils.figutils.svg_to_pdf(svg_path=save_path + ".svg",
                                 pdf_path=save_path + ".pdf")
示例#29
0
def main(args=None):
    parser = argparse.ArgumentParser(description="Combine SVG sample.")
    parser.add_argument("input", nargs="+", help="input SVGs")
    parser.add_argument("-o", "--output", help="output SVG", required=True)

    options = parser.parse_args(args)

    w = 0
    svgs = []
    for i, path in enumerate(options.input):
        xml = ET.parse(path)
        for elem in xml.iter(GROUP):
            elem.attrib.pop("id", None)
        for elem in xml.iter(SYMBOL):
            elem.set("id", fixid(elem.get("id"), i))
        for elem in xml.iter(USE):
            elem.set(HREF, fixid(elem.get(HREF), i))

        f = BytesIO()
        xml.write(f)

        svg = sg.fromstring(f.getvalue().decode("us-ascii"))
        width = float(svg.width[:-2])
        w = max(w, width)
        svgs.append(svg)

    h = 0
    elems = []
    for svg in svgs:
        height = float(svg.height[:-2])
        width = float(svg.width[:-2])
        root = svg.getroot()
        root.moveto((w - width) / 2, h)
        h += height

        elems.append(root)

    fig = sg.SVGFigure(w, h)
    fig.append(elems)
    fig.save(options.output)
示例#30
0
文件: svg.py 项目: vsoch/mriqc-1
def combine_svg(svg_list):
    """
    Composes the input svgs into one standalone svg
    """
    import numpy as np
    import svgutils.transform as svgt

    # Read all svg files and get roots
    svgs = [svgt.fromstring(f.encode('utf-8')) for f in svg_list]
    roots = [f.getroot() for f in svgs]

    # Query the size of each
    sizes = [(int(f.width[:-2]), int(f.height[:-2])) for f in svgs]

    # Calculate the scale to fit all widths
    scales = [1.0] * len(svgs)
    if not all([width[0] == sizes[0][0] for width in sizes[1:]]):
        ref_size = sizes[0]
        for i, els in enumerate(sizes):
            scales[i] = ref_size[0] / els[0]

    newsizes = [
        tuple(size)
        for size in np.array(sizes) * np.array(scales)[..., np.newaxis]
    ]

    # Compose the views panel: total size is the width of
    # any element (used the first here) and the sum of heights
    totalsize = [newsizes[0][0], np.sum(newsizes, axis=0)[1]]
    fig = svgt.SVGFigure(totalsize[0], totalsize[1])

    yoffset = 0
    for i, r in enumerate(roots):
        size = newsizes[i]
        r.moveto(0, yoffset, scale=scales[i])
        yoffset += size[1]
        fig.append(r)
    return fig