A very incomplete example showing how to make some interactive and javascript widgets for examining parameter space


In [1]:
from IPython.html.widgets import interact, interactive, fixed
from IPython.html import widgets
from IPython.display import clear_output, display, HTML
from ipywidgets import StaticInteract, RangeWidget, RadioWidget

In [2]:
%run ph2co_grid_computation.py


/Users/adam/repos/astroquery/astroquery/lamda/__init__.py:21: UserWarning: Experimental: LAMDA has not yet been refactored to have its API match the rest of astroquery.
  warnings.warn("Experimental: LAMDA has not yet been refactored to have its API match the rest of astroquery.")
WARNING:astropy:AstropyDeprecationWarning: 'dtypes' has been renamed to the singular 'dtype'.
WARNING: AstropyDeprecationWarning: 'dtypes' has been renamed to the singular 'dtype'. [astropy.table.table]
      Tex               tau        ...      brightness           T_B      
       K                           ... erg / (cm2 Hz s sr)        K       
---------------- ----------------- ... ------------------- ---------------
-0.0817529700928  -0.0342780871976 ...   1.56037207206e-22  0.100352601934
   6.09190527741     41.9634499416 ...   1.73595925381e-14   2.66518509246
 -0.171716538322 -0.00182074261889 ...   2.06896749361e-22 0.0053264336307
/Users/adam/repos/astropy/astropy/units/quantity.py:608: RuntimeWarning: invalid value encountered in true_divide
  return np.true_divide(self, other)

In [53]:
import sys
sys.path += ['/Users/adam/virtual-python/lib/python2.7/site-packages/mpld3-0.0.1-py2.7.egg']
sys.path += ['/Users/adam/virtual-python/lib/python2.7/site-packages/JSAnimation-0.1-py2.7.egg-info']

In [34]:
class LinkedView(plugins.PluginBase):
    """A simple plugin showing how multiple axes can be linked"""
    
    FIG_JS = jinja2.Template("""
    var linedata{{ id }} = {{ linedata }};

    ax{{ axid }}.axes.selectAll(".paths{{ collid }}")
	    .on("mouseover", function(d, i){
             line{{ elid }}.data = linedata{{ id }}[i];
             line{{ elid }}.lineobj.transition()
                .attr("d", line{{ elid }}.line(line{{ elid }}.data))
                .style("stroke", this.style.fill);})
    """)

    def __init__(self, points, line, linedata):
        self.points = points
        self.line = line
        self.linedata = linedata
        self.id = self.generate_unique_id()

    def _fig_js_args(self):
        points = self._get_d3obj(self.points)
        line = self._get_d3obj(self.line)
        return dict(id=self.id,
                    axid=points.axid,
                    collid=points.collid,
                    elid=line.elid,
                    lineaxid=line.axid,
                    lineid=line.lineid,
                    linedata=json.dumps(self.linedata))
    
    
class Slider(plugins.PluginBase):
    FIG_JS = jinja2.Template("""
        fig.root.append("div")
          .append("slider")
            .on("slide", function(evt,value) {
                     d3.select('#slider3text').text(value);
                }
                );
    """)
    
 #                   line = ax{{ axid }}.axes.selectAll(".line{{ elid }}");
 #               line.data = linedata{{ id }}[value];

In [129]:
fig, ((ax1,ax2),(ax3,ax4)) = plt.subplots(2,2)
d3fig = fig_to_d3(fig)

#lines1 = ax1.plot(temperatures, taugrid_71M)
points1 = ax1.scatter(temperatures, taugrid_71M[:,10])
lines2 = ax2.plot(temperatures, texgrid_71M, 'w')
ax2.set_ylim(0,50)
lines3 = ax3.plot(densities, taugrid_71M.T,'w')
lines4 = ax4.plot(densities, taugrid_71M.T,'w')

linedata = np.array([(temperatures,tx) for tx in texgrid_71M]).swapaxes(1,2)
plugins.connect(fig, LinkedView(points1, lines2[0], linedata.tolist()))

linedata = np.array([(densities,tx) for tx in taugrid_71M]).swapaxes(1,2)
plugins.connect(fig, LinkedView(points1, lines3[0], linedata.tolist()))

linedata = np.array([(densities,tx) for tx in texgrid_71M]).swapaxes(1,2)
plugins.connect(fig, LinkedView(points1, lines4[0], linedata.tolist()))

plugins.connect(fig, plugins.ResetButton())
#plugins.connect(fig, Slider())

display_d3(fig)

