Example #1
0
 def dump_match_img(qres, ibs, aid, qreq_=None, fnum=None, *args, **kwargs):
     import plottool as pt
     import matplotlib as mpl
     # Pop save kwargs from kwargs
     save_keys = ['dpi', 'figsize', 'saveax', 'fpath', 'fpath_strict', 'verbose']
     save_vals = ut.dict_take_pop(kwargs, save_keys, None)
     savekw = dict(zip(save_keys, save_vals))
     fpath = savekw.pop('fpath')
     if fpath is None and 'fpath_strict' not in savekw:
         savekw['usetitle'] = True
     was_interactive = mpl.is_interactive()
     if was_interactive:
         mpl.interactive(False)
     # Make new figure
     if fnum is None:
         fnum = pt.next_fnum()
     #fig = pt.figure(fnum=fnum, doclf=True, docla=True)
     fig = pt.plt.figure(fnum)
     fig.clf()
     # Draw Matches
     ax, xywh1, xywh2 = qres.show_matches(ibs, aid, colorbar_=False, qreq_=qreq_, fnum=fnum, **kwargs)
     if not kwargs.get('notitle', False):
         pt.set_figtitle(qres.make_smaller_title())
     # Save Figure
     # Setting fig=fig might make the dpi and figsize code not work
     img_fpath = pt.save_figure(fpath=fpath, fig=fig, **savekw)
     if was_interactive:
         mpl.interactive(was_interactive)
     pt.plt.close(fig)  # Ensure that this figure will not pop up
     #if False:
     #    ut.startfile(img_fpath)
     return img_fpath
Example #2
0
    def __init__(   self, path='', codes=None, difficulties=None, df=None, user=None, place_asked=None,
                    lower_bound = 50,upper_bound = 236, session_numbers=True):    
        """Sets matplotlib to be non-interactive. All other defaults are same as in Drawable.
        """

        Drawable.__init__(self, path, codes,difficulties, df,user,place_asked,lower_bound,upper_bound,session_numbers)
        interactive(False) #disable matplotlib interactivity
Example #3
0
def visualize(M_pri, C_pri, E, lps, nug):
    """
    Shows the EP algorithm's approximate posterior superimposed on the true posterior.
    Requires a fitted EP object as an input.
    """
    import matplotlib
    matplotlib.interactive(True)
    k=0
    
    x = linspace(E.M_pri[k] - 4.*np.sqrt(E.C_pri[k,k]), E.M_pri[k] + 4.*np.sqrt(E.C_pri[k,k]), 500)
    
    pri_real = norm_dens(x, M_pri[k], C_pri[k,k])
    norms = np.random.normal(size=10000)*np.sqrt(nug[k])
    
    def this_lp(x, k=k, norms=norms):
        return np.array([pm.flib.logsum(lps[k](xi + norms)) - np.log((len(norms))) for xi in x])
        
    like_real = this_lp(x)
    where_real_notnan = np.where(1-np.isnan(like_real))
    x_realplot = x[where_real_notnan]
    like_real = like_real[where_real_notnan]
    like_real = np.exp(like_real - like_real.max())
    like_approx = norm_dens(x, E.mu[k], E.V[k] + nug[k])
    post_real = like_real * pri_real[where_real_notnan]
    
    smoove_mat = np.asarray(pm.gp.cov_funs.gaussian.euclidean(x_realplot,x_realplot,amp=1,scale=.1))
    smoove_mat /= np.sum(smoove_mat, axis=0)
    # like_real = np.dot(smoove_mat, like_real)
    # post_real = np.dot(smoove_mat, post_real)
    post_real /= post_real.max() 
    
    post_approx = norm_dens(x, E.M[k], E.C[k,k])
    post_approx2 = pri_real * like_approx
    post_approx2 /= post_approx2.sum()
    
    post_approx /= post_approx.sum()
    post_real /= post_real.sum()
    like_real *= post_real.max()/like_real.max()      
    pri_real *= post_real.max()
    like_approx *= post_approx.max() / like_approx.max()
    
    # figure(1, figsize=(9,6))
    clf()
    plot(x, pri_real, 'g:', linewidth=2, label='Prior')
    plot(x_realplot, like_real, 'b-.', linewidth=2, label='Likelihood')
    plot(x, like_approx, 'r-.', linewidth=2, label='Approx. likelihood')
    plot(x_realplot, post_real, 'b-', linewidth=2, label='Posterior')
    plot(x, post_approx, 'r-', linewidth=2, label='Approx. posterior')
    plot(x, post_approx2, 'g-', linewidth=2, label='Approx. posterior meth 2')
    legend(loc=0).legendPatch.set_alpha(0.)
    xlabel(r'$f(x)$')
    axis('tight')
    m1r = sum(x[where_real_notnan]*post_real)/sum(post_real)
    m1em2 = sum(x*post_approx2)/sum(post_approx2)
    m1em = sum(x*post_approx)/sum(post_approx)
    m2r = sum(x[where_real_notnan]**2*post_real)/sum(post_real)
    m2em = sum(x**2*post_approx)/sum(post_approx)
    m2em2 = sum(x**2*post_approx2)/sum(post_approx2)
    print 'Posterior means: real: %s, EM: %s EM2: %s' % (m1r, m1em, m1em2)
    print 'Posterior variances: real: %s, EM: %s EM2: %s' % (m2r-m1r**2, m2em-m1em**2, m2em2-m1em2**2)
Example #4
0
def main():
    import wafo.spectrum.models as sm
    import matplotlib
    matplotlib.interactive(True)
    Sj = sm.Jonswap()
    S = Sj.tospecdata()  # Make spec
    S.plot()
    R = S.tocovdata(rate=3)
    R.plot()
    x = R.sim(ns=1024 * 4)
    inds = np.hstack((21 + np.arange(20),
                     1000 + np.arange(20),
                     1024 * 4 - 21 + np.arange(20)))
    sample, mu1o, mu1o_std = R.simcond(x[:, 1], method='approx',
                                       i_unknown=inds)

    import matplotlib.pyplot as plt
    # inds = np.atleast_2d(inds).reshape((-1,1))
    plt.plot(x[:, 1], 'k.', label='observed values')
    plt.plot(inds, mu1o, '*', label='mu1o')
    plt.plot(inds, sample.ravel(), 'r+', label='samples')
    plt.plot(inds, mu1o - 2 * mu1o_std, 'r',
             inds, mu1o + 2 * mu1o_std, 'r', label='2 stdev')
    plt.legend()
    plt.show('hold')
def activate_matplotlib(backend):
    """Activate the given backend and set interactive to True."""

    import matplotlib
    if backend.startswith('module://'):
        # Work around bug in matplotlib: matplotlib.use converts the
        # backend_id to lowercase even if a module name is specified!
        matplotlib.rcParams['backend'] = backend
    else:
        matplotlib.use(backend)
    matplotlib.interactive(True)

    # This must be imported last in the matplotlib series, after
    # backend/interactivity choices have been made
    import matplotlib.pylab as pylab

    # XXX For now leave this commented out, but depending on discussions with
    # mpl-dev, we may be able to allow interactive switching...
    #import matplotlib.pyplot
    #matplotlib.pyplot.switch_backend(backend)

    pylab.show._needmain = False
    # We need to detect at runtime whether show() is called by the user.
    # For this, we wrap it into a decorator which adds a 'called' flag.
    pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive)
Example #6
0
    def pre_interact(self):
        """Initialize matplotlib before user interaction begins"""

        push = self.shell.push
        # Code to execute in user's namespace
        lines = ["import matplotlib",
                 "matplotlib.use('GTKAgg')",
                 "matplotlib.interactive(1)",
                 "import matplotlib.pylab as pylab",
                 "from matplotlib.pylab import *\n"]

        map(push,lines)

        # Execute file if given.
        if len(sys.argv)>1:
            import matplotlib
            matplotlib.interactive(0) # turn off interaction
            fname = sys.argv[1]
            try:
                inFile = file(fname, 'r')
            except IOError:
                print('*** ERROR *** Could not read file <%s>' % fname)
            else:
                print('*** Executing file <%s>:' % fname)
                for line in inFile:
                    if line.lstrip().find('show()')==0: continue
                    print('>>', line)
                    push(line)
                inFile.close()
            matplotlib.interactive(1)   # turn on interaction
Example #7
0
def _on_config_change():
    # dpi
    dpi = _config['dpi']
    matplotlib.rcParams['savefig.dpi'] = dpi
    matplotlib.rcParams['figure.dpi'] = dpi
    
    # Width and height
    width = float(_config['width']) / dpi
    height = float(_config['height']) / dpi
    matplotlib.rcParams['figure.figsize'] = (width, height)
    
    # Font size
    fontsize = _config['fontsize']
    matplotlib.rcParams['font.size'] = fontsize
    
    # Default Figure Format
    fmt = _config['format']
    supported_formats = _config['supported_formats']
    if fmt not in supported_formats:
        raise ValueError("Unsupported format %s" %fmt)
    matplotlib.rcParams['savefig.format'] = fmt
    
    # Interactive mode
    interactive = _config['interactive']
    matplotlib.interactive(interactive)
Example #8
0
    def mpl_execfile(fname,*where,**kw):
        """matplotlib-aware wrapper around safe_execfile.

        Its interface is identical to that of the :func:`execfile` builtin.

        This is ultimately a call to execfile(), but wrapped in safeties to
        properly handle interactive rendering."""

        import matplotlib
        import matplotlib.pyplot as plt

        #print '*** Matplotlib runner ***' # dbg
        # turn off rendering until end of script
        is_interactive = matplotlib.rcParams['interactive']
        matplotlib.interactive(False)
        safe_execfile(fname,*where,**kw)
        matplotlib.interactive(is_interactive)
        # make rendering call now, if the user tried to do it
        if plt.draw_if_interactive.called:
            plt.draw()
            plt.draw_if_interactive.called = False

        # re-draw everything that is stale
        try:
            da = plt.draw_all
        except AttributeError:
            pass
        else:
            da()
Example #9
0
def matplotlib_interactive(interactive=False):
    import matplotlib

    if not interactive:
        matplotlib.use("Agg")  # allows running without X11 on compute nodes
    matplotlib.interactive(interactive)
    return interactive
Example #10
0
 def show(self):
     self.fig.canvas.mpl_connect('motion_notify_event', self.update)
     #self.fig.canvas.mpl_connect('button_press_event', self.on_button_press)
     self.fig.canvas.mpl_connect('axes_leave_event', self.on_leave_axes)
     self.fig.canvas.mpl_connect('resize_event', self.on_resize)
     matplotlib.interactive(False)   # Need this or there is not sys.exit
     pylab.show()
Example #11
0
def run_script(args):
    
    matplotlib.interactive(False)
    
    Rprop0 = args.Rpp0 
    Rprop1 = args.Rpp1    
            
    theta = np.arange(args.theta[0], args.theta[1], args.theta[2])
        
    warray_amp = create_theta_spike(args.pad,
                                    Rprop0, Rprop1, theta,
                                    args.f, args.points, args.reflectivity_method)
    
    fig = plt.figure()
    ax1 = fig.add_subplot(111)

    plt.gray()
    aspect = float(warray_amp.shape[1]) / warray_amp.shape[0]
    ax1.imshow(warray_amp, aspect=aspect, cmap=args.colour)
    
    plt.title(args.title % locals())
    plt.ylabel('time (ms)')
    plt.xlabel('trace')
    
    fig_path = tempfile.mktemp('.jpeg')
    plt.savefig(fig_path)
    
    with open(fig_path, 'rb') as fd:
        data = fd.read()
        
    unlink(fig_path)
        
    return data
Example #12
0
    def __init__(self, fig, ax, points, verbose=False):
        matplotlib.interactive(True)
        if points is None:
            raise RuntimeError("""First add points to a figure or canvas.""")
        canvas = fig.canvas
        self.ax = ax
        self.dragged = None
        self.points = points
        self.verbose = verbose
        x, y = get_pointsxy(points)
        self.line = Line2D(x, y, marker='o', markerfacecolor='r',
                           linestyle='none', animated=True)
        self.ax.add_line(self.line)

        if False:  # FIXME:  Not really sure how to use this.
            cid = self.points.add_callback(self.points_changed)
        self._ind = None  # The active point.

        canvas.mpl_connect('draw_event', self.draw_callback)
        canvas.mpl_connect('button_press_event', self.button_press_callback)
        canvas.mpl_connect('key_press_event', self.key_press_callback)
        canvas.mpl_connect('button_release_event',
                           self.button_release_callback)
        canvas.mpl_connect('motion_notify_event', self.motion_notify_callback)
        self.canvas = canvas
