def makeMatrix(colomns, rows):
	if rows == 0:
		rows == 1
	fig = sg.SVGFigure(str(50+25*colomns)+'mm', str(25*rows)+'mm')
	
	for row in range(rows):
		selection = ''
		if row == rows-1:
			selection += '_l'

		# Left termination
		fig_term_l = sg.fromfile('elements/term_l'+selection+'.svg')
		plot_term_l = fig_term_l.getroot()
		plot_term_l.moveto(0, 72.0/25.4*25*row)
		fig.append([plot_term_l])

		# add the luminet2 tiles
		for colomn in range(colomns):
			if (colomn == colomns-1):
				fig_tile = sg.fromfile('elements/tile_r.svg')
			else:
				fig_tile = sg.fromfile('elements/tile.svg')
			plot_tile = fig_tile.getroot()
			plot_tile.moveto(72.0/25.4*25*(1+colomn), 72.0/25.4*25*row)
			fig.append([plot_tile])

	name = 'matrix/matrix_'+str(colomns)+'x'+str(rows)
	print 'generating '+name
	fig.save(name+'.svg')
	
	os.system('/Applications/Inkscape.app/Contents/Resources/bin/inkscape -E '+name+'.eps '+name+'.svg')#+' > /dev/null 2>&1')
	os.system('pstoedit -dt -f dxf:-polyaslines -xscale 31.75 -yscale 31.75 '+name+'.eps '+name+'.dxf')#+' > /dev/null 2>&1')
	os.system('rm '+name+'.eps')#+' > /dev/null 2>&1')
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')
Exemple #3
0
    def mergeSvgFiles(self):

        files = (self.circosFile, self.colorbarFile, self.legendFile)
        fOutSVG = self.fantomCircosSVG
        fOutPNG = self.fantomCircosPNG
        # create new SVG figure
        width, height = "18cm", "18cm"
        fig = sg.SVGFigure(width, height)

        # load matpotlib-generated figures
        fig1 = sg.fromfile(files[0])
        fig2 = sg.fromfile(files[1])
        fig3 = sg.fromfile(files[2])

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

        plot1.moveto(0, 5, scale=0.21)
        plot2.moveto(490, 550, scale=0.25)
        plot3.moveto(180, 280, scale=0.6)

        # add text labels
        # txt1 = sg.TextElement(25,20, "A", size=12, weight="bold")
        # txt2 = sg.TextElement(305,20, "B", size=12, weight="bold")

        # append plots and labels to figure
        fig.append([plot1, plot2, plot3])
        # fig.append([txt1, txt2])

        # save generated SVG files
        fig.save(fOutSVG)
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)
Exemple #5
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)
Exemple #6
0
    def create_pensive_cowboy_emoji(self, input, output_dir, offset):
        """
      Takes an emoji as input and applies a cowboy hat, then puts it in a city
      and tells it some bad news.
      """
        print(f"pensiving and cowboyfy-ing {input}.... haw yee.")
        # create output path, if it doesn't exist
        Path(output_dir).mkdir(parents=True, exist_ok=True)
        # get filename without path or extension
        input_filename = Path(input).stem

        # load input svg
        input_file = sg.fromfile(input)
        # move input slightly down
        input_root = input_file.getroot()
        input_root.moveto(0, offset)

        # load the all knowing pensive face svg.
        all_knowing_face = sg.fromfile('res/pensive.svg')
        # move pensive face to same spot as input svg
        all_knowing_root = all_knowing_face.getroot()
        # the pensive face is 20x26, so account for that and move it, move it.
        all_knowing_root.moveto(5, offset + 8)

        # apply the offset to the expected height
        final_height = self.standard_size + offset
        # overlay the emojis on a workspace and save that as an output svg
        Figure(f"{self.standard_size}px", f"{final_height}px", input_root,
               self.all_powerful_root,
               all_knowing_root).save(f"{output_dir}/{input_filename}.svg")
Exemple #7
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
Exemple #8
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")
Exemple #9
0
def overlayCartoon(figFile, cartoonFile, x, y, scalee=1):
    """ Add cartoon to a figure file. """
    # Overlay Figure 4 cartoon
    template = st.fromfile(figFile)
    cartoon = st.fromfile(cartoonFile).getroot()

    cartoon.moveto(x, y, scale=scalee)

    template.append(cartoon)
    template.save(figFile)
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")
Exemple #11
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
Exemple #12
0
def overlayCartoon(figFile, cartoonFile, x, y, scalee=1, scale_x=1, scale_y=1, rotate=None):
    """ Add cartoon to a figure file. """

    # Overlay Figure cartoons
    template = st.fromfile(figFile)
    cartoon = st.fromfile(cartoonFile).getroot()

    cartoon.moveto(x, y, scale_x=scalee * scale_x, scale_y=scalee * scale_y)
    if rotate:
        cartoon.rotate(rotate, x, y)

    template.append(cartoon)
    template.save(figFile)
Exemple #13
0
def add_legend(input_svg, legend_svg, outfile):
    """
    Create a new svg by putting one svg on top of another.

    Args:
        input_svg (str): name for first svg file
        legend_svg (str): name for second svg file (will be drawn on top of first)
        outfile (list): name for the output figure file

    """
    template = st.fromfile(input_svg)
    second_svg = st.fromfile(legend_svg)
    template.append(second_svg)
    template.save(outfile)
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))
Exemple #15
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
Exemple #16
0
    def add_overlay(self, is_temperature):
        temp_path = self.svg_path[0:-4] + '_temp_rect.svg'
        output_path = self.svg_path[0:-4] + '_filled_rooms_{0}.svg'.format(
            'temperature' if is_temperature else 'co2')

        dwg = svgwrite.Drawing(temp_path)
        dwg.add(
            dwg.path(d="M0 0 L0 {0} L{1} {2} L{3} 0 Z".format(
                self.view_box[3], self.view_box[2], self.view_box[3],
                self.view_box[2]),
                     fill='#ffffff',
                     opacity=0,
                     id="floor-plan-overlay",
                     visibility="hidden"))
        dwg.add(
            dwg.rect(insert=(0, 0),
                     size=(0, 0),
                     fill="white",
                     stroke="black",
                     id="value-box",
                     visibility="hidden"))
        dwg.add(
            dwg.text(
                text="",
                insert=(0, 0),
                fill="black",
                id="room-title-text",
                visibility="hidden",
                style=
                "font-weight: bold; font-size: 60px; font-family: 'Roboto Mono', monospace;"
            ))
        dwg.add(
            dwg.text(
                text="",
                insert=(0, 0),
                fill="black",
                id="room-value-text",
                visibility="hidden",
                style="font-size: 40px; font-family: 'Roboto Mono', monospace;"
            ))
        dwg.save()  # Save the path to a temporary file
        floor_plan = st.fromfile(
            self.svg_path[0:-4] + '_filled_rooms_{0}.svg'.format(
                'temperature' if is_temperature else 'co2'))
        second_svg = st.fromfile(temp_path)
        floor_plan.append(second_svg)
        floor_plan.save(output_path)
        os.remove(temp_path)
