Esempio n. 1
0
def print_balance_sheets_and_money_stocks(*args):
    MusteriA.book_end_of_period()
   
    
    if len(args)==0:
        args = ("b1","b2","pA")
    if "b1" in args and Xbankasi.get_total_assets() > 0: display_svg(SVG(Xbankasi.draw_balance_sheet("JP Morgan", width=500)))
    if "b2" in args and Ybankasi.get_total_assets() > 0: display_svg(SVG(Ybankasi.draw_balance_sheet("Citibank", width=500)))
    if "pA" in args and MusteriA.get_total_assets() > 0: display_svg(SVG(MusteriA.draw_balance_sheet("Goodlife", width=500)))

        
    print_money_stocks()
Esempio n. 2
0
def print_balance_sheets_and_money_stocks(*args):
    MusteriA.book_end_of_period()
    MusteriB.book_end_of_period()
    MusteriC.book_end_of_period()
    
    if len(args)==0:
        args = ("bk","hd","fd","ts","pd")
    
    if "bk" in args and Bank.get_total_assets() > 0: display_svg(SVG(Bank.draw_balance_sheet("Bank", width=500)))
    if "hd" in args and Household.get_total_assets() > 0: display_svg(SVG(Household.draw_balance_sheet("Household", width=500)))
    if "fd" in args and Fed.get_total_assets() > 0: display_svg(SVG(Fed.draw_balance_sheet("Fed", width=500)))
    if "ts" in args and Treasury.get_total_assets() > 0: display_svg(SVG(Treasury.draw_balance_sheet("Treasury", width=500)))  
    if "pd" in args and Primary_Dealer.get_total_assets() > 0: display_svg(SVG(Primary_Dealer.draw_balance_sheet("Primary Dealer", width=500)))
    print_money_stocks()
Esempio n. 3
0
    def show(self) -> "SVG":
        graph = pydot.Dot("graphic", graph_type=self.gtype, bgcolor="white")

        for child in self.nodes:
            graph = child.get_graph(graph)

        return SVG(data=graph.create_svg())
Esempio n. 4
0
 def render_plotly_svg (self, fig, width=None, height=None):
     """
     Function to render a plotly figure in SVG inside jupyter
     """
     if STATIC_EXPORT:
         svg_fig = self.plotly_scope.transform(fig, format="svg", width=width, height=height)
         return SVG(svg_fig)
def show_chart(filepath, *, stp=False, subfolder="", title="on"):
    '''
    Show chart from specified filepath. Rename filepaths for use as chart titles.
    
    Inputs:
    filepath (str):  file path
    stp (boolean): stp breakdown used or not
    subfolder (str): subfolder of in which to find files (required if stp==True)
    title (str): "on" or "off"
    
    Outputs:
    plot     
    '''
    savepath = get_savepath(stp=stp)
    if subfolder != "":
        imgpath = os.path.join(savepath["figures"], subfolder, filepath)
    else:
        imgpath = os.path.join(savepath["figures"], filepath)

    if title == "on":
        title_string = filepath
        for v in variable_renaming:  # replace short strings with full variable names
            title_string = title_string.replace(v, f"{variable_renaming[v]}")
        title_string = title_string.replace(" by",
                                            "\n ### by").replace(".svg", "")
        display(Markdown(f"### {title_string}"))
        if (stp == True) & ~any(
                s in filepath
                for s in ["overall", "sex", "Index of Multiple Deprivation"]):
            display(
                Markdown(
                    f"Zero percentages may represent suppressed low numbers; raw numbers were rounded to nearest 7"
                ))

    display(SVG(filename=imgpath))
Esempio n. 6
0
def print_balance_sheets_and_money_stocks(*args):
    MusteriA.book_end_of_period()

    if len(args) == 0:
        args = ("b1", "b2", "pA", "pB", "pC", "cb", "ts")
    if "b1" in args and Xbankasi.get_total_assets() > 0:
        display_svg(SVG(Xbankasi.draw_balance_sheet("Banka X", width=500)))
    if "b2" in args and Ybankasi.get_total_assets() > 0:
        display_svg(SVG(Ybankasi.draw_balance_sheet("Banka Y", width=500)))
    if "pA" in args and MusteriA.get_total_assets() > 0:
        display_svg(SVG(MusteriA.draw_balance_sheet("Müşteri A", width=500)))
    if "cb" in args and Merkez_Bankasi.get_total_assets() > 0:
        display_svg(
            SVG(Merkez_Bankasi.draw_balance_sheet("Merkez Bankası",
                                                  width=500)))

    print_money_stocks()
Esempio n. 7
0
 def display_diagrams():
     if os.path.isfile(output_name + ".svg") and os.path.getmtime(input_path) <= os.path.getmtime(output_name + ".svg"):
         if not notebook_options.no_mcd:
             display(SVG(filename=output_name + ".svg"))
         if notebook_options.mld:
             mld = read_contents(output_name + ".html")
             display(HTML(mld))
         return True
