Example #1
0
    def build_logo(self, logo):
        '''This method will create the small background image that goes
        behind the logo, effectilly a matte. We needed it for our logo
        but it may not be necessary for MVP of site. Something we
        could add later as it is probably one of the trickier things
        to generalize.
        '''
        self.logo = logo
        ## Load image to embed
        # TODO: Surround this line with a try/except to prove the sting is an SVG (XMLSyntaxError?)
        self.fig_logo = sg.fromstring(self.logo)
        # TODO: Following line needs to be more robust for arbitrary SVGs.
        self.logo_size = self._svg_size(self.fig_logo)

        ## Create embedded image's solid background. It will provide
        ## a 1 module ("pixel") wide margin in all directions.
        self.logo_box_size = 9 * self.scale_factor  # must represent an odd number of modules since qr code lengths are odd modules long.
        fig_background = svgwrite.Drawing(filename='noname.svg',
                                          size=(self.logo_box_size,
                                                self.logo_box_size))
        fig_background.add(
            fig_background.rect(insert=(0, 0),
                                size=(self.logo_box_size, self.logo_box_size),
                                fill=self.module_color))
        self.fig_background = sg.fromstring(
            fig_background.tostring())  # patch data from svgwrite to svgutils
Example #2
0
File: plot.py Project: jerdra/niviz
def plot_orthogonal_views(data,
                          bbox_nii=None,
                          auto_brightness=False,
                          display_modes=['x', 'y', 'z'],
                          n_cuts=10,
                          plot_func=nplot.plot_anat,
                          figure_title=""):

    if bbox_nii is None:
        bbox_nii = nimg.threshold_img(data, 1e-3)

    cuts = cuts_from_bbox(data, cuts=n_cuts)
    if auto_brightness:
        robust_params = robust_set_limits(bbox_nii.get_fdata().reshape(-1), {})
    else:
        robust_params = {}

    svgs = []
    for d in display_modes:
        plot_params = {
            "display_mode": d,
            "cut_coords": cuts[d],
            **robust_params
        }
        display = plot_func(data, **plot_params)
        svg = extract_svg(display)
        svg = svg.replace("figure_1", f"{figure_title}-{d}")
        svgs.append(fromstring(svg))
        display.close()
    return svgs
Example #3
0
    def build_qrcode(self,
                     to_encode=None,
                     module_color=None,
                     background_color=None,
                     scale_factor=None):
        '''Create base QR Code'''
        if not (self.to_encode
                or to_encode):  # If we have no data, we can't do anything.
            return

        # If any data has changed, save it.
        if to_encode:
            self.to_encode = to_encode
        if module_color:
            self.module_color = module_color
        if background_color:
            self.background_color = background_color
        if scale_factor:
            self.scale_factor = scale_factor

        self.QRsvg = io.BytesIO()
        self.qr = segno.make(self.to_encode, micro=False, error='H')
        # saving base qr code to StringIO buffer
        self.qr.save(self.QRsvg,
                     color=self.module_color,
                     background=self.background_color,
                     kind='svg')
        self.fig_qr = sg.fromstring(self.QRsvg.getvalue())
        self.qr_size = float(self.fig_qr.get_size()
                             [0])  # only grab first size because it's a square
        self.middle = (self.qr_size *
                       self.scale_factor) / 2  # typically not an integer