def _check_svg_file(svg_file):
    """ Try to read a SVG file if `svg_file` is a string.
    Raise an exception in case of error or return the svg object.

    If `svg_file` is a svgutils svg object, will just return it.

    Parameters
    ----------
    svg_file: str or svgutils.transform.SVGFigure object
        If a `str`: path to a '.svg' file,
        otherwise a svgutils svg object is expected.

    Returns
    -------
    svgutils svg object

    Raises
    ------
    Exception if any error happens.
    """
    if isinstance(svg_file, str):
        try:
            svg = sg.fromfile(svg_file)
        except Exception as exc:
            raise Exception('Error reading svg file {}.'.format(svg_file)) from exc
        else:
            return svg

    if isinstance(svg_file, sg.SVGFigure):
        return svg_file

    raise ValueError('Expected `svg_file` to be `str` or `svgutils.SVG`, got {}.'.format(type(svg_file)))
Exemple #18
0
def _add_python_power(badge_svg, pypower_svgfile, coords, scale):
    """ Add the pypower_svgfile to the badge svg.

    Parameters
    ----------
    badge_svg: SVG content

    pypower_svgfile: str
        Path to the SVG file

    coords: 2-tuple of int
        Example: (STARS_X, STARS_Y)

    scale: float
        Example: STARS_SCALE

    Returns
    -------
    SVG content
    """
    pp = sg.fromfile(pypower_svgfile)
    badge_height = float(badge_svg.get_size()[1])

    return merge_svg_files(badge_svg,
                           pp,
                           coords[0],
                           badge_height - coords[1],
                           scale=scale)
Exemple #19
0
def game_to_svg(game_state):
    """
    converts game to an svg
    """
    board = game_state.board
    fig = sg.fromfile('baroque_chess_images/' + 'chess_50.svg')
    for i in range(8):
        for j in range(8):
            pos = board[i][j]
            if pos > 1:
                filename = PIECE_MAP[pos]
                svg_file = sg.fromfile('baroque_chess_images/' + filename)
                piece_svg = svg_file.getroot()
                piece_svg.moveto(j * 50 + 2, i * 50 + 2)
                fig.append(piece_svg)
    return fig
Exemple #20
0
def place_letter_on_svg(figure, letter_svg, unit_width, x, y, h):
    letter_object = transform.fromfile(letter_svg)
    letter_root = letter_object.getroot()
    # 13.229 and 26.458 are letter svg view box w and h
    letter_root.scale_xy(unit_width / 13.229, h / 26.458)
    letter_root.moveto(x, y)
    figure.append(letter_root)
Exemple #21
0
def build_avatar_component(path, icon_size=None, avatar_size=None):
    from .models import BaseAvatar
    icon_size = icon_size or BaseAvatar.ICON_SIZE
    avatar_component_size = avatar_size or (899.2, 1415.7)
    scale_factor = icon_size[1] / avatar_component_size[1]
    x_to_center = (icon_size[0] / 2) - (
        (avatar_component_size[0] * scale_factor) / 2)
    svg = SVG(f'{COMPONENT_BASE}{path}')
    if path.startswith('Wallpaper') or path.startswith('Makeup'):
        src = transform.fromfile(f'{COMPONENT_BASE}{path}')

        if src.width is not None:
            src_width = float(re.sub('[^0-9]', '', src.width))
        else:
            src_width = 900

        if src.height is not None:
            src_height = float(re.sub('[^0-9]', '', src.height))
        else:
            src_height = 1415
        scale_factor = icon_size[1] / src_height
        if path.startswith('Makeup'):
            scale_factor = scale_factor / 2

        svg = svg.scale(scale_factor)
        if path.startswith('Makeup'):
            x_to_center = (icon_size[0] / 2) - ((src_width * scale_factor) / 2)
            svg = svg.move(x_to_center, src_height * scale_factor / 2)

    if not path.startswith('Wallpaper') and not path.startswith('Makeup'):
        svg = svg.scale(scale_factor)
        svg = svg.move(x_to_center, 0)
    return svg
Exemple #22
0
 def __init__(self):
     self.table = sg.fromfile('staging_table.svg')
     self.blue = self.table.find_id("svg_226")
     self.red = self.table.find_id("svg_231")
     self.black = self.table.find_id("svg_241")
     self.green = self.table.find_id("svg_236")
     self.marker = self.table.find_id("svg_43")
Exemple #23
0
 def write(self):
     # Process cards into a list of svg pages
     label = click.style('Processing Cards', fg='yellow')
     with click.progressbar(self.cards, label=label, show_eta=True) as cards:
         _pages = []
         _page = self.get_new_page()
         for card in cards:
             i = self.cards.index(card)
             svg_card = sg.fromfile(card)
             h = i % self.n
             x = '%spx' % self.get_x_transform(_page, svg_card)
             y = '%spx' % self.get_y_transform(_page, svg_card, h)
             svg_card.root.set("x", x)
             svg_card.root.set("y", y)
             _page.append(svg_card)
             if not h and i:
                 _pages.append(_page)
                 _page = self.get_new_page()
             if card == self.cards[-1]:
                 _pages.append(_page)
     # Create directory if does not exist.
     output = self.dir + ".paginated"
     if not os.path.isdir(output):
         os.mkdir(output)
     # Write svg_pages to files.
     label = click.style('Writing pages', fg='yellow')
     with click.progressbar(_pages, label=label, show_eta=True) as pages:
         i = 1
         for page in pages:
             f = os.path.join(output, '%05d.svg' % i)
             page.save(f)
             i = i + 1
