Example #1
0
def showInference(bn,ie,size="4",cmap=INFOcmap):
  """
  Shows a bn annoted with results from inference : entropy and mutual informations
  """
  vals={bn.variable(n).name():ie.H(n) for n in bn.ids()}
  gr=getBN(bn,size,_normalizeVals(vals,hilightExtrema=False),cmap)

  mi=min(vals.values())
  ma=max(vals.values())

  fig = mpl.figure.Figure(figsize=(8,3))
  canvas = fc(fig)
  ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
  norm = mpl.colors.Normalize(vmin=mi, vmax=ma)
  cb1 = mpl.colorbar.ColorbarBase(ax1, cmap=cmap,
                                   norm=norm,
                                   orientation='horizontal')
  cb1.set_label('Entropy')
  png=print_figure(canvas.figure,"png") # from IPython.core.pylabtools
  png_legend="<img style='vertical-align:middle' src='data:image/png;base64,%s'>"%encodestring(png).decode('ascii')

  IPython.display.display(IPython.display.HTML("<div align='center'>"+
                              gr.data+
                              "</div><div align='center'>"+
                              "<font color='"+_proba2bgcolor(0.01,cmap)+"'>"+str(mi)+"</font>"
                              +png_legend+
                              "<font color='"+_proba2bgcolor(0.99,cmap)+"'>"+str(ma)+"</font>"
                              "</div>"))
Example #2
0
def xkcd_plot(x,
              ys,
              jiggleScale=5,
              xmin=0,
              xmax=-1,
              ymin=0,
              ymax=-1,
              ylim_min=1e-5,
              ylim_max=10,
              xticks=[[4.75, 4.75]],
              plotname="xkcd.png",
              useLabels=False,
              the_labs=None):
    xticks = []
    for xt in x:
        #        print 'tick locations' ,xt
        xticks.append([xt, xt])
    nx = np.linspace(x[0], x[-1], num=257, endpoint=True)
    #xmin = 0# x[0] - x[0] * .1
    #xmax = x[-1] + x[-1] * .1
    maxofys = np.max(ys)
    ylim_max = maxofys * 1.1
    # Add the jiggles
    scale = jiggleScale
    yn = []
    newscale = 0

    for y in ys:
        newscale = np.max([newscale, scale * np.max(y)])

    scale = newscale

    for y in ys:
        yy = np.interp(nx, x, y)
        if not useLabels:
            yy += rand_func() * scale
        yn.append(yy)

    ys = yn
    x = nx
    # Set up a figure
    fig = Figure()
    canvas = fc(fig)

    # Plot the data
    ax = fig.add_subplot(1, 1, 1)
    colors = ['c', 'r', 'g', 'b', 'y']
    verticaloffset = .003
    plts = []
    for i in range(len(ys)):
        # lay down a white line first to create overlap effect
        #        ax.plot(x[xmin:xmax], ys[i][ymin:ymax], 'white', lw=7)
        pzzz, = ax.plot(x[xmin:xmax],
                        ys[i][ymin:ymax] + verticaloffset,
                        colors[i % len(colors)],
                        lw=2)
        plts.append(pzzz)

    ax.set_xlim(x[0] * .9, x[-1] * 1.2)
    # Poor man's x-axis. There's probably a better way of doing this.
    #    xaxis = nx
    xaxis = [ylim_min] * 257
    if not useLabels:
        xaxis += rand_func() * scale / 2.5 - (ylim_max - ylim_min) * .02


#    print "axis endpoints", x[0], x[-1], xaxis[0], xaxis[-1]
    xxaxis = ((x[0:-1] - x[0] - 2) * 1.1 + (x[0] + 1.5) * 1.1)

    if useLabels:
        ax.legend(plts, the_labs, loc='upper left')
    ax.set_ylim(np.min(xaxis) * 4, ylim_max * 1.1)

    # Poor man's x-ticks
    #    for x in xticks:
    #        yaxis = [-0.001, 0.001]
    #        ax.plot(x, yaxis, 'k', lw=1.5)

    #    ax.set_yscale('log')
    #    ax.set_xscale('log')
    # XKCD font. This won't work on your machine. Install the font
    # and change the path to the place where you installed it.
    #prop = fm.FontProperties(fname='/Users/damon/Library/Fonts/Humor-Sans.ttf')
    #    ax.text(4.5, -0.5, 'PEAK', size=11)

    # Turn off decoration
    if not useLabels:
        ax.plot(xxaxis, xaxis[0:-1], 'k', lw=2)
        ax.arrow(xxaxis[-1],
                 xaxis[-2],
                 0.1,
                 0,
                 fc='k',
                 width=(ylim_max - ylim_min) * .001,
                 head_width=(ylim_max - ylim_min) * .03,
                 head_length=.2)
        ax.set_xticks([])
        ax.set_yticks([])
        ax.set_xticklabels([])
        ax.set_yticklabels([])
        ax.set_frame_on(False)

    return fig

    # Turn off all clipping
    def noclip(ax):
        "Turn off all clipping in axes ax; call immediately before drawing"
        ax.set_clip_on(False)
        artists = []
        artists.extend(ax.collections)
        artists.extend(ax.patches)
        artists.extend(ax.lines)
        artists.extend(ax.texts)
        artists.extend(ax.artists)
        for a in artists:
            a.set_clip_on(False)

    noclip(ax)

    # Save
    fig.savefig(plotname)
