Python IPython.display.SVG Examples

The following are 25 code examples of IPython.display.SVG(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module IPython.display , or try the search function .
Example #1
Source File: widget.py    From altair_widgets with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def plot(self, show=True):
        kwargs = {
            e["encoding"]: _get_plot_command(e) for e in self.settings["encodings"]
        }
        kwargs = {k: v for k, v in kwargs.items() if v is not None}

        mark_opts = {k: v for k, v in self.settings["mark"].items()}
        mark = mark_opts.pop("mark")
        Chart_mark = getattr(altair.Chart(self.df), mark)
        self.chart = Chart_mark(**mark_opts).encode(**kwargs)
        if show and self.show:
            clear_output()
            display("Updating...")
            with io.StringIO() as f:
                self.chart.save(f, format="svg")
                f.seek(0)
                html = f.read()
            clear_output()
            display(self.controller)
            display(SVG(html)) 
Example #2
Source File: Chorogrid.py    From chorogrid with MIT License 6 votes vote down vote up
def done(self, show=True, save_filename=None):
        """if show == True, displays the svg in IPython notebook. If save_filename
           is specified, saves svg file"""
        svgstring = ET.tostring(self.svg).decode('utf-8')
        svgstring = svgstring.replace('</svg>', ''.join(self.additional_svg) + '</svg>')
        svgstring = svgstring.replace(">", ">\n")
        if save_filename is not None:
            if save_filename[-4:] != '.svg':
                save_filename += '.svg'
            with open(save_filename, 'w+', encoding='utf-8') as f:
                f.write(svgstring)
        if show:
            display(SVG(svgstring))
   
    # the methods to draw square grids, map (traditional choropleth),
    # hex grid, four-hex grid, multi-square grid 
Example #3
Source File: Chorogrid.py    From chorogrid with MIT License 6 votes vote down vote up
def done_and_overlay(self, other_chorogrid, show=True, save_filename=None):
        """Overlays a second chorogrid object on top of the root object."""
        svgstring = ET.tostring(self.svg).decode('utf-8')
        svgstring = svgstring.replace('</svg>', ''.join(self.additional_svg) + '</svg>')
        svgstring = svgstring.replace(">", ">\n")
        svgstring = svgstring.replace("</svg>", "")
        svgstring_overlaid = ET.tostring(other_chorogrid.svg).decode('utf-8')
        svgstring_overlaid = svgstring_overlaid.replace('</svg>', 
                                 ''.join(other_chorogrid.additional_svg) + '</svg>')
        svgstring_overlaid = svgstring_overlaid.replace(">", ">\n")
        svgstring_overlaid = re.sub('<svg.+?>', '', svgstring_overlaid)
        svgstring += svgstring_overlaid
        if save_filename is not None:
            if save_filename[-4:] != '.svg':
                save_filename += '.svg'
            with open(save_filename, 'w+', encoding='utf-8') as f:
                f.write(svgstring)
        if show:
            display(SVG(svgstring))
            
    # the .done() method 
Example #4
Source File: tedd.py    From incubator-tvm with Apache License 2.0 6 votes vote down vote up
def dump_graph(dot_string,
               show_svg=True,
               dot_file_path='',
               output_dot_string=False):
    """Output dot_string in various formats."""
    if dot_file_path:
        try:
            dot_file = open(dot_file_path, "w+")
            dot_file.write(dot_string)
            dot_file.close()
        except IOError:
            print('Cannot open file: ' + dot_file_path)
    if show_svg:
        from IPython.display import display
        from IPython.display import SVG
        src = Source(dot_string)
        display(SVG(src.pipe(format='svg')))
    if output_dot_string:
        return dot_string
    return None 
Example #5
Source File: visualize.py    From catalyst with Apache License 2.0 6 votes vote down vote up
def display_graph(g, format='svg', include_asset_exists=False):
    """
    Display a TermGraph interactively from within IPython.
    """
    try:
        import IPython.display as display
    except ImportError:
        raise NoIPython("IPython is not installed.  Can't display graph.")

    if format == 'svg':
        display_cls = display.SVG
    elif format in ("jpeg", "png"):
        display_cls = partial(display.Image, format=format, embed=True)

    out = BytesIO()
    _render(g, out, format, include_asset_exists=include_asset_exists)
    return display_cls(data=out.getvalue()) 
Example #6
Source File: visualize.py    From zipline-chinese with Apache License 2.0 6 votes vote down vote up
def display_graph(g, format='svg', include_asset_exists=False):
    """
    Display a TermGraph interactively from within IPython.
    """
    try:
        import IPython.display as display
    except ImportError:
        raise NoIPython("IPython is not installed.  Can't display graph.")

    if format == 'svg':
        display_cls = display.SVG
    elif format in ("jpeg", "png"):
        display_cls = partial(display.Image, format=format, embed=True)

    out = BytesIO()
    _render(g, out, format, include_asset_exists=include_asset_exists)
    return display_cls(data=out.getvalue()) 
Example #7
Source File: __init__.py    From IPlantUML with MIT License 6 votes vote down vote up
def plantuml_exec(*file_names, **kwargs):
    """
    Given a list of UML documents, generate corresponding SVG diagrams.

    :param file_names: the filenames of the documents for parsing by PlantUML.
    :param kwargs: optionally `plantuml_path`, indicating where the PlantUML
        jar file resides.
    :return: the path to the generated SVG UML diagram.
    """
    plantuml_path = kwargs.get('plantuml_path', PLANTUMLPATH)

    cmd = ["java",
           "-splash:no",
           "-jar", plantuml_path,
           "-tsvg"] + list(file_names)

    return _exec_and_get_paths(cmd, file_names) 
Example #8
Source File: __init__.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        super(IPTestCase, self).setUp()
        try:
            import IPython
            from IPython.display import HTML, SVG
            self.ip = IPython.InteractiveShell()
            if self.ip is None:
                raise TypeError()
        except Exception:
                raise SkipTest("IPython could not be started")

        self.addTypeEqualityFunc(HTML, self.skip_comparison)
        self.addTypeEqualityFunc(SVG,  self.skip_comparison) 
Example #9
Source File: analysis.py    From llvmlite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def view_dot_graph(graph, filename=None, view=False):
    """
    View the given DOT source.  If view is True, the image is rendered
    and viewed by the default application in the system.  The file path of
    the output is returned.  If view is False, a graphviz.Source object is
    returned.  If view is False and the environment is in a IPython session,
    an IPython image object is returned and can be displayed inline in the
    notebook.

    This function requires the graphviz package.

    Args
    ----
    - graph [str]: a DOT source code
    - filename [str]: optional.  if given and view is True, this specifies
                      the file path for the rendered output to write to.
    - view [bool]: if True, opens the rendered output file.

    """
    # Optionally depends on graphviz package
    import graphviz as gv

    src = gv.Source(graph)
    if view:
        # Returns the output file path
        return src.render(filename, view=view)
    else:
        # Attempts to show the graph in IPython notebook
        try:
            __IPYTHON__
        except NameError:
            return src
        else:
            import IPython.display as display
            format = 'svg'
            return display.SVG(data=src.pipe(format))


# Ctypes binding 
Example #10
Source File: browser.py    From igv-jupyter with MIT License 5 votes vote down vote up
def display_svg(self):
        """
        Display the current SVG image.  You must call get_svg() before calling this method.
        """
        if self.svg == None:
            return "Must call get_svg() first"
        elif self.svg == "FETCHING":
            return 'Awaiting SVG - try again in a few seconds'
        else:
            svg = self.svg
            self.svg == None
            display(SVG(svg)) 
Example #11
Source File: browser.py    From igv-jupyter with MIT License 5 votes vote down vote up
def get_svg(self):
        """
        Fetch the current IGV view as an SVG image.  To display the message call display_svg()
        """
        self.svg = "FETCHING"
        return self._send({
            "id": self.igv_id,
            "command": "toSVG"
        }) 
Example #12
Source File: browser.py    From igv-jupyter with MIT License 5 votes vote down vote up
def to_svg(self):
        """
        Fetch the current IGV view as an SVG image and display it in this cell
        """
        div_id = self._gen_id();
        display(HTML("""<div id="%s"></div>""" % div_id))
        self._send({
            "id": self.igv_id,
            "div": div_id,
            "command": "toSVG"
        }) 
Example #13
Source File: utils.py    From incremental-sequence-learning with MIT License 5 votes vote down vote up
def draw_strokes_custom_color( data, factor = 10, svg_filename = 'test.svg', color_data = None, stroke_width = 1 ):
  min_x, max_x, min_y, max_y = get_bounds( data, factor )
  dims = ( 50 + max_x - min_x, 50 + max_y - min_y )
    
  dwg = svgwrite.Drawing( svg_filename, size = dims )
  dwg.add( dwg.rect( insert = ( 0, 0 ), size = dims, fill = 'white' ) )

  lift_pen = 1
  abs_x = 25 - min_x 
  abs_y = 25 - min_y

  for i in range( len( data ) ):

    x = float( data[ i, 0 ] )/factor
    y = float( data[ i, 1 ] )/factor

    prev_x = abs_x
    prev_y = abs_y

    abs_x += x
    abs_y += y

    if ( lift_pen == 1 ):
      p = "M "+str( abs_x )+", "+str( abs_y )+" "
    else:
      p = "M +"+str( prev_x )+", "+str( prev_y )+" L "+str( abs_x )+", "+str( abs_y )+" "

    lift_pen = data[ i, 2 ]

    the_color = "black"

    if ( color_data is not None ):
      the_color = "rgb( "+str( int( color_data[ i, 0 ] ) )+", "+str( int( color_data[ i, 1 ] ) )+", "+str( int( color_data[ i, 2 ] ) )+" )"

    dwg.add( dwg.path( p ).stroke( the_color, stroke_width ).fill( the_color ) )
  dwg.save( )
  display( SVG( dwg.tostring( ) ) ) 
Example #14
Source File: test_dot.py    From xarray-simlab with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_filenames_and_formats(model):

    # Test with a variety of user provided args
    filenames = [
        "modelpdf",
        "model.pdf",
        "model.pdf",
        "modelpdf",
        "model.pdf.svg",
    ]
    formats = ["svg", None, "svg", None, None]
    targets = [
        "modelpdf.svg",
        "model.pdf",
        "model.pdf.svg",
        "modelpdf.png",
        "model.pdf.svg",
    ]

    result_types = {
        "png": Image,
        "pdf": type(None),
        "svg": SVG,
    }

    for filename, format, target in zip(filenames, formats, targets):
        expected_result_type = result_types[target.split(".")[-1]]
        result = dot_graph(model, filename=filename, format=format)
        assert os.path.isfile(target)
        assert isinstance(result, expected_result_type)
        _ensure_not_exists(target) 
Example #15
Source File: dot.py    From xarray-simlab with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_display_cls(format):
    """
    Get the appropriate IPython display class for `format`.

    Returns `IPython.display.SVG` if format=='svg', otherwise
    `IPython.display.Image`.

    If IPython is not importable, return dummy function that swallows its
    arguments and returns None.
    """
    dummy = lambda *args, **kwargs: None
    try:
        import IPython.display as display
    except ImportError:
        # Can't return a display object if no IPython.
        return dummy

    if format in IPYTHON_NO_DISPLAY_FORMATS:
        # IPython can't display this format natively, so just return None.
        return dummy
    elif format in IPYTHON_IMAGE_FORMATS:
        # Partially apply `format` so that `Image` and `SVG` supply a uniform
        # interface to the caller.
        return partial(display.Image, format=format)
    elif format == "svg":
        return display.SVG
    else:
        raise ValueError(f"Unknown format '{format}' passed to `dot_graph`") 
Example #16
Source File: plotly.py    From lddmm-ot with MIT License 5 votes vote down vote up
def ishow(cls, figure_or_data, format='png', width=None, height=None,
              scale=None):
        """Display a static image of the plot described by `figure_or_data`
        in an IPython Notebook.

        positional arguments:
        - figure_or_data: The figure dict-like or data list-like object that
                          describes a plotly figure.
                          Same argument used in `py.plot`, `py.iplot`,
                          see https://plot.ly/python for examples
        - format: 'png', 'svg', 'jpeg', 'pdf'
        - width: output width
        - height: output height
        - scale: Increase the resolution of the image by `scale` amount
               Only valid for PNG and JPEG images.

        example:
        ```
        import plotly.plotly as py
        fig = {'data': [{'x': [1, 2, 3], 'y': [3, 1, 5], 'type': 'bar'}]}
        py.image.ishow(fig, 'png', scale=3)
        """
        if format == 'pdf':
            raise exceptions.PlotlyError(
                "Aw, snap! "
                "It's not currently possible to embed a pdf into "
                "an IPython notebook. You can save the pdf "
                "with the `image.save_as` or you can "
                "embed an png, jpeg, or svg.")
        img = cls.get(figure_or_data, format, width, height, scale)
        from IPython.display import display, Image, SVG
        if format == 'svg':
            display(SVG(img))
        else:
            display(Image(img)) 
Example #17
Source File: helpers.py    From mol2vec with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def depict_identifier(mol, identifier, radius, useFeatures=False, **kwargs):
    """Depict an identifier in Morgan fingerprint.
    
    Parameters
    ----------
    mol : rdkit.Chem.rdchem.Mol
        RDKit molecule
    identifier : int or str
        Feature identifier from Morgan fingerprint
    radius : int
        Radius of Morgan FP
    useFeatures : bool
        Use feature-based Morgan FP
    
    Returns
    -------
    IPython.display.SVG
    """
    identifier = int(identifier)
    info = {}
    AllChem.GetMorganFingerprint(mol, radius, bitInfo=info, useFeatures=useFeatures)
    if identifier in info.keys():
        atoms, radii = zip(*info[identifier])
        return depict_atoms(mol, atoms, radii, **kwargs)
    else:
        return mol_to_svg(mol, **kwargs) 
Example #18
Source File: utils.py    From incremental-sequence-learning with MIT License 5 votes vote down vote up
def draw_strokes( data, factor = 10, svg_filename = 'sample.svg' ):
  min_x, max_x, min_y, max_y = get_bounds( data, factor )
  dims = ( 50 + max_x - min_x, 50 + max_y - min_y )
    
  dwg = svgwrite.Drawing( svg_filename, size = dims )
  dwg.add( dwg.rect( insert = ( 0, 0 ), size = dims, fill = 'white' ) )

  lift_pen = 1
    
  abs_x = 25 - min_x 
  abs_y = 25 - min_y
  p = "M%s, %s " % ( abs_x, abs_y )
    
  command = "m"

  for i in range( len( data ) ):
    if ( lift_pen == 1 ):
      command = "m"
    elif ( command != "l" ):
      command = "l"
    else:
      command = ""
    x = float( data[ i, 0 ] )/factor
    y = float( data[ i, 1 ] )/factor
    lift_pen = data[ i, 2 ]
    p += command+str( x )+", "+str( y )+" "

  the_color = "black"
  stroke_width = 1

  dwg.add( dwg.path( p ).stroke( the_color, stroke_width ).fill( "none" ) )

  dwg.save( )
  display( SVG( dwg.tostring( ) ) ) 
Example #19
Source File: helpers.py    From mol2vec with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def mol_to_svg(mol, molSize=(300, 300), kekulize=True, drawer=None, font_size=0.8, **kwargs):
    """Generates a SVG from mol structure.
    
    Inspired by: http://rdkit.blogspot.ch/2016/02/morgan-fingerprint-bit-statistics.html
    
    Parameters
    ----------
    mol : rdkit.Chem.rdchem.Mol
    molSize : tuple
    kekulize : bool 
    drawer : funct
        Specify which drawing function to use (default: rdMolDraw2D.MolDraw2DSVG)
    font_size : float
        Atom font size

    Returns
    -------
    IPython.display.SVG
    """
    from IPython.display import SVG    
    
    mc = _prepare_mol(mol, kekulize)
    mol_atoms = [a.GetIdx() for a in mc.GetAtoms()]
    if drawer is None:
        drawer = rdMolDraw2D.MolDraw2DSVG(*molSize)
    drawer.SetFontSize(font_size)
    drawer.DrawMolecule(mc, highlightAtomRadii={x: 0.5 for x in mol_atoms}, **kwargs)
    drawer.FinishDrawing()
    svg = drawer.GetDrawingText()
    return SVG(svg.replace('svg:', '')) 
Example #20
Source File: helpers.py    From mol2vec with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _prepare_mol(mol, kekulize):
    """Prepare mol for SVG depiction (embed 2D coords)
    """
    mc = Chem.Mol(mol.ToBinary())
    if kekulize:
        try:
            Chem.Kekulize(mc)
        except:
            mc = Chem.Mol(mol.ToBinary())
    if not mc.GetNumConformers():
        rdDepictor.Compute2DCoords(mc)
    return mc 
Example #21
Source File: utils.py    From incremental-sequence-learning with MIT License 5 votes vote down vote up
def draw_strokes_pdf( data, param, factor = 10, svg_filename = 'sample_pdf.svg' ):
  min_x, max_x, min_y, max_y = get_bounds( data, factor )
  dims = ( 50 + max_x - min_x, 50 + max_y - min_y )

  dwg = svgwrite.Drawing( svg_filename, size = dims )
  dwg.add( dwg.rect( insert = ( 0, 0 ), size = dims, fill = 'white' ) )

  abs_x = 25 - min_x 
  abs_y = 25 - min_y

  num_mixture = len( param[ 0 ][ 0 ] )

  for i in range( len( data ) ):

    x = float( data[ i, 0 ] )/factor
    y = float( data[ i, 1 ] )/factor

    for k in range( num_mixture ):
      pi = param[ i ][ 0 ][ k ]
      if pi > 0.01: # optimisation, ignore pi's less than 1% chance
        mu1 = param[ i ][ 1 ][ k ]
        mu2 = param[ i ][ 2 ][ k ]
        s1 = param[ i ][ 3 ][ k ]
        s2 = param[ i ][ 4 ][ k ]
        sigma = np.sqrt( s1*s2 )
        dwg.add( dwg.circle( center = ( abs_x+mu1*factor, abs_y+mu2*factor ), r = int( sigma*factor ) ).fill( 'red', opacity = pi/( sigma*sigma*factor ) ) )

    prev_x = abs_x
    prev_y = abs_y

    abs_x += x
    abs_y += y


  dwg.save( )
  display( SVG( dwg.tostring( ) ) ) 
Example #22
Source File: __init__.py    From IPlantUML with MIT License 5 votes vote down vote up
def plantuml_web(*file_names, **kwargs):
    """
    Given a list of UML documents, generate corresponding SVG diagrams, using
    PlantUML's web service via the plantweb module.

    :param file_names: the filenames of the documents for parsing by PlantUML.
    :return: the path to the generated SVG UML diagram.
    """
    cmd = ["plantweb",
           "--format",
           "auto"] + list(file_names)

    return _exec_and_get_paths(cmd, file_names) 
Example #23
Source File: utilsDrawing.py    From CheTo with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def drawSVGsToHTMLGrid(svgs, cssTableName='default', tableHeader='', namesSVGs=[], size=(150,150), numColumns=4, numRowsShown=2, noHeader=False):
    rows=[]
    names=copy.deepcopy(namesSVGs)
    rows = [SVG(i).data for i in svgs]
    d=int(len(rows)/numColumns)
    x=len(rows)%numColumns
    if x > 0:
        rows+=['']*(numColumns-x)
        d+=1
        if len(names)>0:
            names+=['']*(numColumns-x)
    rows=np.array(rows).reshape(d,numColumns)
    finalRows=[]
    if len(names)>0:
        names = np.array(names).reshape(d,numColumns)
        for r,n in zip(rows,names):
            finalRows.append(r)
            finalRows.append(n)
        d*=2
    else:
        finalRows=rows

    headerRemove = int(max(numColumns,d))
    df=pd.DataFrame(finalRows)

    style = '<style>\n'
    style += 'table.'+cssTableName+' { border-collapse: collapse; border: none;}\n'
    style += 'table.'+cssTableName+' tr, table.'+cssTableName+' th, table.'+cssTableName+' td { border: none;}\n'
    style += 'table.'+cssTableName+' td { width: '+str(size[0])+'px; max-height: '+str(size[1])+'px; background-color: white; text-align:center;}\n'
    if noHeader:
        style += 'table.'+cssTableName+' th {  width: '+str(size[0])+'px; max-height: 0px; background-color: white;}\n'
    else:
        style += 'table.'+cssTableName+' th { color: #ffffff; background-color: #848482; text-align: center;}\n'
        style += '.headline { color: #ffffff; background-color: #848482; text-align: center; font-size: 18px;\
        font-weight: bold; padding: 10px 10px 10px 10px}\n'
    style += '</style>\n'
    if not noHeader:
        style += '<div class="headline">'+str(tableHeader)+'</div>\n'
    style += '<div id="" style="overflow-y:scroll; overflow-x:hidden; max-height:'+str(size[1]*numRowsShown+size[1]/2)+'px; background-color: white; border:1px solid grey">\n'
    dfhtml=style+df.to_html()+'\n</div>\n'
    dfhtml=dfhtml.replace('class="dataframe"','class="'+cssTableName+'"')
    dfhtml=dfhtml.replace('<th></th>','')
    for i in range(0,headerRemove):
        dfhtml=dfhtml.replace('<th>'+str(i)+'</th>','')
    return dfhtml

# build an svg grid image to print 
Example #24
Source File: helpers.py    From mol2vec with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def depict_atoms(mol, atom_ids, radii, molSize=(300, 300), atm_color=(0, 1, 0), oth_color=(0.8, 1, 0)):
    """Get a depiction of molecular substructure. Useful for depicting bits in fingerprints.
    
    Inspired by: http://rdkit.blogspot.ch/2016/02/morgan-fingerprint-bit-statistics.html
    
    Parameters
    ----------
    mol : rdkit.Chem.rdchem.Mol
    atom_ids : list
        List of atoms to depict
    radii : list
        List of radii - how many atoms around each atom with atom_id to highlight
    molSize : tuple
    atm_color, oth_color : tuple
        Colors of central atoms and surrounding atoms and bonds
    
    Returns
    -------
    IPython.display.SVG
    """
    atoms_to_use = []
    bonds = []
    for atom_id, radius in zip(atom_ids, radii):    
        if radius > 0:
            env = Chem.FindAtomEnvironmentOfRadiusN(mol, radius, atom_id)
            bonds += [x for x in env if x not in bonds]
            for b in env:
                atoms_to_use.append(mol.GetBondWithIdx(b).GetBeginAtomIdx())
                atoms_to_use.append(mol.GetBondWithIdx(b).GetEndAtomIdx())
            atoms_to_use = list(set(atoms_to_use))       
        else:
            atoms_to_use.append(atom_id)
            env = None
    if sum(radii) == 0:
        return mol_to_svg(mol, molSize=molSize, highlightBonds=False, highlightAtoms=atoms_to_use,
                          highlightAtomColors={x: atm_color for x in atom_ids})
    else:
        colors = {x: atm_color for x in atom_ids}
        for x in atoms_to_use:
            if x not in atom_ids:
                colors[x] = oth_color
        bond_colors = {b: oth_color for b in bonds}
        return mol_to_svg(mol, molSize=molSize, highlightAtoms=atoms_to_use, highlightAtomColors=colors,
                          highlightBonds=bonds, highlightBondColors=bond_colors) 
Example #25
Source File: __init__.py    From IPlantUML with MIT License 4 votes vote down vote up
def plantuml(line, cell):
    """
    Generate and inline the SVG portrayal of the given PlantUML UML spec.

    :param line: if not empty, it is the base file name to give to the
        serialized cell contents and the generated SVG files.
    :param cell: the PlantUML language UML specification.
    :return: a IPython SVG object for the diagram or None given error.
    """

    parser = argparse.ArgumentParser()
    parser.add_argument("-j", "--jar", action="store_true",
                        help="render using plantuml.jar (default is plantweb)")
    parser.add_argument("-n", "--name", type=str, default=None,
                        help="persist as <name>.uml and <name>.svg after rendering")
    parser.add_argument("-p", "--plantuml-path", default=None,
                        help="specify PlantUML jar path (default={})".format(PLANTUMLPATH))
    args = parser.parse_args(line.split() if line else "")
    retain = args.name is not None
    base_name = args.name or str(uuid.uuid4())
    use_web = not (args.jar or args.plantuml_path)

    uml_path = base_name + ".uml"
    with open(uml_path, 'w') as fp:
        fp.write(cell)

    try:
        output = None
        if use_web:
            output = plantuml_web(uml_path)
        else:
            plantuml_path = os.path.abspath(args.plantuml_path or PLANTUMLPATH)
            output = plantuml_exec(uml_path, plantuml_path=plantuml_path)
        svg_name = output[0]
        return SVG(filename=svg_name)
    finally:
        if not retain:
            if os.path.exists(uml_path):
                os.unlink(uml_path)
            svg_path = base_name + ".svg"
            if os.path.exists(svg_path):
                os.unlink(svg_path)