Exemple #24
0
    def __init__(self, file: Union[Path, str]):
        from svgutils.transform import fromfile

        self.file: Path = Path(file)

        if self.file.suffix in (".eps", ".pdf"):
            self._convert_to_svg()

        svg = fromfile(f"{self.file!s}")

        doc_width, w_unit = self.get_width_height(svg, "width")
        doc_height, h_unit = self.get_width_height(svg, "height")
        assert w_unit == h_unit, "Units of SVG drawing dimensions must match!"

        min_x, min_y, vb_width, vb_height = self.get_view_box(svg)
        assert abs(min_x) < 1e-3 and abs(min_y) < 1e-3, \
            "The min-x/y of the SVG viewBox is non-zero, comment out this line to try loading it anyway"

        user_units_scale = vb_height / doc_height
        assert abs(user_units_scale - vb_width / doc_width) < 1e-2, "Vertical scale is different than horizontal in SVG"

        xform_scale = self.get_svg_scale(svg)

        self.scale = xform_scale * w_unit.to_px(1) / user_units_scale
        self.svg = sc.SVG()
        self.svg.root = svg.getroot().root
Exemple #25
0
def _add_qrcode(badge_svg, qrcode_svgfile, coords, box_size=10):
    """ Add a QRCode SVG content to badge_svg.

    Parameters
    ----------
    badge_svg: SVG content

    qrcode_svgfile: str
        Path to the SVG file

    box_size: int
        Size of the QRCode.
        This is the value of the parameter `box_size` to create the
        QRCode in the function `docstamp.qrcode.save_into_qrcode`.

    coords: 2-tuple of int
        Example: (STARS_X, STARS_Y)

    scale: float
        Example: STARS_SCALE

    Returns
    -------
    SVG content
    """
    #print(qr.get_size())
    #qr.set_size(('57mm', '57mm'))
    qr = sg.fromfile(qrcode_svgfile)

    qr_height = float(qr.height.replace('mm', ''))
    badge_height = float(badge_svg.get_size()[1])
    scale = box_size/qr_height

    return merge_svg_files(badge_svg, qr, coords[0], badge_height - coords[1], scale=scale)
Exemple #26
0
def merge_badge_svgfiles(template_svgfile, pypower_svgfile, qrcode_svgfile, box_size=10):
    """ Merge pypower_file and qrcode_file contents into the correct position
    in the badge file template_svgfile.

    Parameters
    ----------
    template_svgfile: str
        Path to the badge template file.

    pypower_svgfile: str
        Path to the Python Power stars svg file.

    qrcode_svgfile: str
        Path to the SVG file.

    box_size: int
        Size of the QRCode.
        This is the value of the parameter `box_size` to create the
        QRCode in the function `docstamp.qrcode.save_into_qrcode`.

    Returns
    -------
    SVG content
    """
    bg = sg.fromfile(template_svgfile)

    stars_coords = (coordinates['stars_x'], coordinates['stars_y'])
    stars_scale  = coordinates['stars_scale']
    bg = _add_python_power(bg, pypower_svgfile, coords=stars_coords, scale=stars_scale)

    qrcode_coords = (coordinates['qrcode_x'], coordinates['qrcode_y'])
    bg = _add_qrcode(bg,  qrcode_svgfile, coords=qrcode_coords, box_size=box_size)

    return bg
Exemple #27
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'
Exemple #28
0
def _check_svg_file(svg_file):
    """ Try to read a SVG file if `svg_file` is a string.
    Raise an exception in case of error or return the svg object.

    If `svg_file` is a svgutils svg object, will just return it.

    Parameters
    ----------
    svg_file: str or svgutils.transform.SVGFigure object
        If a `str`: path to a '.svg' file,
        otherwise a svgutils svg object is expected.

    Returns
    -------
    svgutils svg object

    Raises
    ------
    Exception if any error happens.
    """
    if isinstance(svg_file, str):
        try:
            svg = sg.fromfile(svg_file)
        except Exception as exc:
            raise Exception('Error reading svg file {}.'.format(svg_file)) from exc
        else:
            return svg
    elif isinstance(svg_file, sg.SVGFigure):
        return svg_file
    else:
        raise ValueError('Expected `svg_file` to be `str` or `svgutils.SVG`, got {}.'.format(type(svg_file)))
Exemple #29
0
def build_avatar_component(path, icon_size=None, avatar_size=None):
    icon_size = icon_size or (215, 215)
    avatar_component_size = avatar_size or (899.2, 1415.7)
    scale_factor = icon_size[1] / avatar_component_size[1]
    x_to_center = (icon_size[0] / 2) - ((avatar_component_size[0] * scale_factor) / 2)
    svg = SVG(f'{COMPONENT_BASE}{path}')
    if path.startswith('Wallpaper'):
        src = transform.fromfile(f'{COMPONENT_BASE}{path}')

        #       TODO: Consider width aswell...
        #        if src.width != None:
        #            src_width = float(re.sub('[^0-9]','', src.width))
        #        else:
        #            src_width = 900

        if src.height is not None:
            src_height = float(re.sub('[^0-9]', '', src.height))
        else:
            src_height = 1415
        scale_factor = icon_size[1] / src_height
        svg = svg.scale(scale_factor)
    if not path.startswith('Wallpaper'):
        svg = svg.scale(scale_factor)
        svg = svg.move(x_to_center, 0)
    return svg
Exemple #30
0
def load_single_fig(fname, width="4300px", height="4300px"):
    """Loads the SVG of a single figure and adjusts its size."""
    fig = sg.fromfile(fname)
    fig.width = width
    fig.height = height

    return fig
Exemple #31
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')
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
Exemple #34
0
 def __init__(self, svgfile, coords=(0, 0)):
     self.file = svgfile
     self.data = sg.fromfile(svgfile).getroot()
     self.dim = self.get_size()
     self.width = self.dim[0]
     self.height = self.dim[1]
     self.x = coords[0]
     self.y = coords[1]
def combine_vertically(figfile1, figfile2, figwidth1, figheight1, figwidth2, figheight2, outfile="out.svg"):
    #create new SVG figure
    fig = sg.SVGFigure(str(max(figwidth1, figwidth2))+"cm", str(figheight1+figheight2)+"cm")
    figdir = os.path.dirname(figfile1)
    # load matpotlib-generated figures
    fig1 = sg.fromfile(figfile1)
    fig2 = sg.fromfile(figfile2)
    # get the plot objects
    plot1 = fig1.getroot()
    plot2 = fig2.getroot()
    plot1.moveto(0, 0, scale=1)
    plot2.moveto(0, cm2px(figheight1), scale=1)

    # append plots and labels to figure
    fig.append([plot1, plot2])
    # save generated SVG files
    fig.save(os.path.join(figdir, outfile))