Example #4
0
def combine_svg(svg_list, axis='vertical'):
    """
    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]


    if axis == 'vertical':
        # 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]]
        totalsize = [newsizes[0][0], np.sum(newsizes, axis=0)[1]]

    elif axis == 'horizontal':
        # Calculate the scale to fit all heights
        scales = [1.0] * len(svgs)
        if not all([height[0] == sizes[0][1] for height in sizes[1:]]):
            ref_size = sizes[0]
            for i, els in enumerate(sizes):
                scales[i] = ref_size[1]/els[1]

        newsizes = [tuple(size)
                    for size in np.array(sizes) * np.array(scales)[..., np.newaxis]]
        totalsize = [np.sum(newsizes, axis=0)[0], newsizes[0][1]]


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

    if axis == 'vertical':
        yoffset = 0
        for i, r in enumerate(roots):
            size = newsizes[i]
            r.moveto(0, yoffset, scale=scales[i])
            yoffset += size[1]
            fig.append(r)
    elif axis == 'horizontal':
        xoffset = 0
        for i, r in enumerate(roots):
            size = newsizes[i]
            r.moveto(xoffset, 0, scale=scales[i])
            xoffset += size[0]
            fig.append(r)

    return fig
Example #5
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)
Example #6
0
def combine_svg_files():
    output = sg.fromstring(svg_tpl)
    for root, dirs, files in os.walk(INPUT_SVG_DIR):
        for filename in files:
            name, ext = os.path.splitext(filename)
            filepath = os.path.join(root, filename)
            if ext in ['.svg']:
                make_symbol(output, name, filepath)
    output.save(OUTPUT_SVG_DIR + '/ionicons.svg')
Example #7
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()))
Example #8
0
    def _generate_report(self):
        anat_img = nib.load(self.inputs.in_file)
        mask_img = nib.load(self.inputs.mask_file)
        assert nvol(anat_img) == 1
        assert nvol(mask_img) == 1

        plot_params = robust_set_limits_in_mask(anat_img, mask_img)

        template = self.inputs.template
        parc_file = getresource(
            f"tpl-{template}_RegistrationCheckOverlay.nii.gz")
        assert parc_file is not None
        parc_img = nib.load(parc_file)

        levels = np.unique(np.asanyarray(parc_img.dataobj).astype(np.int32))
        levels = (levels[levels > 0] - 0.5).tolist()
        colors = color_palette("husl", len(levels))

        label = None
        if isdefined(self.inputs.label):
            label = self.inputs.label

        compress = self.inputs.compress_report

        n_cuts = 7
        cuts = cuts_from_bbox(mask_img, cuts=n_cuts)

        outfiles = []
        for dimension in ["z", "y", "x"]:
            display = plot_anat(
                anat_img,
                draw_cross=False,
                display_mode=dimension,
                cut_coords=cuts[dimension],
                title=label,
                **plot_params,
            )

            display.add_contours(parc_img,
                                 levels=levels,
                                 colors=colors,
                                 linewidths=0.25)
            display.add_contours(mask_img,
                                 levels=[0.5],
                                 colors="r",
                                 linewidths=0.5)

            label = None  # only on first

            svg = extract_svg(display, compress=compress)
            svg = svg.replace("figure_1", str(uuid4()), 1)

            outfiles.append(fromstring(svg))

        self._out_report = op.abspath(self.inputs.out_report)
        compose_view(bg_svgs=outfiles, fg_svgs=None, out_file=self._out_report)
Example #9
0
def test_skew():
    svg_fig = transform.fromstring(circle)
    group = svg_fig.getroot()

    # Test skew in y-axis
    group.skew(0, 30)
    ok_("skewY(30" in group.root.get("transform"))

    # Test skew in x-axis
    group.skew(30, 0)
    ok_("skewX(30" in group.root.get("transform"))
Example #10
0
def plot_segs(image_nii,
              seg_niis,
              out_file,
              bbox_nii=None,
              masked=False,
              colors=None,
              compress="auto",
              **plot_params):
    """
    Generate a static mosaic with ROIs represented by their delimiting contour.

    Plot segmentation as contours over the image (e.g. anatomical).
    seg_niis should be a list of files. mask_nii helps determine the cut
    coordinates. plot_params will be passed on to nilearn plot_* functions. If
    seg_niis is a list of size one, it behaves as if it was plotting the mask.
    """
    from svgutils.transform import fromstring
    from nilearn import image as nlimage

    plot_params = {} if plot_params is None else plot_params

    image_nii = _3d_in_file(image_nii)
    canonical_r = rotation2canonical(image_nii)
    image_nii = rotate_affine(image_nii, rot=canonical_r)
    seg_niis = [
        rotate_affine(_3d_in_file(f), rot=canonical_r) for f in seg_niis
    ]
    data = image_nii.get_fdata()

    plot_params = robust_set_limits(data, plot_params)

    bbox_nii = (image_nii if bbox_nii is None else rotate_affine(
        _3d_in_file(bbox_nii), rot=canonical_r))

    if masked:
        bbox_nii = nlimage.threshold_img(bbox_nii, 1e-3)

    cuts = cuts_from_bbox(bbox_nii, cuts=7)
    plot_params["colors"] = colors or plot_params.get("colors", None)
    out_files = []
    for d in plot_params.pop("dimensions", ("z", "x", "y")):
        plot_params["display_mode"] = d
        plot_params["cut_coords"] = cuts[d]
        svg = _plot_anat_with_contours(image_nii,
                                       segs=seg_niis,
                                       compress=compress,
                                       **plot_params)
        # Find and replace the figure_1 id.
        svg = svg.replace("figure_1", "segmentation-%s-%s" % (d, uuid4()), 1)
        out_files.append(fromstring(svg))

    return out_files
Example #11
0
    def _generate_report(self):
        in_img = nib.load(self.inputs.in_file)
        assert nvol(in_img) == 1

        mask_img = nib.load(self.inputs.mask_file)
        assert nvol(mask_img) == 1

        label = None
        if isdefined(self.inputs.label):
            label = self.inputs.label

        compress = self.inputs.compress_report

        n_cuts = 7
        cuts = cuts_from_bbox(mask_img, cuts=n_cuts)

        img_vals = in_img.get_fdata()[np.asanyarray(mask_img.dataobj).astype(
            np.bool)]
        vmin = img_vals.min()
        vmax = img_vals.max()

        outfiles = []
        for dimension in ["z", "y", "x"]:
            display = plot_epi(
                in_img,
                draw_cross=False,
                display_mode=dimension,
                cut_coords=cuts[dimension],
                title=label,
                vmin=vmin,
                vmax=vmax,
                colorbar=(dimension == "z"),
                cmap=plt.cm.gray,
            )
            display.add_contours(mask_img, levels=[0.5], colors="r")
            label = None  # only on first
            svg = extract_svg(display, compress=compress)
            svg = svg.replace("figure_1", str(uuid4()), 1)
            outfiles.append(fromstring(svg))

        self._out_report = op.abspath(self.inputs.out_report)
        compose_view(bg_svgs=outfiles, fg_svgs=None, out_file=self._out_report)
Example #12
0
File: plot.py Project: jerdra/niviz
def plot_montage(data,
                 orientation,
                 bbox_nii=None,
                 n_cuts=15,
                 n_cols=5,
                 auto_brightness=False,
                 plot_func=nplot.plot_anat,
                 figure_title="figure"):
    '''
    Plot a montage of cuts for a given orientation
    for an image
    '''

    if bbox_nii is None:
        bbox_nii = nimg.threshold_img(data, 1e-3)

    cuts = cuts_from_bbox(bbox_nii, cuts=n_cuts)
    if auto_brightness:
        robust_params = robust_set_limits(bbox_nii.get_fdata().reshape(-1), {})
    else:
        robust_params = {}

    svgs = []
    for i in range(n_cuts // n_cols):

        start = i * n_cols
        end = min(i * n_cols + n_cols, n_cuts)
        row_cuts = cuts[orientation][start:end]

        plot_params = {
            "display_mode": orientation,
            "cut_coords": row_cuts,
            **robust_params
        }

        display = plot_func(data, **plot_params)
        svg = extract_svg(display)
        svg = svg.replace("figure_1", f"{figure_title}:{start}-{end}")
        svgs.append(fromstring(svg))

    return svgs
Example #13
0
    def _generate_report(self):
        epi_img = nib.load(self.inputs.in_file)
        mask_img = nib.load(self.inputs.mask_file)
        assert nvol(epi_img) == 1
        assert nvol(mask_img) == 1

        label = None
        if isdefined(self.inputs.label):
            label = self.inputs.label

        compress = self.inputs.compress_report

        n_cuts = 7
        cuts = cuts_from_bbox(mask_img, cuts=n_cuts)

        plot_params = robust_set_limits_in_mask(epi_img, mask_img)

        outfiles = []
        for dimension in ["z", "y", "x"]:
            display = plot_epi(
                epi_img,
                draw_cross=False,
                display_mode=dimension,
                cut_coords=cuts[dimension],
                title=label,
                colorbar=(dimension == "z"),
                cmap=plt.get_cmap("gray"),
                **plot_params,
            )

            display.add_contours(mask_img, levels=[0.5], colors="r")

            label = None  # only on first

            svg = extract_svg(display, compress=compress)
            svg = svg.replace("figure_1", str(uuid4()), 1)

            outfiles.append(fromstring(svg))

        self._out_report = op.abspath(self.inputs.out_report)
        compose_view(bg_svgs=outfiles, fg_svgs=None, out_file=self._out_report)
Example #14
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)
Example #15
0
def plot_segs(image_nii,
              seg_niis,
              out_file,
              bbox_nii=None,
              masked=False,
              colors=None,
              compress="auto",
              **plot_params):
    """ plot segmentation as contours over the image (e.g. anatomical).
    seg_niis should be a list of files. mask_nii helps determine the cut
    coordinates. plot_params will be passed on to nilearn plot_* functions. If
    seg_niis is a list of size one, it behaves as if it was plotting the mask.
    """
    plot_params = {} if plot_params is None else plot_params

    image_nii = _3d_in_file(image_nii)
    data = image_nii.get_fdata()

    plot_params = robust_set_limits(data, plot_params)

    bbox_nii = nb.load(image_nii if bbox_nii is None else bbox_nii)
    if masked:
        bbox_nii = nlimage.threshold_img(bbox_nii, 1e-3)

    cuts = cuts_from_bbox(bbox_nii, cuts=7)
    plot_params["colors"] = colors or plot_params.get("colors", None)
    out_files = []
    for d in plot_params.pop("dimensions", ("z", "x", "y")):
        plot_params["display_mode"] = d
        plot_params["cut_coords"] = cuts[d]
        svg = _plot_anat_with_contours(image_nii,
                                       segs=seg_niis,
                                       compress=compress,
                                       **plot_params)
        # Find and replace the figure_1 id.
        svg = svg.replace("figure_1", "segmentation-%s-%s" % (d, uuid4()), 1)
        out_files.append(fromstring(svg))

    return out_files
Example #16
0
File: svg.py Project: 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
Example #17
0
def test_group_class():
    svg_fig = transform.fromstring(circle)
    group = svg_fig.getroot()
    ok_((group.root.attrib["class"] == "main"))
Example #18
0
 def __init__(self, svg):
     obj = transform.fromstring(svg)
     self.root = obj.getroot().root
Example #19
0
    def drawSVG(self,
                path=None,
                target='TARGET_0000000001__64__MNXC3',
                subplot_size=[200,200],
                #reac_size=[20,60],
                reac_fill_color='#ddd',
                reac_stroke_color='black',
                reac_stroke_width=2,
                arrow_stroke_color='black',
                arrow_stroke_width=2,
                font_family='sans-serif',
                font_size=10,
                font_color='black',
                plot_only_central=True,
                filter_cofactors=True,
                filter_sink_species=False):
        """Generate a reaction SVG image from the rpgraph object.

        :param rpgraph: rpGraph object to draw the SVG from
        :param target: source node to calculate the hierarchy tree organisation of the reaction (should be TARGET)
        :param suboplot_size: The size in pixels of the subplot boxes used to draw the SVG  (default: [200, 200])
        :param reac_fill_color: Hex (or name) color code to fill of the reaction box (default: '#ddd')
        :param reac_stroke_color: Hex (or name) color code of the reaction box stroke (default: 'black')
        :param reac_stroke_width: Size of the reaction rectangle stroke width (default: 2)
        :param arrow_stroke_color: Hex (or name) color code of the reaction arrows (default: 'black')
        :param arrow_stroke_width: Size of the reaction arrows (default: 2)
        :param font_family: The font of the cofactors (default: 'sans-serif'
        :param font_size: The font size of the cofactors (default: 10)
        :param font_color: The font color of the cofactors (default: 'black')
        :param plot_only_central: Do not draw the chemical structure of the non-central species (default: True)
        :param filter_cofactors: Do not draw the chemical structire of the identified cofactors (see: data/mnx_cofactors.json) (default: True)
        :param filter_sink_species: Do not draw the chemical structure of sink species (default: False)

        :type rpgraph: rpGraph
        :type target: str
        :type suboplot_size: list
        :type reac_fill_color: str
        :type reac_stroke_color: str
        :type reac_stroke_width: int
        :type arrow_stroke_color: str
        :type arrow_stroke_width: int
        :type font_family: str
        :type font_size: int
        :type font_color: str
        :type plot_only_central: bool
        :type filter_cofactors: bool
        :type filter_sink_species: bool

        :returns: tuple (svg, resG, mod_pos, reac_cofactors_name)
            - svg - SVG as string
            - regG - Result networkx object with the cofactors removed
            - mod_pos - The calculates positions for the objects
            - reac_cofactors_name - Dictionnary of reactions with the subtrates and products ID's

        :rtype: tuple
        """
        if not self.G:
            self.logger.error('The G needs to be initialised')
            return False
        #TODO: Check this one: /Users/melchior/Downloads/rpglobalscore_77/rp_109_2.sbml.xml
        reac_size = [subplot_size[0]/8, subplot_size[1]/2]
        #gather all the inchis and convert to svg
        resG, pos, reac_cofactors_id = self.hierarchyPos(self.G,
                                                         target,
                                                         plot_only_central=plot_only_central,
                                                         filter_cofactors=filter_cofactors,
                                                         filter_sink_species=filter_sink_species)
        self.logger.debug('+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=')
        ######## convert the id's to string name #####
        reac_cofactors_name = {}
        for reac_id in reac_cofactors_id:
            if not reac_id in reac_cofactors_name:
                reac_cofactors_name[reac_id] = {'substrates': [], 'products': []}
            for sub in reac_cofactors_id[reac_id]['substrates']:
                try:
                    name = self.G.node.get(sub)['name']
                except KeyError:
                    name = sub
                if name=='':
                    name = sub
                reac_cofactors_name[reac_id]['substrates'].append(name)
            for pro in reac_cofactors_id[reac_id]['products']:
                try:
                    name = self.G.node.get(pro)['name']
                except KeyError:
                    name = pro
                if name=='':
                    name = pro
                reac_cofactors_name[reac_id]['products'].append(name)
        ############# Calculate the size of the image ##### 
        id_inchi = {}
        self.logger.debug('positions: '+str(pos))
        for node in list(resG.nodes):
            if resG.node.get(node)['type']=='species':
                id_inchi[node] = resG.node.get(node)['brsynth']['inchi']
        id_svg = self.drawChemicalList(id_inchi, subplot_size)
        self.logger.debug('============================')
        a = {}
        for n in pos:
            if not pos[n][0] in a:
                a[pos[n][0]] = []
            a[pos[n][0]].append(pos[n][1])
        self.logger.debug('a: '+str(a))
        largest_y = 0
        for i in a:
            if len(a[i])>largest_y:
                largest_y = len(a[i])
        if largest_y==0:
            largest_y = 1
        self.logger.debug('largest_y: '+str(largest_y))
        u_x_layers = sorted(list(set([pos[i][0] for i in pos])))
        u_y_layers = sorted(list(set([pos[i][1] for i in pos])))
        self.logger.debug('u_x_layers: '+str(u_x_layers))
        self.logger.debug('u_y_layers: '+str(u_y_layers))
        background_len_x = subplot_size[0]*len(u_x_layers)
        background_len_y = subplot_size[1]*largest_y
        self.logger.debug('background_len_x: '+str(background_len_x))
        self.logger.debug('background_len_y: '+str(background_len_y))
        mod_pos = {}
        #adjust the x axis lications for the boxes to be close to each other
        #TODO: readjust to equidistant on the y-axis nodes that are not
        for node in pos:
            mod_pos[node] = (pos[node][0]*(subplot_size[0]*(len(u_x_layers)-1)), #not sure why I have to correct that
                             (pos[node][1]*background_len_y))
        self.logger.debug('============================')
        self.logger.debug('mod_pos: '+str(mod_pos))
        ########### draw the background #############
        len_fig_x = background_len_x
        len_fig_y = background_len_y
        self.logger.debug('len_fig_x: '+str(len_fig_x))
        self.logger.debug('len_fig_y: '+str(len_fig_y))
        fig = sg.SVGFigure(str(len_fig_x),
                           str(len_fig_y))
        background_white = draw.Drawing(len_fig_x, len_fig_y, origin=(0,0))
        background_white.append(draw.Rectangle(0, 0, len_fig_x, len_fig_y, fill='#ffffff'))
        a = sg.fromstring(background_white.asSvg())
        b_w = a.getroot()
        b_w.moveto(0, background_len_y)#WARNING: not sure why I have to + subpot
        fig.append(b_w)
        nodes_attach_locs = {}
        for node_id in mod_pos:
            node = self.G.node.get(node_id)
            self.logger.debug('\tSpecies: '+str(node_id))
            if node['type']=='species':
                self.logger.debug('\tNode pos: '+str(mod_pos[node_id]))
                self.logger.debug('\tx: '+str(mod_pos[node_id][0]))
                self.logger.debug('\ty: '+str(mod_pos[node_id][1]))
                move_x = mod_pos[node_id][0]
                # because of the nature of the x y locations, need to reverse them here
                if mod_pos[node_id][1]==0.0:
                    y_coord = mod_pos[node_id][1]+subplot_size[1]/2
                    move_y = len_fig_y-mod_pos[node_id][1]-subplot_size[1]
                elif mod_pos[node_id][1]==len_fig_y:
                    y_coord = mod_pos[node_id][1]-subplot_size[1]/2
                    move_y = len_fig_y-mod_pos[node_id][1]
                else:
                    y_coord = mod_pos[node_id][1]
                    move_y = len_fig_y-mod_pos[node_id][1]-subplot_size[1]/2
                self.logger.debug('\tmove_x: '+str(move_x))
                self.logger.debug('\tmove_y: '+str(move_y))
                f = sg.fromstring(id_svg[node_id])
                p = f.getroot()
                #Rememeber that you are moving the object on the x and y axis while the coordinates are coordinates so its reversed
                p.moveto(move_x, move_y)
                fig.append(p)
                nodes_attach_locs[node_id] = {'left': (mod_pos[node_id][0], y_coord),
                                              'right': (mod_pos[node_id][0]+subplot_size[0], y_coord)}
            elif node['type']=='reaction':
                d = draw.Drawing(subplot_size[0], subplot_size[1], origin=(0,0))
                d.append(draw.Rectangle(0, 0, subplot_size[0], subplot_size[1], fill='#FFFFFF'))
                edge_x = subplot_size[0]/2-reac_size[1]/2
                edge_y = subplot_size[1]/2-reac_size[0]/2
                self.logger.debug('\tedge_x: '+str(edge_x))
                self.logger.debug('\tedge_y: '+str(edge_y))
                self.logger.debug('\tx: '+str(mod_pos[node_id][0]))
                self.logger.debug('\ty: '+str(mod_pos[node_id][1]+subplot_size[1]))
                if reac_cofactors_name[node_id]['substrates']:
                    d.append(draw.Line(subplot_size[0]/2, edge_y-reac_size[0],
                                       subplot_size[0]/2, edge_y-self.arrowhead_comp_x,
                                       stroke=arrow_stroke_color, stroke_width=arrow_stroke_width, fill='none', marker_end=self.arrowhead))
                if reac_cofactors_name[node_id]['products']:
                    d.append(draw.Line(subplot_size[0]/2, edge_y+reac_size[0],
                                       subplot_size[0]/2, (subplot_size[1]/2)+reac_size[1]/3,
                                       stroke=arrow_stroke_color, stroke_width=arrow_stroke_width, fill='none', marker_end=self.arrowhead))
                y_shift = 0.0
                for sub in reac_cofactors_name[node_id]['substrates']:
                    self.logger.debug(sub)
                    d.append(draw.Text(sub, font_size,
                                       subplot_size[0]/2, ((subplot_size[1]/2)-reac_size[1]/3)-y_shift-font_size,
                                       font_family=font_family, center=True, fill=font_color))
                    y_shift += font_size
                y_shift = 0.0
                for pro in reac_cofactors_name[node_id]['products']:
                    self.logger.debug(pro)
                    d.append(draw.Text(pro, font_size,
                                       subplot_size[0]/2, ((subplot_size[1]/2)+reac_size[1]/3)+y_shift+font_size+self.arrowhead_comp_x,
                                       font_family=font_family, center=True, fill=font_color))
                    y_shift += font_size
                d.append(draw.Rectangle(edge_x, edge_y,
                                        reac_size[1], reac_size[0],
                                        fill=reac_fill_color,
                                        stroke_width=reac_stroke_width,
                                        stroke=reac_stroke_color))
                a = sg.fromstring(d.asSvg())
                a_r = a.getroot()
                move_x = mod_pos[node_id][0]
                if mod_pos[node_id][1]==0.0:
                    move_y = len_fig_y-mod_pos[node_id][1]
                elif mod_pos[node_id][1]==len_fig_y:
                    move_y = len_fig_y-mod_pos[node_id][1]+subplot_size[1]
                else:
                    move_y = len_fig_y-mod_pos[node_id][1]-subplot_size[1]/2+subplot_size[1]
                self.logger.debug('\tmove_x: '+str(move_x))
                self.logger.debug('\tmove_y: '+str(move_y))
                a_r.moveto(move_x, move_y)
                fig.append(a_r)
                nodes_attach_locs[node_id] = {'left': (move_x+edge_x,
                                                       move_y-subplot_size[1]/2),
                                              'right': (move_x+subplot_size[0]-edge_x+reac_stroke_width/2,
                                                        move_y-subplot_size[1]/2)}
            self.logger.debug('\t-------------------------------')
        self.logger.debug('nodes_attach_locs: '+str(nodes_attach_locs))
        self.logger.debug(list(resG.edges))
        arrow_box = draw.Drawing(len_fig_x, len_fig_y, origin=(0,0))
        ################ Add the arrowhead depending on edge direction #######
        #depending on the directions of the node, switch the source and the target
        #and calculate the center pocitions of the arrows
        edge_pos = {}
        strict_edge_pos = {}
        for edge in list(resG.edges):
            #left to right
            if pos[edge[0]][0]>pos[edge[1]][0]:
                source_x = nodes_attach_locs[edge[0]]['left'][0]
                source_y = nodes_attach_locs[edge[0]]['left'][1]
                target_x = nodes_attach_locs[edge[1]]['right'][0]
                target_y = nodes_attach_locs[edge[1]]['right'][1]
                edge_pos[edge] = {'source': (round(source_x, 2), round(source_y, 2)),
                                  'L1': (round(source_x+(target_x-source_x)/2, 2), round(source_y, 2)),
                                  'L2': (round(source_x+(target_x-source_x)/2, 2), round(target_y, 2)),
                                  'target': (round(target_x+self.arrowhead_comp_x, 2), round(target_y, 2)),
                                  'arrow_direction': self.rev_arrowhead_flat}
                strict_edge_pos[edge] = {'source': (int(round(source_x, 0)), int(round(source_y, 0))),
                                  'L1': (int(round(source_x+(target_x-source_x)/2, 0)), int(round(source_y, 0))),
                                  'L2': (int(round(source_x+(target_x-source_x)/2, 0)), int(round(target_y, 0))),
                                  'target': (int(round(target_x, 0)), int(round(target_y, 0))),
                                  'arrow_direction': self.rev_arrowhead_flat}
                '''
                edge_pos[edge] = {'source': [source_x, source_y],
                                  'L1': [source_x+(target_x-source_x)/2+self.arrowhead_comp_y/2, source_y],
                                  'L2': [source_x+(target_x-source_x)/2+self.arrowhead_comp_y/2, target_y],
                                  'target': [target_x+self.arrowhead_comp_x, target_y],
                                  'arrow_direction': self.rev_arrowhead_flat}
                '''
            #right to left
            elif pos[edge[0]][0]<pos[edge[1]][0]:
                source_x = nodes_attach_locs[edge[0]]['right'][0]
                source_y = nodes_attach_locs[edge[0]]['right'][1]
                target_x = nodes_attach_locs[edge[1]]['left'][0]
                target_y = nodes_attach_locs[edge[1]]['left'][1]
                edge_pos[edge] = {'source': (round(source_x, 2), round(source_y, 2)),
                                  'L1': (round(source_x+(target_x-source_x)/2, 2), round(source_y, 2)),
                                  'L2': (round(source_x+(target_x-source_x)/2, 2), round(target_y, 2)),
                                  'target': (round(target_x-self.arrowhead_comp_x, 2), round(target_y, 2)),
                                  'arrow_direction': self.arrowhead_flat}
                strict_edge_pos[edge] = {'source': (int(round(source_x, 0)), int(round(source_y, 0))),
                                  'L1': (int(round(source_x+(target_x-source_x)/2, 0)), int(round(source_y, 0))),
                                  'L2': (int(round(source_x+(target_x-source_x)/2, 0)), int(round(target_y, 0))),
                                  'target': (int(round(target_x, 0)), int(round(target_y, 0))),
                                  'arrow_direction': self.arrowhead_flat}
                '''
                edge_pos[edge] = {'source': [source_x, source_y],
                                  'L1': [source_x+(target_x-source_x)/2-self.arrowhead_comp_y/2, source_y],
                                  'L2': [source_x+(target_x-source_x)/2-self.arrowhead_comp_y/2, target_y],
                                  'target': [target_x-self.arrowhead_comp_x, target_y],
                                  'arrow_direction': self.arrowhead_flat}
                '''
            else:
                self.logger.error('Cannot connect same y-axi')
        #calculate the center positions of the arrows
        self.logger.debug('edge_pos: '+str(edge_pos))
        self.logger.debug('strict_edge_pos: '+str(strict_edge_pos))
        ############# Calculate the overlaps ##########
        #find the edges that have the same source/target locations - if more than that do not go in the same direction
        # then create a input/output location and update the positions
        #NOTE: have to make strings from the edge locations to be able to be
        overlaps_arrow = {'node': {}, 'L': {}}
        #overlaps_edge = {'node': {}, 'L': {}}
        for edge in strict_edge_pos:
            source_id = str(strict_edge_pos[edge]['source'][0])+'-'+str(strict_edge_pos[edge]['source'][1])
            target_id = str(strict_edge_pos[edge]['target'][0])+'-'+str(strict_edge_pos[edge]['target'][1])
            l1_id = str(strict_edge_pos[edge]['L1'][0])+'-'+str(strict_edge_pos[edge]['L1'][1])
            l2_id = str(strict_edge_pos[edge]['L2'][0])+'-'+str(strict_edge_pos[edge]['L1'][1])
            ####### make the nodes and arrow overlaps_arrow #######
            if not source_id in overlaps_arrow['node']:
                overlaps_arrow['node'][source_id] = [strict_edge_pos[edge]['arrow_direction']]
            else:
                overlaps_arrow['node'][source_id].append(strict_edge_pos[edge]['arrow_direction'])
            if not target_id in overlaps_arrow['node']:
                overlaps_arrow['node'][target_id] = [strict_edge_pos[edge]['arrow_direction']]
            else:
                overlaps_arrow['node'][target_id].append(strict_edge_pos[edge]['arrow_direction'])
            if not l1_id in overlaps_arrow['L']:
                overlaps_arrow['L'][l1_id] = [strict_edge_pos[edge]['arrow_direction']]
            else:
                overlaps_arrow['L'][l1_id].append(strict_edge_pos[edge]['arrow_direction'])
            if not l2_id in overlaps_arrow['L']:
                overlaps_arrow['L'][l2_id] = [strict_edge_pos[edge]['arrow_direction']]
            else:
                overlaps_arrow['L'][l2_id].append(strict_edge_pos[edge]['arrow_direction'])
            ##### make the overlap edge ####
            """
            if not source_id in overlaps_edge['node']:
                overlaps_edge['node'][source_id] = [edge]
            else:
                overlaps_edge['node'][source_id].append(edge)
            if not target_id in overlaps_edge['node']:
                overlaps_edge['node'][target_id] = [edge]
            else:
                overlaps_edge['node'][target_id].append(edge)
            if not l1_id in overlaps_edge['L']:
                overlaps_edge['L'][l1_id] = [edge]
            else:
                overlaps_edge['L'][l1_id].append(edge)
            if not l2_id in overlaps_edge['L']:
                overlaps_edge['L'][l2_id] = [edge]
            else:
                overlaps_edge['L'][l2_id].append(edge)
            """
        ########## Add entry/exit of node if same side node has multiple types #######
        #adjust the perpendecular arrows if there is overlap with reversed directions
        #TODO: adjust arrows that overlap in the same direction but do not have the same destination
        self.logger.debug('overlaps_arrow: '+str(overlaps_arrow))
        #self.logger.debug('overlaps_edge: '+str(overlaps_edge))
        for pos_id in overlaps_arrow['node']:
            #if the direction of the node locations are not the same then you need seperate the input/output
            if len(overlaps_arrow['node'][pos_id])>1:
                if not overlaps_arrow['node'][pos_id].count(self.arrowhead_flat)==len(overlaps_arrow['node'][pos_id]) or overlaps_arrow['node'][pos_id].count(self.rev_arrowhead_flat)==len(overlaps_arrow['node'][pos_id]):
                    for edge in strict_edge_pos:
                        source_id = str(strict_edge_pos[edge]['source'][0])+'-'+str(strict_edge_pos[edge]['source'][1])
                        target_id = str(strict_edge_pos[edge]['target'][0])+'-'+str(strict_edge_pos[edge]['target'][1])
                        if source_id==pos_id and strict_edge_pos[edge]['arrow_direction']==self.arrowhead_flat:
                            edge_pos[edge]['source'] = (edge_pos[edge]['source'][0], edge_pos[edge]['source'][1]-self.arrowhead_comp_y/2)
                            edge_pos[edge]['L1'] = (edge_pos[edge]['L1'][0], edge_pos[edge]['L1'][1]-self.arrowhead_comp_y/2)
                        elif source_id==pos_id and strict_edge_pos[edge]['arrow_direction']==self.rev_arrowhead_flat:
                            edge_pos[edge]['source'] = (edge_pos[edge]['source'][0], edge_pos[edge]['source'][1]+self.arrowhead_comp_y/2)
                            edge_pos[edge]['L1'] = (edge_pos[edge]['L1'][0], edge_pos[edge]['L1'][1]+self.arrowhead_comp_y/2)
                        if target_id==pos_id and strict_edge_pos[edge]['arrow_direction']==self.arrowhead_flat:
                            edge_pos[edge]['target'] = (edge_pos[edge]['target'][0], edge_pos[edge]['target'][1]-self.arrowhead_comp_y/2)
                            edge_pos[edge]['L2'] = (edge_pos[edge]['L2'][0], edge_pos[edge]['L2'][1]-self.arrowhead_comp_y/2)
                        elif target_id==pos_id and strict_edge_pos[edge]['arrow_direction']==self.rev_arrowhead_flat:
                            edge_pos[edge]['target'] = (edge_pos[edge]['target'][0], edge_pos[edge]['target'][1]+self.arrowhead_comp_y/2)
                            edge_pos[edge]['L2'] = (edge_pos[edge]['L2'][0], edge_pos[edge]['L2'][1]+self.arrowhead_comp_y/2)
        #TODO: problem of overlap of arrows
        #1) loop through all the arrows in the same layer
        #2) for each node and each entry/exit, record the perpendicular locations
        #3) if two overlap when they should not then add y_shift
        #           - if they are entry/exit
        #           - if they are entry or exit that overlap with other entry/exit from another reaction
        #do the same for the the perpendicular
        '''
        for pos_id in overlaps_arrow['edge']:
        for edge in strict_edge_pos:
            source_id = str(strict_edge_pos[edge]['source'][0])+'-'+str(strict_edge_pos[edge]['source'][1])
            target_id = str(strict_edge_pos[edge]['target'][0])+'-'+str(strict_edge_pos[edge]['target'][1])
        '''
        #calculate the perpendicular overlaps
        '''
        for edge in edge_pos:
            perpendicular_layers = []
            for comp_edge in edge_pos:
                #if edge_pos[comp_edge]['L1']==edge_pos[edge]['L1']:
                x, y = lineIntersection(edge_pos[comp_edge]['L1'][0], edge_pos[comp_edge]['L1'][1], edge_pos[edge]['L1'][0], edge_pos[edge]['L1'][1])
                if not x==None and y==None:
                    perpendicular_layers.append(comp_edge)
            if len(perpendicular_layers)>1:
                pass
                #cases to ignore:
                #   - when they overlap but go in the same direction and the same target or source
                #case when overlap but they go to the same direction and not the same target
                #case when 
        '''

        for pos_id in overlaps_arrow['L']:
            if len(overlaps_arrow['L'][pos_id])>1:
                #TODO: need a better overlap algo that takes into consideration if they do not overlap
                #example /Users/melchior/Downloads/rpglobalscore_101/rp_1_1.sbml.xml
                #BUG: /Users/melchior/Downloads/rpglobalscore_101/rp_3_2.sbml.xml --> line not detected to be moved
                #BUG: three perpendicular lines drawn: /Users/melchior/Downloads/rpglobalscore_101/rp_2_2.sbml.xml
                #BUG: HO being shown, should be cofactor: /Users/melchior/Downloads/rpglobalscore_91/rp_2_1.sbml.xml
                #BUG: this one should not shift perpendivular lines: /Users/melchior/Downloads/rpglobalscore_101/rp_12_1.sbml.xml
                if not overlaps_arrow['L'][pos_id].count(self.arrowhead_flat)==len(overlaps_arrow['L'][pos_id]) or overlaps_arrow['L'][pos_id].count(self.rev_arrowhead_flat)==len(overlaps_arrow['L'][pos_id]):
                    '''Close but removes some that should have seperated
                    #ignore cases where there are only 2 that go in opposite direction and actually never meet
                    if len(overlaps_arrow['L'][pos_id])==2:
                        if not strict_edge_pos[overlaps_edge['L'][pos_id][0]]['L1'][1]-strict_edge_pos[overlaps_edge['L'][pos_id][0]]['L2'][1]>0 and not strict_edge_pos[overlaps_edge['L'][pos_id][1]]['L1'][1]-strict_edge_pos[overlaps_edge['L'][pos_id][1]]['L2'][1]>0:
                            continue
                        if not strict_edge_pos[overlaps_edge['L'][pos_id][0]]['L1'][1]-strict_edge_pos[overlaps_edge['L'][pos_id][0]]['L2'][1]<0 and not strict_edge_pos[overlaps_edge['L'][pos_id][1]]['L1'][1]-strict_edge_pos[overlaps_edge['L'][pos_id][1]]['L2'][1]<0:
                            continue
                    '''
                    #TODO: need to detect if there are any criss-cross of perpendecular arrows at their target of source to seperate in either direction
                    for edge in strict_edge_pos:
                        l1_id = str(strict_edge_pos[edge]['L1'][0])+'-'+str(strict_edge_pos[edge]['L1'][1])
                        l2_id = str(strict_edge_pos[edge]['L2'][0])+'-'+str(strict_edge_pos[edge]['L1'][1])
                        if l1_id==pos_id and strict_edge_pos[edge]['arrow_direction']==self.arrowhead_flat:
                            '''
                            edge_pos[edge]['L1'] = (edge_pos[edge]['L1'][0]-self.arrowhead_comp_y/2, edge_pos[edge]['L1'][1])
                            edge_pos[edge]['L2'] = (edge_pos[edge]['L2'][0]-self.arrowhead_comp_y/2, edge_pos[edge]['L2'][1])
                            '''
                            edge_pos[edge]['L1'] = (edge_pos[edge]['L1'][0]+self.arrowhead_comp_y/2, edge_pos[edge]['L1'][1])
                            edge_pos[edge]['L2'] = (edge_pos[edge]['L2'][0]+self.arrowhead_comp_y/2, edge_pos[edge]['L2'][1])
                        elif l1_id==pos_id and strict_edge_pos[edge]['arrow_direction']==self.rev_arrowhead_flat:
                            '''
                            edge_pos[edge]['L1'] = (edge_pos[edge]['L1'][0]+self.arrowhead_comp_y/2, edge_pos[edge]['L1'][1])
                            edge_pos[edge]['L2'] = (edge_pos[edge]['L2'][0]+self.arrowhead_comp_y/2, edge_pos[edge]['L2'][1])
                            '''
                            edge_pos[edge]['L1'] = (edge_pos[edge]['L1'][0]-self.arrowhead_comp_y/2, edge_pos[edge]['L1'][1])
                            edge_pos[edge]['L2'] = (edge_pos[edge]['L2'][0]-self.arrowhead_comp_y/2, edge_pos[edge]['L2'][1])
                        if l2_id==pos_id and strict_edge_pos[edge]['arrow_direction']==self.arrowhead_flat:
                            '''
                            edge_pos[edge]['L1'] = (edge_pos[edge]['L1'][0]-self.arrowhead_comp_y/2, edge_pos[edge]['L1'][1])
                            edge_pos[edge]['L2'] = (edge_pos[edge]['L2'][0]-self.arrowhead_comp_y/2, edge_pos[edge]['L2'][1])
                            '''
                            edge_pos[edge]['L1'] = (edge_pos[edge]['L1'][0]+self.arrowhead_comp_y/2, edge_pos[edge]['L1'][1])
                            edge_pos[edge]['L2'] = (edge_pos[edge]['L2'][0]+self.arrowhead_comp_y/2, edge_pos[edge]['L2'][1])
                        elif l2_id==pos_id and strict_edge_pos[edge]['arrow_direction']==self.rev_arrowhead_flat:
                            '''
                            edge_pos[edge]['L1'] = (edge_pos[edge]['L1'][0]+self.arrowhead_comp_y/2, edge_pos[edge]['L1'][1])
                            edge_pos[edge]['L2'] = (edge_pos[edge]['L2'][0]+self.arrowhead_comp_y/2, edge_pos[edge]['L2'][1])
                            '''
                            edge_pos[edge]['L1'] = (edge_pos[edge]['L1'][0]-self.arrowhead_comp_y/2, edge_pos[edge]['L1'][1])
                            edge_pos[edge]['L2'] = (edge_pos[edge]['L2'][0]-self.arrowhead_comp_y/2, edge_pos[edge]['L2'][1])
        ############## Finally draw ##################
        for edge in edge_pos:
            p = draw.Path(stroke=arrow_stroke_color,
                          stroke_width=arrow_stroke_width,
                          fill='none',
                          marker_end=edge_pos[edge]['arrow_direction'])
            p.M(edge_pos[edge]['source'][0], edge_pos[edge]['source'][1]).L(edge_pos[edge]['L1'][0], edge_pos[edge]['L1'][1]).L(edge_pos[edge]['L2'][0], edge_pos[edge]['L2'][1]).L(edge_pos[edge]['target'][0], edge_pos[edge]['target'][1])
            arrow_box.append(p)
        a = sg.fromstring(arrow_box.asSvg())
        a_b = a.getroot()
        a_b.moveto(0, background_len_y)#WARNING: not sure why I have to + subpot
        fig.append(a_b)
        svg = fig.to_str().decode("utf-8")
        if path:
            open(path, 'w').write(svg)
        return svg, resG, mod_pos, reac_cofactors_name, nodes_attach_locs
Example #20
0
def test_scale_xy():
    svg_fig = transform.fromstring(circle)
    group = svg_fig.getroot()

    group.scale_xy(0, 30)
    ok_('scale(0' in group.root.get('transform'))
Example #21
0
def plot_registration(
    anat_nii,
    div_id,
    plot_params=None,
    order=("z", "x", "y"),
    cuts=None,
    estimate_brightness=False,
    label=None,
    contour=None,
    compress="auto",
):
    """
    Plots the foreground and background views
    Default order is: axial, coronal, sagittal
    """
    plot_params = {} if plot_params is None else plot_params

    # Use default MNI cuts if none defined
    if cuts is None:
        raise NotImplementedError  # TODO

    out_files = []
    if estimate_brightness:
        plot_params = robust_set_limits(anat_nii.get_fdata().reshape(-1),
                                        plot_params)

    # FreeSurfer ribbon.mgz
    ribbon = contour is not None and np.array_equal(
        np.unique(contour.get_fdata()), [0, 2, 3, 41, 42])

    if ribbon:
        contour_data = contour.get_fdata() % 39
        white = nlimage.new_img_like(contour, contour_data == 2)
        pial = nlimage.new_img_like(contour, contour_data >= 2)

    # Plot each cut axis
    for i, mode in enumerate(list(order)):
        plot_params["display_mode"] = mode
        plot_params["cut_coords"] = cuts[mode]
        if i == 0:
            plot_params["title"] = label
        else:
            plot_params["title"] = None

        # Generate nilearn figure
        display = plot_anat(anat_nii, **plot_params)
        if ribbon:
            kwargs = {"levels": [0.5], "linewidths": 0.5}
            display.add_contours(white, colors="b", **kwargs)
            display.add_contours(pial, colors="r", **kwargs)
        elif contour is not None:
            display.add_contours(contour,
                                 colors="b",
                                 levels=[0.5],
                                 linewidths=0.5)

        svg = extract_svg(display, compress=compress)
        display.close()

        # Find and replace the figure_1 id.
        svg = svg.replace("figure_1", "%s-%s-%s" % (div_id, mode, uuid4()), 1)
        out_files.append(fromstring(svg))

    return out_files
Example #22
0
def test_get_size():
    svg_fig = transform.fromstring(circle)
    w, h = svg_fig.get_size()
    ok_((w=='150') & (h=='50'))
Example #23
0
def compose_view(bg_svgs, fg_svgs, ref=0, out_file='report.svg'):
    """
    Composes the input svgs into one standalone svg and inserts
    the CSS code for the flickering animation
    """
    import svgutils.transform as svgt

    # Read all svg files and get roots
    svgs = [svgt.fromstring(f) for f in bg_svgs + fg_svgs]
    roots = [f.getroot() for f in svgs]

    # Query the size of each
    sizes = []
    for f in svgs:
        viewbox = f.root.get("viewBox").split(" ")
        width = int(viewbox[2])
        height = int(viewbox[3])
        sizes.append((width, height))
    nsvgs = len(bg_svgs)

    sizes = np.array(sizes)

    # Calculate the scale to fit all widths
    width = sizes[ref, 0]
    scales = width / sizes[:, 0]
    heights = sizes[:, 1] * scales

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

    yoffset = 0
    for i, r in enumerate(roots):
        r.moveto(0, yoffset, scale=scales[i])
        if i == (nsvgs - 1):
            yoffset = 0
        else:
            yoffset += heights[i]

    # Group background and foreground panels in two groups
    if fg_svgs:
        newroots = [
            svgt.GroupElement(roots[:nsvgs], {'class': 'background-svg'}),
            svgt.GroupElement(roots[nsvgs:], {'class': 'foreground-svg'})
        ]
    else:
        newroots = roots
    fig.append(newroots)
    fig.root.attrib.pop("width")
    fig.root.attrib.pop("height")
    fig.root.set("preserveAspectRatio", "xMidYMid meet")
    out_file = op.abspath(out_file)
    fig.save(out_file)

    # Add styles for the flicker animation
    if fg_svgs:
        with open(out_file, 'r' if PY3 else 'rb') as f:
            svg = f.read().split('\n')

        svg.insert(2, """<style type="text/css">
@keyframes flickerAnimation%s { 0%% {opacity: 1;} 100%% { opacity: 0; }}
.foreground-svg { animation: 1s ease-in-out 0s alternate none infinite paused flickerAnimation%s;}
.foreground-svg:hover { animation-play-state: running;}
</style>""" % tuple([uuid4()] * 2))
        with open(out_file, 'w' if PY3 else 'wb') as f:
            f.write('\n'.join(svg))
    return out_file
Example #24
0
def chicpeaDownload(request, url):
    queryDict = request.POST
    output_format = queryDict.get("output_format")
    CSS = queryDict.get("css-styles")
    WIDTH = int(queryDict.get("svg-width")) + 40 + 50
    HEIGHT = int(queryDict.get("svg-height")) + 100
    tissue = queryDict.get("tissue").replace(' ', '_')
    returnFileName = 'CHiCP-' + queryDict.get("searchTerm") + '-' + tissue + '.' + output_format

    fig1 = fromstring(queryDict.get("data-main"))
    layout = ColumnLayout(1)
    layout.add_figure(fig1)

    if queryDict.get("data-bait") and queryDict.get("data-target"):
        s1 = queryDict.get("data-bait")
        s2 = queryDict.get("data-target")
        layoutPanels = VerticalLayout()
        layoutPanels.add_figure(fromstring(s1))
        layoutPanels.add_figure(fromstring(s2))
        layoutPanels._generate_layout()
        svgPanels = layoutPanels.to_str()
        fig2 = fromstring(svgPanels)
    else:
        fig2 = fromstring("<svg></svg>")

    layout.add_figure(fig2)
    layout._generate_layout()
    SVG = layout.to_str().decode()
    p = re.compile(r'translate\((\d+), 0\)')
    m = p.search(SVG)
    SVG = re.sub(r'translate\(\d+, 0\)', r'translate('+str(int(m.group(1)) + 60)+', 50)', SVG)
    SVG = SVG.replace('translate(0, 270)', 'translate(0, 390)')

    SVG = SVG.replace('<g>', '<g transform="translate(20,50) scale(1)">', 1)
    SVG = SVG.replace('<svg ', '<svg style="width:'+str(WIDTH)+'px;height:'+str(HEIGHT)+'px;" ')
    SVG = SVG.replace("</svg>", '<defs><style type="text/css">'+CSS+'</style></defs></svg>')

    if output_format == "svg":
        response = HttpResponse(content_type='image/svg+xml')
        response['Content-Disposition'] = 'attachment; filename="' + returnFileName + '"'
        response.write(SVG)
    elif output_format == "pdf" or output_format == "png":
        mime_type = "application/x-pdf" if output_format == "pdf" else "image/png"

        response = HttpResponse(content_type=mime_type)
        response['Content-Disposition'] = 'attachment; filename="' + returnFileName + '"'
        iFile = NamedTemporaryFile(delete=False)
        oFile = NamedTemporaryFile(delete=False)
        iFile.write(SVG.encode())
        iFile.close()

        if output_format == "pdf":
            svg2pdf(SVG.encode('utf-8'), write_to=str(oFile.name))
        else:
            svg2png(SVG.encode('utf-8'), write_to=str(oFile.name))

        fileData = oFile.read()
        response.write(fileData)
    else:
        retJSON = {"error": "output format was not recognised"}
        response = JsonResponse(retJSON)
    return response
Example #25
0
def test_group_class():
    svg_fig = transform.fromstring(circle)
    group = svg_fig.getroot()
    ok_((group.root.attrib['class'] == 'main'))
Example #26
0
def test_group_class():
    svg_fig = transform.fromstring(circle)
    group = svg_fig.getroot()
    ok_((group.root.attrib['class'] == 'main'))
Example #27
0
def test_get_size():
    svg_fig = transform.fromstring(circle)
    w, h = svg_fig.get_size()
    ok_((w == "150") & (h == "50"))
Example #28
0
image_map = {}


# generic intro
class intro:
    pass


intro.track = False
intro.para = ''

# background element
background = sg.fromstring('''<?xml version="1.0" encoding="UTF-8" ?>
<svg>
  <path
     style="color:#000000;fill:#ffeeaa;fill-opacity:1;fill-rule:nonzero;stroke:#003000;stroke-width:7.92078352;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate"
     d="m 63.739544,3.9653885 2300.419856,0 c 33.1097,0 59.7648,26.6551095 59.7648,59.7648205 l 0,2510.122491 c 0,33.1097 -26.6551,59.7648 -59.7648,59.7648 l -2300.419856,0 c -33.10971,0 -59.7648202,-26.6551 -59.7648202,-59.7648 l 0,-2510.122491 c 0,-33.109711 26.6551102,-59.7648205 59.7648202,-59.7648205 z"/>
</svg>
''')


class RectElement(sg.FigureElement):
    '''inkscape rectangle using style
       x, y = upper left corner of the element
    '''
    def __init__(self, x, y, is_index):
        fill = 'a6a607' if is_index else 'ffcc66'
        style = 'fill:#' + fill + ';fill-opacity:1;stroke:#003000;stroke-width:4;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none'
        linedata = "m %.5f,%.5f 0,%.5f %.5f,0 0,%.5f z" % (
            x, y, RECT_HEIGHT, RECT_WIDTH, -RECT_HEIGHT)
        line = sg.etree.Element(sg.SVG + "path", {
Example #29
0
def test_scale_xy():
    svg_fig = transform.fromstring(circle)
    group = svg_fig.getroot()

    group.scale(0, 30)
    ok_("scale(0" in group.root.get("transform"))
Example #30
0
def chicpeaDownload(request, url):
    queryDict = request.POST
    output_format = queryDict.get("output_format")
    CSS = queryDict.get("css-styles")
    WIDTH = int(queryDict.get("svg-width")) + 40 + 50
    HEIGHT = int(queryDict.get("svg-height")) + 60
    tissue = queryDict.get("tissue").replace(' ', '_')
    returnFileName = 'CHiCP-' + queryDict.get("searchTerm") + '-' + tissue + '.' + output_format

    fig1 = fromstring(queryDict.get("data-main"))
    layout = ColumnLayout(1)
    layout.add_figure(fig1)

    if queryDict.get("data-bait") and queryDict.get("data-target"):
        s1 = queryDict.get("data-bait")
        s2 = queryDict.get("data-target")
        layoutPanels = VerticalLayout()
        layoutPanels.add_figure(fromstring(s1))
        layoutPanels.add_figure(fromstring(s2))
        layoutPanels._generate_layout()
        svgPanels = layoutPanels.to_str()
        fig2 = fromstring(svgPanels)
    else:
        fig2 = fromstring("<svg></svg>")

    layout.add_figure(fig2)
    layout._generate_layout()
    SVG = layout.to_str().decode()
    p = re.compile(r'translate\((\d+), 0\)')
    m = p.search(SVG)
    SVG = re.sub(r'translate\(\d+, 0\)', r'translate('+str(int(m.group(1)) + 60)+', 50)', SVG)
    SVG = SVG.replace('translate(0, 270)', 'translate(0, 390)')

    SVG = SVG.replace('<g>', '<g transform="translate(20,30) scale(1)">', 1)
    SVG = SVG.replace('<svg ', '<svg style="width:'+str(WIDTH)+'px;height:'+str(HEIGHT)+'px;" ')
    SVG = SVG.replace("</svg>", '<defs><style type="text/css">'+CSS+'</style></defs></svg>')

    if output_format == "svg":
        response = HttpResponse(content_type='image/svg+xml')
        response['Content-Disposition'] = 'attachment; filename="' + returnFileName + '"'
        response.write(SVG)
    elif output_format == "pdf" or output_format == "png":
        mime_type = "application/x-pdf" if output_format == "pdf" else "image/png"

        response = HttpResponse(content_type=mime_type)
        response['Content-Disposition'] = 'attachment; filename="' + returnFileName + '"'
        iFile = NamedTemporaryFile(delete=False)
        oFile = NamedTemporaryFile(delete=False)
        iFile.write(SVG.encode())
        iFile.close()

        if output_format == "pdf":
            svg2pdf(SVG.encode('utf-8'), write_to=str(oFile.name))
        else:
            svg2png(SVG.encode('utf-8'), write_to=str(oFile.name))

        fileData = oFile.read()
        response.write(fileData)
    else:
        retJSON = {"error": "output format was not recognised"}
        response = JsonResponse(retJSON)
    return response