Example #3
0
    b = signal.firwin(20, 0.15, window=('kaiser', 8))
    response = signal.lfilter(b,1,coeffs)+1
    return response

# Make some data
x = linspace(1.0, 9.0, num=257, endpoint=True)
y1 = 1.5 + 10.0 * (sin(x) * sin(x) / sqrt(x)) * exp(-0.5 * (x - 5.0) * (x - 5.0))
y2 = 3.0 + 10.0 * (sin(x) * sin(x) / sqrt(x)) * exp(-0.5 * (x - 7.0) * (x - 7.0))

y1 *= rand_func()
y2 *= rand_func()
x *= rand_func()

# Set up a figure
fig = figure()
canvas = fc(fig)
# Plot the data
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y1, 'c', lw=2)
ax.plot(x, y2, 'white', lw=7)
ax.plot(x, y2, 'r', lw=2)
ax.set_ylim(0, 8)
ax.set_xlim(0, 10)

# Poor man's x-axis. There's probably a better way of doing this.
yaxis = [1.0] * 257 * rand_func(3)
xaxis = linspace(0.5,9,257)
#xaxis *= rand_func()
ax.plot(xaxis, yaxis, 'k', lw=2)
ax.arrow(9, 1, 0.1, 0, fc='k', lw=2, head_width=0.2, head_length=0.15)
# Poor man's x-tick
Example #4
0
File: xkcd.py Project: afcarl/viz

# Make some data
x = linspace(1.0, 9.0, num=257, endpoint=True)
y1 = 1.5 + 10.0 * (sin(x) * sin(x) / sqrt(x)) * exp(-0.5 * (x - 5.0) *
                                                    (x - 5.0))
y2 = 3.0 + 10.0 * (sin(x) * sin(x) / sqrt(x)) * exp(-0.5 * (x - 7.0) *
                                                    (x - 7.0))

y1 *= rand_func()
y2 *= rand_func()
x *= rand_func()

# Set up a figure
fig = figure()
canvas = fc(fig)
# Plot the data
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y1, 'c', lw=2)
ax.plot(x, y2, 'white', lw=7)
ax.plot(x, y2, 'r', lw=2)
ax.set_ylim(0, 8)
ax.set_xlim(0, 10)

# Poor man's x-axis. There's probably a better way of doing this.
yaxis = [1.0] * 257 * rand_func(3)
xaxis = linspace(0.5, 9, 257)
#xaxis *= rand_func()
ax.plot(xaxis, yaxis, 'k', lw=2)
ax.arrow(9, 1, 0.1, 0, fc='k', lw=2, head_width=0.2, head_length=0.15)
# Poor man's x-tick
Example #5
0
def _reprInformation(bn, evs=None, size=None, cmap=_INFOcmap, asString=False):
    """
  repr a bn annotated with results from inference : Information and mutual information

  Parameters
  ----------
  bn: pyAgrum.BayesNet
    the model
  evs: Dict[str|int,str|int|List[float]]
    the observations
  size: int|str
    size of the rendered graph
  cmap: matplotlib.colours.Colormap
    the cmap
  asString: bool
    returns the string or display the HTML

  Returns
  -------
  str|None
    return the HTML string or directly display it.
  """
    if size is None:
        size = gum.config["notebook", "default_graph_size"]

    if evs is None:
        evs = {}

    gr, mi, ma = getInformationGraph(bn, evs, size, cmap, withMinMax=True)
    # dynamic member makes pylink unhappy
    # pylint: disable=no-member
    gsvg = IPython.display.SVG(gr.create_svg(encoding="utf-8"))
    width = int(gsvg.data.split("width=")[1].split('"')[1].split("pt")
                [0]) / mpl.pyplot.rcParams['figure.dpi']  # pixel in inches
    if width < 5:
        width = 5

    fig = mpl.figure.Figure(figsize=(width, 1))
    fig.patch.set_alpha(0)
    canvas = fc(fig)
    ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
    norm = mpl.colors.Normalize(vmin=mi, vmax=ma)
    cb1 = mpl.colorbar.ColorbarBase(ax1,
                                    cmap=cmap,
                                    norm=norm,
                                    orientation='horizontal')
    cb1.set_label('Entropy')
    cb1.ax.text(mi,
                -2,
                f"{mi:.4f}",
                ha='left',
                va='top',
                color=gumcols.proba2bgcolor(0.01, cmap))
    cb1.ax.text(ma,
                -2,
                f"{ma:.4f}",
                ha='right',
                va='top',
                color=gumcols.proba2bgcolor(0.99, cmap))
    png = IPython.core.pylabtools.print_figure(
        canvas.figure, "png")  # from IPython.core.pylabtools
    png_legend = f"<img style='vertical-align:middle' src='data:image/png;base64,{encodebytes(png).decode('ascii')}'>"

    sss = f"<div align='center'>{gsvg.data}<br/>{png_legend}</div>"

    if asString:
        return sss

    return IPython.display.display(IPython.display.HTML(sss))