Exemple #36
0
def make_symbol(container: sg.SVGFigure, name, filepath):
    icon = sg.fromfile(filepath)
    size = get_view_box(icon)
    symbol = sg.fromstring(
        symbol_tpl.format(size['x'], size['y'], size['width'], size['height'],
                          name))
    symbol.append(icon.getroot())
    container.append(symbol)
Exemple #37
0
def qrcode_to_svgfigure(qrcode: qrcode.image.svg.SvgPathImage,
                        color: str = "") -> sg.SVGFigure:
    tmp_file = tempfile.NamedTemporaryFile(mode="w+b", delete=True)
    qrcode.save(tmp_file.name)
    if color:
        replace_file_content(tmp_file.name, "fill:#000000",
                             "fill:#{}".format(color))
    return sg.fromfile(tmp_file.name)
Exemple #38
0
 def __init__(self, fname=None, fix_mpl=False):
     if fname:
         fname = os.path.join(CONFIG['svg.file_path'], fname)
         svg = _transform.fromfile(fname)
         if fix_mpl:
             w, h = svg.get_size()
             svg.set_size((w.replace('pt', ''), h.replace('pt', '')))
         super(SVG, self).__init__(svg.getroot().root)
         self._width = Unit(svg.width).to('px')
         self._height = Unit(svg.height).to('px')
Exemple #39
0
def mergesvg(model, mus):
    """
    model: svg file, containing Music Box paper sheet
    mus: extracted from Lilypond
    """
    for compass in mus:
        # Program here setup of coordinates to create figures 
        dwg = svgwrite.Drawing('compass.svg')
        for note in compass: # note is a pair of x,y coordinates
            dwg.add(dwg.circle((note), r=5, fill='blue'))
            #square = dwg.add(dwg.rect((20,20),(80,80), fill='blue'))
        dwg.saveas('music.svg')
        
        
    template = st.fromfile('template/4x6-index-card-portrait.svg')
    
    music = st.fromfile('music.svg')
    
    template.append(music)
    template.save('rollingnotes.svg')
def el(char, path, x, y, scale=1, offset=(10, 30)):
    toret = []
    if char is not None:
        toret.append(RectElement(x + offset[0], y + offset[1]))
        toret.append(sg.TextElement(x + offset[0], y + offset[1],
                        char, size=24, weight='bold', font='Arial'))
    if path.endswith(".svg"):
        svg = sg.fromfile(path)
        svg = svg.getroot()
        svg.moveto(str(x), str(y), scale)
        return [svg] + toret
def add_label(figfile, fig_width, fig_height, label, loc=(15, 20), labelsize=12):
    savedir = os.path.dirname(figfile)
    fig = sg.SVGFigure(str(fig_width)+"cm", str(fig_height)+"cm")
    figA = sg.fromfile(figfile)
    # get the plot objects
    plot1 = figA.getroot()
    # add text labels
    txt1 = sg.TextElement(loc[0], loc[1], label, size=labelsize, weight="bold")
    fig.append([plot1])
    fig.append([txt1])
    # save generated SVG files
    fig.save(figfile)
Exemple #42
0
def saveQrCodeSVG(filename,text, ptext):
    factory = qrcode.image.svg.SvgPathImage
    img = qrcode.make(text, image_factory=factory,box_size=30, border=4)
    svf = open(filename,"w")
    img.save(svf,"SVG")
    svf.close()
    
    text_svg_fname = filename+".text.svg"
    merged_svg_name = filename+'.merged.svg'
    svg_document = svgwrite.Drawing(filename = text_svg_fname,
                                    size = ("41mm", "41mm"))
    
#    svg_document.add(svg_document.rect(insert = (0, 0),
#                                       size = ("41mm", "41mm"),
#                                       stroke_width = "1",
#                                       stroke = "black",
#                                       fill = "rgb(240,240,240)"))
    
    svg_document.add(svg_document.text(ptext,
                                       insert = (106, 10),
                                       fill = "rgb(0,0,0)",
                                       style = "font-size:1mm; font-family:Arial"))
    svg_document.add(svg_document.text(text,
                                       insert = (7.5, 117),
                                       fill = "rgb(0,0,0)",
                                       style = "font-size:1.8mm; font-family:Arial"))
    svg_document.save()

#    dwg.add(dwg.text('Test', insert=(0, 0.2), fill='red'))

#    ##PDF
#    drawing = svg2rlg(filename)
#    renderPDF.drawToFile(drawing, filename+".pdf")
    
    template = st.fromfile(text_svg_fname)
    second_svg = st.fromfile(filename)
    template.append(second_svg)
    template.save(merged_svg_name)
    drawing = svg2rlg(merged_svg_name)
    renderPDF.drawToFile(drawing, filename+".pdf")
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')
def el(char, path, x, y, w=None, h=None, scale=1, offset=(0, 0)):
    svg, textel = [], []

    if char is not None:
        textel = [sg.TextElement(x + offset[0] + 0.5, y + offset[1] + 11, char,
                                 size=14, weight='bold', font='Arial')]

    if path is not None:
        svg = sg.fromfile(path)
        if w is not None and h is not None:
            svg.set_size((w, h))
        svg = svg.getroot()
        svg.moveto(str(x), str(y), scale)
        svg = [svg]
    return svg + textel
def addLayout(design,images):
    tree = ET.parse(__location__+"/templates/"+design+".xml").getroot()
    # All the following aren't actually needed.. yet!
    #name= tree.findtext("name")
    #type= tree.findtext("type")
    #case= tree.findtext("case")
    # for each layout..
    for image in tree.findall('image'):
        isource = image.get("source")
        ipos = image.get("position").split(",")

        img = sg.fromfile(__location__+'/templates/%s' % isource)
        iobj = img.getroot()
        iobj.moveto(ipos[0],ipos[1])
        images.append(iobj)
    return True