Esempio n. 8
0
    def build_model(self,
                    char_dimension=16,
                    display_summary=False,
                    display_architecture=False,
                    loss='sparse_categorical_crossentropy',
                    optimizer='rmsprop',
                    metrics=['accuracy']):
        if self.verbose > 3:
            print('-----> Stage: build model')

        sent_encoder = self._build_sentence_block(
            char_dimension=char_dimension,
            max_len_of_sentence=self.max_len_of_sentence,
            max_num_of_setnence=self.max_num_of_setnence)

        doc_encoder = self._build_document_block(
            sent_encoder=sent_encoder,
            num_of_label=self.num_of_label,
            max_len_of_sentence=self.max_len_of_sentence,
            max_num_of_setnence=self.max_num_of_setnence,
            loss=loss,
            optimizer=optimizer,
            metrics=metrics)

        if display_architecture:
            print('Sentence Architecture')
            IPython.display.display(
                SVG(
                    model_to_dot(sent_encoder).create(prog='dot',
                                                      format='svg')))
            print()
            print('Document Architecture')
            IPython.display.display(
                SVG(
                    model_to_dot(doc_encoder).create(prog='dot',
                                                     format='svg')))

        if display_summary:
            print(doc_encoder.summary())

        self.model = {'sent_encoder': sent_encoder, 'doc_encoder': doc_encoder}

        return doc_encoder
Esempio n. 9
0
	def plot(self, save=None, trackWidth=800, labelsWidth=200, showLog=False):
		"""Produce the plot, optionally save to file"""
		self.renderer.trackWidth=trackWidth
		self.renderer.labelsWidth=labelsWidth  #does not work?
	
		self.renderer.setShowLog(showLog)
		svg=self.renderer.toSVG()
		if save is not None:
			with open(save, "w") as text_file:
				text_file.write(svg)
		
		return SVG(data=svg)
Esempio n. 10
0
def model_layers_graph(model, show_shapes=True):
    '''
    Display a Keras model in a notebook by rendering it as SVG
    '''
    dot = model_to_dot(model, show_shapes=show_shapes)
    #dot.set( 'rankdir', 'LR')
    #for n in dot.get_nodes():
    #    n.set('style', 'filled')
    #    n.set('fillcolor', 'aliceblue')
    #    n.set('fontsize', '10')
    #    n.set('fontname', 'Trebuchet MS, Tahoma, Verdana, Arial, Helvetica, sans-serif')
    img = dot.create_svg()
    return SVG(data=img)
Esempio n. 11
0
 def display_solution(self, lis):  # prend une liste d etats actions
     "Print or otherwise display the state."
     # print ("display state")
     # clear_output()
     if lis != False:
         buf = lis[1]
         lis = []
         while buf.parent is not None:
             lis.append(buf.state)
             buf = buf.parent
         lis.append(buf.state)
         lis.reverse()
         print("Profondeur:  ", len(lis) - 1)
         for e in lis:
             display(SVG(chess.svg.board(board=e, size=400)))
     else:
         print("Non trouve le chemin")
Esempio n. 12
0
def print_balance_sheets_and_money_stocks(*args):
    MusteriA.book_end_of_period()
    MusteriB.book_end_of_period()
    MusteriC.book_end_of_period()
    
    if len(args)==0:
        args = ("b1","b2","pA","pB","pC","cb","ts") #ts ekledik.
    if "b1" in args and Xbankasi.get_total_assets() > 0: display_svg(SVG(Xbankasi.draw_balance_sheet("Banka X", width=500)))
    if "b2" in args and Ybankasi.get_total_assets() > 0: display_svg(SVG(Ybankasi.draw_balance_sheet("Banka Y", width=500)))
    if "pA" in args and MusteriA.get_total_assets() > 0: display_svg(SVG(MusteriA.draw_balance_sheet("Müşteri A", width=500)))
    if "pB" in args and MusteriB.get_total_assets() > 0: display_svg(SVG(MusteriB.draw_balance_sheet("Müşteri B", width=500)))
    if "pC" in args and MusteriC.get_total_assets() > 0: display_svg(SVG(MusteriC.draw_balance_sheet("Müşteri C", width=500)))
    if "cb" in args and Merkez_Bankasi.get_total_assets() > 0: display_svg(SVG(Merkez_Bankasi.draw_balance_sheet("Merkez Bankası", width=500)))
    if "ts" in args and Hazine.get_total_assets() > 0: display_svg(SVG(Hazine.draw_balance_sheet("Hazine", width=500)))  #bu satırı ekledik.
    print_money_stocks()
Esempio n. 13
0
    def display(self, format="png"):
        """
        Return an object that can be used to display this sequence.
        This is used for IPython Notebook.

        :param format: "png" or "svg"
        """
        from sebastian.core.transforms import lilypond
        seq = HSeq(self) | lilypond()

        lily_output = write_lilypond.lily_format(seq)
        if not lily_output.strip():
            #In the case of empty lily outputs, return self to get a textual display
            return self

        if format == "png":
            suffix = ".preview.png"
            args = ["lilypond", "--png", "-dno-print-pages", "-dpreview"]
        elif format == "svg":
            suffix = ".preview.svg"
            args = [
                "lilypond", "-dbackend=svg", "-dno-print-pages", "-dpreview"
            ]

        f = tempfile.NamedTemporaryFile(suffix=suffix)
        basename = f.name[:-len(suffix)]
        args.extend(["-o" + basename, "-"])

        #Pass shell=True so that if your $PATH contains ~ it will
        #get expanded. This also changes the way the arguments get
        #passed in. To work correctly, pass them as a string
        p = sp.Popen(" ".join(args), stdin=sp.PIPE, shell=True)
        stdout, stderr = p.communicate("{ %s }" % lily_output)
        if p.returncode != 0:
            # there was an error
            #raise IOError("Lilypond execution failed: %s%s" % (stdout, stderr))
            return None

        if not ipython:
            return f.read()
        if format == "png":
            return Image(data=f.read(), filename=f.name, format="png")
        else:
            return SVG(data=f.read(), filename=f.name)