Example #6
0
def xkcd_plot (x,ys,jiggleScale=5,xmin=0,xmax=-1,ymin=0,ymax=-1,ylim_min=1e-5,ylim_max=10,xticks=[[4.75,4.75]],plotname="xkcd.png",useLabels=False,
the_labs=None): 
    xticks = []
    for xt in x: 
#        print 'tick locations' ,xt
        xticks.append([xt,xt])
    nx = np.linspace(x[0], x[-1], num=257, endpoint=True)
    #xmin = 0# x[0] - x[0] * .1
    #xmax = x[-1] + x[-1] * .1
    maxofys = np.max(ys)
    ylim_max = maxofys*1.1
    # Add the jiggles
    scale = jiggleScale
    yn = []
    newscale = 0; 

    for y in ys: 
        newscale = np.max([newscale,scale*np.max(y)])

    scale = newscale

    for y in ys: 
        yy = np.interp(nx,x,y)
        if not useLabels:
            yy += rand_func() * scale 
        yn.append(yy)

    ys = yn
    x  = nx
    # Set up a figure
    fig = Figure()
    canvas = fc(fig)
 
# Plot the data
    ax = fig.add_subplot(1, 1, 1)
    colors = ['c','r','g','b','y']
    verticaloffset = .003
    plts = []
    for i  in range(len(ys)): 
        # lay down a white line first to create overlap effect
#        ax.plot(x[xmin:xmax], ys[i][ymin:ymax], 'white', lw=7)
        pzzz, = ax.plot(x[xmin:xmax], ys[i][ymin:ymax]+verticaloffset, colors[i%len(colors)], lw=2)
        plts.append(pzzz)


    
    ax.set_xlim(x[0]*.9,x[-1]*1.2)
    # Poor man's x-axis. There's probably a better way of doing this.
#    xaxis = nx
    xaxis = [ylim_min] * 257
    if not useLabels:
        xaxis += rand_func() * scale/2.5-(ylim_max-ylim_min)*.02
#    print "axis endpoints", x[0], x[-1], xaxis[0], xaxis[-1]
    xxaxis = ((x[0:-1]-x[0]-2)*1.1+(x[0]+1.5)*1.1)


    if useLabels:
        ax.legend(plts, the_labs,loc='upper left')
    ax.set_ylim(np.min(xaxis)*4, ylim_max*1.1)
 
    # Poor man's x-ticks
#    for x in xticks: 
#        yaxis = [-0.001, 0.001]
#        ax.plot(x, yaxis, 'k', lw=1.5)

#    ax.set_yscale('log')
#    ax.set_xscale('log')
    # XKCD font. This won't work on your machine. Install the font
    # and change the path to the place where you installed it.
    #prop = fm.FontProperties(fname='/Users/damon/Library/Fonts/Humor-Sans.ttf')
#    ax.text(4.5, -0.5, 'PEAK', size=11)
    
   # Turn off decoration
    if not useLabels:
        ax.plot(xxaxis, xaxis[0:-1], 'k', lw=2)
        ax.arrow(xxaxis[-1], xaxis[-2], 0.1, 0, fc='k', width=(ylim_max-ylim_min)*.001,head_width= (ylim_max-ylim_min)*.03, head_length=.2)
        ax.set_xticks([])
        ax.set_yticks([])
        ax.set_xticklabels([])
        ax.set_yticklabels([])
        ax.set_frame_on(False)

    return fig
 
# Turn off all clipping
    def noclip(ax): 
        "Turn off all clipping in axes ax; call immediately before drawing" 
        ax.set_clip_on(False) 
        artists = [] 
        artists.extend(ax.collections) 
        artists.extend(ax.patches) 
        artists.extend(ax.lines) 
        artists.extend(ax.texts) 
        artists.extend(ax.artists) 
        for a in artists: 
            a.set_clip_on(False) 
    noclip(ax)
 
# Save
    fig.savefig(plotname)