Exemple #46
0
def _add_python_power(badge_svg, pypower_svgfile, coords, scale):
    """ Add the pypower_svgfile to the badge svg.

    Parameters
    ----------
    badge_svg: SVG content

    pypower_svgfile: str
        Path to the SVG file

    coords: 2-tuple of int
        Example: (STARS_X, STARS_Y)

    scale: float
        Example: STARS_SCALE

    Returns
    -------
    SVG content
    """
    pp = sg.fromfile(pypower_svgfile)
    badge_height = float(badge_svg.get_size()[1])

    return merge_svg_files(badge_svg, pp, coords[0], badge_height - coords[1], scale=scale)
Exemple #47
0
def compose_svg(pieces_to_put, options):
    board_svg_filename = os.path.join(options.board_theme_dir, _BOARD_SVG_BASENAME)
    board_ini_filename = os.path.join(options.board_theme_dir, _BOARD_INI_BASENAME)

    # Check for existance ourselves since ConfigParser would throw NoSectionError
    # at us for a missing file.
    if not os.path.exists(board_ini_filename):
        raise IOError(errno.ENOENT, "No such file or directory: '%s'" % board_ini_filename)

    config = ConfigParser.RawConfigParser(defaults={'river': 0.0})
    config.read(board_ini_filename)

    output_board_offset_left_pixel = config.getfloat(_BOARD_CONFIG_SECTION, 'left')
    output_board_offset_top_pixel = config.getfloat(_BOARD_CONFIG_SECTION, 'top')
    output_board_width_pixel = config.getfloat(_BOARD_CONFIG_SECTION, 'width')
    output_board_height_pixel = config.getfloat(_BOARD_CONFIG_SECTION, 'height')
    output_board_river_height_pixel = config.getfloat(_BOARD_CONFIG_SECTION, 'river')

    jobs = []
    for put_piece in pieces_to_put:
        x_rel = float(put_piece.x) / _MAX_X
        y_rel = float(_MAX_Y - put_piece.y) / _MAX_Y
        basename = _FILENAME_OF_PARTY_PIECE[put_piece.party][put_piece.piece]
        filename = os.path.join(options.pieces_theme_dir, basename)
        jobs.append((x_rel, y_rel, filename))

    if options.debug:
        for x_rel in (0.0, 1.0):
            for y_rel in (0.0, 1.0):
                jobs.append((x_rel, y_rel, os.path.join(options.pieces_theme_dir, _DIAMOND_FILE_NAME)))

    # Read board
    board_fig = sg.fromfile(board_svg_filename)
    board_root = board_fig.getroot()

    # Scale board to output
    board_width_pixel, board_height_pixel = [_length_string_to_pixel(e, options.resolution_dpi) for e in board_fig.get_size()]
    height_factor = board_height_pixel / float(board_width_pixel)
    board_scale = options.width_pixel / board_width_pixel
    board_root.moveto(0, 0, scale=board_scale)

    output_board_offset_left_pixel *= board_scale
    output_board_offset_top_pixel *= board_scale
    output_board_width_pixel *= board_scale
    output_board_height_pixel *= board_scale
    output_board_river_height_pixel *= board_scale

    # Initialize output figure
    output_fig = sg.SVGFigure(
            str(options.width_pixel),
            str(options.width_pixel * height_factor))
    output_fig.append([board_root, ])

    for (x_rel, y_rel, filename) in jobs:
        piece_fig = sg.fromfile(filename)
        piece_root = piece_fig.getroot()
        original_piece_width_pixel, original_piece_height_pixel = [
                _length_string_to_pixel(s, options.resolution_dpi)
                for s in piece_fig.get_size()
                ]

        # Scale and put piece onto board
        center_x_pixel = output_board_offset_left_pixel + output_board_width_pixel * x_rel
        center_y_pixel = output_board_offset_top_pixel + (output_board_height_pixel - output_board_river_height_pixel) * y_rel \
                + (output_board_river_height_pixel if (y_rel >= 0.5) else 0.0)

        maximum_future_piece_width_pixel = output_board_width_pixel / _MAX_X * options.piece_scale
        maximum_future_piece_height_pixel = output_board_height_pixel / _MAX_Y * options.piece_scale

        scale = min(maximum_future_piece_width_pixel / original_piece_width_pixel, maximum_future_piece_height_pixel / original_piece_height_pixel)

        future_piece_width_pixel = original_piece_width_pixel * scale
        future_piece_height_pixel = original_piece_height_pixel * scale

        x_pixel = center_x_pixel - future_piece_width_pixel / 2.0
        y_pixel = center_y_pixel - future_piece_height_pixel / 2.0
        piece_root.moveto(x_pixel, y_pixel, scale=scale)
        output_fig.append([piece_root, ])

    output_fig.save(options.output_file)
Exemple #48
0
def add_file(fig, filename, x_cm, y_cm, scale=1.0):
    figSub = sg.fromfile(filename)
    plSub = figSub.getroot()
    plSub.moveto(x_cm * cm_to_pt, y_cm * cm_to_pt, scale=scale)
    fig.append(plSub)
Exemple #49
0
def randEmojis(N,filenames):
    """returns N svg elements sourced from fileNames"""
    fNames = np.random.choice(filenames,N)
    return [sg.fromfile(fName) for fName in fNames]
#!/usr/bin/env python
#coding=utf-8

import svgutils.transform as sg

# open source svg files 
# (for sake of example we read the same file twice)
fig1 = sg.fromfile('mpl_template.svg')
fig2 = sg.fromfile('mpl_template.svg')

# get the root of figure code
plot1 = fig1.getroot()
plot2 = fig2.getroot()

# create a new figure of specified size
fig = sg.SVGFigure("12cm", "13cm")

# move the plots
plot1.moveto(0,0)
plot2.moveto(200, 0)

# add text labels
txt1 = sg.TextElement(25,20, "A", size=12, weight="bold")
txt2 = sg.TextElement(225,20, "B", size=12, weight="bold")

fig.append([plot1, plot2])
fig.append([txt1, txt2])

# save figures
fig.save('final_figure1.svg')
Exemple #51
0
import svgutils.transform as sg

dx = -20
dy = -45

fig1 = sg.fromfile("finitem.svg")
plot1 = fig1.getroot()
plot1.moveto(0 + dx, 10 + dy)
txt1 = sg.TextElement(10, 20, "A", size=18, weight="bold")

fig2 = sg.fromfile("populations.svg")
plot2 = fig2.getroot()
plot2.moveto(430 + dx + 40, 10 + dy + 15)
txt2 = sg.TextElement(440, 20, "B", size=18, weight="bold")

