Ejemplo n.º 1
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
Ejemplo n.º 2
0
def string_to_compose(string):
    """Convert an SVG string to a ``svgutils.compose.SVG``."""
    from svgutils.compose import SVG
    from svgutils.transform import fromstring

    svg_figure = fromstring(string)
    element = SVG()
    element.root = svg_figure.getroot().root
    return element, list(map(float, svg_figure.get_size()))
Ejemplo n.º 3
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}').scale(scale_factor).move(x_to_center, 0)
    return svg
Ejemplo n.º 4
0
def build_temporary_avatar_component(
    icon_size=None,
    avatar_size=None,
    primary_color='#18C708',
    secondary_color='#FFF',
    component_type='cardigan',
    component_category='clothing'
):
    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)
    payload = {
        'category': component_category,
        'item': component_type,
        'primary_color': primary_color,
        'secondary_color': secondary_color
    }
    with NamedTemporaryFile(mode='w+') as tmp:
        svg_data = get_svg_template(**payload)
        tmp.write(str(svg_data))
        tmp.seek(0)
        svg = SVG(tmp.name).scale(scale_factor).move(x_to_center, 0)
    return svg
Ejemplo n.º 5
0
 def __init__(self, width_or_filename, height=None, *svgelements):
     if height is None:
         # some pretty hacky code to autodetect height
         assert len(svgelements) == 0
         svgfigure = svgutils.transform.fromfile(width_or_filename)
         svg = SVG(width_or_filename).scale(1)  # scale of 1 converts to an Element
         super(Element, self).__init__(self._parse_string_dimension(svgfigure.width),
                                       self._parse_string_dimension(svgfigure.height), svg)
     else:
         super(Element, self).__init__(width_or_filename, height, *svgelements)
Ejemplo n.º 6
0
Archivo: utils.py Proyecto: svipal/web
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
Ejemplo n.º 7
0
def plot_locus(grange,
               groupby,
               cellannot,
               files,
               size_factor='rdepth',
               tag='RG',
               mapq=10,
               frames_before=None,
               frames_after=None,
               normalize=True,
               palettes=sc.pl.palettes.vega_20_scanpy,
               add_total=True,
               style='fill',
               binsize=50,
               binarize=False,
               frame_width=40,
               add_labels=True,
               width_overlap=18.,
               extend_window=0,
               save=None,
               **kwargs):

    if isinstance(grange, dict):
        names = [k for k in grange]
        ranges = [grange[k] for k in grange]

    elif not isinstance(grange, list):
        ranges = [grange]
        names = ['']

    elif isinstance(grange, list):
        names = [''] * len(grange)
        ranges = granges
    if frames_before is None:
        frames_before = Frame()

    if extend_window > 0:
        ranges = [_extend(gr, extend_window) for gr in ranges]

    with tempfile.TemporaryDirectory() as tmpdir:
        for i, (name, gr) in enumerate(zip(names, ranges)):
            sct = SingleCellTracks(cellannot,
                                   files,
                                   size_factor=size_factor,
                                   tag=tag,
                                   mapq=mapq)

            frame = copy.deepcopy(frames_before)
            frame.properties['title'] = name

            fig = sct.plot(gr,
                           groupby,
                           frames_before=frame,
                           frames_after=frames_after,
                           normalize=normalize,
                           palettes=palettes,
                           add_total=add_total,
                           style=style,
                           binsize=binsize,
                           add_labels=add_labels if i == (len(names) -
                                                          1) else False,
                           binarize=binarize,
                           **kwargs)
            fig.savefig(os.path.join(tmpdir, f'{name}_{gr}.svg'))

        panel = SVG(os.path.join(tmpdir, f'{name}_{gr}.svg'))
        width, height = panel.width, panel.height

        composite_figure = Figure(
            f"{(width-width_overlap)*len(names)+width_overlap}pt",
            f"{height}pt", *[
                SVG(os.path.join(tmpdir, f'{name}_{gr}.svg')).move(
                    (width - width_overlap) * i, 0)
                for i, (name, gr) in enumerate(zip(names, ranges))
            ])
        if save is not None:
            composite_figure.save(save)
            os.makedirs(save.split('.')[0], exist_ok=True)
            for name, gr in zip(names, ranges):
                shutil.copy(os.path.join(tmpdir, f'{name}_{gr}.svg'),
                            save.split('.')[0])

    return composite_figure