Example #13
0
def run_script(args):
    
    matplotlib.interactive(False)
    
    array_amp = np.zeros([args.time])
    array_time = np.arange(args.time)
    
    Rpp = args.reflectivity_model(args.Rpp0, args.Rpp1, args.theta1)
    
    array_amp[args.time // 2] = Rpp
    
    r = ricker_alg(1,128, args.f)
    
    warray_amp = np.convolve(array_amp, r, mode='same')
    
    fig = plt.figure()
    
    ax1 = fig.add_subplot(111)

    ax1.plot(warray_amp, array_time)
    
    plt.title(args.title % locals())
    plt.ylabel('time (ms)')
    plt.xlabel('amplitude')
    
    ax = plt.gca()
    ax.set_ylim(ax.get_ylim()[::-1])
    ax.set_xlim(args.xlim)
    
    return return_current_figure()
    def test_interactive_mode():
        '''
import matplotlib
matplotlib.interactive(True)
matplotlib.use('FltkAgg')

from pylab import *
plot([1,2,3])
xlabel('time (s)')

from fltk import *
window = Fl_Window(300,300)
window.label("Window Test")
window.show()
Fl.run()
        '''

        import matplotlib
        matplotlib.interactive(True)
#        matplotlib.use('FltkAgg')
        
        import pylab
#        manager = pylab.get_current_fig_manager()
        
        pylab.plot([1,2,3])
        pylab.xlabel('time (s)')
        pylab.draw()
        
        window = Fl_Window(300,300)
        window.label("Window Test")
        window.show()
        Fl.run()
Example #15
0
def plot_sphere_func(f, grid='Clenshaw-Curtis', theta=None, phi=None, colormap='jet', fignum=0):

    # Note: all grids except Clenshaw-Curtis have holes at the poles

    import matplotlib
    matplotlib.use('WxAgg')
    matplotlib.interactive(True)
    from mayavi import mlab

    if grid == 'Driscoll-Healy':
        b = f.shape[0] / 2
    elif grid == 'Clenshaw-Curtis':
        b = (f.shape[0] - 2) / 2
    elif grid == 'SOFT':
        b = f.shape[0] / 2
    elif grid == 'Gauss-Legendre':
        b = (f.shape[0] - 2) / 2

    if theta is None or phi is None:
        theta, phi = meshgrid(b=b, convention=grid)

    phi = np.r_[phi, phi[0, :][None, :]]
    theta = np.r_[theta, theta[0, :][None, :]]
    f = np.r_[f, f[0, :][None, :]]

    x = np.sin(theta) * np.cos(phi)
    y = np.sin(theta) * np.sin(phi)
    z = np.cos(theta)

    mlab.figure(fignum, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(600, 400))
    mlab.clf()
    mlab.mesh(x, y, z, scalars=f, colormap=colormap)

    # mlab.view(90, 70, 6.2, (-1.3, -2.9, 0.25))
    mlab.show()
Example #16
0
def test_matplotlib():
    import matplotlib
    import matplotlib.colors

    # Override system defaults before importing pylab
    matplotlib.use('TkAgg')
    #matplotlib.rc('text', usetex=True)
    matplotlib.interactive(True)
    from matplotlib.font_manager import fontManager, FontProperties
    import pylab

    print "matplotlib is installed in", os.path.dirname(matplotlib.__file__)
    print "matplotlib version", matplotlib.__version__
    print "matplotlib.rcParams:"
    pprint.pprint(matplotlib.rcParams)

    x = [0, 1, 2, 3, 4]
    y = [0, 1, 4, 9, 16]
    pylab.plot(x, y, 'bo-', linewidth=2.0)

    pylab.title("Hello Matplotlib!")

    pylab.draw()
    #pylab.show()  # requires manual quit of plot window
    time.sleep(0.5)
Example #17
0
    def __init__(self):

        self._draw_count = 0
        interactive = matplotlib.is_interactive()
        matplotlib.interactive(False)
        self.roi_callback = None

        self._draw_zoom_rect = None

        self.fig = Figure(facecolor=settings.BACKGROUND_COLOR)

        FigureCanvas.__init__(self, self.fig)
        FigureCanvas.setSizePolicy(self,
                                   QtWidgets.QSizePolicy.Expanding,
                                   QtWidgets.QSizePolicy.Expanding)

        FigureCanvas.updateGeometry(self)
        self.manager = FigureManager(self, 0)
        matplotlib.interactive(interactive)

        self._resize_timer = QtCore.QTimer()
        self._resize_timer.setInterval(250)
        self._resize_timer.setSingleShot(True)
        self._resize_timer.timeout.connect(self._on_timeout)

        self.renderer = None
Example #18
0
def run_script(args):

    
    matplotlib.interactive(False)
        
    left = (args.left[0], args.left[1])
    right = (args.right[0], args.right[1])


    l1 = (150,110,110)
    l2 = (110,150,110)
    l3 = (110,110,150)
    layers= [l1,l2]

    # This is a hack to conserve colors
    colourmap = { rgb(l1[0],l1[1],l1[2]): args.Rock0,
                  rgb(l2[0],l2[1],l2[2]): args.Rock1 }
    
    if not isinstance(args.Rock2, str):
        colourmap[rgb( l3[0],l3[1],l3[2])] = args.Rock2
        layers.append( l3 )
    
    model = mb.body( traces = args.ntraces,
                     pad = args.pad,
                     margin=args.margin,
                     left = left,
                     right = right,
                     layers = layers
                   )

    return modelr_plot(model, colourmap, args)
 def test_chinese_restaurant_process(self):
     print sys.path
     from matplotlib import pyplot
     import matplotlib
     from scipy import stats
     alpha = 20
     test_size = 1000
     tests = 1000
     data = [0]
     for j in range(0, tests):
         cr = ChineseRestaurant(alpha, Numbers())
         for i in range(0, test_size):
             new_sample = cr.draw()
             if new_sample >= len(data):
                 data.append(0)
             data[new_sample] += 1
         assert cr.heap[1] == test_size
     pyplot.switch_backend('Qt5Agg')
     #data=sorted(data, reverse=True)
     print len(data)
     actual_plot, = pyplot.plot(range(1,len(data)), data[1:], label='actual avg')
     expected = [0]
     remain = test_size * tests
     for i in range(1, len(data)):
         break_ = stats.beta.mean(1.0, float(alpha)) * remain
         expected.append(break_)
         remain -= break_
     #print est
     expected_plot, = pyplot.plot(range(1,len(data)), expected[1:], 'r', linewidth=1, label='expected')
     matplotlib.interactive(True)
     pyplot.ylabel("People at Table")
     pyplot.xlabel("Table Number")
     pyplot.title("Chinese Restaurant Process Unit Test")
     pyplot.legend()
     pyplot.show(block=True)
def euclSpaceMapp(gDirected,distMat,top100List,top100ListIdxs):
    print('extract euclidean space mapping')
    allCoordinates = euclideanCoords(gDirected,distMat)
    print('Mapped nodes to euclidean space')
    xpl=[x[0] for x in allCoordinates]
    minXpl = min(xpl)
    if minXpl < 0:
       aminXpl = abs(minXpl)
       xpl = np.array([x+aminXpl+1 for x in xpl])
    ypl=[x[1] for x in allCoordinates]
    minYpl = min(ypl)
    if minYpl < 0:
       aminYpl = abs(minYpl)
       ypl = np.array([y+aminYpl+1 for y in ypl])
    fig = pyplot.figure()
    ax = pyplot.gca()
    ax.scatter(xpl,ypl)
    ax.set_ylim(min(ypl)-1,max(ypl)+1)
    ax.set_xlim(min(xpl)-1,max(xpl)+1)
    labels = top100List
    for label, x, y in zip(labels, xpl[top100ListIdxs], ypl[top100ListIdxs]):
       pyplot.annotate(label, xy = (x, y), xytext = (-10, 10),textcoords = 'offset points', ha = 'right', va = 'bottom',
           bbox = dict(boxstyle = 'round,pad=0.2', fc = 'yellow', alpha = 0.5),
           arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
    interactive(True)
    pyplot.show()
    # pyplot.savefig('./images/'+str(year)+'_euclSpaceMapping_via_shortestPaths.jpg', bbox_inches='tight', format='jpg')
    pyplot.savefig('./images/'+str(year)+'_euclSpaceMapping_via_distMatrix.jpg', bbox_inches='tight', format='jpg')
    pyplot.close()
Example #21
0
def run_script(args):
    matplotlib.interactive(False)

    """if args.transparent == 'False' or args.transparent == 'No':
        transparent = False
    else:
        transparent = True"""

    args.ntraces = 300
    args.pad = 150
    args.reflectivity_method = zoeppritz
    args.title = "Channel - angle gather (AVA)"
    args.theta = (0, 50, 0.5)
    args.wavelet = ricker
    args.wiggle_skips = 10
    args.aspect_ratio = 1
    args.thickness = 50
    args.margin = 1
    args.slice = "angle"

    transparent = False
    # This is a hack to conserve colors
    l1 = (150, 110, 110)
    l2 = (110, 150, 110)
    l3 = (110, 110, 150)
    layers = [l1, l2]
    colourmap = {rgb(150, 110, 110): args.Rock0, rgb(110, 150, 110): args.Rock1}

    if not isinstance(args.Rock2, str):
        colourmap[rgb(110, 110, 150)] = args.Rock2
        layers.append(l3)
    # Get the physical model (an array of rocks)
    model = mb.channel(pad=args.pad, thickness=args.thickness, traces=args.ntraces, layers=layers)

    return modelr_plot(model, colourmap, args)
Example #22
0
    def __init__(self):
        self._draw_count = 0
        interactive = matplotlib.is_interactive()
        matplotlib.interactive(False)
        self.roi_callback = None

        self.fig = Figure(facecolor='#ffffff')
        try:
            self.fig.set_tight_layout(True)
        except AttributeError:  # matplotlib < 1.1
            pass

        FigureCanvas.__init__(self, self.fig)
        FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)

        FigureCanvas.updateGeometry(self)
        self.manager = FigureManager(self, 0)
        matplotlib.interactive(interactive)

        self._resize_timer = QTimer()
        self._resize_timer.setInterval(250)
        self._resize_timer.setSingleShot(True)
        self._resize_timer.timeout.connect(self._on_timeout)

        self.renderer = None
Example #23
0
def _on_config_change():
    # dpi
    dpi = _config['dpi']
    
    # For older versions of matplotlib, savefig.dpi is not synced with
    # figure.dpi by default
    matplotlib.rcParams['figure.dpi'] = dpi
    if matplotlib.__version__ < '2.0.0':
        matplotlib.rcParams['savefig.dpi'] = dpi
    
    # Width and height
    width = float(_config['width']) / dpi
    height = float(_config['height']) / dpi
    matplotlib.rcParams['figure.figsize'] = (width, height)
    
    # Font size
    fontsize = _config['fontsize']
    matplotlib.rcParams['font.size'] = fontsize
    
    # Default Figure Format
    fmt = _config['format']
    supported_formats = _config['supported_formats']
    if fmt not in supported_formats:
        raise ValueError("Unsupported format %s" %fmt)

    if matplotlib.__version__ < '1.2.0':
        matplotlib.rcParams.update({'savefig.format': fmt})
    else:
        matplotlib.rcParams['savefig.format'] = fmt
    
    # Interactive mode
    interactive = _config['interactive']
    matplotlib.interactive(interactive)
Example #24
0
def load_pylab():
	try:
		import matplotlib,sys
		if not 'matplotlib.backends' in sys.modules: matplotlib.interactive(True)
		import pylab
		return pylab
	except:
		print __name__, "module failed to import pylab: plotting methods will not work"
Example #25
0
def init(theModuleManager, pre_import=True):

    if hasattr(sys, 'frozen') and sys.frozen:
        # matplotlib supports py2exe by checking for matplotlibdata in the appdir
        # but this is only done on windows (and therefore works for our windows
        # installer builds).  On non-windows, we have to stick it in the env
        # to make sure that MPL finds its datadir (only if we're frozen)
        mpldir = os.path.join(theModuleManager.get_appdir(), 'matplotlibdata')
        os.environ['MATPLOTLIBDATA'] = mpldir

    
    # import the main module itself
    # this doesn't import numerix yet...
    global matplotlib
    import matplotlib

    # use WX + Agg backend (slower, but nicer that WX)
    matplotlib.use('WXAgg')
    # interactive mode: user can use pylab commands from any introspection
    # interface, changes will be made immediately and matplotlib cooperates
    # nicely with main WX event loop
    matplotlib.interactive(True)
    
    # with matplotlib 1.0.1 we can't do this anymore.
    # makes sure we use the numpy backend
    #from matplotlib import rcParams
    #rcParams['numerix'] = 'numpy'

    theModuleManager.setProgress(25, 'Initialising matplotlib_kit: config')

    # @PATCH:
    # this is for the combination numpy 1.0.4 and matplotlib 0.91.2
    # matplotlib/numerix/ma/__init__.py:
    # . normal installation fails on "from numpy.ma import *", so "from
    #   numpy.core.ma import *" is done, thus bringing in e.g. getmask
    # . pyinstaller binaries for some or other reason succeed on 
    #   "from numpy.ma import *" (no exception raised), therefore do
    #   not do "from numpy.core.ma import *", and therefore things like
    #   getmask are not imported.
    # solution:
    # we make sure that "from numpy.ma import *" actually brings in
    # numpy.core.ma by importing that and associating the module
    # binding to the global numpy.ma.
    #if hasattr(sys, 'frozen') and sys.frozen:
    #    import numpy.core.ma
    #    sys.modules['numpy.ma'] = sys.modules['numpy.core.ma']

    # import the pylab interface, make sure it's available from this namespace
    global pylab
    import pylab

    theModuleManager.setProgress(90, 'Initialising matplotlib_kit: pylab')

    # build up VERSION
    global VERSION
    VERSION = '%s' % (matplotlib.__version__,)

    theModuleManager.setProgress(100, 'Initialising matplotlib_kit: complete')
Example #26
0
def main():
    import wafo.spectrum.models as sm
    import matplotlib
    matplotlib.interactive(True)
    Sj = sm.Jonswap()
    S = Sj.tospecdata()   #Make spec
    S.plot()
    R = S.tocovdata()
    R.plot()
Example #27
0
def create(*data, **kwargs):
    """
    Create an interactive plot window for the given data.

    >>> create(dataobj(dict1, 'Title1', 'XaxisKey1',
    ...        labels=['a', 'b'], xscale='1/degree'),
    ...        dataobj(dict2, 'Title2'))

    The inputs should define data dictionaries to plot as a list
    containing the dictionary itself, a name for the dictionary to use
    in titles and labels, and optionally a dictionary of extra settings
    described below. The only optional keyword argument is `title`
    which sets the window title.

    Dictionary options allowed per data definition:
        'labels': a list of labels for 2+ dimensional data
        'xname':  a dictionary key (string) to plot on the x-axis
        'yname':  a dictionary key (string) to plot on the y-axis
        'xscale': a string or number defining scale factor for x-axis
        'yscale': a string or number defining scale factor for y-axis
    """
    app_created = False
    app = QtCore.QCoreApplication.instance()
    if app is None:
        app = QtGui.QApplication(sys.argv)
        app_created = True
    app.references = getattr(app, 'references', set())

    # Backwards compatibility
    data = list(data)
    for i, d in enumerate(data):
        if isinstance(d, dict):
            data[i] = [d, '']
        elif isinstance(d, np.ndarray) and isiterable(d.dtype.names):
            data[i] = [{n: d[n] for n in d.dtype.names}, '']
        elif isiterable(d[-1]) and len(d) == 4:
            d[-2] = {'xname': d[-2], 'labels': list(d[-1])}
            d.pop()
        elif isinstance(d[2], string_types) and len(d) >= 3:
            if len(d) == 3:
                d[-1] = {'xname': d[-1]}
            else:
                d[-1]['xname'] = d[-1].get('xname', d[2])
                d.pop(2)

    interactive = mpl.is_interactive()
    try:
        mpl.interactive(False)
        i = Interact(data, app, **kwargs)
    finally:
        mpl.interactive(interactive)
    app.references.add(i)
    i.show()
    i.raise_()
    if app_created:
        app.exec_()
    return i
Example #28
0
def showplot(**kwargs):
    """ Show the plot. """
    interactive = kwargs.get('interactive')
    if interactive is not None:
        matplotlib.interactive(interactive)
    print("Showing plot...")
    pyplot.show()
    if interactive:
        # from code import InteractiveConsole
        import code
        code.interact("Interact with the data...")
Example #29
0
def load_pylab():
	try:
		import matplotlib,sys
		set_interactive = ('matplotlib.backends' not in sys.modules)
		if set_interactive: matplotlib.interactive(True)
		import pylab
	except:
		print __name__, "module failed to import pylab: plotting methods will not work"
	else:
		if set_interactive and hasattr(pylab, 'ion'): pylab.ion()
		return pylab
    def begin(self,inference):
        print "begin"
        self.visitNr=1
        self.gm=inference.gm()
        self.labelVector=opengm.LabelVector()
        self.labelVector.resize(self.gm.numberOfVariables)
        matplotlib.interactive(True)
        self.fig = plt.figure()
        self.cmap = matplotlib.colors.ListedColormap ( numpy.random.rand ( self.numLabels,3))

        win = self.fig.canvas.manager.window
Example #31
0
def xyz2d(xyz, b_show=False):
    """

    :param xyz: array of shape (N, 3) last dimention for x, y and z
    :param b_show: show matplotlib plot of result grid
    :return: (z2d, x_min, y_min, x_resolution, y_resolution) suits to input to save_grd()
    """

    x_uniq = np.unique(xyz[:, 0])
    y_uniq = np.unique(xyz[:, 1])

    idx = np.lexsort(xyz[:, :-1].T, axis=0)
    if np.array_equal(idx, np.arange(xyz.shape[0])):
        # input data is conformed to grid
        idx = idx.reshape(y_uniq.size, x_uniq.size)
        x2d, y2d, z2d = xyz[idx, :].T
    else:
        print('input data is not conformed to grid')

        # I'm fairly sure there's a more efficient way of doing this...
        def get_z(xyz, x, y):
            ind = (xyz[:, (0, 1)] == (x, y)).all(axis=1)
            row = xyz[ind, :]
            return row[0, 2]

        x2d, y2d = np.meshgrid(x_uniq, y_uniq)
        z = np.array(
            [get_z(xyz, x, y) for (x, y) in zip(np.ravel(x2d), np.ravel(y2d))])
        z2d = z.reshape(x2d.shape)

    x_min, x_max = x_uniq[[0, -1]]
    y_min, y_max = y_uniq[[0, -1]]
    x_resolution = np.diff(x2d[:2, 0]).item()
    y_resolution = np.diff(y2d[0, :2]).item()

    # check grid is ok
    assert x_min == x2d[0, 0]
    assert y_min == y2d[0, 0]
    assert x_resolution == (x_max - x_min) / (x_uniq.size - 1)
    assert y_resolution == (y_max - y_min) / (y_uniq.size - 1)

    if b_show:
        # graphics/interactivity
        if True:  # __debug__:
            import matplotlib

            matplotlib.rcParams['axes.linewidth'] = 1.5
            matplotlib.rcParams['figure.figsize'] = (16, 7)
            try:
                matplotlib.use(
                    'Qt5Agg'
                )  # must be before importing plt (raises error after although docs said no effect)
            except ImportError:
                pass
            from matplotlib import pyplot as plt

            matplotlib.interactive(True)
            plt.style.use('bmh')

        plt.pcolormesh(x2d, y2d, z2d)
        plt.xlim(x_min, x_max)
        plt.ylim(y_min, y_max)
        plt.show()

    return z2d, x_min, y_max, x_resolution, y_resolution
Example #32
0
def default_globals():
    """Creates default globals for code that the client side can execute.

    This is geared for convenient (not necessarily efficient) plotting
    with `matplotlib`.
    """
    # @note This imports modules at a function-scope rather than at a
    # module-scope, which does not satisfy PEP8. This is intentional, as it
    # allows for a cleaner scope separation between the client core code (e.g.
    # `CallPythonClient`) and the client user code (e.g. `plot(x, y)`).
    # TODO(eric.cousineau): Consider relegating this to a different module,
    # possibly when this falls under `pydrake`.
    import numpy as np
    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib
    import matplotlib.pyplot as plt
    import pylab  # See `%pylab?` in IPython.

    # TODO(eric.cousineau): Where better to put this?
    matplotlib.interactive(True)
    _fix_pyplot(plt)

    def disp(value):
        """Alias for print."""
        print(value)

    def wait():
        """Waits to allow user interaction with plots."""
        plt.show(block=True)

    def pause(interval):
        """Pause for `interval` seconds, letting the GUI flush its event queue.

        @note This is a *necessary* function to be defined if these globals are
        not used!
        """
        plt.pause(interval)

    def box(bmin, bmax, rstride=1, cstride=1, **kwargs):
        """Plots a box bmin[i] <= x[i] <= bmax[i] for i < 3."""
        fig = plt.gcf()
        ax = fig.gca(projection='3d')
        u = np.linspace(1, 9, 5) * np.pi / 4
        U, V = np.meshgrid(u, u)
        cx, cy, cz = (bmax + bmin) / 2
        dx, dy, dz = bmax - bmin
        X = cx + dx * np.cos(U) * np.sin(V)
        Y = cy + dy * np.sin(U) * np.sin(V)
        Z = cz + dz * np.cos(V) / np.sqrt(2)
        ax.plot_surface(X, Y, Z, rstride=rstride, cstride=cstride, **kwargs)

    def plot3(x, y, z, **kwargs):
        """Plots a 3d line plot."""
        fig = plt.gcf()
        ax = fig.gca(projection='3d')
        ax.plot(x, y, z, **kwargs)

    def sphere(n, rstride=1, cstride=1, **kwargs):
        """Plots a sphere."""
        fig = plt.gcf()
        ax = fig.gca(projection='3d')
        u = np.linspace(0, np.pi, n)
        v = np.linspace(0, 2 * np.pi, n)
        X = np.outer(np.sin(u), np.sin(v))
        Y = np.outer(np.sin(u), np.cos(v))
        Z = np.outer(np.cos(u), np.ones_like(v))
        ax.plot_surface(X, Y, Z, rstride=rstride, cstride=cstride, **kwargs)

    def surf(x, y, Z, rstride=1, cstride=1, **kwargs):
        """Plots a 3d surface."""
        fig = plt.gcf()
        ax = fig.gca(projection='3d')
        X, Y = np.meshgrid(x, y)
        ax.plot_surface(X, Y, Z, rstride=rstride, cstride=cstride, **kwargs)

    def show():
        """Shows `matplotlib` images without blocking.

        Generally not needed if `matplotlib.is_interactive()` is true.
        """
        plt.show(block=False)

    def magic(N):
        """Provides simple odd-only case for magic squares.

        @ref https://scipython.com/book/chapter-6-numpy/examples/creating-a-magic-square  # noqa
        """
        assert N % 2 == 1
        magic_square = np.zeros((N, N), dtype=int)
        n = 1
        i, j = 0, N // 2
        while n <= N**2:
            magic_square[i, j] = n
            n += 1
            newi, newj = (i - 1) % N, (j + 1) % N
            if magic_square[newi, newj]:
                i += 1
            else:
                i, j = newi, newj
        return magic_square

    # Use <module>.__dict__ to simulate `from <module> import *`, since that is
    # normally invalid in a function with nested functions.
    return _merge_dicts(globals(), plt.__dict__, pylab.__dict__, locals())
Example #33
0
from __future__ import division

import os
import shutil
import warnings
import datetime
warnings.filterwarnings("ignore")
import numpy as np
import nibabel as nib
import matplotlib
import matplotlib.style
matplotlib.use('Agg')   # generate pdf output by default
matplotlib.interactive(False)
matplotlib.style.use('classic')
from matplotlib.backends.backend_pdf import PdfPages
from eddy_qc.QUAD import (quad_tables, quad_mot, quad_s2v_mot, quad_eddy, 
                            quad_ol_mat, quad_cnr_maps, quad_cnr_msr, 
                            quad_avg_maps, quad_susc, quad_json)
from eddy_qc.utils import (fslpy, utils, ref_page)


#=========================================================================================
# FSL QUAD (QUality Assessment for DMRI)
# Matteo Bastiani
# 01-06-2017, FMRIB, Oxford
#=========================================================================================
def main(eddyBase, eddyIdx, eddyParams, mask, bvalsFile, bvecsFile, oDir, field, slspecFile, verbose):
    """
    Generate a QC report pdf for single subject dMRI data.
    The script will look for EDDY output files that are generated according to the user
    specified options. If a feature (e.g., output the CNR maps) has not been used, then
def line_profile(
        image,
        order=2,
        plotter=None,  # noqa: C901
        comparisons=None,
        **viewer_kwargs):
    """View the image with a line profile.

    Creates and returns an ipywidget to visualize the image along with a line
    profile.

    The image can be 2D or 3D.

    Parameters
    ----------
    image : array_like, itk.Image, or vtk.vtkImageData
        The 2D or 3D image to visualize.

    order : int, optional
        Spline order for line profile interpolation. The order has to be in the
        range 0-5.

    plotter : 'plotly', 'bqplot', or 'ipympl', optional
        Plotting library to use. If not defined, use plotly if available,
        otherwise bqplot if available, otherwise ipympl.

    comparisons: dict, optional
        A dictionary whose keys are legend labels and whose values are other
        images whose intensities to plot over the same line.

    viewer_kwargs : optional
        Keyword arguments for the viewer. See help(itkwidgets.view).

    """

    profiler = LineProfiler(image=image, order=order, **viewer_kwargs)

    if not plotter:
        try:
            import plotly.graph_objs as go
            plotter = 'plotly'
        except ImportError:
            pass
    if not plotter:
        try:
            import bqplot
            plotter = 'bqplot'
        except ImportError:
            pass
    if not plotter:
        plotter = 'ipympl'

    if plotter == 'plotly':
        layout = go.Layout(xaxis=dict(title='Distance'),
                           yaxis=dict(title='Intensity'))
        fig = go.FigureWidget(layout=layout)
    elif plotter == 'bqplot':
        x_scale = bqplot.LinearScale()
        y_scale = bqplot.LinearScale()
        x_axis = bqplot.Axis(scale=x_scale,
                             grid_lines='solid',
                             label='Distance')
        y_axis = bqplot.Axis(scale=y_scale,
                             orientation='vertical',
                             grid_lines='solid',
                             label='Intensity')
        labels = ['Reference']
        display_legend = False
        if comparisons:
            display_legend = True
            labels += [label for label in comparisons.keys()]
        lines = [
            bqplot.Lines(scales={
                'x': x_scale,
                'y': y_scale
            },
                         labels=labels,
                         display_legend=display_legend,
                         enable_hover=True)
        ]
        fig = bqplot.Figure(marks=lines, axes=[x_axis, y_axis])
    elif plotter == 'ipympl':
        ipython = IPython.get_ipython()
        ipython.enable_matplotlib('widget')

        matplotlib.interactive(False)

        fig, ax = plt.subplots()
    else:
        raise ValueError('Invalid plotter: ' + plotter)

    def update_plot():
        if plotter == 'plotly':
            distance, intensity = profiler.get_profile(image)
            fig.data[0]['x'] = distance
            fig.data[0]['y'] = intensity
            if comparisons:
                for ii, image_ in enumerate(comparisons.values()):
                    distance, intensity = profiler.get_profile(image_)
                    fig.data[ii + 1]['x'] = distance
                    fig.data[ii + 1]['y'] = intensity
        elif plotter == 'bqplot':
            distance, intensity = profiler.get_profile(image)
            if comparisons:
                for image_ in comparisons.values():
                    distance_, intensity_ = profiler.get_profile(image_)
                    distance = np.vstack((distance, distance_))
                    intensity = np.vstack((intensity, intensity_))
            fig.marks[0].x = distance
            fig.marks[0].y = intensity
        elif plotter == 'ipympl':
            ax.plot(*profiler.get_profile(image))
            if comparisons:
                ax.plot(*profiler.get_profile(image), label='Reference')
                for label, image_ in comparisons.items():
                    ax.plot(*profiler.get_profile(image_), label=label)
                ax.legend()
            else:
                ax.plot(*profiler.get_profile(image))

            ax.set_xlabel('Distance')
            ax.set_ylabel('Intensity')
            fig.canvas.draw()
            fig.canvas.flush_events()

    def update_profile(change):
        if plotter == 'plotly':
            update_plot()
        elif plotter == 'bqplot':
            update_plot()
        elif plotter == 'ipympl':
            is_interactive = matplotlib.is_interactive()
            matplotlib.interactive(False)
            ax.clear()
            update_plot()
            matplotlib.interactive(is_interactive)

    if plotter == 'plotly':
        distance, intensity = profiler.get_profile(image)
        trace = go.Scattergl(x=distance, y=intensity, name='Reference')
        fig.add_trace(trace)
        if comparisons:
            for label, image_ in comparisons.items():
                distance, intensity = profiler.get_profile(image_)
                trace = go.Scattergl(x=distance, y=intensity, name=label)
                fig.add_trace(trace)
        widget = widgets.VBox([profiler, fig])
    elif plotter == 'bqplot':
        update_plot()
        widget = widgets.VBox([profiler, fig])
    elif plotter == 'ipympl':
        update_plot()
        widget = widgets.VBox([profiler, fig.canvas])

    profiler.observe(update_profile, names=['point1', 'point2'])

    return widget
Example #35
0
# Script to demonstrate Bolton's "pixelsplines" code.
#
# Meant to be executed incrementally/interactively
# from a Python command line.
#
# bolton@utah2013may
#

# Import statements.
import os
import numpy as n
import matplotlib as m

m.rc('text', usetex=True)
m.use('TkAgg')
m.interactive(True)
m.rc('font', size=16)
from matplotlib import pyplot as p
#import pyfits as pf
from astropy.io import fits as pf
import pixelsplines as pxs

# We'll assume that you have an up-to-date idlspec2d
# from which we'll get the toy data to play with:
tfile = os.getenv('IDLSPEC2D_DIR') + '/templates/spEigenStar-55734.fits'
hdulist = pf.open(tfile)
flux = hdulist[0].data
npix = hdulist[0].header['NAXIS1']
nstar = hdulist[0].header['NAXIS2']
coeff0 = hdulist[0].header['COEFF0']
coeff1 = hdulist[0].header['COEFF1']
Example #36
0
"""Tools for making bar plots for finance data.
"""

import tempfile
import os
import subprocess
import logging

import pandas
import matplotlib              # Need these lines to prevent emacs hanging or
matplotlib.interactive(False)  # exceptions when using non-GUI virtual machine
matplotlib.use('PS')           # in an interactive session 
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, MonthLocator
from matplotlib.finance import candlestick_ohlc
from aocks import aocksplot


def prep_plot_data(orig_data, start_end_date=(None, None), mode=None):
    """Prepare pandas DataFrame for plotting.

    :arg orig_data:      Original pandas DataFrame.

    :arg start_end_date: Option tuple of start, end dates.

    :arg mode=None:      Optional string indicating data mode (see
                         infer_data_mode for more info).  

    ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
Example #37
0
    def _matplotlib_config(self, name):
        """Return various items needed to setup the user's shell with matplotlib"""

        # Initialize matplotlib to interactive mode always
        import matplotlib
        from matplotlib import backends
        matplotlib.interactive(True)

        def use(arg):
            """IPython wrapper for matplotlib's backend switcher.

            In interactive use, we can not allow switching to a different
            interactive backend, since thread conflicts will most likely crash
            the python interpreter.  This routine does a safety check first,
            and refuses to perform a dangerous switch.  It still allows
            switching to non-interactive backends."""

            if arg in backends.interactive_bk and arg != self.mpl_backend:
                m = (
                    'invalid matplotlib backend switch.\n'
                    'This script attempted to switch to the interactive '
                    'backend: `%s`\n'
                    'Your current choice of interactive backend is: `%s`\n\n'
                    'Switching interactive matplotlib backends at runtime\n'
                    'would crash the python interpreter, '
                    'and IPython has blocked it.\n\n'
                    'You need to either change your choice of matplotlib backend\n'
                    'by editing your .matplotlibrc file, or run this script as a \n'
                    'standalone file from the command line, not using IPython.\n'
                    % (arg, self.mpl_backend))
                raise RuntimeError, m
            else:
                self.mpl_use(arg)
                self.mpl_use._called = True

        self.matplotlib = matplotlib

        # Take control of matplotlib's error handling, which can normally
        # lock up the python interpreter when raw_input() is called
        import matplotlib.backends as backend
        backend.error_msg = error

        # we'll handle the mainloop, tell show not to
        import matplotlib.backends
        matplotlib.backends.show._needmain = False
        self.mpl_backend = matplotlib.rcParams['backend']

        # we also need to block switching of interactive backends by use()
        self.mpl_use = matplotlib.use
        self.mpl_use._called = False
        # overwrite the original matplotlib.use with our wrapper
        matplotlib.use = use

        # We need to detect at runtime whether show() is called by the user.
        # For this, we wrap it into a decorator which adds a 'called' flag.
        backend.draw_if_interactive = flag_calls(backend.draw_if_interactive)

        # This must be imported last in the matplotlib series, after
        # backend/interactivity choices have been made
        try:
            import matplotlib.pylab as pylab
            self.pylab = pylab
            self.pylab_name = 'pylab'
        except ImportError:
            import matplotlib.matlab as matlab
            self.pylab = matlab
            self.pylab_name = 'matlab'

        # Build a user namespace initialized with matplotlib/matlab features.
        user_ns = {'__name__': '__main__', '__builtins__': __builtin__}

        # Be careful not to remove the final \n in the code string below, or
        # things will break badly with py22 (I think it's a python bug, 2.3 is
        # OK).
        pname = self.pylab_name  # Python can't interpolate dotted var names
        exec(
            "import matplotlib\n"
            "import matplotlib.%(pname)s as %(pname)s\n"
            "from matplotlib.%(pname)s import *\n" % locals()) in user_ns

        # Build matplotlib info banner
        b = """
  Welcome to pylab, a matplotlib-based Python environment.
  For more information, type 'help(pylab)'.
  """
        return user_ns, b
Example #38
0
import matplotlib as mpl
import matplotlib.pyplot as plt

import pyfits

import exorings
import j1407

from scipy.optimize import fmin
#from scipy.ndimage import convolve
from scipy.interpolate import UnivariateSpline
from scipy.interpolate import interp1d

from matplotlib.patches import PathPatch

mpl.interactive(True)
# set sensible imshow defaults
mpl.rc('image', interpolation='nearest', origin='lower', cmap='gray')
mpl.rc('axes.formatter', limits=(-7, 7))

G = 6.6738480e-11  # m3 kg-1 s-2
yr = 365.242189669 * 86400  # sec
msol = 1.98855e30  # kg
rsol = 6.5500e8  # m
mjup = 1.8986e27  # kg
rjup = 6.9911e7  # m
mearth = 5.97219e24  # kg
mmoon = 7.3476e22  # kg
au = 1.49597870700e11  # m
pc = 3.0856e16  # m
Example #39
0
from os.path import isfile, join
import pytz
from pytz import timezone
import numpy as np
np.random.seed(sum(map(ord, 'calmap')))
import pandas as pd
import calmap
import datetime
import matplotlib as plt

directory = '/Users/stefan/Library/Mobile Documents/iCloud~com~altifondo~HealthFit/Documents/'

onlyfiles = [f for f in listdir(directory) if isfile(join(directory, f))]

# timezone = pytz.timezone("Europe/Vienna")
plt.interactive(False)


class Workout:
    def __init__(self, duration_in_seconds, timestamp, calories,
                 avg_temperature, sport, sub_sport):
        self.duration_in_seconds = duration_in_seconds
        self.max_heart_rate = 0  # max_heart_rate
        self.avg_heart_rate = 0  # max_heart_rate
        self.date = timestamp
        self.avg_temperature = avg_temperature
        self.total_calories = calories
        self.sport = sport
        self.sub_sport = sub_sport

    def duration_minutes(self):
Example #40
0
import time
import jax
import numpy as np
import sys
sys.path.insert(0, "../")
from scipy.io.wavfile import read

import theanoxla
import theanoxla.tensor as T
from theanoxla import layers

import matplotlib.pyplot as plt
from matplotlib import interactive
interactive(False)
#https://github.com/google/jax/blob/master/jax/lib/xla_bridge.py
from jax.lib import xla_client
from sklearn.metrics import roc_auc_score, accuracy_score

BS = 1

value, step = T.PiecewiseConstant(0, {10: 1, 20: 2})
f = theanoxla.function(outputs=[value], updates={step: step + 1})

for epoch in range(100):
    print(f())
Example #41
0
from bokeh.plotting import figure, output_file, show
from bokeh.io import show, output_file
from bokeh.plotting import figure
from bokeh.models import GraphRenderer, StaticLayoutProvider, Oval
from bokeh.models.graphs import from_networkx, NodesAndLinkedEdges, EdgesAndLinkedNodes
from bokeh.palettes import *
import numpy
import matplotlib as mpl
from bokeh.models.sources import ColumnDataSource
import math
from bokeh.core.property_mixins import LineProps
from bokeh.models.annotations import LabelSet, Label
from bokeh.models.arrow_heads import TeeHead
from bokeh.models.tools import WheelZoomTool, PanTool
mpl.use('WXAgg')
mpl.interactive(False)
import pylab as pl
from pylab import get_current_fig_manager as gcfm
import numpy as np
import random
import wx

if os.name == "nt":  # if windows
    pyqt_plugins = os.path.join(os.path.dirname(PyQt5.__file__), "..", "..",
                                "..", "Library", "plugins")
    QApplication.addLibraryPath(pyqt_plugins)


class Visualizer(object):
    '''
    used to visualize data
Example #42
0
fwd_returns.unstack().T

y = returns.copy()

##########

_x = np.random.randn(1000)

pd.Series(_x).hist()

plt.show(block=True)

import matplotlib.pyplot as plt

plt.interactive(True)

#plt.show()

_x_ws = mstats.winsorize(_x, limits=[0.1, .1])

pd.Series(_x_ws).hist()

X_raw.describe()

X_d1 = X_raw[X_raw.index.get_level_values('date') == 'D001']

X_d1.describe()

##############
# winsorize
Example #43
0
def plot_stuff(ens, acf, sd, deph, rate, s1, s2, dt, wsd, wdeph):
    """
    arr - a vector of y-values that are plot
    plot_mean, save_plot - bools telling to plot the mean and save the plot or not, respectively
    """
    dim_x = np.arange(ens.shape[1]) * dt

    plt.figure(1)
    plt.title(f'Energies of state {s1} (red) and {s2} (blue)')
    plt.xlabel('Time (fs)')
    plt.ylabel('Energy (eV)')
    plt.plot(dim_x, ens[0, :], c='r')
    plt.plot(dim_x, ens[1, :], c='b')
    interactive(True)
    plt.show()

    plt.figure(2)
    plt.title(f'Normalized AUF between state {s1} and {s2}')
    plt.xlabel('Time (fs)')
    plt.ylabel('Normalized AUF')
    plt.ylim(-1, 1)
    #    plt.plot(ts, acf[:, 1, 0], c='r')
    #    plt.plot(ts, acf[:, 1, 1], c='b')
    plt.plot(dim_x, acf[:, 1, 2], c='g')
    plt.axhline(0, c="black")
    interactive(True)
    plt.show()

    plt.figure(3)
    plt.title(f'Un-normalized AUF between state {s1} and {s2}')
    plt.xlabel('Time (fs)')
    plt.ylabel('Un-normalized AUF')
    #    plt.plot(ts, acf[:, 1, 0], c='r')
    #    plt.plot(ts, acf[:, 1, 1], c='b')
    plt.plot(dim_x, acf[:, 0, 2], c='g')
    plt.axhline(0, c="black")
    interactive(True)
    plt.show()

    plt.figure(4)
    plt.title(f'Dephasing time between state {s1} and {s2}')
    plt.xlabel('Time (fs)')
    plt.ylabel('Dephasing (arbitrary units)')
    plt.xlim(0, wdeph)
    plt.plot(dim_x, deph[:, 0], c='r')
    plt.plot(dim_x, deph[:, 1], c='b')
    print(f'The dephasing time is : {rate:f} fs')
    line_broadening = 1 / rate * fs_to_nm
    print(f'The homogenous line broadening is  : {line_broadening:f} nm')
    interactive(True)
    plt.show()

    plt.figure(5)
    plt.title(f'Influence spectrum state {s1}')
    plt.xlabel('Frequency (cm-1)')
    plt.ylabel('Spectral Density (arbitrary units)')
    plt.xlim(0, wsd)
    plt.plot(sd[0, 1, :], sd[0, 0, :], c='g')
    interactive(True)
    plt.show()

    plt.figure(6)
    plt.title(f'Influence spectrum state {s2}')
    plt.xlabel('Frequency (cm-1)')
    plt.ylabel('Spectral Density (arbitrary units)')
    plt.xlim(0, wsd)
    plt.plot(sd[1, 1, :], sd[1, 0, :], c='g')
    interactive(True)
    plt.show()

    plt.figure(7)
    plt.title(f'Influence spectrum across state {s1} and {s2}')
    plt.xlabel('Frequency (cm-1)')
    plt.ylabel('Spectral Density (arbitrary units)')
    plt.xlim(0, wsd)
    plt.plot(sd[2, 1, :], sd[2, 0, :], c='g')
    interactive(False)
    plt.show()
    fileName = "MOs.png"
    plt.savefig(fileName, format='png', dpi=300)
Example #44
0
 def __exit__(self, exc_type, exc_value, traceback):
     if self.wasinteractive:
         interactive(True)
         install_repl_displayhook()
     del self.wasinteractive
Example #45
0
import numpy as np
import matplotlib as mpl

mpl.interactive(0)
mpl.use("Agg")
from pyyeti import cla


def scatm(sol, nas, Vars, se):
    return Vars[se]["atm"] @ sol.a


def net_ifltm(sol, nas, Vars, se):
    return Vars[se]["net_ifltm"] @ sol.a


def net_ifatm(sol, nas, Vars, se):
    return Vars[se]["net_ifatm"] @ sol.a


def get_xyr():
    # return the xr, yr, and rr indexes for the "cglf" data recovery
    # ... see :func:`cla.DR_Defs.add`
    xr = np.array([1, 3, 6, 8])  # 'x' row(s)
    yr = xr + 1  # 'y' row(s)
    rr = np.arange(4) + 10  # rss  rows
    return xr, yr, rr


def cglf(sol, nas, Vars, se):
    resp = Vars[se]["cglf"] @ sol.a
Example #46
0
    def nosql_draw(check_func, rchip1_fpath, rchip2_fpath, kpts1, kpts2):
        # This gets executed in the child thread and does drawing async style
        #from matplotlib.backends.backend_pdf import FigureCanvasPdf as FigureCanvas
        #from matplotlib.backends.backend_pdf import Figure
        #from matplotlib.backends.backend_svg import FigureCanvas
        #from matplotlib.backends.backend_svg import Figure
        from matplotlib.backends.backend_agg import FigureCanvas
        try:
            from matplotlib.backends.backend_agg import Figure
        except ImportError:
            from matplotlib.figure import Figure

        kpts1_ = vt.offset_kpts(kpts1, (0, 0), (resize_factor, resize_factor))
        kpts2_ = vt.offset_kpts(kpts2, (0, 0), (resize_factor, resize_factor))

        #from matplotlib.figure import Figure
        if check_func is not None and check_func():
            return

        rchip1 = vt.imread(rchip1_fpath)
        rchip1 = vt.resize_image_by_scale(rchip1, resize_factor)
        if check_func is not None and check_func():
            return
        rchip2 = vt.imread(rchip2_fpath)
        rchip2 = vt.resize_image_by_scale(rchip2, resize_factor)
        if check_func is not None and check_func():
            return

        try:
            idx = cm.daid2_idx[daid]
            fm   = cm.fm_list[idx]
            fsv  = None if cm.fsv_list is None else cm.fsv_list[idx]
            fs   = None if fsv is None else fsv.prod(axis=1)
        except KeyError:
            fm = []
            fs = None
            fsv = None

        maxnum = 200
        if fs is not None and len(fs) > maxnum:
            # HACK TO ONLY SHOW TOP MATCHES
            sortx = fs.argsort()[::-1]
            fm = fm.take(sortx[:maxnum], axis=0)
            fs = fs.take(sortx[:maxnum], axis=0)

        was_interactive = mpl.is_interactive()
        if was_interactive:
            mpl.interactive(False)
        #fnum = 32
        fig = Figure()
        canvas = FigureCanvas(fig)  # NOQA
        #fig.clf()
        ax = fig.add_subplot(1, 1, 1)
        if check_func is not None and check_func():
            return
        #fig = pt.plt.figure(fnum)
        #H1 = np.eye(3)
        #H2 = np.eye(3)
        #H1[0, 0] = .5
        #H1[1, 1] = .5
        #H2[0, 0] = .5
        #H2[1, 1] = .5
        ax, xywh1, xywh2 = pt.show_chipmatch2(rchip1, rchip2, kpts1_, kpts2_, fm,
                                              fs=fs, colorbar_=False, ax=ax)
        if check_func is not None and check_func():
            return
        savekw = {
            # 'dpi' : 60,
            'dpi' : 80,
        }
        axes_extents = pt.extract_axes_extents(fig)
        #assert len(axes_extents) == 1, 'more than one axes'
        extent = axes_extents[0]
        with io.BytesIO() as stream:
            # This call takes 23% - 15% of the time depending on settings
            fig.savefig(stream, bbox_inches=extent, **savekw)
            stream.seek(0)
            data = np.fromstring(stream.getvalue(), dtype=np.uint8)
        if check_func is not None and check_func():
            return
        pt.plt.close(fig)
        image = cv2.imdecode(data, 1)
        thumbsize = 221
        max_dsize = (thumbsize, thumbsize)
        dsize, sx, sy = vt.resized_clamped_thumb_dims(vt.get_size(image), max_dsize)
        if check_func is not None and check_func():
            return
        image = vt.resize(image, dsize)
        vt.imwrite(fpath, image)
        if check_func is not None and check_func():
            return
Example #47
0
 def __call__(self):
     """Turn the interactive mode off."""
     interactive(False)
     uninstall_repl_displayhook()
Example #48
0
def main():
    import matplotlib
    matplotlib.interactive(True)
    matplotlib.use('Qt5Agg')
    import matplotlib.pyplot as plt
    plt.ion()

    while True:
        xx, yy, zz = np.mgrid[-10:10:50j, -10:10:50j, -1:1:3j]
        data = heightmap1(50,
                          50,
                          2,
                          xx.flatten(),
                          yy.flatten(),
                          zz.flatten(),
                          octaves=0.5 + np.random.random_sample() * 5,
                          lacunarity=0.5 + np.random.random_sample() * 5)
        points = np.stack((xx.flatten(), yy.flatten(), zz.flatten()), axis=-1)
        #data = scipy.interpolate.griddata(points, data, (xx,yy,zz))
        #imgplot = plt.imshow(data[:,:,0])
        #plt.clim(data.min(), data.max())
        #plt.pause(1)
        #data = heightmap1(50,50,2, xx.flatten(), yy.flatten(), zz.flatten(), smooth=True, octaves=0.5+np.random.random_sample()*5,
        #                  lacunarity=0.5+np.random.random_sample()*5)
        #data = scipy.interpolate.griddata(points, data, (xx,yy,zz))
        #imgplot = plt.imshow(data[:,:,0])
        #plt.clim(data.min(), data.max())
        #plt.pause(1)
        data = heightmap2(50,
                          50,
                          2,
                          xx.flatten(),
                          yy.flatten(),
                          zz.flatten(),
                          smooth=True,
                          randomtype=int(np.random.random_sample() * 10))
        data = scipy.interpolate.griddata(points, data, (xx, yy, zz))
        plt.figure()
        imgplot = plt.imshow(data[:, :, 0])
        plt.clim(data.min(), data.max())
        plt.pause(1)

        data = heightmap2(60,
                          60,
                          2,
                          xx.flatten(),
                          yy.flatten(),
                          zz.flatten(),
                          smooth=True,
                          scale=0.1)
        data = scipy.interpolate.griddata(points, data, (xx, yy, zz))
        plt.figure()
        imgplot = plt.imshow(data[:, :, 0])
        plt.clim(data.min(), data.max())
        plt.pause(1)

        data = heightmap3(60, 60, 2, xx.flatten(), yy.flatten(), zz.flatten(),
                          True)
        data = scipy.interpolate.griddata(points, data, (xx, yy, zz))
        plt.figure()
        imgplot = plt.imshow(data[:, :, 0])
        plt.clim(data.min(), data.max())
        plt.pause(1)
Example #49
0
def set_agg():
    "set agg as backend"

    matplotlib.use('Agg')
    matplotlib.interactive(False)
Example #50
0
import pandas as pd
import numpy as np
import gym
import tensorflow as tf
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import interactive
interactive(True)
import pdb
import logging

log = logging.getLogger()
#log.addHandler(logging.StreamHandler())
import policy_gradient
# create gym
env = gym.make('trading-v0')

sess = tf.InteractiveSession()

# create policygradient
pg = policy_gradient.PolicyGradient(sess,
                                    obs_dim=5,
                                    num_actions=3,
                                    learning_rate=1e-2)

# train model, loading if possible
alldf, summrzed = pg.train_model(env, episodes=1001,
                                 log_freq=100)  #, load_model=True)
#print df
#pd.DataFrame(sharpes).expanding().mean().plot()
Example #51
0
def test_forwardbackward(numobservations, numiter):
    ########
    # generate observation
    observations, truenumhot, truenumcold = generate_observations(
        numobservations)
    obs_indices = {1: 0, 2: 1, 3: 2}
    numstates = 2
    vocabsize = 3

    #####
    # HMM initialization

    # initialize initial probs
    unnormalized = numpy.random.rand(numstates)
    initialprob = unnormalized / sum(unnormalized)

    # initialize emission probs
    emis = numpy.zeros((numstates, vocabsize))
    for s in range(numstates):
        unnormalized = numpy.random.rand(vocabsize)
        emis[s] = unnormalized / sum(unnormalized)

    # initialize transition probs
    trans = numpy.zeros((numstates, numstates))
    for s in range(numstates):
        unnormalized = numpy.random.rand(numstates)
        trans[s] = unnormalized / sum(unnormalized)

    print("OBSERVATIONS:")
    print(observations)
    print("\n")

    print("Random initialization:")
    print("INITIALPROB")
    print(initialprob)
    print("\n")

    print("EMIS")
    print(emis)
    print("\n")

    print("TRANS")
    print(trans)
    print("\n")

    input()

    for iteration in range(numiter):

        forward = forwardprobs(observations, initialprob, trans, emis,
                               numstates, obs_indices)
        backward = backwardprobs(observations, trans, emis, numstates,
                                 obs_indices)

        gamma, xi = expectation(observations, trans, emis, numstates,
                                obs_indices, forward, backward)

        initialprob, trans, emis = maximization(observations, gamma, xi,
                                                numstates, obs_indices,
                                                vocabsize)

        print("Re-computed:")
        print("INITIALPROB")
        print(initialprob)
        print("\n")

        print("EMIS")
        print(emis)
        print("\n")

        print("TRANS")
        print(trans)
        print("\n")

        print("GAMMA(1)")
        print(gamma[0])
        print("\n")

        print("GAMMA(2)")
        print(gamma[1])
        print("\n")

        # the first truenumhot observations were generated from the "hot" state.
        # what is the probability of being in state 1 for the first
        # truenumhot observations as opposed to the rest
        avgprob_state1_for_truehot = sum(gamma[0][:truenumhot]) / truenumhot
        avgprob_state1_for_truecold = sum(gamma[0][truenumhot:]) / truenumcold
        print("Average prob. of being in state 1 when true state was Hot:",
              avgprob_state1_for_truehot)
        print("Average prob. of being in state 1 when true state was Cold:",
              avgprob_state1_for_truecold)

        # plot observations and probabilities of being in certain states
        from matplotlib import interactive
        interactive(True)
        xpoints = numpy.arange(len(observations))
        fig, ax1 = plt.subplots()
        ax1.plot(xpoints, observations, "b-")
        plt.ylim([0, 4])
        ax1.set_xlabel("timepoints")
        ax1.set_ylabel("observations", color="b")

        ax2 = ax1.twinx()
        ax2.plot(xpoints, gamma[0], "r-")
        plt.ylim([0.0, 1.0])
        ax2.set_ylabel("prob", color="r")
        plt.show()
        input()
        plt.close()
Example #52
0
def plot_stuff(x_grid, y_grid, x_grid_scaled, y_grid_scaled, sd, w_en,
               w_en_scaled, nconds, outs, energies, ts, dt):

    plt.figure(1)
    plt.xlabel('Time (fs)')
    plt.ylabel('Energy (eV)')
    for iconds in range(nconds):
        plt.imshow(y_grid[iconds, :, :].T,
                   aspect='auto',
                   extent=(0, len(ts) * dt, np.min(x_grid), np.max(x_grid)),
                   origin='lower',
                   interpolation='bicubic',
                   cmap='hot')
    plt.plot(ts * dt, w_en, 'w')
    interactive(True)
    plt.show()

    plt.figure(2)
    plt.xlabel('Time (fs)')
    plt.ylabel('Excess Energy (eV)')
    for iconds in range(nconds):
        plt.imshow(y_grid_scaled[iconds, :, :].T,
                   aspect='auto',
                   extent=(0, len(ts) * dt, np.min(x_grid_scaled),
                           np.max(x_grid_scaled)),
                   origin='lower',
                   interpolation='bicubic',
                   cmap='hot')
    plt.plot(ts * dt, w_en_scaled, 'w')
    interactive(True)
    plt.show()

    plt.figure(3)
    plt.xlabel('Time (fs)')
    plt.ylabel('State Number')
    for iconds in range(nconds):
        plt.imshow(outs[:, :, iconds].T,
                   aspect='auto',
                   origin='lower',
                   extent=(0, len(ts) * dt, 0, outs.shape[1]),
                   interpolation='bicubic',
                   cmap='hot')
    interactive(True)
    plt.show()

    plt.figure(4)
    plt.xlabel('Energy (eV)')
    plt.ylabel('Counts')
    plt.hist(w_en, bins='auto')
    interactive(True)
    plt.show()

    plt.figure(5)
    plt.xlabel('Energy (eV)')
    plt.ylabel('Counts')
    plt.hist(w_en_scaled, bins='auto')
    interactive(True)
    plt.show()

    plt.figure(6)
    plt.xlabel('Time (fs)')
    plt.ylabel('State Energy (eV)')
    plt.plot(ts * dt, energies[:, :, 0])
    interactive(True)
    plt.show()

    plt.figure(7)
    plt.ylabel('State Number')
    plt.xlabel('Freqencies cm-1')
    sd_int = sd[:, 0, :int(sd.shape[2] / 2)]
    sd_freq = sd[0, 1, :int(sd.shape[2] / 2)]
    plt.imshow(sd_int,
               aspect='auto',
               origin='lower',
               extent=(np.min(sd_freq), np.max(sd_freq), 0, sd_int.shape[0]),
               interpolation='bicubic',
               cmap='hot')
    interactive(False)
    plt.show()
Example #53
0
    def show(self):
        # 设置legend
        if self.is_stack:
            self.ax.fill([-1, 0, 0, -1], [-1, -1, -1.1, -1.1], label='Other Time', fc='white', ec='black')
            self.ax.fill([-1, 0, 0, -1], [-1, -1, -1.1, -1.1], hatch=Bar.hatchx, label='Semantic Time', fc='#CCCCCC', ec='black')
            self.ax.legend(loc=2, frameon=False, prop={'size': 9})

        # 设置X、Y限制
        self.ax.tick_params(direction='in')
        self.ax.set_xticks(self.xs)
        self.ax.set_xlim(self.xs[0], self.xs[-1])
        if self.yscale=='log':
            self.ax.set_ylim(1, Bar.ylim)
            self.ax.set_yscale('log')
        else:
            self.ax.set_yticks(self.ys)
            self.ax.set_ylim(self.ys[0], self.ys[-1])

        # 设置下方X、Y轴标题位置
        xLabel_x = (self.xs[0] + self.xs[-1]/5*4)/2;
        # xLabel_x = 3
        xLabel_y = 0.3
        # xLabel_y = 1
        if self.yscale!='log':  xLabel_y -= 120
        if self.y_type=='TQSP': xLabel_y = 0.5
        if self.y_type=='RTree': xLabel_y = 0.3
        # if self.y_type=='NW':
        #     xLabel_x = 3
        #     xLabel_y = -35 - 100
        if self.xLabel!=None:
            # self.ax.text(xLabel_x, xLabel_y, self.xLabel)
            # self.ax.set_xlabel(self.xLabel, va='bottom', visible=True)
            self.ax.set_title(self.xLabel, fontsize=9, verticalalignment='bottom', pad=17)
        if self.yLabel!=None:   self.ax.set_ylabel(self.yLabel)

        # 隐藏下方x轴的label
        xaxis = self.ax.get_xaxis()
        x_labels = xaxis.get_ticklabels()
        for i in range(len(x_labels)):
            x_labels[i].set_visible(False)
        xaxis.set_ticklabels(x_labels)
        # 隐藏下方x轴的刻度线
        x_lines = xaxis.get_ticklines()
        for ln in x_lines:
            ln.set_visible(False)

        # 设置左边Y轴刻度
        self.ax_x = self.ax.twinx()
        if self.yscale=='log':
            self.ax_x.set_ylim(1, Bar.ylim)
            self.ax_x.set_yscale('log')
        else:
            self.ax_x.set_yticks(self.ys)
            self.ax_x.set_ylim(self.ys[0], self.ys[-1])

        # 设置右边Y轴刻度
        self.ax_y = self.ax.twiny()
        self.ax_y.tick_params(direction='in')
        self.ax_y.set_xticks(self.xs)
        self.ax_y.set_xlim(self.xs[0], self.xs[-1])

        # self.fig.canvas.draw()
        # 改变上方x轴的labels
        xaxis = self.ax_y.get_xaxis()
        x_labels = xaxis.get_ticklabels()
        for i in range(len(x_labels)):
            if i==0 or i==len(x_labels)-1:
                x_labels[i].set_visible(False)
            else:
                x_labels[i].set_text(self.x_txts[i-1])
        xaxis.set_ticklabels(x_labels)
        # self.ax.grid('on')
        interactive(True)
        plt.show()
#!/usr/bin/env python

import pytransp.plot.plot_eq as pe
import sys
import numpy as np
import pytransp.classes.transp_output as to
import matplotlib
import matplotlib.pyplot as plt
matplotlib.interactive(True)

if len(sys.argv)==1:
    print("Please give as input the shots id and requested time. The simulations will be luckily found in /home/vallar/tr_client/TCV/<<shot>>")
    print('\n e.g. \n compare_transp_eq.py 62855V01 62855V02 1.3 \n')
    sys.exit()

fnames = ['']*(len(sys.argv)-2)
for i, el in enumerate(sys.argv[1:-1]):
    _pre = "/home/vallar/NoTivoli/tr_client/TCV/"
    pre = _pre+el[0:5]+"/"
    suff=''
    if el[-1]!="F":
        suff=".CDF"
    fnames[i] = pre+el+suff
time=float(sys.argv[-1])

print 'Reading files ', fnames
print 'At time ', time, 's' 

output=np.empty((len(fnames)), dtype='object')
for i,el in enumerate(fnames):
    output[i]=to.transp_output(el)
Example #55
0
    def _export(self, phase: SimPhase, basename: str) -> None:
        '''
        Export the current plot to the current screen if displaying plots
        and/or to a file with the passed basename if saving plots.

        Parameters
        -----------
        phase : SimPhase
            Current simulation phase.
        basename : str
            Basename excluding filetype of the plot to be exported. For
            convenience, this method internally prepends this basename by the
            identifying prefix ``fig_`` *before* writing this file.
        '''

        #FIXME: DRY. This functionality perfectly duplicates the
        #AnimCellsWhileSolving.__exit__() method, which is bad.

        # Id displaying this plot *AND* the current matplotlib backend fails to
        # support "true" non-blocking behavior...
        if (phase.p.plot.is_after_sim_show
                and not mpl_config.is_backend_current_nonblockable()):
            # Update all artists displayed by this plot.
            pyplot.draw()

            #FIXME: DRY. This functionality perfectly duplicates the
            #VisualCellsABC._show_frame(() method, which is also bad.

            # Temporarily yield the time slice for the smallest amount of time
            # required by the current matplotlib backend to handle queued
            # events in the GUI-specific event loop of the current process.
            with mplutil.deprecations_ignored():
                pyplot.pause(0.0001)

            # Disable the "fake" non-blocking behavior enabled by the prior
            # _export_prep() call.
            matplotlib.interactive(False)

        # If saving this plot...
        if phase.p.plot.is_after_sim_save:
            # Filetype and basename of the file to be saved.
            filetype = phase.p.plot.image_filetype
            basename = 'fig_{}.{}'.format(basename, filetype)

            # Absolute path of the file to be saved.
            filename = pathnames.join(phase.export_dirname, basename)

            # Log this saving attempt.
            logs.log_debug('Saving plot: %s', filename)

            # Save this plot to this file.
            pyplot.savefig(
                filename,
                dpi=phase.p.plot.image_dpi,
                format=filetype,
                transparent=True,
            )

        #FIXME: Non-ideal. Under a threading scenario, this will introduce race
        #conditions. Ideally, the figure associated with this plot should be
        #explicitly passed to the mplfigure.close_figure() function as is
        #currently done in the VisualCellsABC.close() method.

        # If *NOT* displaying this plot, close this plot to conserve resources.
        if not phase.p.plot.is_after_sim_show:
            mplfigure.close_figure_current()
    def render(self, dir_name=None):
        '''
        a simple plotter
        '''
        train_length = 1
        plt.ion()
        interactive(True)
        plt.cla()
        self.ax.axis('off')
        # some useful constants
        epsilon = 0.1
        extension_x_of_connections = 2

        min_x = -1 * train_length
        max_x = self.ls1 + self.lc + self.ls2 + 2 * extension_x_of_connections
        max_y = self.nr_agents - 1 + epsilon
        min_y = 0 - epsilon

        nr_conflicts = self.conflict_detector()

        if nr_conflicts > 0:
            color = 'red'
        else:
            color = 'gray'

        # getting the number of passangers
        sizes_lst = []
        for agent_id in range(self.nr_agents):
            sizes_lst.append(self.states[2 * agent_id + 1])

        # getting the destinations
        destinations_y = np.array(range(self.nr_agents))
        destinations_x = np.array(
            self.destinations) + 2 * extension_x_of_connections

        # drawing the rails

        # the non-overlapping tracks
        for agent_id in range(self.nr_agents):
            self.ax.plot([0, self.ls1 - 1], [agent_id, agent_id],
                         linestyle='dashed',
                         color='gray')

        # the first connections
        for agent_id in range(self.nr_agents):
            self.ax.plot(
                [self.ls1 - 1, self.ls1 + extension_x_of_connections - 1],
                [agent_id, (self.nr_agents - 1.0) / 2.0],
                linestyle='dashed',
                color='gray')

        # single track
        self.ax.plot([
            self.ls1 + extension_x_of_connections - 1,
            self.ls1 + self.lc + extension_x_of_connections - 1
        ], [(self.nr_agents - 1.0) / 2.0, (self.nr_agents - 1.) / 2.0],
                     linestyle='dashed',
                     color='gray')

        # the second connections
        for agent_id in range(self.nr_agents):
            self.ax.plot([
                self.ls1 + self.lc + extension_x_of_connections - 1,
                self.ls1 + self.lc + 2 * extension_x_of_connections - 1
            ], [(self.nr_agents - 1.0) / 2.0, agent_id],
                         linestyle='dashed',
                         color='gray')

        # the second non-overlapping
        for agent_id in range(self.nr_agents):
            self.ax.plot([
                self.ls1 + self.lc + 2 * extension_x_of_connections - 1,
                self.ls1 + self.lc + self.ls2 + 2 * extension_x_of_connections
            ], [agent_id, agent_id],
                         linestyle='dashed',
                         color='gray')

        # autoscale on unknown axis and known lims on the other
        self.ax.set_autoscaley_on(True)
        self.ax.set_xlim(min_x, max_x)
        self.ax.set_ylim(min_y, max_y * 1.15)

        # getting the coordinates of the trains
        x_data, y_data = self.get_x_y(
            epsilon=0.02 * (max_y - min_y),
            extension_x_of_connections=extension_x_of_connections)

        # converting the x and y of the locomotive to trains of length 3
        x_trains = []
        y_trains = []

        for x, y in zip(x_data, y_data):
            for length in range(train_length):
                x_trains.append(x - length)
                y_trains.append(y)
        x_trains = np.array(x_trains)
        y_trains = np.array(y_trains)

        # adding the text, the number of passangers, the timestamp, number of conflicts
        epsilon = 0.05
        for train_id in range(self.nr_agents):
            self.ax.text(x_data[train_id] - 1,
                         y_data[train_id] + epsilon,
                         str(int(sizes_lst[train_id])),
                         fontfamily='sans-serif')

        self.ax.text((max_x - min_x) * 0.5 - 5, 1.15 * max_y,
                     'time step: ' + str(int(self.timestamp)))
        self.ax.text((max_x - min_x) * 0.5 - 5,
                     1.1 * max_y,
                     'conflicts: ' + str(int(nr_conflicts)),
                     color=color)
        self.ax.text(
            (max_x - min_x) * 0.5 - 5,
            1.05 * max_y,
            'arrived at dest.: ' + str(int(np.sum(self.terminated_lst))),
            color='blue')

        # drawing the trains (the body, and the loco)
        self.ax.scatter(x_trains - 1,
                        y_trains,
                        color=color,
                        marker='s',
                        alpha=0.6)
        self.ax.scatter(x_data, y_data, color='black', marker='>')

        # drawing the destinations
        self.ax.scatter(destinations_x,
                        destinations_y,
                        color='blue',
                        marker='s')

        plt.draw()
        plt.show()
        plt.pause(0.1)

        if dir_name:

            if not os.path.exists(dir_name):
                os.makedirs(dir_name)

            plt.savefig(
                os.path.join(dir_name, 'fig_' + str(self.timestamp) + '.png'))
Example #57
0
    def testFrame(self, gui=True):
        #from pylab import *
        import matplotlib
        from matplotlib import pyplot as plt
        #close('all')
        if self.image.dataSource.moduleName == 'TQDataSource':
            self.analysisController._checkTQ()
        if gui:
            matplotlib.interactive(False)
            plt.figure()

        zp = self.do.zp

        analysisMDH = self.analysisController.analysisMDH

        self._checkmap('DarkMapID')
        self._checkmap('VarianceMapID')
        self._checkmap('FlatfieldMapID')

        mn = self.image.dataSource.moduleName
        if mn == 'BufferedDataSource':
            mn = self.image.dataSource.dataSource.moduleName

        ft = remFitBuf.fitTask(
            dataSourceID=self.image.seriesName,
            frameIndex=zp,
            metadata=MetaDataHandler.NestedClassMDHandler(analysisMDH),
            dataSourceModule=mn)
        res = ft(gui=gui, taskQueue=self.tq)

        if gui:
            plt.figure()
            try:
                d = ft.ofd.filteredData.T
                #d = ft.data.squeeze().T
                plt.imshow(d,
                           cmap=plt.cm.hot,
                           interpolation='nearest',
                           clim=(np.median(d.ravel()), d.max()))
                plt.plot([p.x for p in ft.ofd], [p.y for p in ft.ofd],
                         'o',
                         mew=2,
                         mec='g',
                         mfc='none',
                         ms=9)
                if ft.driftEst:
                    plt.plot([p.x for p in ft.ofdDr], [p.y for p in ft.ofdDr],
                             'o',
                             mew=2,
                             mec='b',
                             mfc='none',
                             ms=9)
                #if ft.fitModule in remFitBuf.splitterFitModules:
                #        plot([p.x for p in ft.ofd], [d.shape[0] - p.y for p in ft.ofd], 'o', mew=2, mec='g', mfc='none', ms=9)
                #axis('tight')
                plt.xlim(0, d.shape[1])
                plt.ylim(d.shape[0], 0)
                plt.xticks([])
                plt.yticks([])

                vx, vy, _ = self.image.voxelsize_nm

                plt.plot(res.results['fitResults']['x0'] / vx,
                         res.results['fitResults']['y0'] / vy,
                         '+b',
                         mew=2)

                if 'startParams' in res.results.dtype.names:
                    plt.plot(res.results['startParams']['x0'] / vx,
                             res.results['startParams']['y0'] / vy,
                             'xc',
                             mew=2)

                if 'tIm' in dir(ft.ofd):
                    plt.figure()
                    plt.imshow(ft.ofd.tIm.T,
                               cmap=plt.cm.hot,
                               interpolation='nearest')
                    #axis('tight')
                    plt.xlim(0, d.shape[1])
                    plt.ylim(d.shape[0], 0)
                    plt.xticks([])
                    plt.yticks([])
                    plt.plot(res.results['fitResults']['x0'] / vx,
                             res.results['fitResults']['y0'] / vy, '+b')

                #figure()
                #imshow()
            except AttributeError:
                #d = self.image.data[:,:,zp].squeeze().T
                if isinstance(ft.bg, np.ndarray):
                    # We expect our background estimate to take the form of a numpy array, correct our data by subtracting the background
                    d = (ft.data - ft.bg).squeeze().T
                elif hasattr(ft.bg, 'get_background'):
                    # To support GPU background calculation and to minimize the number of CPU-GPU transfers, our background estimate can instead be
                    # a proxy for a background buffer on the GPU. During fitting this will usually be accessed directly from the GPU fitting code, but in
                    # this case (when displaying the data we fitted) we need to get at it from our CPU code using the `get_background` method of the proxy.
                    #
                    # NB - the background returned by `get_background()` will not have been flatfielded. As this is just display code we ignore this,
                    # but any computational code should perform flatfielding correction on the results of the get_background call.
                    #
                    # TODO - document GPU background interface via creating a base class in PYME.IO.buffers
                    d = (ft.data - ft.bg.get_background().reshape(
                        ft.data.shape)).squeeze().T
                else:
                    raise RuntimeError('Background format not understood')

                plt.imshow(d,
                           cmap=plt.cm.jet,
                           interpolation='nearest',
                           clim=[0, d.max()])
                plt.xlim(0, d.shape[1])
                plt.ylim(d.shape[0], 0)

                vx, vy, _ = self.image.voxelsize_nm

                plt.plot(res.results['fitResults']['x0'] / vx,
                         res.results['fitResults']['y0'] / vy, 'ow')
                pass

            plt.show()

            matplotlib.interactive(True)

        return ft, res
#
from __future__ import print_function
from __future__ import division
import os
import myokit
import myokit.lib.fit as fitlib
import methods
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as pl

# Some versions of CMA enable matplotlib's interactive mode
interactive = matplotlib.is_interactive()
#import cma
matplotlib.interactive(interactive)
del (interactive)

EXP = 'outward-experiment'
SIM = os.path.join(methods.RESULTS, 'sim-outward-currents.csv')
TABLE = os.path.join(methods.RESULTS, 'sim-outward-current-table.csv')

# Log interval
DT = 0.2e-3

# Voltage steps
VSTEPS_mV = np.arange(-40, 50 + 10, 10)

# Offset ignored when fitting at the start of each trace
CAPACITANCE = 0.01  # 10 ms
Example #59
0
    def draw(self):
        # Adding rc=self.rcParams does not validate/parses the params which then
        # throws an error during plotting!
        with mpl.rc_context():
            if not self.theme_applied:
                _set_default_theme_rcparams(mpl)
                # will be empty if no theme was applied
            for key in six.iterkeys(self.rcParams):
                val = self.rcParams[key]
                # there is a bug in matplotlib which does not allow None directly
                # https://github.com/matplotlib/matplotlib/issues/2543
                try:
                    if key == 'text.dvipnghack' and val is None:
                        val = "none"
                    mpl.rcParams[key] = val
                except Exception as e:
                    msg = """Setting "mpl.rcParams['%s']=%s" raised an Exception: %s""" % (key, str(val), str(e))
                    warnings.warn(msg, RuntimeWarning)
                    # draw is not allowed to show a plot, so we can use to result for ggsave
                # This sets a rcparam, so we don't have to undo it after plotting
            mpl.interactive(False)
            if self.facet_type == "grid" and len(self.facets) > 1:
                fig, axs = plt.subplots(self.n_high, self.n_wide,
                                        sharex=True, sharey=True)
                plt.subplots_adjust(wspace=.05, hspace=.05)
            elif self.facet_type == "wrap" or len(self.facets)==1:
                # add (more than) the needed number of subplots
                fig, axs = plt.subplots(self.n_high, self.n_wide)
                # there are some extra, remove the plots
                subplots_available = self.n_wide * self.n_high
                if self.n_dim_x:
                    extra_subplots = subplots_available - self.n_dim_x
                else:
                    extra_subplots = 0
                for extra_plot in axs.flatten()[-extra_subplots:]:
                    extra_plot.axis('off')

                # plots is a mapping from xth-plot -> subplot position
                plots = []
                for x in range(self.n_wide):
                    for y in range(self.n_high):
                        plots.append((x, y))
                plots = sorted(plots, key=lambda x: x[1] + x[0] * self.n_high + 1)
            else:
                fig, axs = plt.subplots(self.n_high, self.n_wide)
            axs = np.atleast_2d(axs)
            # Set the default plot to the first one
            plt.subplot(self.n_wide, self.n_high, 1)

            # Aes need to be initialized BEFORE we start faceting. This is b/c
            # we want to have a consistent aes mapping across facets.
            self.data = assign_visual_mapping(self.data, self.aesthetics, self)

            # Faceting just means doing an additional groupby. The
            # dimensions of the plot remain the same
            if self.facets:
                # geom_bar does not work with faceting yet
                _check_geom_bar = lambda x :isinstance(x, geom_bar)
                if any(map(_check_geom_bar, self.geoms)):
                    msg = """Facetting is currently not supported with geom_bar. See
                    https://github.com/yhat/ggplot/issues/196 for more information"""
                    warnings.warn(msg, RuntimeWarning)
                # the current subplot in the axs and plots
                cntr = 0
                #first grids: faceting with two variables and defined positions
                if len(self.facets) == 2 and self.facet_type != "wrap":
                    # store the extreme x and y coordinates of each pair of axes
                    axis_extremes = np.zeros(shape=(self.n_high * self.n_wide, 4))
                    xlab_offset = .15
                    for _iter, (facets, frame) in enumerate(self.data.groupby(self.facets)):
                        pos = self.facet_pairs.index(facets) + 1
                        plt.subplot(self.n_wide, self.n_high, pos)
                        for layer in self._get_layers(frame):
                            for geom in self.geoms:
                                callbacks = geom.plot_layer(layer)
                        axis_extremes[_iter] = [min(plt.xlim()), max(plt.xlim()),
                                                min(plt.ylim()), max(plt.ylim())]
                    # find the grid wide data extremeties
                    xlab_min, ylab_min = np.min(axis_extremes, axis=0)[[0, 2]]
                    xlab_max, ylab_max = np.max(axis_extremes, axis=0)[[1, 3]]
                    # position of vertical labels for facet grid
                    xlab_pos = xlab_max + xlab_offset
                    ylab_pos = ylab_max - float(ylab_max - ylab_min) / 2
                    # This needs to enumerate all possibilities
                    for pos, facets in enumerate(self.facet_pairs):
                        pos += 1
                        # Plot the top and right boxes
                        if pos <= self.n_high: # first row
                            plt.subplot(self.n_wide, self.n_high, pos)
                            plt.table(cellText=[[facets[1]]], loc='top',
                                      cellLoc='center', cellColours=[['lightgrey']])
                        if (pos % self.n_high) == 0: # last plot in a row
                            plt.subplot(self.n_wide, self.n_high, pos)
                            x = max(plt.xticks()[0])
                            y = max(plt.yticks()[0])
                            ax = axs[pos % self.n_high][pos % self.n_wide]
                            ax = plt.gca()
                            ax.text(1, 0.5, facets[0],
                                     bbox=dict(
                                         facecolor='lightgrey',
                                         edgecolor='black',
                                         color='black',
                                         width=mpl.rcParams['font.size'] * 1.65
                                     ),
                                     transform=ax.transAxes,
                                     fontdict=dict(rotation=-90, verticalalignment="center", horizontalalignment='left')
                            )

                    plt.subplot(self.n_wide, self.n_high, pos)
                    # Handle the different scale types here
                    # (free|free_y|free_x|None) and also make sure that only the
                    # left column gets y scales and the bottom row gets x scales
                    scale_facet_grid(self.n_wide, self.n_high,
                                     self.facet_pairs, self.facet_scales)

                else: # now facet_wrap > 2 or facet_grid w/ only 1 facet
                    for facet, frame in self.data.groupby(self.facets):
                        for layer in self._get_layers(frame):
                            for geom in self.geoms:
                                if self.facet_type == "wrap" or 1==1:
                                    if cntr + 1 > len(plots):
                                        continue
                                    pos = plots[cntr]
                                    if pos is None:
                                        continue
                                    y_i, x_i = pos
                                    pos = x_i + y_i * self.n_high + 1
                                    ax = plt.subplot(self.n_wide, self.n_high, pos)
                                else:
                                    ax = plt.subplot(self.n_wide, self.n_high, cntr)
                                    # TODO: this needs some work
                                    if (cntr % self.n_high) == -1:
                                        plt.tick_params(axis='y', which='both',
                                                        bottom='off', top='off',
                                                        labelbottom='off')
                                callbacks = geom.plot_layer(layer)
                                if callbacks:
                                    for callback in callbacks:
                                        fn = getattr(ax, callback['function'])
                                        fn(*callback['args'])
                        title = facet
                        if isinstance(facet, tuple):
                            title = ", ".join(facet)
                        plt.table(cellText=[[title]], loc='top',
                                  cellLoc='center', cellColours=[['lightgrey']])
                        cntr += 1

                    # NOTE: Passing n_high for cols (instead of n_wide) and
                    # n_wide for rows because in all previous calls to
                    # plt.subplot, n_wide is passed as the number of rows, not
                    # columns.
                    scale_facet_wrap(self.n_wide, self.n_high, range(cntr), self.facet_scales)
            else: # no faceting
                for geom in self.geoms:
                    _aes = self.aesthetics
                    if geom.aes:
                        # update the default mapping with the geom specific one
                        _aes = _aes.copy()
                        _aes.update(geom.aes)
                    if not geom.data is None:
                        data = _apply_transforms(geom.data, _aes)
                        data = assign_visual_mapping(data, _aes, self)
                    else:
                        data = self.data
                    for layer in self._get_layers(data, _aes):
                        ax = plt.subplot(1, 1, 1)
                        callbacks = geom.plot_layer(layer)
                        if callbacks:
                            for callback in callbacks:
                                fn = getattr(ax, callback['function'])
                                fn(*callback['args'])

            # Handling the details of the chart here; probably be a better
            # way to do this...
            if self.title:
                if self.facets:
                    # This is currently similar what plt.title uses
                    plt.gcf().suptitle(self.title, verticalalignment='baseline',
                                       fontsize=mpl.rcParams['axes.titlesize'])
                else:
                    plt.title(self.title)
            if self.xlab:
                if self.facet_type == "grid":
                    fig.text(0.5, 0.025, self.xlab)
                else:
                    for ax in plt.gcf().axes:
                        ax.set_xlabel(self.xlab)
            if self.ylab:
                if self.facet_type == "grid":
                    fig.text(0.025, 0.5, self.ylab, rotation='vertical')
                else:
                    for ax in plt.gcf().axes:
                        ax.set_ylabel(self.ylab)
            # in case of faceting, this should be applied to all axis!
            for ax in plt.gcf().axes:
                if self.xmajor_locator:
                    ax.xaxis.set_major_locator(self.xmajor_locator)
                if self.xtick_formatter:
                    ax.xaxis.set_major_formatter(self.xtick_formatter)
                    fig.autofmt_xdate()
                if self.xbreaks: # xbreaks is a list manually provided
                    ax.xaxis.set_ticks(self.xbreaks)
                if self.xtick_labels:
                    if isinstance(self.xtick_labels, dict):
                        labs = []
                        for lab in plt.xticks()[1]:
                            lab = lab.get_text()
                            lab = self.xtick_labels.get(lab)
                            labs.append(lab)
                        ax.xaxis.set_ticklabels(labs)
                    elif isinstance(self.xtick_labels, list):
                        ax.xaxis.set_ticklabels(self.xtick_labels)
                if self.ytick_labels:
                    if isinstance(self.ytick_labels, dict):
                        labs = []
                        for lab in plt.yticks()[1]:
                            lab = lab.get_text()
                            lab = self.ytick_labels.get(lab)
                            labs.append(lab)
                        ax.yaxis.set_ticklabels(labs)
                    elif isinstance(self.ytick_labels, list):
                        ax.yaxis.set_ticklabels(self.ytick_labels)
                if self.ytick_formatter:
                    ax.yaxis.set_major_formatter(self.ytick_formatter)
                if self.xlimits:
                    ax.set_xlim(self.xlimits)
                if self.ylimits:
                    ax.set_ylim(self.ylimits)
                if self.scale_y_reverse:
                    ax.invert_yaxis()
                if self.scale_x_reverse:
                    ax.invert_xaxis()
                if self.scale_y_log:
                    ax.set_yscale('log', basey=self.scale_y_log)
                if self.scale_x_log:
                    ax.set_xscale('log', basex=self.scale_x_log)

            # TODO: Having some issues here with things that shouldn't have a
            # legend or at least shouldn't get shrunk to accomodate one. Need
            # some sort of test in place to prevent this OR prevent legend
            # getting set to True.
            if self.legend:
                # works with faceted and non-faceted plots
                ax = axs[0][self.n_wide - 1]
                box = ax.get_position()
                ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
                
                cntr = 0
                # py3 and py2 have different sorting order in dics, so make that consistent
                for ltype in sorted(self.legend.keys()):
                    legend = self.legend[ltype]
                    lname = self.aesthetics.get(ltype, ltype)
                    new_legend = draw_legend(ax, legend, ltype, lname, cntr)
                    ax.add_artist(new_legend)
                    cntr += 1

            # Finaly apply any post plot callbacks (theming, etc)
            if self.theme_applied:
                for ax in plt.gcf().axes:
                    self._apply_post_plot_callbacks(ax)
            else:
                for ax in plt.gcf().axes:
                    _theme_grey_post_plot_callback(ax)

        return plt.gcf()
    def plot_incorrect_distance(self, flat_map):
        from matplotlib import pyplot as plt
        from matplotlib import interactive
        interactive(True)
        score_correct = []
        score_incorrect = []
        for member in flat_map:
            score = member.get('maps_with')[0].get('score')
            if score < 0.2:
                if member.get('correct') == 'y':
                    score_correct.append(score)
                else:
                    score_incorrect.append(score)
        plt.hist([score_correct, score_incorrect],
                 10,
                 histtype='bar',
                 color=['green', 'red'],
                 label=['correct', 'incorrect'])
        plt.title('Number of (in)correct matches for scores (part 1)')
        plt.xlabel('Matching score')
        plt.ylabel('Number of matches')
        plt.legend()
        plt.show()
        print("Percentage below score 0.2 incorrect: " + str(
            len(score_incorrect) /
            (len(score_incorrect) + len(score_correct)) * 100))

        score_correct = []
        score_incorrect = []
        for member in flat_map:
            score = member.get('maps_with')[0].get('score')
            if score >= 0.2:
                if member.get('correct') == 'y':
                    score_correct.append(score)
                else:
                    score_incorrect.append(score)
        plt.hist([score_correct, score_incorrect],
                 10,
                 histtype='bar',
                 color=['green', 'red'],
                 label=['correct', 'incorrect'])
        plt.title('Number of (in)correct matches for scores (part 2)')
        plt.xlabel('Matching score')
        plt.ylabel('Number of matches')
        plt.legend()
        plt.show()
        print("Percentage above score 0.2 incorrect: " + str(
            len(score_incorrect) /
            (len(score_incorrect) + len(score_correct)) * 100))

        score_correct = []
        score_incorrect = []
        for member in flat_map:
            score = member.get('maps_with')[0].get('score')
            if member.get('correct') == 'y':
                score_correct.append(score)
            else:
                score_incorrect.append(score)
        print("Total percentage incorrect: " + str(
            len(score_incorrect) /
            (len(score_incorrect) + len(score_correct)) * 100))