fig3 = sg.fromfile("onetoone-new.svg")
plot3 = fig3.getroot()
plot3.moveto(0 + dx, 325 + dy)
txt3 = sg.TextElement(10, 335, "C", size=18, weight="bold")

fig4 = sg.fromfile("randnoself.svg")
plot4 = fig4.getroot()
plot4.moveto(430 + dx, 325 + dy)
txt4 = sg.TextElement(440, 335, "D", size=18, weight="bold")

fig = sg.SVGFigure("9.65in", "7in")
fig.append([plot1, plot2, plot3, plot4])
fig.append([txt1, txt2, txt3, txt4])
fig.save("csa-pane.svg")
Exemple #52
0
    handles, legend_labels = ax1.get_legend_handles_labels()
    hl = sorted(zip(handles, legend_labels), key=operator.itemgetter(1))
    handles, legend_labels = zip(*hl)
    ax1.legend(handles, legend_labels,# title="connection method, slope",
               fancybox=True, loc="best", numpoints=1, handlelength=2.2)
    
    fname = "%s_scaling_native.svg" % scaling_mode
    fig1.savefig(fname)
    print "saved '%s'" % fname




import svgutils.transform as sg

fig1 = sg.fromfile("CSAConnector_random(0.1).svg")
plot1 = fig1.getroot()
plot1.moveto(0, 10)
txt1 = sg.TextElement(10, 20, "A", size=18, weight="bold")

fig2 = sg.fromfile("CSAConnector_oneToOne.svg")
plot2 = fig2.getroot()
plot2.moveto(430, 10)
txt2 = sg.TextElement(440, 20, "B", size=18, weight="bold")

fig3 = sg.fromfile("CSAConnector_strong_scaling_random(0.1).svg")
plot3 = fig3.getroot()
plot3.moveto(0, 325)
txt3 = sg.TextElement(10, 335, "C", size=18, weight="bold")

fig4 = sg.fromfile("CSAConnector_weak_scaling_random(0.1).svg")
def load_svg(path):
    return sg.fromfile(path).getroot()
Exemple #54
0
def create_label_page(ids, page_num):
    global x,y

    label_sheet = sg.SVGFigure('612', '792') # 8.5"x11" paper at 72dpi
    labels = []

    # Convert the base label pdf to svg
    pdf2svg(label_pdf, 'output/label.svg')

    for nodeid in ids:
        nodeidstr = nodeid.replace(':', '')

        if QR_IN_USE:
            # Create the QR code
            img = qrcode.make(QR_CODE_STR.format(nodeid),
                    image_factory=qrcode.image.svg.SvgPathImage,
                    box_size=7,
                    version=4,
                    border=0)
            img.save('output/qr_{}.svg'.format(nodeidstr))

            # Color the QR code
            with open('output/qr_{}.svg'.format(nodeidstr), 'r+') as f:
                svg = f.read()
                f.seek(0)
                svg = svg.replace('fill:#000000;', 'fill:{};'.format(QR_COLOR))
                f.write(svg)

        # Create the node specific svg
        fig = sg.SVGFigure('{}px'.format(label_pixels_x), '{}px'.format(label_pixels_y))

        rawlabel = sg.fromfile('output/label.svg')
        rawlabelr = rawlabel.getroot()

        if QR_IN_USE:
            qr = sg.fromfile('output/qr_{}.svg'.format(nodeidstr))
            qrr = qr.getroot()
            # position correctly (hand tweaked)
            qrr.moveto(label_qr_pos_x, label_qr_pos_y, label_qr_scale)

        # position modifications based on text
        (x_mod, y_mod, nodeid) = position_label(nodeid)

        #txt = sg.TextElement(100,318, nodeid, size=28, font='Courier')
        txt = sg.TextElement(label_id_pos_x+x_mod,
                             label_id_pos_y+y_mod,
                             nodeid,
                             size=label_id_font,
                             font='Droid Sans',
                             letterspacing=label_id_letterspacing,
                             anchor='middle')

        if QR_IN_USE:
            fig.append([rawlabelr, qrr, txt])
        else:
            fig.append([rawlabelr, txt])
        fig.save('output/label_{}.svg'.format(nodeidstr))

        if label_rotate:
                fig = sg.SVGFigure('{}px'.format(label_pixels_y), '{}px'.format(label_pixels_x))
                dlabel = sg.fromfile('output/label_{}.svg'.format(nodeidstr))
                dlabelr = dlabel.getroot()
                dlabelr.rotate(90, x=0, y=0)
                dlabelr.moveto(0, -1*label_pixels_y)
                fig.append([dlabelr])
                fig.save('output/label_{}.svg'.format(nodeidstr))

    #       labels.append(fig)

            # Convert the id specific image to pdf
    #       sh.rsvg_convert('-f', 'pdf', '-o', 'label_{}.pdf'.format(nodeidstr),
    #               'label_{}.svg'.format(nodeidstr))

            # Stamp the label with id specific image
    #       pdftk(CASE_LABEL, 'stamp', 'unique_{}.pdf'.format(nodeidstr), 'output',
    #               'label_{}.pdf'.format(nodeidstr))

    #       pdf2svg('label_{}.pdf'.format(nodeidstr), 'label_{}.svg'.format(nodeidstr))

        lbl = sg.fromfile('output/label_{}.svg'.format(nodeidstr))
        lblr = lbl.getroot()
        pos = get_coordinates()
        lblr.moveto(pos[0], pos[1], 1) # position correctly (hand tweaked)

        if pos[2]:
            labels.append(lblr)

    label_sheet.append(labels)
    label_sheet.save('output/all_labels_{}.svg'.format(page_num))
    sh.rsvg_convert('-f', 'pdf', '-d', '72', '-p', '72', '-o',
            'output/all_labels_{}.pdf'.format(page_num),
            'output/all_labels_{}.svg'.format(page_num))

    # cleanup after yourself
    x = POSITION_START_X
    y = POSITION_START_Y
    for fl in glob.glob('output/label_*'):
        os.remove(fl)