Esempio n. 14
0
def run_rscape(outdir, sto_filename, fold=True, output=True):
    truncated_filename = sto_filename[sto_filename.rfind('/') +
                                      1:sto_filename.rfind('.sto')]

    if fold:
        arguments = ['R-scape', '--fold', '--outdir', outdir, sto_filename]
    else:
        arguments = ['R-scape', '--r2rall', '--outdir', outdir, sto_filename]

    result = subprocess.run(arguments, capture_output=True)
    if output:
        print(result.stdout.decode())

    # List of the suffixes of excess files to delete
    deleted_file_suffix = [
        'cov', 'dplot.ps', 'dplot.svg', 'power', 'sorted.cov', 'surv',
        'surv.ps', 'surv.svg', 'R2R.sto', 'R2R.sto.pdf'
    ]

    for suffix in deleted_file_suffix:
        file_to_delete = "{}/{}_1.{}".format(outdir, truncated_filename,
                                             suffix)
        if os.path.exists(file_to_delete):
            os.remove(file_to_delete)

    svg_filename = "{}/{}_1.R2R.sto.svg".format(outdir, truncated_filename)

    if fold:
        deleted_fold_suffix = [
            'dplot.ps', 'dplot.svg', 'power', 'R2R.sto', 'R2R.sto.pdf', 'cov'
        ]
        for suffix in deleted_fold_suffix:
            file_to_delete = "{}/{}_1.fold.{}".format(outdir,
                                                      truncated_filename,
                                                      suffix)
            if os.path.exists(file_to_delete):
                os.remove(file_to_delete)
        os.remove("{}/{}_1.sorted.fold.cov".format(outdir, truncated_filename,
                                                   suffix))
        svg_filename = "{}/{}_1.fold.R2R.sto.svg".format(
            outdir, truncated_filename)

    display(SVG(filename=svg_filename))
Esempio n. 15
0
def save(scene, imgName, w=None, h=None, dpi=90,\
             take_region=False, units="px"):
    ipython_inline = False
    if imgName == "%%inline":
        ipython_inline = True
        ext = "PNG"
    elif imgName == "%%inlineSVG":
        ipython_inline = True
        ext = "SVG"        
    elif imgName.startswith("%%return"):
        try:
            ext = imgName.split(".")[1].upper()
        except IndexError:
            ext = 'SVG'
        imgName = '%%return'
    else:
        ext = imgName.split(".")[-1].upper()

    main_rect = scene.sceneRect()
    aspect_ratio = main_rect.height() / main_rect.width()

    # auto adjust size
    if not w and not h:
        units = "px"
        w = main_rect.width()
        h = main_rect.height()
        ratio_mode = QtCore.Qt.KeepAspectRatio
    elif w and h:
        ratio_mode = QtCore.Qt.IgnoreAspectRatio
    elif h is None :
        h = w * aspect_ratio
        ratio_mode = QtCore.Qt.KeepAspectRatio
    elif w is None:
        w = h / aspect_ratio
        ratio_mode = QtCore.Qt.KeepAspectRatio

    # Adjust to resolution
    if units == "mm":
        if w:
            w = w * 0.0393700787 * dpi
        if h:
            h = h * 0.0393700787 * dpi
    elif units == "in":
        if w:
            w = w * dpi
        if h:
            h = h * dpi
    elif units == "px":
        pass
    else:
        raise Exception("wrong unit format")

    x_scale, y_scale = w/main_rect.width(), h/main_rect.height()

    if ext == "SVG":
        from PyQt4 import QtSvg
        svg = QtSvg.QSvgGenerator()
        targetRect = QtCore.QRectF(0, 0, w, h)
        svg.setSize(QtCore.QSize(w, h))
        svg.setViewBox(targetRect)
        svg.setTitle("Generated with ETE http://etetoolkit.org")
        svg.setDescription("Generated with ETE http://etetoolkit.org")

        if imgName == '%%return':
            ba = QtCore.QByteArray()
            buf = QtCore.QBuffer(ba)
            buf.open(QtCore.QIODevice.WriteOnly)
            svg.setOutputDevice(buf)
        else:
            svg.setFileName(imgName)

        pp = QPainter()
        pp.begin(svg)
        scene.render(pp, targetRect, scene.sceneRect(), ratio_mode)
        pp.end()
        if imgName == '%%return':
            compatible_code = str(ba)
            print('from memory')
        else:
            compatible_code = open(imgName).read()
        # Fix a very annoying problem with Radial gradients in
        # inkscape and browsers...
        compatible_code = compatible_code.replace("xml:id=", "id=")
        compatible_code = re.sub('font-size="(\d+)"', 'font-size="\\1pt"', compatible_code)
        compatible_code = compatible_code.replace('\n', ' ')
        compatible_code = re.sub('<g [^>]+>\s*</g>', '', compatible_code)
        # End of fix
        if ipython_inline:
            from IPython.core.display import SVG
            return SVG(compatible_code)

        elif imgName == '%%return':
            return x_scale, y_scale, compatible_code
        else:
            open(imgName, "w").write(compatible_code)


    elif ext == "PDF" or ext == "PS":
        if ext == "PS":
            format = QPrinter.PostScriptFormat
        else:
            format = QPrinter.PdfFormat

        printer = QPrinter(QPrinter.HighResolution)
        printer.setResolution(dpi)
        printer.setOutputFormat(format)
        printer.setPageSize(QPrinter.A4)
        printer.setPaperSize(QtCore.QSizeF(w, h), QPrinter.DevicePixel)
        printer.setPageMargins(0, 0, 0, 0, QPrinter.DevicePixel)

        #pageTopLeft = printer.pageRect().topLeft()
        #paperTopLeft = printer.paperRect().topLeft()
        # For PS -> problems with margins
        #print paperTopLeft.x(), paperTopLeft.y()
        #print pageTopLeft.x(), pageTopLeft.y()
        # print  printer.paperRect().height(),  printer.pageRect().height()
        #topleft =  pageTopLeft - paperTopLeft

        printer.setFullPage(True);
        printer.setOutputFileName(imgName);
        pp = QPainter(printer)
        targetRect =  QtCore.QRectF(0, 0 , w, h)
        scene.render(pp, targetRect, scene.sceneRect(), ratio_mode)
    else:
        targetRect = QtCore.QRectF(0, 0, w, h)
        ii= QImage(w, h, QImage.Format_ARGB32)
        ii.fill(QColor(QtCore.Qt.white).rgb())
        ii.setDotsPerMeterX(dpi / 0.0254) # Convert inches to meters
        ii.setDotsPerMeterY(dpi / 0.0254)
        pp = QPainter(ii)
        pp.setRenderHint(QPainter.Antialiasing)
        pp.setRenderHint(QPainter.TextAntialiasing)
        pp.setRenderHint(QPainter.SmoothPixmapTransform)

        scene.render(pp, targetRect, scene.sceneRect(), ratio_mode)
        pp.end()
        if ipython_inline:
            ba = QtCore.QByteArray()
            buf = QtCore.QBuffer(ba)
            buf.open(QtCore.QIODevice.WriteOnly)
            ii.save(buf, "PNG")
            from IPython.core.display import Image
            return Image(ba.data())
        elif imgName == '%%return':
            ba = QtCore.QByteArray()
            buf = QtCore.QBuffer(ba)
            buf.open(QtCore.QIODevice.WriteOnly)
            ii.save(buf, "PNG")
            return x_scale, y_scale, ba.toBase64()
        else:
            ii.save(imgName)

    return w/main_rect.width(), h/main_rect.height()