Ejemplo n.º 8
0
#!/usr/bin/env python
#coding=utf-8

from sys import argv
from svgutils.compose import Figure, SVG

Figure(
    20,
    20,
    SVG(argv[1]),
    SVG(argv[2]),
).save(argv[3])
Ejemplo n.º 9
0
def pyx_script_pmsm(ad, best_chromosome, best_idx, Q, p, proj_name):
    if proj_name is None:
        name = 'Q%dp%didx%d' % (Q, p, best_idx)
    else:
        name = 'Q%dp%didx%d%s' % (Q, p, best_idx, proj_name)

    # output location 1
    filename_cross_sectional_view = "../_pemd2020/%s.svg" % (
        "Figure_selected_optimal_design_%s" % (name))
    # output location 2
    filename_cross_sectional_view = ad.solver.output_dir + "%s.svg" % (
        "Figure_selected_optimal_design_%s" % (name))
    # output location 3
    filename_cross_sectional_view = '../release/' + "%s.svg" % (
        "Figure_selected_optimal_design_%s" % (name))

    # Plot cross section view
    import bearingless_spmsm_design
    spmsm_best = bearingless_spmsm_design.bearingless_spmsm_design(
        spmsm_template=ad.spec.acm_template,
        x_denorm=best_chromosome[:-3],
        counter=999,
        counter_loop=1)
    spmsm_best.ID = name
    import VanGogh
    tool_tikz = VanGogh.VanGogh_TikZPlotter()
    spmsm_best.draw_spmsm(
        tool_tikz, bool_pyx=True)  # collecting track_path list for tool_tikz

    # 就算可以直接画出来,也只有最小部分而已,没有做镜像和旋转!
    # tool_tikz.c.writePDFfile("../test"+proj_name)
    # tool_tikz.c.writeEPSfile("Figure_selected_optimal_design_%s"%(name))
    tool_tikz.c.writePDFfile(filename_cross_sectional_view[:-4])
    tool_tikz.c.writeSVGfile("../a")
    # print('Write to pdf file:', "../test"+proj_name)
    # raise Exception('DEBUG HERE')
    tool_tikz.c = pyx.canvas.canvas()

    # Use tool_tikz.track_path to redraw the model
    def redraw_cross_section_outline_with_pyx(tool_tikz, no_repeat_stator,
                                              no_repeat_rotor,
                                              mm_rotor_outer_radius,
                                              mm_air_gap_length,
                                              mm_rotor_outer_steel_radius,
                                              mm_rotor_inner_radius):
        # PyX
        tool_tikz.c = pyx.canvas.canvas(
        )  # clear the canvas because we want to redraw 90 deg with the data tool_tikz.track_path

        print('Index   | Path data')
        p_stator = None  #pyx.path.path()
        p_rotor = None  #pyx.path.path()
        for index, path in enumerate(
                tool_tikz.track_path
        ):  # track_path is passed by reference and is changed by mirror
            # Failed to fill the closed path, because there is no arc-like path available.
            # p = pyx.path.line(4, 0, 5, 0) << pyx.path.line(5, 0, 5, 1) << pyx.path.line(5, 1, 4, 1)
            # p.append(path.closepath())
            # tool_tikz.c.stroke(p)
            # tool_tikz.c.stroke(path.rect(0, 0, 1, 1), [pyx.style.linewidth.Thick,
            #                      pyx.color.rgb.red,
            #                      pyx.deco.filled([pyx.color.rgb.green])])

            path_mirror = deepcopy(path)
            # for mirror copy (along x-axis)
            path_mirror[1] = path[1] * -1
            path_mirror[3] = path[3] * -1
            # for mirror copy (along y-axis)
            # path_mirror[0] = path[0]*-1
            # path_mirror[2] = path[2]*-1

            bool_exclude_path = False

            # rotate path and plot
            if is_at_stator(path, mm_rotor_outer_radius, mm_air_gap_length):
                Q = no_repeat_stator
            else:
                Q = no_repeat_rotor * 2

            EPS = 1e-6
            if is_at_stator(path, mm_rotor_outer_radius, mm_air_gap_length):
                # 按照Eric的要求,把不必要的线给删了。
                if abs(path[1] + path[3]) < EPS:  # 镜像对称线
                    bool_exclude_path = True
                if abs(path[0] - path[2]) + np.cos(
                        2 * np.pi / Q / 2) < EPS:  # 旋转对称线(特别情况,tan(90°) = ∞
                    bool_exclude_path = True
                else:
                    if abs(
                            abs((path[1] - path[3]) / (path[0] - path[2])) -
                            abs(np.tan(2 * np.pi / Q / 2))) < EPS:  # 旋转对称线
                        bool_exclude_path = True

            if not is_at_stator(path, mm_rotor_outer_radius,
                                mm_air_gap_length):
                # 按照Eric的要求,把不必要的线给删了。
                if  (abs(np.sqrt(path[0]**2+path[1]**2) - mm_rotor_inner_radius)<EPS or abs(np.sqrt(path[2]**2+path[3]**2) - mm_rotor_inner_radius)<EPS) \
                    and (len(path)==4): # 转子铁芯内径到外径的直线(len(path)==4)
                    bool_exclude_path = True

            #     # 特别的是,画永磁体的时候,边界要闭合哦。
            #     if abs(np.sqrt(path[0]**2+path[1]**2) - mm_rotor_outer_steel_radius) < EPS or abs(np.sqrt(path[2]**2+path[3]**2) - mm_rotor_outer_steel_radius) < EPS:
            #         bool_exclude_path = False

            # A trick that makes sure models with different outer diameters have the same scale.
            # tool_tikz.draw_arc([125,0], [-125,0], relangle=sign*180, untrack=True)
            tool_tikz.c.fill(
                pyx.path.circle(0, 0, 125), [pyx.color.transparency(1)]
            )  # use this if THICK is used. <- Warn: Transparency not available in PostScript, proprietary ghostscript extension code inserted. (save as eps format)
            # tool_tikz.c.fill(pyx.path.circle(0, 0, 125), [pyx.color.rgb.white]) # use this if THICK is used. <- this will over-write everthing... how to change zorder?

            _ = 2 * np.pi / Q

            if True:  # full model
                for counter in range(Q):

                    # 转子:旋转复制
                    if not is_at_stator(path, mm_rotor_outer_radius,
                                        mm_air_gap_length):
                        path[0], path[1] = rotate(_, path[0], path[1])
                        path[2], path[3] = rotate(_, path[2], path[3])
                        路径 = tool_tikz.pyx_draw_path(
                            path,
                            sign=1,
                            bool_exclude_path=bool_exclude_path,
                            bool_stroke=True)
                        if 路径 is not None:
                            if p_rotor is None:
                                p_rotor = 路径
                            else:
                                p_rotor = p_rotor << 路径

                    # 定子:镜像+旋转复制
                    if is_at_stator(path, mm_rotor_outer_radius,
                                    mm_air_gap_length):

                        path[0], path[1] = rotate(_, path[0], path[1])
                        path[2], path[3] = rotate(_, path[2], path[3])
                        路径 = tool_tikz.pyx_draw_path(
                            path,
                            sign=1,
                            bool_exclude_path=bool_exclude_path,
                            bool_stroke=True)
                        # print(index, '\t|', ',\t'.join(['%g'%(el) for el in path]))
                        if 路径 is not None:
                            if p_stator is None:
                                p_stator = 路径
                            else:
                                p_stator = p_stator << 路径

                        path_mirror[0], path_mirror[1] = rotate(
                            _, path_mirror[0], path_mirror[1])
                        path_mirror[2], path_mirror[3] = rotate(
                            _, path_mirror[2], path_mirror[3])
                        路径 = tool_tikz.pyx_draw_path(
                            path_mirror,
                            sign=-1,
                            bool_exclude_path=bool_exclude_path,
                            bool_stroke=True)
                        if 路径 is not None:
                            if p_stator is None:
                                p_stator = 路径
                            else:
                                p_stator = p_stator << 路径

                    # break
            else:  # backup

                # 转子:旋转复制
                if not is_at_stator(path, mm_rotor_outer_radius,
                                    mm_air_gap_length):
                    path[0], path[1] = rotate(0.5 * np.pi - 0.5 * 0.5 * _,
                                              path[0], path[1])
                    path[2], path[3] = rotate(0.5 * np.pi - 0.5 * 0.5 * _,
                                              path[2], path[3])
                    pyx_draw_path(tool_tikz,
                                  path,
                                  sign=1,
                                  bool_exclude_path=bool_exclude_path)
                    # print(index, '\t|', ',\t'.join(['%g'%(el) for el in path]))

                    # path[0], path[1] = rotate(0.5*np.pi - 0*0.5*_, path[0], path[1])
                    # path[2], path[3] = rotate(0.5*np.pi - 0*0.5*_, path[2], path[3])
                    # pyx_draw_path(tool_tikz, path, sign=1, bool_exclude_path=bool_exclude_path)

                # 定子:镜像+旋转复制
                if is_at_stator(path, mm_rotor_outer_radius,
                                mm_air_gap_length):

                    path[0], path[1] = rotate(0.5 * np.pi - 0.5 * _, path[0],
                                              path[1])
                    path[2], path[3] = rotate(0.5 * np.pi - 0.5 * _, path[2],
                                              path[3])
                    pyx_draw_path(tool_tikz,
                                  path,
                                  sign=1,
                                  bool_exclude_path=bool_exclude_path)
                    # print(index, '\t|', ',\t'.join(['%g'%(el) for el in path]))

                    path_mirror[0], path_mirror[1] = rotate(
                        0.5 * np.pi - 0.5 * _, path_mirror[0], path_mirror[1])
                    path_mirror[2], path_mirror[3] = rotate(
                        0.5 * np.pi - 0.5 * _, path_mirror[2], path_mirror[3])
                    pyx_draw_path(tool_tikz,
                                  path_mirror,
                                  sign=-1,
                                  bool_exclude_path=bool_exclude_path)

                    # 注意,所有 tack_path 中的 path 都已经转动了90度了!
                    # for mirror copy (along y-axis)
                    path[0] *= -1
                    path[2] *= -1
                    pyx_draw_path(tool_tikz,
                                  path,
                                  sign=-1,
                                  bool_exclude_path=bool_exclude_path)

                    path_mirror[0] *= -1
                    path_mirror[2] *= -1
                    pyx_draw_path(tool_tikz,
                                  path_mirror,
                                  sign=1,
                                  bool_exclude_path=bool_exclude_path)

        # You can have a cool logo if you un-comment this...
        # tool_tikz.c.fill(p_stator, [pyx.color.gray(0.8)])
        # tool_tikz.c.fill(p_rotor, [pyx.color.gray(0.4)])
        # tool_tikz.c.stroke(p_stator)
        # tool_tikz.c.stroke(p_rotor)

    if True:  # Draw the outline?
        redraw_cross_section_outline_with_pyx(
            tool_tikz, spmsm_best.Q, spmsm_best.p,
            spmsm_best.Radius_OuterRotor, spmsm_best.Length_AirGap,
            spmsm_best.Radius_OuterRotorSteel, spmsm_best.Radius_InnerRotor)
        # tool_tikz.c.writePDFfile("../Test_Fill_Plot" + proj_name)
        tool_tikz.c.writeSVGfile("../b")
        tool_tikz.c.writePDFfile(filename_cross_sectional_view[:-4] +
                                 'outline')
        print('Final cross sectional outline files are printed to',
              filename_cross_sectional_view[:-4] + 'outline')
        # tool_tikz.c.writePDFfile("Figure_selected_optimal_design_%s"%(name))
        # tool_tikz.c.writeEPSfile("Figure_selected_optimal_design_%s"%(name))
        # tool_tikz.c.writeSVGfile("Figure_selected_optimal_design_%s"%(name))
        # print('Write to pdf file: Figure_selected_optimal_design_%s.pdf.'%(name))
        # os.system('start %s'%("selected_optimal_design%s.pdf"%(spmsm_best.name)))
        # quit()

        # Option 1
        if True:
            from svgutils.compose import Figure, SVG  # https://svgutils.readthedocs.io/en/latest/tutorials/composing_multipanel_figures.html

            Figure(
                "5cm",
                "5cm",
                SVG("../a.svg"),
                SVG("../b.svg"),  # the order of a and b matters.
            ).save(filename_cross_sectional_view)
            os.system(
                'inkscape --file=%s --export-area-drawing --without-gui --export-pdf=%s.pdf'
                % (filename_cross_sectional_view,
                   filename_cross_sectional_view[:-4]))

        else:

            # Option 2
            import svgutils.transform as sg

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

            # load matpotlib-generated figures
            fig1 = sg.fromfile('../a.svg')
            fig2 = sg.fromfile('../b.svg')

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

            # append plots and labels to figure
            fig.append([plot1, plot2])
            fig.save("../d.svg")