Exemple #55
0
def addColorbar_to_svg(svgtext_or_filename,data2color=None, scratchpath=None, colorbarlimits=None, colorbar_ylabel=None, colorbar_ticks_side=None, colorbar_aspectratio=6, ticks=None,colorbar_filename=None,
                       # Following set of parameters describes location of colorbar. These used to be
                       frameon=True,colorbar_location=None,):
    """
colorbar_filename: If you want to get access to the colorbar by itself, set this. Otherwise, a tempfile is used.

The return value is the full svg text with colorbar added.
    """
    if colorbar_location is None:
        colorbar_location={}
    cblocation=dict(expandx=1, movebartox='auto',movebartoy='auto',scalebar=.75)
    cblocation.update(colorbar_location)

    def isdec(cc):
                return(cc.isdigit() or cc in '.')

    # Determine enough information to draw a colorbar:

    """ Add a colorbar. However, there are various possibilities for how; see above.
    """
    import svgutils.transform as sg
    import sys 

    # First, save svgtext to a file, if it is not one, and choose a (temporary) filename for the colorbar svg:
    # (Why can we use sg.fromfile no problem, but sg.fromtext causes Unicode trouble?)
    import tempfile
    to_delete=[] # Collect list of temp files that must be deleted explicitly
    if '\n' not in svgtext_or_filename:
        insvgfn=svgtext_or_filename
    else:
        tmpfh,insvgfn=tempfile.mkstemp()
        to_delete += [insvgfn]
        os.write(tmpfh, svgtext_or_filename)
        os.close(tmpfh) # see http://stackoverflow.com/questions/9944135/how-do-i-close-the-files-from-tempfile-mkstemp
    tmpfinalfh,outfilename=tempfile.mkstemp()
    to_delete += [outfilename]
    os.close(tmpfinalfh) # see #153. Otherwise, we have a file descriptor leak. But this way we get the file name

    if colorbar_filename is None:
        tmpcbfh,CBfilename=tempfile.mkstemp()
        to_delete += [CBfilename]
        os.close(tmpcbfh)
    else:
        CBfilename = colorbar_filename
        
    # Load svg into svgutils; determine units of the layout
    base_svg=sg.fromfile(insvgfn)
    def _getSizeWithUnits(svgbase):
        from cpblUtilities.mathgraph import tonumeric
        # Assume measure is digits then units:
        ww,hh=svgbase.get_size()
        ww,unitsSuffix=''.join([cc  for cc in ww if isdec(cc)]),''.join([cc  for cc in ww if not isdec(cc)])  
        hh,unitsSuffix2=''.join([cc  for cc in hh if isdec(cc)]),''.join([cc  for cc in hh if not isdec(cc)])
        return(tonumeric(ww),tonumeric(hh),unitsSuffix,unitsSuffix2)
    ww,hh,u1,u2=_getSizeWithUnits(base_svg) #   ww,hh=base_svg.get_size() # This is sometimes just numbers, but sometimes there are units too (px).
    unitsSuffix=''
    #if 1:#any(not isdec(cc) for cc in ww): # What to do when there are units? .. .isdigit()
    #    ww,unitsSuffix=''.join([cc  for cc in ww if isdec(cc)]),''.join([cc  for cc in ww if not isdec(cc)])  
    #    hh,unitsSuffix2=''.join([cc  for cc in hh if isdec(cc)]),''.join([cc  for cc in hh if not isdec(cc)])
    #    assert unitsSuffix==unitsSuffix2

    # Create a dummy axis to hang the colorbar on:
    plt.figure(6354)
    hax=plt.gca()
    from cpblUtilities.color import addColorbarNonImage
    if 'fontsize' in colorbar_location: # This is measured in points.
        plt.rcParams.update({        'font.size': colorbar_location['fontsize'],})
    hbax=addColorbarNonImage(data2color,ylabel=colorbar_ylabel,ticks=ticks, colorbar_ticks_side=colorbar_ticks_side) # data2color=None,data=None,datarange=None,cmap=None,useaxis=None,ylabel=None,colorbarfilename=None,location=None,ticks=None):

    plt.setp(hax,'visible',False) # In fact, I think I've seen example where this hax was even in a different figure, already closed!
    hbax.ax.set_aspect(colorbar_aspectratio)
    plt.gcf().frameon=frameon
    plt.savefig(CBfilename+'.svg', bbox_inches='tight', pad_inches=0.1,frameon=frameon) 
    #plt.savefig(CBfilename+'.png', bbox_inches='tight', pad_inches=0.1) # for testing
    # Or, I can just grab it directly!  So above saving is no longer needed, except that I want one colorbar created at some point for each standard variable...
    from svgutils.transform import from_mpl
    cbsvg=sg.from_mpl(plt.gcf()) 

    if cblocation['movebartox']=='auto':
        assert cblocation['movebartoy']=='auto'
        # Try to put it in the bottom right??
        cbww,cbhh,u1,u2=_getSizeWithUnits(base_svg) #   ww,hh=base_svg.get_size() # This is sometimes just numbers, but sometimes there are units too (px)self.                
        ###cbsvg=sg.fromfile(CBfilename+'.svg')
        svg1,svg2 = base_svg.getroot(),cbsvg.getroot()
        #cbsize=[int(''.join([cc for cc in ss  if cc.isdigit()])) for ss in cbsvg.get_size()] # Strip off the "pt" units that I have from this MPL colorbar at the moment :(
        #cbw,cbh= int(ww)/10, int(ww)/10 * cbsize[1]/cbsize[0]
        if 0: # should I fix the colorbar to be a certain fraction of the map size? Or keep it fixed the same for all maps?
            cbsvg.set_size(cbw,cbh)
        cblocation['movebartox']=ww-cbww
        cblocation['movebartoy']=hh-cbhh
