def gen_wavedrom_render(waveform_obj): render_str = """{ "signal": [""" for i, signals in enumerate(w_obj.signals): if signals.datatype == VCD_DATATYPE_LOGIC: str_wave = signals.return_wave_string() if i < len(w_obj.signals) - 1: render_str = render_str + """{ "name":""" + '"' + signals.name + """" , "wave":""" + str_wave + """},""" else: render_str = render_str + """{ "name":""" + '"' + signals.name + """" , "wave":""" + str_wave + """}]}""" else: str_data = signals.return_data_string() str_wave = signals.return_wave_string() if i < len(w_obj.signals) - 1: render_str = render_str + """{ "name":""" + '"' + signals.name + """" , "wave":""" + str_wave + """, "data":""" + str_data + """},""" else: render_str = render_str + """{ "name":""" + '"' + signals.name + """" , "wave":""" + str_wave + """, "data":""" + str_data + """}]}""" #print(signals.name+" "+signals.symbol+" "+str(signals.data)) print(render_str) # generate .svg file svg = wavedrom.render(render_str) # try to save file try: svg_filename = waveform_obj.filename.split('.')[0] + "_waveform.svg" svg.saveas(svg_filename) print("File succefully generated as " + svg_filename) except: print("Failed to generate file.")
def render_wavedrom_py(node, outpath, bname, image_format): """ Render a wavedrom image """ # Try to convert node, raise error with code on failure try: svgout = render(node["code"]) except JSONDecodeError as exception: raise SphinxError( "Cannot render the following json code: \n{} \n\nError: {}".format( node['code'], exception)) if not os.path.exists(outpath): os.makedirs(outpath) # SVG can be directly written and is supported on all versions if image_format == 'image/svg+xml': fname = "{}.{}".format(bname, "svg") fpath = os.path.join(outpath, fname) svgout.saveas(fpath) return fname if image_format == 'application/pdf': fname = "{}.{}".format(bname, "pdf") fpath = os.path.join(outpath, fname) cairosvg.svg2pdf(svgout.tostring(), write_to=fpath) return fname if image_format == 'image/png': fname = "{}.{}".format(bname, "png") fpath = os.path.join(outpath, fname) cairosvg.svg2png(svgout.tostring(), write_to=fpath) return fname raise SphinxError("No valid wavedrom conversion supplied")
def _make_test(name): inputfile = "test/{}.json".format(name) with open(inputfile, "r") as f: jinput = f.read() output = render(jinput)
def test_draw(): """ Test draw function """ svg = wavedrom.render(""" { "signal": [ { "name": "H", "wave": "P.......","period": 2 }, { "name": "D", "wave": "105.......0.100000111110." }, { "name": "Q", "wave": "zp.........5555z.", "data": "D0 D1 D2 D3" } ]}""") svg.saveas("demo1.svg")
def action(self, elem, doc): if isinstance(elem, pf.Link) and (("wavedrom" in elem.classes) or ("bitfield" in elem.classes)): fn = elem.url options = elem.attributes idn = elem.identifier caption = elem.content with open(fn, "r", encoding="utf-8") as f: data = f.read() data = self.validatejson(data) self.get_options(options, data, elem, doc) assert self.source is not None, "mandatory option input is not set" assert os.path.exists( self.source) == 1, "input file does not exist" assert isinstance(self.convert_to_png, bool), "option png is boolean" assert isinstance(self.convert_to_pdf, bool), "option pdf is boolean" assert isinstance(self.convert_to_eps, bool), "option eps is boolean" output = wavedrom.render(data, self.svg_filename) output.saveas(self.svg_filename) # pf.debug(output.tostring()) self.render_images() pf.debug("[inline] generate wavedrom from", self.linkto) # pf.debug(elem) try: elem.classes.remove("wavedrom") except: elem.classes.remove("bitfield") elem = pf.Image(*caption, classes=elem.classes, url=self.linkto, identifier=idn, title="fig:", attributes=elem.attributes) # pf.debug(elem) return elem if isinstance(elem, pf.Image) and "wavedrom" in elem.classes: pf.debug("#") pf.debug( "# Inline wavedrom in image link syntax, which is *obsolete*, is detected." ) pf.debug( "# Use hyperlink syntax from now - Just remove ! in front.") pf.debug("# Removing link for safety.") pf.debug("#") return []
def _draw_regs(self, outdir, rmap): imgdir = outdir / ('%s_img' % rmap.config['name'].value) imgdir.mkdir(exist_ok=True) bits = rmap.config['data_width'].value lanes = bits // 16 if bits > 16 else 1 for reg in rmap: reg_wd = {"reg": [], "options": {"bits": bits, "lanes": lanes}} bit_pos = -1 for bf in reg: if bit_pos == -1 and bf.lsb > 0: reg_wd["reg"].append({"bits": bf.lsb}) elif bf.lsb - bit_pos > 1: reg_wd["reg"].append({"bits": bf.lsb - bit_pos - 1}) reg_wd["reg"].append({ "name": bf.name, "attr": bf.access, "bits": bf.width }) bit_pos = bf.msb if (bits - 1) > bit_pos: reg_wd["reg"].append({"bits": bits - bit_pos - 1}) wavedrom.render(json.dumps(reg_wd)).saveas( str(imgdir / ("%s.svg" % reg.name.lower())))
def render_wavedrom(self, node, outpath, bname, format): """ Render a wavedrom image """ # Try to convert node, raise error with code on failure try: svgout = render(node["code"]) except JSONDecodeError as e: raise SphinxError( "Cannot render the following json code: \n{} \n\nError: {}".format( node['code'], e)) if not os.path.exists(outpath): os.makedirs(outpath) # SVG can be directly written and is supported on all versions if format == 'image/svg+xml': fname = "{}.{}".format(bname, "svg") fpath = os.path.join(outpath, fname) svgout.saveas(fpath) return fname # It gets a bit ugly, if the output does not support svg. We use cairosvg, because it is the easiest # to use (no dependency on installed programs). But it only works for Python 3. try: import cairosvg except: raise SphinxError( __("Cannot import 'cairosvg'. In Python 2 wavedrom figures other than svg are " "not supported, in Python 3 ensure 'cairosvg' is installed.")) if format == 'application/pdf': fname = "{}.{}".format(bname, "pdf") fpath = os.path.join(outpath, fname) cairosvg.svg2pdf(svgout.tostring(), write_to=fpath) return fname if format == 'image/png': fname = "{}.{}".format(bname, "png") fpath = os.path.join(outpath, fname) cairosvg.svg2png(svgout.tostring(), write_to=fpath) return fname raise SphinxError("No valid wavedrom conversion supplied")
def _render_vcd(fname): with open(fname) as f: vcd = VcdParser() vcd.parse(f) data = vcd.scope.toJson() f.seek(0) timestep = _find_timestep(f) f.seek(0) tmax = _max_time(f) wsignals = [] _process_scope(data, timestep, tmax, [data['name']], wsignals) return wavedrom.render(json.dumps( { 'signal': wsignals, 'head': { 'text': 'Counterexample' }, } ))
def save(self, signals_data=[], filename=""): """ Save SVG code on given filename @param signals: signals data @type signals: list of signal dict @param filename: file name to be used @type filename: string @return: success code/fail code @rtype: integer """ result_data = { "signal": signals_data, "config": { "hscale": self.hscale } } print(result_data) svg = wavedrom.render(json.dumps(result_data)) try: svg.saveas(filename) return 0 except: return -1 return 0
def test_render(file): jinput = open(file).read() wavedrom.render(jinput)
# @brief https://pypi.org/project/wavedrom/ import wavedrom # Simple waveform example svg = wavedrom.render(""" { "signal": [ { "name": "CLK", "wave": "P.......", "period": 2 }, { "name": "CMD", "wave": "x.3x=x4x=x=x=x=x", "data": "RAS NOP CAS NOP NOP NOP NOP", "phase": 0.5 }, { "name": "ADDR", "wave": "x.=x..=x........", "data": "ROW COL", "phase": 0.5 }, { "name": "DQS", "wave": "z.......0.....z." }, { "name": "DQ", "wave": "z.........z.....", "data": "D0 D1 D2 D3" } ]}""") svg.saveas("demo1.svg")
def render(wave): return wavedrom.render(wave).tostring()