Esempio n. 16
0
 def svg(self, line, cell):
     """Render the cell as an SVG literal"""
     display(SVG(cell))
Esempio n. 17
0
elif config['gpml_wikipathways_id']:
    r = requests.get('http://www.wikipathways.org//wpi/wpi.php',
                     params={
                         'action': 'downloadFile',
                         'type': 'gpml',
                         'pwTitle':
                         'Pathway:%s' % config['gpml_wikipathways_id'],
                         'revision': 0,
                     })
    if r.status_code == 200:
        print("Loaded GPML from WikiPathways")
        gpml = r.text
    else:
        raise Exception("Error loading GPML from WikiPathways (%d)" %
                        r.status_code)
else:
    raise Exception("Select a source for GPML")

if gpml:

    # xref_synonyms_fn=get_extended_xref_via_unification_list,
    svg, metadata = gpml2svg.gpml2svg(gpml,
                                      xref_urls=xref_urls,
                                      xref_synonyms=xref_syns,
                                      node_colors=node_colors)

    View = SVG(svg)

    View
Esempio n. 18
0
 def svg(self):
     """Display basic 3-D scatterplot in IPython Notebook as SVG."""
     return SVG(self._repr_svg_())
Esempio n. 19
0
 def _to_svg(self, *,
             zcolor: str = "#CCFFCC",
             xcolor: str = "#FF8888",
             hscale: float = 1.0, vscale: float = 1.0,
             scale: float = 1.0,
             svg_code_only: bool = False
             ):
     # pylint: disable = too-many-locals, too-many-statements, too-many-branches
     # TODO: reuse from phase circuit once cleaned up and restructured
     num_qubits = self.num_qubits
     vscale *= scale
     hscale *= scale
     cx_block = self._cx_block
     phase_block = self._phase_block
     pre_cx_gates = [gate for layer in reversed(cx_block) for gate in layer.gates]
     gadgets = list(phase_block.gadgets)*self._circuit_rep
     post_cx_gates = list(reversed(pre_cx_gates))
     _layers: List[int] = [0 for _ in range(num_qubits)]
     pre_cx_gates_depths: List[int] = []
     max_cx_gates_depth: int = 0
     for gate in pre_cx_gates:
         m = min(gate)
         M = max(gate)
         d = max(_layers[q] for q in range(m, M+1))
         max_cx_gates_depth = max(max_cx_gates_depth, d+1)
         pre_cx_gates_depths.append(d)
         for q in range(m, M+1):
             _layers[q] = d+1
     num_digits = int(ceil(log10(num_qubits)))
     line_height = int(ceil(30*vscale))
     row_width = int(ceil(120*hscale))
     cx_row_width = int(ceil(40*hscale))
     pad_x = int(ceil(10*hscale))
     margin_x = int(ceil(40*hscale))
     pad_y = int(ceil(20*vscale))
     r = pad_y//2-2
     font_size = 2*r
     pad_x += font_size*(num_digits+1)
     delta_fst = row_width//4
     delta_snd = 2*row_width//4
     width = (2*pad_x + 2*margin_x + row_width*len(gadgets)
              + 2*max_cx_gates_depth * cx_row_width)
     height = pad_y + line_height*(num_qubits+1)
     builder = SVGBuilder(width, height)
     levels: List[int] = [0 for _ in range(num_qubits)]
     max_lvl = 0
     base_x = pad_x + margin_x
     for (ctrl, trgt) in pre_cx_gates:
         qubit_span = range(min(ctrl, trgt), max(ctrl, trgt)+1)
         lvl = max(levels[q] for q in qubit_span)
         max_lvl = max(max_lvl, lvl)
         x = base_x + lvl * row_width//3
         for q in qubit_span:
             levels[q] = lvl+1
         y_ctrl = pad_y + (ctrl+1)*line_height
         y_trgt = pad_y + (trgt+1)*line_height
         builder.line((x, y_ctrl), (x, y_trgt))
         builder.circle((x, y_ctrl), r, zcolor)
         builder.circle((x, y_trgt), r, xcolor)
     base_x = base_x + (max_lvl+1) * row_width//3
     levels = [0 for _ in range(num_qubits)]
     max_lvl = 0
     for gadget in gadgets:
         fill = zcolor if gadget.basis == "Z" else xcolor
         other_fill = xcolor if gadget.basis == "Z" else zcolor
         qubit_span = range(min(gadget.qubits), max(gadget.qubits)+1)
         lvl = max(levels[q] for q in qubit_span)
         max_lvl = max(max_lvl, lvl)
         x = base_x + lvl * row_width
         for q in qubit_span:
             levels[q] = lvl+1
         if len(gadget.qubits) > 1:
             text_y = pad_y+min(gadget.qubits)*line_height+line_height//2
             for q in gadget.qubits:
                 y = pad_y + (q+1)*line_height
                 builder.line((x, y), (x+delta_fst, text_y))
             for q in gadget.qubits:
                 y = pad_y + (q+1)*line_height
                 builder.circle((x, y), r, fill)
             builder.line((x+delta_fst, text_y), (x+delta_snd, text_y))
             builder.circle((x+delta_fst, text_y), r, other_fill)
             builder.circle((x+delta_snd, text_y), r, fill)
             builder.text((x+delta_snd+2*r, text_y), str(gadget.angle), font_size=font_size)
         else:
             for q in gadget.qubits:
                 y = pad_y + (q+1)*line_height
                 builder.circle((x, y), r, fill)
             builder.text((x+r, y-line_height//3), str(gadget.angle), font_size=font_size)
     base_x = base_x + (max_lvl+1) * row_width
     levels = [0 for _ in range(num_qubits)]
     max_lvl = 0
     for (ctrl, trgt) in post_cx_gates:
         qubit_span = range(min(ctrl, trgt), max(ctrl, trgt)+1)
         lvl = max(levels[q] for q in qubit_span)
         max_lvl = max(max_lvl, lvl)
         x = base_x + lvl * row_width//3
         for q in qubit_span:
             levels[q] = lvl+1
         y_ctrl = pad_y + (ctrl+1)*line_height
         y_trgt = pad_y + (trgt+1)*line_height
         builder.line((x, y_ctrl), (x, y_trgt))
         builder.circle((x, y_ctrl), r, zcolor)
         builder.circle((x, y_trgt), r, xcolor)
     width = base_x + max_lvl * row_width//3 + pad_x + margin_x
     _builder = SVGBuilder(width, height)
     for q in range(num_qubits):
         y = pad_y + (q+1) * line_height
         _builder.line((pad_x, y), (width-pad_x, y))
         _builder.text((0, y), f"{str(q):>{num_digits}}", font_size=font_size)
         _builder.text((width-pad_x+r, y), f"{str(q):>{num_digits}}", font_size=font_size)
     _builder >>= builder
     svg_code = repr(_builder)
     if svg_code_only:
         return svg_code
     try:
         # pylint: disable = import-outside-toplevel
         from IPython.core.display import SVG # type: ignore
     except ModuleNotFoundError as _:
         raise ModuleNotFoundError("You must install the 'IPython' library.")
     return SVG(svg_code)
Esempio n. 20
0
Ybankasi.make_asset_accounts(['Reserves'])
Ybankasi.make_liability_accounts(['Goodlife Deposit','Equity'])

# Müşterilerin varlık ve yükümlülük kalemleri tanımlanıyor.
MusteriA.make_asset_accounts(['Fixed Assets','Goodlife Deposit'])
MusteriA.make_liability_accounts(['Equity'])


#Başlangıç
Xbankasi.book(debit=[('Reserves',100)],credit=[('Equity',100)])
Ybankasi.book(debit=[('Reserves',100)],credit=[('Equity',100)])
MusteriA.book(debit=[('Fixed Assets',100)],credit=[('Equity',100)])


#Başlangıç- Bilançolar
display_svg(SVG(Xbankasi.draw_balance_sheet("JP Morgan", width=500)))
display_svg(SVG(MusteriA.draw_balance_sheet("Goodlife", width=500)))
display_svg(SVG(Ybankasi.draw_balance_sheet("Citibank", width=500)))


#kod2
#Başlangıç
Xbankasi.book(debit=[('Fixed Assets',100)],credit=[('Goodlife Deposit',100)])
MusteriA.book(debit=[('Goodlife Deposit',100)],credit=[('Fixed Assets',100)])


#Başlangıç- Bilançolar
display_svg(SVG(Xbankasi.draw_balance_sheet("JP Morgan", width=500)))
display_svg(SVG(MusteriA.draw_balance_sheet("Goodlife", width=500)))

#kod3
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
plt.style.use('fivethirtyeight')

# Yoyo despin revisited (cord constraint)


from IPython.core.display import SVG

SVG(filename='./yoyo-rocket.svg')

A rocket yoyo-despinning mechanism uses cords wrapped around the
payload. These cords unravel and slow the spinning of the rocket. In
this tutorial, you will consider the engineering system, conservation of
angular momentum, and conservation of energy. 

# Engineering system - kinematics

As the yoyo mass unravels, it moves further from the payload. The total
distance from the payload center of mass (COM) is described by 

$\mathbf{r}_{P/G} = R\hat{e}_R + l\hat{e}_{\theta}$

where $R$ is the payload radius, $l$ is the length of the cord, and
$\hat{e}_R$ and $\hat{e}_{\theta}$ are unit vectors in a cylindrical
coordinate system. The length of the cord depends upon the angle of the
payload, $\theta$. Consider a spool of thread rolling across the floor,
the thread left on the floor is equal to distance traveled or,
$R\theta$. Now, the position of yoyo P is
Esempio n. 22
0
    def svg(self):
        """Display heatmap in IPython Notebook as SVG.

        """
        return SVG(self._repr_svg_())
Esempio n. 23
0
 def show(self) -> "SVG":
     return SVG(data=self.get_graph().create_svg())
Esempio n. 24
0

# Merkez Bankasının varlık ve yükümlülük kalemleri tanımlanıyor.
Merkez_Bankasi.make_asset_accounts(['Dış Varlıklar','İç Varlıklar','Degerleme','APİ'])
Merkez_Bankasi.make_liability_accounts(['Bankaların Döviz Rezervleri','Hazinenin Döviz Rezervleri','Emisyon','Kamu Mevduatı','Rezervler'])



#Başlangıç
Xbankasi.book(debit=[('Dış Varlıklar',50)],credit=[('Sermaye',50)])
Xbankasi.book(debit=[('Devlet Tahvili',50)],credit=[('Sermaye',50)])
Merkez_Bankasi.book(debit=[('Dış Varlıklar',50)],credit=[('Sermaye',50)])


#Başlangıç- Bilançolar
display_svg(SVG(Xbankasi.draw_balance_sheet("Banka X", width=500)))
display_svg(SVG(Merkez_Bankasi.draw_balance_sheet("Merkez Bankası", width=500)))



"""
Kod1
https://paravefinans595106776.wordpress.com/2021/03/05/
bolum-ii-para-politikasi-islemlerinden-alacaklar-ve-borclar/

"""


#Kod1

Xbankasi.book(debit=[('Rezervler',200)],credit=[('Merkez Bankasına Borçlar',200)])
Esempio n. 25
0
# Primary Dealer 
Primary_Dealer.make_asset_accounts(['Deposits','Treasury Securities'])
Primary_Dealer.make_liability_accounts(['Debts to Fed'])  
                                                                      
# Household 
Household.make_asset_accounts(['Deposits','Treasury Securities'])
Household.make_liability_accounts(['Loans'])




#Kod0 Banka, hanehalkına kredi verir.
Bank.book(debit=[('Loans',100)],credit=[('Deposits',100)])
Household.book(debit=[('Deposits',100)],credit=[('Loans',100)])

display_svg(SVG(Bank.draw_balance_sheet("Bank", width=500)))
display_svg(SVG(Household.draw_balance_sheet("Household", width=500)))



#Kod1

"""Fed,primary dealers ile repo işlemi yapar. Burada primary dealerslerin repo için teminat verdiği tahvilleri bilanço dışında gösterdiğini varsayıyoruz """



Fed.book(debit=[('Credits to Financial Institutions',200)],credit=[('Reserves',200)])
Bank.book(debit=[('Reserves',200)],credit=[('Deposits',200)])
Primary_Dealer.book(debit=[('Deposits',200)],credit=[('Debts to Fed',200)])

Esempio n. 26
0
    def visualize(self,
                  saliency,
                  smiles,
                  save_filepath=None,
                  visualize_ratio=1.0,
                  color_fn=red,
                  scaler=min_max_scaler,
                  legend=''):
        mol = Chem.MolFromSmiles(smiles)
        num_atoms = mol.GetNumAtoms()
        rdDepictor.Compute2DCoords(mol)
        Chem.SanitizeMol(mol)
        Chem.Kekulize(mol)
        n_atoms = mol.GetNumAtoms()
        # highlight = list(range(n_atoms))

        # --- type check ---
        assert saliency.ndim == 1
        # Cut saliency array for unnecessary tail part
        saliency = saliency[:num_atoms]
        # Normalize to [0, 1]
        saliency = scaler(saliency)
        # normed_saliency = copy.deepcopy(saliency)

        if visualize_ratio < 1.0:
            threshold_index = int(n_atoms * visualize_ratio)
            idx = numpy.argsort(saliency)
            idx = numpy.flip(idx, axis=0)
            # set threshold to top `visualize_ratio` saliency
            threshold = saliency[idx[threshold_index]]
            saliency = numpy.where(saliency < threshold, 0., saliency)
        else:
            threshold = numpy.min(saliency)

        highlight_atoms = list(
            map(lambda g: g.__int__(),
                numpy.where(saliency >= threshold)[0]))
        atom_colors = {i: color_fn(e) for i, e in enumerate(saliency)}
        bondlist = [bond.GetIdx() for bond in mol.GetBonds()]

        def color_bond(bond):
            begin = saliency[bond.GetBeginAtomIdx()]
            end = saliency[bond.GetEndAtomIdx()]
            return color_fn(is_visible(begin, end))

        bondcolorlist = {
            i: color_bond(bond)
            for i, bond in enumerate(mol.GetBonds())
        }
        drawer = rdMolDraw2D.MolDraw2DSVG(500, 375)
        drawer.DrawMolecule(mol,
                            highlightAtoms=highlight_atoms,
                            highlightAtomColors=atom_colors,
                            highlightBonds=bondlist,
                            highlightBondColors=bondcolorlist,
                            legend=legend)
        drawer.FinishDrawing()
        svg = drawer.GetDrawingText()
        if save_filepath:
            extention = save_filepath.split('.')[-1]
            if extention == 'svg':
                print('saving svg to {}'.format(save_filepath))
                with open(save_filepath, 'w') as f:
                    f.write(svg)
            elif extention == 'png':
                import cairosvg
                print('saving png to {}'.format(save_filepath))
                # cairosvg.svg2png(
                #     url=svg_save_filepath, write_to=save_filepath)
                # print('svg type', type(svg))
                cairosvg.svg2png(bytestring=svg, write_to=save_filepath)
            else:
                raise ValueError(
                    'Unsupported extention {} for save_filepath {}'.format(
                        extention, save_filepath))
        else:
            from IPython.core.display import SVG
            return SVG(svg.replace('svg:', ''))
        corpus=tokenized_train, model=w2v_model, num_features=500)
    avg_wv_test_features = averaged_word2vec_vectorizer(corpus=tokenized_test,
                                                        model=w2v_model,
                                                        num_features=500)

    # Feature engineering with Glove model
    train_nlp = [tn.nlp(item) for item in norm_train_reviews]
    train_glove_features = np.array(item.vector for item in train_nlp)

    test_nlp = [tn.nlp(item) for item in norm_test_reviews]
    test_glove_features = np.array(item.vector for item in test_nlp)

    w2v_dnn = construct_deepnn_architecture(num_input_features=500)
    SVG(
        model_to_dot(w2v_dnn,
                     show_shapes=True,
                     show_layer_names=False,
                     rankdir="TB").create(prog='dot', format='svg'))

    # Training
    batch_size = 100
    w2v_dnn.fit(avg_wv_train_features,
                y_train,
                epochs=5,
                batch_size=batch_size,
                shuffle=True,
                validation_split=0.1,
                verbose=1)

    # Evaluation
    y_pred = w2v_dnn.predict_classes(avg_wv_test_features)
Esempio n. 28
0

# Merkez Bankasının varlık ve yükümlülük kalemleri tanımlanıyor.
Merkez_Bankasi.make_asset_accounts(['Dış Varlıklar','İç Varlıklar','Degerleme','APİ'])
Merkez_Bankasi.make_liability_accounts(['Hazinenin Döviz Rezervleri','Emisyon','Kamu Mevduatı','Rezervler'])

#Başlangıç
MusteriA.book(debit=[('Mevduat',50)],credit=[('Kredi',50)])
Ybankasi.book(debit=[('Kredi',50)],credit=[('Müşteri A Mevduatı',50)])
Ybankasi.book(debit=[('Rezervler',50)],credit=[('Merkez Bankasına Borçlar',50)])
Xbankasi.book(debit=[('Rezervler',50)],credit=[('Merkez Bankasına Borçlar',50)])
Merkez_Bankasi.book(debit=[('APİ',100)],credit=[('Rezervler',100)])


#Başlangıç- Bilançolar
display_svg(SVG(Xbankasi.draw_balance_sheet("Banka X", width=500)))
display_svg(SVG(Ybankasi.draw_balance_sheet("Banka Y", width=500)))
display_svg(SVG(MusteriA.draw_balance_sheet("Müşteri A", width=500)))
display_svg(SVG(Merkez_Bankasi.draw_balance_sheet("Merkez Bankası", width=500)))

"""
Müşteri A, 30 TL vergi ödemesini Banka Y üzeriden yapıyor.
Banka Y'den çıkan mevduat, Ziraat Bankasına (Banka X) gidiyor.



"""


#Kod-1
MusteriA.book(debit=[('Sermaye',30)],credit=[('Mevduat',30)])
Esempio n. 29
0
def plot_network_visualisations(critical_instabilities,
                                per_second_speech,
                                output_folder,
                                time_zone,
                                relative_scaling=True):
    ## kwargs used to pass stylistic adjustments to visualise_energy_engagement

    critical_times = np.concatenate([
        critical_instabilities.index[0:1],
        critical_instabilities[critical_instabilities].index,
        critical_instabilities.index[-1:]
    ])

    prev_end = pd.to_datetime("2000-01-01").tz_localize(time_zone)

    slice_names = []
    node_data = {}
    edge_data = {}
    max_label_length = max([len(label) for label in per_second_speech.columns])

    for start, end in zip(critical_times[:-1], critical_times[1:]):

        ## Only visualise if we have at least one minute within the slice
        if end - prev_end > np.timedelta64(60, "s"):

            slice_name = start.strftime("%H:%M:%S") + " - " + end.strftime(
                "%H:%M:%S")
            slice_names.append(slice_name)

            node_data[slice_name] = get_node_data(per_second_speech[start:end])

            edge_data[slice_name] = get_edge_data(per_second_speech[start:end])

            prev_end = end

    max_energy = None
    max_engagement = None

    if relative_scaling:

        max_energy = max([slice.energy.max() for slice in node_data.values()])
        max_engagement = max(
            [slice.engagement.max() for slice in edge_data.values()])

    for name in slice_names:

        name_reformatted = re.sub(":", "_", re.sub(" - ", "_to_", name))

        svg_string = visualise_energy_engagement(
            name,
            node_data[name],
            edge_data[name],
            num_nodes=len(per_second_speech.columns),
            max_label_length=max_label_length,
            max_energy=max_energy,
            max_engagement=max_engagement)

        node_data[name].energy.to_csv(
            os.path.join(output_folder, "energy_" + name_reformatted + ".csv"))
        edge_data[name].engagement.to_csv(
            os.path.join(output_folder,
                         "engagement_" + name_reformatted + ".csv"))

        display(SVG(svg_string))

        with open(os.path.join(output_folder, name_reformatted + ".svg"),
                  "w") as file:

            file.write(svg_string)
Esempio n. 30
0
    def visualize(self,
                  saliency,
                  mol,
                  save_filepath=None,
                  visualize_ratio=1.0,
                  color_fn=red_blue_cmap,
                  scaler=abs_max_scaler,
                  legend=''):
        """Visualize or save `saliency` with molecule

        Args:
            saliency (numpy.ndarray): 1-dim saliency array (num_node,)
            mol (Chem.Mol): mol instance of this saliency
            save_filepath (str or None): If specified, file is saved to path.
            visualize_ratio (float): If set, only plot saliency color of top-X
                atoms.
            color_fn (callable): color function to show saliency
            scaler (callable): function which takes `x` as input and outputs
                scaled `x`, for plotting.
            legend (str): legend for the plot
        """
        rdDepictor.Compute2DCoords(mol)
        Chem.SanitizeMol(mol)
        Chem.Kekulize(mol)
        num_atoms = mol.GetNumAtoms()

        # --- type check ---
        if saliency.ndim != 1:
            raise ValueError("Unexpected value saliency.shape={}".format(
                saliency.shape))

        # Cut saliency array for unnecessary tail part
        saliency = saliency[:num_atoms]
        if scaler is not None:
            # Normalize to [-1, 1] or [0, 1]
            saliency = scaler(saliency)

        abs_saliency = numpy.abs(saliency)
        if visualize_ratio < 1.0:
            threshold_index = int(num_atoms * visualize_ratio)
            idx = numpy.argsort(abs_saliency)
            idx = numpy.flip(idx, axis=0)
            # set threshold to top `visualize_ratio` saliency
            threshold = abs_saliency[idx[threshold_index]]
            saliency = numpy.where(abs_saliency < threshold, 0., saliency)
        else:
            threshold = numpy.min(saliency)

        highlight_atoms = list(
            map(lambda g: g.__int__(),
                numpy.where(abs_saliency >= threshold)[0]))
        atom_colors = {i: color_fn(e) for i, e in enumerate(saliency)}
        bondlist = [bond.GetIdx() for bond in mol.GetBonds()]

        def color_bond(bond):
            begin = saliency[bond.GetBeginAtomIdx()]
            end = saliency[bond.GetEndAtomIdx()]
            return color_fn(is_visible(begin, end))

        bondcolorlist = {
            i: color_bond(bond)
            for i, bond in enumerate(mol.GetBonds())
        }
        drawer = rdMolDraw2D.MolDraw2DSVG(500, 375)
        drawer.DrawMolecule(mol,
                            highlightAtoms=highlight_atoms,
                            highlightAtomColors=atom_colors,
                            highlightBonds=bondlist,
                            highlightBondColors=bondcolorlist,
                            legend=legend)
        drawer.FinishDrawing()
        svg = drawer.GetDrawingText()
        if save_filepath:
            extention = save_filepath.split('.')[-1]
            if extention == 'svg':
                with open(save_filepath, 'w') as f:
                    f.write(svg)
            elif extention == 'png':
                # TODO (nakago): check it is possible without cairosvg or not
                try:
                    import cairosvg
                    cairosvg.svg2png(bytestring=svg, write_to=save_filepath)
                except ImportError:
                    self.logger.error(
                        'cairosvg is not installed! '
                        'Please install cairosvg to save by png format.\n'
                        'pip install cairosvg')
                    return None
            else:
                raise ValueError(
                    'Unsupported extention {} for save_filepath {}'.format(
                        extention, save_filepath))
        else:
            try:
                from IPython.core.display import SVG
                return SVG(svg.replace('svg:', ''))
            except ImportError:
                self.logger.error('IPython module failed to import, '
                                  'please install by "pip install ipython"')
                return None