#            if 0: # This was old "auto" code. All junk now?
#                # Try new method with svg_stack rather than svgutils:
#                import svg_stack as ss
#
#                doc = ss.Document()
#
#                A='____tmp_tmppart1.svg'
#                B='../okai/scratch/analysisTIGERcountiesMap_delta12_fourway.svg-tmpCB.svg'
#                C='trash/red_ball.svg'
#                layout1 = ss.HBoxLayout()
#                layout1.addSVG(insvgfn,alignment=ss.AlignTop|ss.AlignHCenter)
#                layout1.addSVG(CBfilename+'.svg',alignment=ss.AlignCenter)#,stretch=0.5)
#                noThisIsDrafty
#    #layout2 = ss.VBoxLayout()
#
#    #layout2.addSVG(C,alignment=ss.AlignCenter)
#    #layout2.addSVG(C,alignment=ss.AlignCenter)
#    #layout2.addSVG(C,alignment=ss.AlignCenter)
#    #layout1.addLayout(layout2)
#
#                doc.setLayout(layout1)
#                print(' Saving (auto mode in cblocation) '+outfilename)
#                doc.save(outfilename)
#

    # else: # Use cblocation values
    # get the plot objects from constituent figures. I don't know why using the cbsvg from above doesn't work
    cbsvg=sg.fromfile(CBfilename+'.svg')
    if colorbar_filename is None: os.remove(CBfilename+'.svg') # no longer needed
    svg1,svg2 = base_svg.getroot(),cbsvg.getroot()
    """
    if cblocation['movebartox']=='auto':
        assert cblocation['movebartoy']=='auto'
        # Below is old debug code working on using more automated fatures of svgutils. I switched to svg_stack, above, instead.
        impoosible_to_get_here
        cbw,cbh=cbsvg.get_size()


        from svgutils.transform import from_mpl
        from svgutils.templates import VerticalLayout,ColumnLayout

        ###svg = fromfile('../tests/circle.svg')
        layout = VerticalLayout#ColumnLayout(2)
        layout.add_figure(base_svg)
        layout.add_figure(cbsvg)

        layout.save('stack_svg.svg')
        oiuoiu
        layout = VerticalLayout()

        fig1 = plt.figure()
        plt.plot([1,2])
        fig2 = plt.figure()
        plt.plot([2,1])

        layout.add_figure(from_mpl(fig1))
        layout.add_figure(from_mpl(fig2))

        print from_mpl(fig1).get_size()
        layout.save('stack_plots.svg')

        fofoiu
    """
    svg2.moveto(cblocation['movebartox'],cblocation['movebartoy'], scale=cblocation['scalebar'])

    #create new SVG figure
    fsvg = sg.SVGFigure(str(float(ww)*cblocation['expandx'])+unitsSuffix,str(float(hh)*cblocation['expandx'])+unitsSuffix)
    #fsvg = sg.SVGFigure(ww,hh)

    # append plots and labels to figure
    fsvg.append([svg1, svg2])
    # save generated SVG files
    fsvg.save(outfilename) # This is a temporary file! It's supposed to include the whole fig, but bug: 2015May: only includes colorbar!!
    # Something is broken, May 2015.
    #Does this work:
    # N.B.!!! This is a kludge. Not sure why the above broke.
    base_svg=sg.fromfile(insvgfn)
    base_svg.append(svg2)
    base_svg.save(outfilename)
    print('       Wrote '+outfilename)

    plt.close(6354)
    try: # Some old version don't have to_str()
        svgstr = base_svg.to_str()
    except AttributeError:
        with open(outfilename, 'r') as f:
            svgstr = f.read()
            
    for fname in to_delete+[insvgfn, outfilename]: # list following + is redundant?
        if os.path.exists(fname):  os.remove(fname)
            
    return svgstr
Exemple #56
0
try:
	count = int(sys.argv[1])
	version = int(sys.argv[2])
except:
	print('{} <count> <version (0 or 1)>'.format(sys.argv[0]))

label_svg = MAIN_LABEL_SVGS[version]
label_pixels_x = 72
label_pixels_y = 54


label_sheet = sg.SVGFigure('792', '612') # 8.5"x11" paper at 72dpi
labels = []

for i in range(count):
	lbl = sg.fromfile(label_svg)
	lblr = lbl.getroot()
	pos = get_coordinates()
	lblr.moveto(pos[0], pos[1], 1) # position correctly (hand tweaked)
	labels.append(lblr)

label_sheet.append(labels)
base_name = 'triumvi_bottom_{}_{}'.format(count, version)
output_name = '{}.svg'.format(base_name)
label_sheet.save(output_name)
with open(output_name, 'r') as f:
	contents = f.read()
	contents = contents.replace(" standalone='yes'", "")
with open(output_name, 'w') as f:
	f.write(contents)
sh.rsvg_convert('-f', 'pdf', '-d', '72', '-p', '72', '-o',
Exemple #57
0
		box_size=7,
		version=4,
		border=0)
	img.save('qr_{}.svg'.format(nodeidstr))

	# Color the QR code
	with open('qr_{}.svg'.format(nodeidstr), 'r+') as f:
		svg = f.read()
		f.seek(0)
		svg = svg.replace('fill:#000000;', 'fill:{};'.format(QR_COLOR))
		f.write(svg)

	# Create the node specific svg
	fig = sg.SVGFigure('{}px'.format(label_pixels_x), '{}px'.format(label_pixels_y))

	rawlabel = sg.fromfile(label_svg)
	rawlabelr = rawlabel.getroot()

	qr = sg.fromfile('qr_{}.svg'.format(nodeidstr))
	qrr = qr.getroot()
	# position correctly (hand tweaked)
	qrr.moveto(label_qr_pos_x, label_qr_pos_y, label_qr_scale)

	if label_txt_func:
		nodeid_txt = label_txt_func(nodeid)
	else:
		nodeid_txt = nodeid
	txt = sg.TextElement(label_id_pos_x,
	                     label_id_pos_y, nodeid_txt,
	                     size=label_id_font,
	                     font='Courier',
Exemple #58
0
import svgutils.transform as sg
import sys 

#create new SVG figure
fig = sg.SVGFigure("16cm", "6.5cm")

# load matpotlib-generated figures
fig1 = sg.fromfile('sigmoid_fit.svg')
fig2 = sg.fromfile('anscombe.svg')

# get the plot objects
plot1 = fig1.getroot()
plot2 = fig2.getroot()
plot2.moveto(280, 0, scale=0.5)

# add text labels
txt1 = sg.TextElement(25,20, "A", size=12, weight="bold")
txt2 = sg.TextElement(305,20, "B", size=12, weight="bold")

# append plots and labels to figure
fig.append([plot1, plot2])
fig.append([txt1, txt2])

# save generated SVG files
fig.save("fig_final.svg")
Exemple #59
0
#!/usr/bin/env python
# coding=utf-8

from svgutils.transform import fromfile
from svgutils.templates import VerticalLayout, ColumnLayout


layout = ColumnLayout(5)

for i in range(12):
    svg = fromfile("../tests/circle.svg")
    layout.add_figure(svg)

layout.save("stack_svg.svg")