# transpose line data and add plugin
#linedata = data.transpose(0, 2, 1).tolist()

#show_d3()


Out[129]:

In [16]:
pb = plugins.PluginBase()
plugins.connect(fig, LinkedView(None,None,None))
pb.figure = fig

In [17]:
pb._get_d3obj(lines1[0])


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-17-3aa76ab3079f> in <module>()
----> 1 pb._get_d3obj(lines1[0])

/Users/adam/virtual-python/lib/python2.7/site-packages/mpld3-0.0.1-py2.7.egg/mpld3/plugins.pyc in _get_d3obj(self, mplobj)
     84         obj = None
     85         for ax in self.figure.axes:
---> 86             obj = obj or ax.objmap.get(mplobj, None)
     87         return obj
     88 

AttributeError: 'AxesSubplot' object has no attribute 'objmap'

In [122]:
densities.size


Out[122]:
20

In [123]:
styleargs = {'linewidth': 2, 'alpha': 0.5, 'color':'#5A228B'}

def setup(tem=5,dens=5,show=False):
    fig, ((ax1,ax2),(ax3,ax4)) = plt.subplots(2,2, sharex='col', sharey='row', squeeze=True, figsize=(10,7))
    plt.subplots_adjust(hspace=0,wspace=0)
    lines1, = ax1.plot(temperatures, taugrid_71M[dens,:], **styleargs)
    ax1.set_ylim(-0.2,0.2)
    ax1.plot(temperatures[tem],taugrid_71M[dens,tem], 'o',alpha=0.5, markeredgecolor='none')
    lines2, = ax3.plot(temperatures, texgrid_71M[dens,:], **styleargs)
    ax3.set_ylim(0,50)
    ax3.plot(temperatures[tem],texgrid_71M[dens,tem], 'o',alpha=0.5, markeredgecolor='none')

    lines3, = ax2.semilogx(densities, taugrid_71M[:,tem], **styleargs)
    ax2.set_ylim(-0.2,0.2)
    ax2.plot(densities[dens],taugrid_71M[dens,tem], 'o',alpha=0.5, markeredgecolor='none')
    lines4, = ax4.semilogx(densities, texgrid_71M[:,tem], **styleargs)
    ax4.plot(densities[dens],texgrid_71M[dens,tem], 'o',alpha=0.5, markeredgecolor='none')
    ax4.set_ylim(0,50)
    plt.suptitle("$T=%i$ K, $n=10^{%0.1f}$ cm$^{-3}$" % (temperatures[tem],np.log10(densities[dens])))
    ax4.set_xlabel('$n(H_2)$')
    ax3.set_xlabel("T")
    ax1.set_ylabel(r"$\tau$")
    ax3.set_ylabel("$T_{ex}$")
    if show:
        plt.show()
    return fig,lines1,lines2,lines3,lines4
    #return ax1,ax2,ax3,ax4

#ax1,ax2,ax3,ax4 = setup()
#fig,lines1,lines2,lines3,lines4 = setup()

def run_plot_temden():
    fig,lines1,lines2,lines3,lines4 = setup()
    
    #@interact(tem=(0,10),dens=(0,10))
    def plot_temden(tem,dens):
        lines1.set_data(temperatures, taugrid_71M[dens,:])
        lines2.set_data(temperatures, texgrid_71M[dens,:])
        lines3.set_data(densities, taugrid_71M[:,tem])
        lines4.set_data(densities, texgrid_71M[:,tem])
        plt.show()
    interact(plot_temden, tem=(0,temperatures.size),dens=(0,densities.size))
    
def dumb_interact():
       interact(setup, tem=(0,temperatures.size),dens=(0,densities.size), show=True)

In [124]:
dumb_interact()



In [57]:
from JSAnimation import IPython_display
from matplotlib import animation

In [78]:
fig,lines1,lines2,lines3,lines4 = setup()

def plot_temden(dens,tem=5):
    lines1.set_data(temperatures, taugrid_71M[dens,:])
    lines2.set_data(temperatures, texgrid_71M[dens,:])
    lines3.set_data(densities, taugrid_71M[:,tem])
    lines4.set_data(densities, texgrid_71M[:,tem])
    plt.suptitle("$T=%i$ K, $n=10^{%0.1f}$ cm$^{-3}$" % (temperatures[tem],np.log10(densities[dens])))
    return lines1,lines2,lines3,lines4

animation.FuncAnimation(fig, plot_temden, frames=10, interval=1, blit=True)


Out[78]:


Once Loop Reflect
<matplotlib.figure.Figure at 0x16bd13790>