def test_embed_svg_url(): import gzip from io import BytesIO svg_data = b'<svg><circle x="0" y="0" r="1"/></svg>' url = 'http://test.com/circle.svg' gzip_svg = BytesIO() with gzip.open(gzip_svg, 'wb') as fp: fp.write(svg_data) gzip_svg = gzip_svg.getvalue() def mocked_urlopen(*args, **kwargs): class MockResponse: def __init__(self, svg): self._svg_data = svg self.headers = {'content-type': 'image/svg+xml'} def read(self): return self._svg_data if args[0] == url: return MockResponse(svg_data) elif args[0] == url + 'z': ret = MockResponse(gzip_svg) ret.headers['content-encoding'] = 'gzip' return ret return MockResponse(None) with mock.patch('urllib.request.urlopen', side_effect=mocked_urlopen): svg = display.SVG(url=url) nt.assert_true(svg._repr_svg_().startswith('<svg')) svg = display.SVG(url=url + 'z') nt.assert_true(svg._repr_svg_().startswith('<svg'))
def plot_model(model, to_file=None, display_image=True, **kwargs): """ Extend tf.keras.utils.plot_model Parameters: model: A Keras model instance to_file: File name of the plot image display_image: """ dot = model_to_dot(model, **kwargs) if to_file is not None: from tensorflow.python.keras.utils.io_utils import path_to_string import os to_file = path_to_string(to_file) _, extension = os.path.splitext(to_file) extension = extension[1:] dot.write(to_file, format=extension) if display_image: try: from IPython import display if to_file is None or extension == 'svg': return display.SVG(dot.create(prog='dot', format='svg')) else: return display.Image(filename=to_file) except ImportError: pass
def draw(self, fill=False, file_path=None, do_display=True, return_png=False, with_points=False, with_handles=False, with_bboxes=False, with_markers=False, color_firstlast=False, with_moves=True): if file_path is not None: _, file_extension = os.path.splitext(file_path) if file_extension == ".svg": self.save_svg(file_path) elif file_extension == ".png": self.save_png(file_path) else: raise ValueError(f"Unsupported file_path extension {file_extension}") svg_str = self.to_str(fill=fill, with_points=with_points, with_handles=with_handles, with_bboxes=with_bboxes, with_markers=with_markers, color_firstlast=color_firstlast, with_moves=with_moves) if do_display: ipd.display(ipd.SVG(svg_str)) if return_png: if file_path is None: img_data = cairosvg.svg2png(bytestring=svg_str) return Image.open(io.BytesIO(img_data)) else: _, file_extension = os.path.splitext(file_path) if file_extension == ".svg": img_data = cairosvg.svg2png(url=file_path) return Image.open(io.BytesIO(img_data)) else: return Image.open(file_path)
def _convert(self, mode, engine="dot"): '''Display automaton `self` in `mode` with Graphviz `engine`.''' from IPython import display if mode in ['dot', 'pretty', 'simple', 'tooltip', 'transitions']: svg = _dot_to_svg(self.dot(mode), engine) return display.SVG(svg) elif mode == 'dot2tex': return display.SVG(self.SVG(mode, engine)) elif mode == 'info': return self.info(details=2) elif mode == 'info,detailed': return self.info(details=3) elif mode == 'info,size': return self.info(details=1) elif mode == 'type': return repr(self) else: raise ValueError('invalid display format: ' + mode)
def plot_model(self, model_id=0, is_IPython=True, filename=None, show_shapes=True): if isinstance(model_id, str): model_id = self.get_model_id(model_id) if is_IPython: display.SVG( kvu.model_to_dot(self._models[model_id], show_shapes=show_shapes).create(prog='dot', format='svg')) else: kvu.plot(model, show_shapes=show_shapes, to_file='model.png')
def save_digraph(digraph, file, format): if not file: if format == 'svg': x = display.SVG(digraph.pipe(format=format)) else: x = display.Image(digraph.pipe(format='png')) display.display(x) else: if '.' not in file: file += '.' + format img = digraph.pipe(format=format) f = open(file, 'wb') f.write(img) f.close()
def _render_graph(graph, layout='dot'): class TempFile: def __init__(self): self.data = b'' def write(self, data): self.data += data def get_bytes(self): return self.data graph.layout(layout) graphviz_data = graph.string() buffer = TempFile() graph.draw(buffer, format='svg') return ipd.display(ipd.SVG(buffer.get_bytes()))
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. """ src = gv.Source(graph) if view: print( "Render landmap or at least I'm trying to save a god damn svg. Beep boop" ) # Returns the output file path if ".svg" in filename: filename = filename.replace(".svg", "") 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))
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))
def display_digraph(digraph, format): # pragma: no coverage if format == 'svg': x = display.SVG(digraph.pipe(format=format)) else: x = display.Image(digraph.pipe(format='png')) display.display(x)
def create_qr(link='', scale=20): s = segno.make(link, micro=False) b = BytesIO() s.save(b, kind='svg', scale=scale) display.display(display.SVG(b.getvalue().decode('UTF-8')))
def seqlogo(pm, ic_scale=True, color_scheme=None, size='medium', format='svg', filename=None, **kwargs): """The plotting method of the `seqlogo` distribution. Depends on using any of the 3 classes exposed by `seqlogo`: * `seqlogo.Ppm` * `seqlogo.Pwm` * `seqlogo.CompletePm` Given an `M x N` PM matrix, where `M` is the number of positions and `N` is the number of letters, calculate and render a WebLogo-like motif plot. When `ic_scale` is `True`, the height of each column is proportional to its information content. The y-axis label and scale will reflect information content. Otherwise, all columns have the same height and y-axis label will reflect "bits" Args: pm (`seqlogo.Pm` subclass): a pre-formatted Pm instance ic_scale (bool): whether or not to scale the column heights (default: True) size (str): small (3.54 in), medium (5 in), large (7.25 in), xlarge (10.25) (default: 'medium') format (str): desired matplotlib supported output format Options are 'eps', 'pdf', 'png', 'jpeg', and 'svg' (default: "svg") filename (None | str): Name of the file to save the figure. If `None`: the figure will not be saved. (default: None) color_scheme (str): the color scheme to use for weblogo: 'auto': None 'monochrome': all black 'base pairing': (NA Only) TAU are orange, GC are blue 'classic': (NA Only) classic WebLogo color scheme for nucleic acids 'hydrophobicity': (AA only) Color based on hydrophobicity 'chemistry': (AA only) Color based on chemical properties 'charge': (AA Only) Color based on charge **kwargs: all additional keyword arguments found at http://weblogo.threeplusone.com/manual.html """ # Ensure color scheme matches the alphabet if pm._alphabet_type in utils._NA_ALPHABETS: if color_scheme is None: color_scheme = 'classic' if color_scheme not in utils.NA_COLORSCHEMES: raise ValueError( '{} color_scheme selected is not an allowed nucleic acid color scheme' .format(color_scheme)) elif pm._alphabet_type in utils._AA_ALPHABETS: if color_scheme is None: color_scheme = 'hydrophobicity' if color_scheme not in utils.AA_COLORSCHEMES: raise ValueError( '{} color_scheme selected is not an allowed amino acid color scheme' .format(color_scheme)) color_scheme = wl.std_color_schemes[color_scheme] # Setup the format writer out_format = wl.formatters[format] # Prepare the logo size stack_width = (_sizes[size] / pm.length) * 72 # Initialize the options if ic_scale: unit_name = 'bits' else: unit_name = 'probability' options = wl.LogoOptions(unit_name=unit_name, color_scheme=color_scheme, show_fineprint=False, stack_width=stack_width, **kwargs) #Initialize the output format logo_format = wl.LogoFormat(pm, options) out = out_format(pm, logo_format) # Create the file if the user supplied an filename if filename: with open('{}'.format(filename), 'wb') as out_file: out_file.write(out) if format == 'svg': svg_hash = hash(out) out = re.sub(rb'("#?glyph.*?)(")', rb'\1 %s\2' % str(svg_hash).encode(), out) try: if get_ipython(): import IPython.display as ipd if format == 'svg': return ipd.SVG(out) elif format in ('png', 'jpeg', 'svg'): return ipd.Image(out) else: raise ValueError( '{} format not supported for plotting in console'.format( format)) except NameError: if filename is None: raise ValueError( 'If not in an IPython/Jupyter console and no filename is given, nothing will be rendered' )
def show_graph(self): import IPython.display as display return display.SVG(data=self.graph().pipe(format="svg"))