Example #1
0
    def plot_std_meshlines(self, step=0.1):
        '''
        plot mesh circles for stdv
        '''

        color = self.std_color

        nstdmax = self.stdmax
        if self.negative:
            axmin = -np.pi / 2.
        else:
            axmin = 0.

        th = np.arange(axmin, np.pi / 2, 0.01)

        for ra in np.arange(0, nstdmax + 0.1 * step, step):
            self.ax.plot(ra * np.sin(th), ra * np.cos(th), ':', color=color)

        if self.normalize:
            self.ax.set_ylabel('$\sigma / \sigma_{obs}$', color=color)
            self.ax.set_xlabel('$\sigma / \sigma_{obs}$', color=color)
        else:
            self.ax.set_ylabel('Standard Deviation', color=color)
            self.ax.set_xlabel('Standard Deviation', color=color)

        xticklabels = plt.getp(plt.gca(), 'xticklabels')
        plt.setp(xticklabels, color=color)
        yticklabels = plt.getp(plt.gca(), 'yticklabels')
        plt.setp(yticklabels, color=color)
Example #2
0
    def plot_std_meshlines(self, step=0.1):
        '''
        plot mesh circles for stdv
        '''

        color = self.std_color

        nstdmax = self.stdmax
        if self.negative:
            axmin = -np.pi / 2.
        else:
            axmin = 0.

        th = np.arange(axmin, np.pi / 2, 0.01)

        for ra in np.arange(0, nstdmax + 0.1 * step, step):
            self.ax.plot(ra * np.sin(th), ra * np.cos(th), ':', color=color)

        if self.normalize:
            self.ax.set_ylabel('$\sigma / \sigma_{obs}$', color=color)
            self.ax.set_xlabel('$\sigma / \sigma_{obs}$', color=color)
        else:
            self.ax.set_ylabel('Standard Deviation', color=color)
            self.ax.set_xlabel('Standard Deviation', color=color)

        xticklabels = plt.getp(plt.gca(), 'xticklabels')
        plt.setp(xticklabels, color=color)
        yticklabels = plt.getp(plt.gca(), 'yticklabels')
        plt.setp(yticklabels, color=color)
Example #3
0
def render_21_output(
    ax, fig, y_out, M=100, y0range=[-1, 1], y1range=[-1, 1], cmap=None,
):
    img = ax.imshow(
        np.reshape(y_out, [M, M]),
        origin='lower',
        extent=[y0range[0], y0range[1], y1range[0], y1range[1]],
        cmap=cmap,
    )
    ax.set_xlabel(r'$y_1$')
    ax.set_ylabel(r'$y_2$')
    axins1 = inset_axes(
        ax,
        width="40%",  # width = 50% of parent_bbox width
        height="5%",  # height : 5%
        loc='upper right',
    )

    imgmin = np.min(y_out)
    imgmax = np.max(y_out)
    color_bar = fig.colorbar(
        img,
        cax=axins1,
        orientation="horizontal",
        ticks=np.linspace(imgmin, imgmax, 3),
    )
    cbxtick_obj = plt.getp(color_bar.ax.axes, 'xticklabels')
    plt.setp(cbxtick_obj, color="white")
    axins1.xaxis.set_ticks_position("bottom")
Example #4
0
def add_percent_ticks():
    ticks=pylab.getp(pylab.gca(),'xticks')
    ticklabels=len(ticks)*['']
    ticklabels[0]='0%'
    ticklabels[-1]='100%'
    pylab.setp(pylab.gca(), xticklabels=ticklabels)

    pylab.setp(pylab.gca(), yticklabels=['0%','100%'])
    ticks=pylab.getp(pylab.gca(),'yticks')
    ticklabels=len(ticks)*['']
    #ticklabels[0]='0%'
    ticklabels[-1]='100%'
    pylab.setp(pylab.gca(), yticklabels=ticklabels)

    xticklabels = pylab.getp(pylab.gca(), 'xticklabels')
    yticklabels = pylab.getp(pylab.gca(), 'yticklabels')
    pylab.setp(xticklabels, fontsize=fontsize)
    pylab.setp(yticklabels, fontsize=fontsize)
Example #5
0
def add_percent_ticks():
    ticks = pylab.getp(pylab.gca(), 'xticks')
    ticklabels = len(ticks) * ['']
    ticklabels[0] = '0%'
    ticklabels[-1] = '100%'
    pylab.setp(pylab.gca(), xticklabels=ticklabels)

    pylab.setp(pylab.gca(), yticklabels=['0%', '100%'])
    ticks = pylab.getp(pylab.gca(), 'yticks')
    ticklabels = len(ticks) * ['']
    #ticklabels[0]='0%'
    ticklabels[-1] = '100%'
    pylab.setp(pylab.gca(), yticklabels=ticklabels)

    xticklabels = pylab.getp(pylab.gca(), 'xticklabels')
    yticklabels = pylab.getp(pylab.gca(), 'yticklabels')
    pylab.setp(xticklabels, fontsize=fontsize)
    pylab.setp(yticklabels, fontsize=fontsize)
Example #6
0
 def modifValZone(self, nameVar, ind, val):
     """modifier dans la zone nameVar la valeur
     ou liste valeur, attention le texte de la zone contient nom et valeur"""
     obj = self.listeZoneText[nameVar][ind].getObject()
     if type(obj) == type([2, 3]):
         for i in range(len(obj)):
             pl.setp(obj[i], text=str(val[i]))
     else:
         nom = pl.getp(obj, 'text').split('\n')[0]
         pl.setp(obj, text=nom + '\n' + str(val)[:16])
     self.redraw()
Example #7
0
 def modifValZone(self, nameVar, ind, val):
     """modifier dans la zone nameVar la valeur
     ou liste valeur, attention le texte de la zone contient nom et valeur"""
     obj = self.listeZoneText[nameVar][ind].getObject()
     if type(obj) == type([2, 3]):
         for i in range(len(obj)):
             pl.setp(obj[i], text=str(val[i]))
     else:
         nom = pl.getp(obj, "text").split("\n")[0]
         pl.setp(obj, text=nom + "\n" + str(val)[:16])
     self.redraw()
Example #8
0
 def modifZoneAttr(self, nameVar, ind, val, media, xy):
     # modify xy
     zone = self.listeZone[nameVar][ind]
     if len(xy[0]) == 3: x, y, z = zip(*xy)
     else: x, y = zip(*xy)
     zone.set_data(x, y)
     # modify media
     if type(media) != type([2]): media = [int(media)]
     self.listeZmedia[nameVar][ind] = media
     # modify text
     textObj = self.listeZoneText[nameVar][ind]
     if type(textObj) == type([2, 3]):
         name = pl.getp(textObj[0], 'text').split('\n')[0]
         pl.setp(textObj[0], text=name + '\n' + str(val)[:16])
         for i in range(len(z)):
             pl.setp(textObj[i + 1], text=str(z[i]))
     else:
         name = pl.getp(textObj, 'text').split('\n')[0]
         pl.setp(textObj, text=name + '\n' + str(val)[:16])
     self.redraw()
Example #9
0
 def plot_stack_weight(self,h=None):
     if h is None:
         try:
             h = self.h
         except:
             h = self.get_hh()
     if isinstance(h,pd.core.frame.DataFrame):
         h_tmp = {}
         h_tmp['weight'] = h
         h = pd.Panel(h_tmp).transpose(1,2,0)
     zhfont1 = matplotlib.font_manager.FontProperties(fname='C:\Windows\Fonts\simkai.ttf')#自定义字体为楷体
     #画出权重的堆积曲线
 #    ax = hh.plot(kind='area')
 #    ax.set_ylim((0,1))
 #    ax.set_title(freq_dict[freq][0]+' change   datalength '+str(freq_len*freq_dict[freq][1])+'days')
     axes = {}
     for method in h.minor_axis:
         hh = h[:,:,method].T
         hh = hh.loc[:,hh.mean().sort_values(ascending=True).index]
         hh = hh.rename(columns=self.CODE_DICT)
         
         fig,ax = plt.subplots()
         #area图有个反人性的地方:legend的颜色顺序和图的颜色顺序相反,这里想办法设置一下
         a = ax.stackplot(hh.index,hh.T)
         try:
             ax.legend([i.decode('utf-8') for i in hh.columns[::-1]],prop=zhfont1)
         except:
             ax.legend(list(hh.columns[::-1]),prop=zhfont1)
         color = []
         for i in range(self.n):
             color.append(plt.getp(a[i],'facecolor'))
         color = color[::-1]
         for i in range(self.n):
             plt.setp(a[i],'facecolor',color[i])
         ax.set_xlim(tuple(hh.index[[0,-1]]))
         ax.set_ylim((0,1))
         plt.title(method)
         axes[method] = ax
     return h,axes
Example #10
0
def icolorbar(mappable,
              loc=2,
              orientation='horizontal',
              borderpad=1,
              width=None,
              height=None,
              ax=None,
              label=None,
              axes_kwargs=None,
              **kwargs):
    '''An inset colorbar.  Should be a simple replacement for colorbar
    orientation='horizontal', width='30%', height='2%'
    orientation='vertical', width='5%', height='25%'
    
    bbox_to_anchor=(1.05, 0., 1, 1),
    bbox_transform=ax2.transAxes,
    borderpad=0,
    
    http://matplotlib.org/examples/axes_grid/demo_colorbar_with_inset_locator.html
    '''

    if ax is None:
        ax = pylab.gca()
    if width is None:
        width = '30%' if orientation == 'horizontal' else '2%'
    if height is None:
        height = '2%' if orientation == 'horizontal' else '25%'

    if label is None:
        try:
            label = mappable.get_label()
            if label.startswith('_'):
                # hide internal names
                label = ''
        except:
            label = ''

    tmp = dict(
        nticks=3,
        ticks=None,
        ticknames=None,
        tickfmt=None,
        tickfcn=None,
        orientation=orientation,
        rotate=None,
        outline=True,
        outline_props=dict(),
        color=None,
    )
    tmp.update(kwargs)
    nticks = tmp.pop('nticks')
    ticks = tmp.pop('ticks')
    tickfmt = tmp.pop('tickfmt')
    tickfcn = tmp.pop('tickfcn')
    ticknames = tmp.pop('ticknames')
    rotate = tmp.pop('rotate')
    outlinetext = tmp.pop('outline')
    outline_props = tmp.pop('outline_props')
    color = tmp.pop('color')

    if 'cax' not in tmp:
        if axes_kwargs is None:
            axes_kwargs = {'borderpad': borderpad}
        tmp['cax'] = inset_axes(ax,
                                width=width,
                                height=height,
                                loc=loc,
                                **axes_kwargs)

    cb = pylab.colorbar(mappable, **tmp)
    cb.set_label(label)

    if ticks is None:
        ticks = np.linspace(cb.vmin, cb.vmax, nticks)
    cb.set_ticks(ticks)

    if tickfcn is not None:
        ticks = map(tickfcn, ticks)

    if tickfmt is not None:
        cb.set_ticklabels(map(tickfmt.format, ticks))

    if ticknames is not None:
        cb.set_ticklabels(ticknames)

    if rotate is not None:
        if not isinstance(rotate, (int, float)):
            rotate = 90

        pylab.setp(pylab.xticks(axes=cb.ax)[1], rotation=rotate, ha='center')

    if color is not None:
        if orientation == 'horizontal':
            pylab.setp(pylab.getp(cb.ax.axes, 'xticklabels'), color=color)
            pylab.setp(pylab.getp(cb.ax.xaxis, 'label'), color=color)
        else:
            pylab.setp(pylab.getp(cb.ax.axes, 'yticklabels'), color=color)
            pylab.setp(pylab.getp(cb.ax.yaxis, 'label'), color=color)

    if outlinetext:
        if orientation == 'horizontal':
            items = [cb.ax.xaxis.get_label(), cb.ax.xaxis.get_ticklabels()]
        else:
            items = [cb.ax.yaxis.get_label(), cb.ax.yaxis.get_ticklabels()]
        outline(items, **outline_props)

    pylab.sca(ax)
    return cb
Example #11
0
def decisionSurface(classifier, fileName=None, **args):

    global data
    global numpy_container
    classifier.train(data)

    numContours = 3
    if 'numContours' in args:
        numContours = args['numContours']
    title = None
    if 'title' in args:
        title = args['title']
    markersize = 5
    fontsize = 'medium'
    if 'markersize' in args:
        markersize = args['markersize']
    if 'fontsize' in args:
        fontsize = args['fontsize']
    contourFontsize = 10
    if 'contourFontsize' in args:
        contourFontsize = args['contourFontsize']
    showColorbar = False
    if 'showColorbar' in args:
        showColorbar = args['showColorbar']
    show = True
    if fileName is not None:
        show = False
    if 'show' in args:
        show = args['show']

    # setting up the grid
    delta = 0.01
    if 'delta' in args:
        delta = args['delta']

    x = arange(xmin, xmax, delta)
    y = arange(ymin, ymax, delta)

    Z = numpy.zeros((len(x), len(y)), numpy.float)
    gridX = numpy.zeros((len(x) * len(y), 2), numpy.float)
    n = 0
    for i in range(len(x)):
        for j in range(len(y)):
            gridX[n][0] = x[i]
            gridX[n][1] = y[j]
            n += 1

    if not numpy_container:
        gridData = VectorDataSet(gridX)
        gridData.attachKernel(data.kernel)
    else:
        gridData = PyVectorDataSet(gridX)
    results = classifier.test(gridData)

    n = 0
    for i in range(len(x)):
        for j in range(len(y)):
            Z[i][j] = results.decisionFunc[n]
            n += 1

    #pylab.figure()
    im = pylab.imshow(numpy.transpose(Z),
                      interpolation='bilinear',
                      origin='lower',
                      cmap=pylab.cm.gray,
                      extent=(xmin, xmax, ymin, ymax))

    if numContours == 1:
        C = pylab.contour(numpy.transpose(Z), [0],
                          origin='lower',
                          linewidths=(3),
                          colors='black',
                          extent=(xmin, xmax, ymin, ymax))
    elif numContours == 3:
        C = pylab.contour(numpy.transpose(Z), [-1, 0, 1],
                          origin='lower',
                          linewidths=(1, 3, 1),
                          colors='black',
                          extent=(xmin, xmax, ymin, ymax))
    else:
        C = pylab.contour(numpy.transpose(Z),
                          numContours,
                          origin='lower',
                          linewidths=2,
                          extent=(xmin, xmax, ymin, ymax))

    pylab.clabel(C, inline=1, fmt='%1.1f', fontsize=contourFontsize)

    # plot the data
    scatter(data, markersize=markersize)
    xticklabels = pylab.getp(pylab.gca(), 'xticklabels')
    yticklabels = pylab.getp(pylab.gca(), 'yticklabels')
    pylab.setp(xticklabels, fontsize=fontsize)
    pylab.setp(yticklabels, fontsize=fontsize)

    if title is not None:
        pylab.title(title, fontsize=fontsize)
    if showColorbar:
        pylab.colorbar(im)

    # colormap:
    pylab.hot()
    if fileName is not None:
        pylab.savefig(fileName)
    if show:
        pylab.show()
            fitData['QF'][ejThreshold].append(bestQF)

            # Plot figures if wished for
            if plotFigures:
                # Left: 2d distribution of chi square. (x = neutron flux // y = quenching factor)
                # Right: Experimental residual spectrum + best fit simulation (x = NPE // y = counts)
                fig = plt.figure(figsize=(6.5,3.25),edgecolor='k',facecolor='w')
                ax0 = plt.subplot(121)
                extent = [sArr[0]/1000.0,sArr[-1]/1000.0,qfSamplingArr[0],qfSamplingArr[-1]]
                h = np.reshape(x2Arr,(nQF,nS))
                plt.imshow(h,aspect='auto',cmap=colorMap,origin='lower',extent=extent,norm=LogNorm(vmin=x2PlotLims[0],vmax=x2PlotLims[1]))
                plt.text(0.7,0.0945,r'$\chi^2$',ha='center',va='center',fontsize=legendFS)
                formatter = LogFormatter(10, labelOnlyBase=False)
                cbaxes = fig.add_axes([0.17, 0.87, 0.25, 0.050])
                cb=plt.colorbar(cax=cbaxes, orientation='horizontal',ticks=x2Ticks, format=formatter)
                plt.setp(plt.getp(cb.ax.axes, 'xticklabels'), fontsize=labelFS,color=colors.black)

                plt.sca(ax0)
                plt.xlim(extent[0],extent[1])
                plt.ylim(extent[2],extent[3])
                plt.xlabel('Neutron flux [1000 n/s]')
                plt.ylabel('Quenching factor')
                ctr = plt.contour(h,[np.min(h)+1,np.min(h)+2],extent=extent,linestyles=['solid','dotted'],colors=['w','w'],origin='lower')

                # Extract sigma levels from contour line
                p = ctr.collections[0].get_paths()[0]
                v = p.vertices
                x = v[:,0]
                y = v[:,1]
                maxScaling = np.max(x) * 1000.0
                minScaling = np.min(x) * 1000.0
Example #13
0
def icolorbar(mappable, loc=2, orientation='horizontal', borderpad=1,
              width=None, height=None, ax=None, 
              label=None, axes_kwargs=None,
              **kwargs):
    '''An inset colorbar.  Should be a simple replacement for colorbar
    orientation='horizontal', width='30%', height='2%'
    orientation='vertical', width='5%', height='25%'
    
    bbox_to_anchor=(1.05, 0., 1, 1),
    bbox_transform=ax2.transAxes,
    borderpad=0,
    
    http://matplotlib.org/examples/axes_grid/demo_colorbar_with_inset_locator.html
    '''
    
    if ax is None: 
        ax = pylab.gca()
    if width is None:
        width = '30%' if orientation == 'horizontal' else '2%'
    if height is None:
        height = '2%' if orientation == 'horizontal' else '25%'
        
    if label is None:
        try:
            label = mappable.get_label()
            if label.startswith('_'):
                # hide internal names
                label = ''
        except:
            label = ''
    
    
    
    tmp = dict(
        nticks=3,
        ticks=None,
        ticknames=None,
        tickfmt=None,
        tickfcn=None,
        orientation=orientation,
        rotate=None,
        outline=True,
        outline_props=dict(),
        color=None,
    )
    tmp.update(kwargs)
    nticks = tmp.pop('nticks')
    ticks = tmp.pop('ticks')
    tickfmt = tmp.pop('tickfmt')
    tickfcn = tmp.pop('tickfcn')
    ticknames = tmp.pop('ticknames')
    rotate = tmp.pop('rotate')
    outlinetext = tmp.pop('outline')
    outline_props = tmp.pop('outline_props')
    color = tmp.pop('color')
    
    if 'cax' not in tmp:
        if axes_kwargs is None:
            axes_kwargs = {'borderpad':borderpad}
        tmp['cax'] = inset_axes(ax, width=width, height=height, loc=loc, **axes_kwargs)
    
    cb = pylab.colorbar(mappable, **tmp)
    cb.set_label(label)
    
    if ticks is None:
        ticks = np.linspace(cb.vmin, cb.vmax, nticks)
    cb.set_ticks(ticks)
    
    if tickfcn is not None:
        ticks = map(tickfcn, ticks)
    
    if tickfmt is not None:
        cb.set_ticklabels(map(tickfmt.format, ticks))
    
    if ticknames is not None:
        cb.set_ticklabels(ticknames)
    
    if rotate is not None:
        if not isinstance(rotate, (int,float)):
            rotate = 90
            
        pylab.setp(pylab.xticks(axes=cb.ax)[1], rotation=rotate, ha='center')
    
    if color is not None:
        if orientation == 'horizontal':
            pylab.setp(pylab.getp(cb.ax.axes, 'xticklabels'), color=color)
            pylab.setp(pylab.getp(cb.ax.xaxis, 'label'), color=color)
        else:
            pylab.setp(pylab.getp(cb.ax.axes, 'yticklabels'), color=color)
            pylab.setp(pylab.getp(cb.ax.yaxis, 'label'), color=color)
    
    if outlinetext:
        if orientation == 'horizontal':
            items = [cb.ax.xaxis.get_label(),
                     cb.ax.xaxis.get_ticklabels()]
        else:
            items = [cb.ax.yaxis.get_label(),
                     cb.ax.yaxis.get_ticklabels()]
        outline(items, **outline_props)
    
    
    pylab.sca(ax)
    return cb
Example #14
0
def plotOrbitalEnergyChange(p, m2, label):
    """Plot the change in orbital energy.
    
    Keyword arguments:
    p -- MESA profile
    m2 -- mass of the secondary
    label -- text appearing in legend
    """
    import mesa_reader as mr
    import matplotlib.pylab as plt
    import numpy as np
    import os
    from math import log
    from scipy.integrate import cumtrapz
    import math

    # import function from another file
    from ipynb.fs.full.functions import getMaxRadiusProfile

    G = 6.67408e-11  # gravitational constant
    # change G to cgs units
    G = G * 1e3

    coreMass = p.he_core_mass + p.c_core_mass + p.o_core_mass + p.si_core_mass + p.fe_core_mass
    # change from Msuns to grams
    coreMass = coreMass * 1.989e33

    # get rshred
    r2 = getR2(m2)
    m2 = m2 * 1.989e33  # units
    r2 = r2 * 69.551e9  # units
    rshred = r2 * (2 * coreMass / m2)**(1 / 3)

    radius = p.radius
    radius = radius * 69.551e9

    masses = p.mass
    masses = masses * 1.989e33

    ri = p.radius[0] * 69.551e9
    mi = p.initial_mass * 1.989e33

    deltaEOrb = (mi / ri) - (masses / radius)
    deltaEOrb = deltaEOrb * G * m2 / 2
    deltaEOrb = abs(deltaEOrb)

    # look through everything in the radius array and compare it to rshred
    # when the value is <= rshred, save that index
    # chop the integrand and radius arrays at that index
    i = 0
    for x in radius:
        if x > rshred:
            i += 1

    radius = radius[100:i]
    deltaEOrb = deltaEOrb[100:i]

    point = plt.plot(radius[len(radius) - 1], deltaEOrb[len(deltaEOrb) - 1],
                     'o')
    y = plt.getp(point[0], 'color')
    plt.loglog(radius, deltaEOrb, label=label, color=y)
Example #15
0
def plotDragLum(p, m2, label):
    """Plot the drag luminosity.
    
    Keyword arguments:
    p -- MESA profile
    m2 -- mass of the secondary
    label -- text appearing in legend
    """
    import mesa_reader as mr
    import matplotlib.pylab as plt
    import numpy as np
    import os
    from math import log
    from scipy.integrate import cumtrapz
    import math

    # import function from another file
    from ipynb.fs.full.functions import getMaxRadiusProfile

    G = 6.67408e-11  # gravitational constant
    # change G to cgs units
    G = G * 1e3

    coreMass = p.he_core_mass + p.c_core_mass + p.o_core_mass + p.si_core_mass + p.fe_core_mass
    # change from Msuns to grams
    coreMass = coreMass * 1.989e33

    # get rshred
    r2 = getR2(m2)
    m2 = m2 * 1.989e33  # units
    r2 = r2 * 69.551e9  # units
    rshred = r2 * (2 * coreMass / m2)**(1 / 3)

    radius = p.radius
    radius = radius * 69.551e9

    masses = p.mass
    masses = masses * 1.989e33

    vkep_r = np.sqrt(G * masses / radius)

    rho = p.logRho
    rho = 10**rho

    xi = 4

    rAcc = 2 * G * m2 / vkep_r**2

    dragLum = xi * math.pi * rAcc**2 * rho * vkep_r**3

    # stop at rshred
    i = 0
    for x in radius:
        if x > rshred:
            i += 1

    radius = radius[100:i]
    dragLum = dragLum[100:i]

    point = plt.plot(radius[len(radius) - 1], dragLum[len(dragLum) - 1], 'o')
    y = plt.getp(point[0], 'color')
    plt.loglog(radius, dragLum, label=label, color=y)
Example #16
0
def plotTInspiral(p, m2, label):
    """Plot the inspiral time scale.
    
    Keyword arguments:
    p -- MESA profile
    m2 -- mass of the secondary
    label -- text appearing in the legend
    """
    import mesa_reader as mr
    import matplotlib.pylab as plt
    import numpy as np
    import os
    from math import log
    from scipy.integrate import cumtrapz
    import math

    # import function from another file
    from ipynb.fs.full.functions import getMaxRadiusProfile

    G = 6.67408e-11  # gravitational constant
    # change G to cgs units
    G = G * 1e3

    coreMass = p.he_core_mass + p.c_core_mass + p.o_core_mass + p.si_core_mass + p.fe_core_mass
    # change from Msuns to grams
    coreMass = coreMass * 1.989e33

    radius = p.radius
    radius = radius * 69.551e9

    # setting up constants
    r2 = getR2(m2)
    m2 = m2 * 1.989e33  # units
    r2 = r2 * 69.551e9  # units
    xi = 4
    rshred = r2 * (2 * coreMass / m2)**(1 / 3)
    k = 4 * xi * math.pi * G * m2

    # density
    rho = p.logRho
    rho = 10**rho

    # masses
    masses = p.mass
    masses = masses * 1.989e33

    # keplerian velocity
    vkep_r = np.sqrt(G * masses / radius)

    # dM/dr
    dMdr = np.diff(masses) / np.diff(radius)

    # make all the array sizes the same
    vkep_r = vkep_r[:-1]
    radius = radius[:-1]
    rho = rho[:-1]
    masses = masses[:-1]

    # integrand
    integrand = (dMdr - (masses / radius)) * vkep_r / (k * radius * rho)

    # look through everything in the radius array and compare it to rshred
    # when the value is <= rshred, save that index
    # chop the integrand and radius arrays at that index
    i = 0
    for x in radius:
        if x > rshred:
            i += 1

#     radius = radius[100:i] # cut first
#     integrand = integrand[100:i] # cut first

# actually integrate
    tInspiral = cumtrapz(y=integrand, x=radius)

    radius = radius[100:i]  # int first
    tInspiral = tInspiral[100:i]  # int first

    #     radius = radius[:-1] # cut first

    radius = np.flip(radius)

    point = plt.plot(radius[0], tInspiral[0], 'o')
    y = plt.getp(point[0], 'color')
    plt.loglog(radius, tInspiral, label=label, color=y, linestyle=':')
Example #17
0
def decisionSurface(classifier, fileName = None, **args) :

    global data
    global numpy_container
    classifier.train(data)

    numContours = 3
    if 'numContours' in args :
        numContours = args['numContours']
    title = None
    if 'title' in args :
        title = args['title']
    markersize=5
    fontsize = 'medium'
    if 'markersize' in args :
        markersize = args['markersize']
    if 'fontsize' in args :
        fontsize = args['fontsize']
    contourFontsize = 10
    if 'contourFontsize' in args :
        contourFontsize = args['contourFontsize']    
    showColorbar = False
    if 'showColorbar' in args :
        showColorbar = args['showColorbar']
    show = True
    if fileName is not None :
        show = False
    if 'show' in args :
        show = args['show']

    # setting up the grid
    delta = 0.01
    if 'delta' in args :
        delta = args['delta']
        

    x = arange(xmin, xmax, delta)
    y = arange(ymin, ymax, delta)

    Z = numpy.zeros((len(x), len(y)), numpy.float)
    gridX = numpy.zeros((len(x) *len(y), 2), numpy.float)
    n = 0
    for i in range(len(x)) :
	for j in range(len(y)) :
	    gridX[n][0] = x[i]
	    gridX[n][1] = y[j]
	    n += 1

    if not numpy_container :
        gridData = VectorDataSet(gridX)
        gridData.attachKernel(data.kernel)
    else :
        gridData = PyVectorDataSet(gridX)
    results = classifier.test(gridData)

    n = 0
    for i in range(len(x)) :
	for j in range(len(y)) :
	    Z[i][j] = results.decisionFunc[n]
	    n += 1
    
    #pylab.figure()
    im = pylab.imshow(numpy.transpose(Z), 
                      interpolation='bilinear', origin='lower',
                      cmap=pylab.cm.gray, extent=(xmin,xmax,ymin,ymax) )

    if numContours == 1 :
        C = pylab.contour(numpy.transpose(Z),
                          [0],
                          origin='lower',
                          linewidths=(3),
                          colors = 'black',
                          extent=(xmin,xmax,ymin,ymax))
    elif numContours == 3 :
        C = pylab.contour(numpy.transpose(Z),
                          [-1,0,1],
                          origin='lower',
                          linewidths=(1,3,1),
                          colors = 'black',
                          extent=(xmin,xmax,ymin,ymax))
    else :
        C = pylab.contour(numpy.transpose(Z),
                          numContours,
                          origin='lower',
                          linewidths=2,
                          extent=(xmin,xmax,ymin,ymax))

    pylab.clabel(C,
                 inline=1,
                 fmt='%1.1f',
                 fontsize=contourFontsize)
    
    # plot the data
    scatter(data, markersize=markersize)
    xticklabels = pylab.getp(pylab.gca(), 'xticklabels')
    yticklabels = pylab.getp(pylab.gca(), 'yticklabels')
    pylab.setp(xticklabels, fontsize=fontsize)
    pylab.setp(yticklabels, fontsize=fontsize)

    if title is not None :
        pylab.title(title, fontsize=fontsize)
    if showColorbar :
        pylab.colorbar(im)

    # colormap:
    pylab.hot()
    if fileName is not None :
        pylab.savefig(fileName)
    if show :
        pylab.show()
Example #18
0
 def FillTree(self):
     # For ease of coding
     T = self.TreeCtrlMain
     
     # starting from the top, grab ALL the wx windows available
     w = wx.GetTopLevelWindows()
     
     # find all the windows that are plot windows for wxagg
     self.plot_windows = []
     for x in w:
         if type(x) == matplotlib.backends.backend_wxagg.FigureFrameWxAgg:
             self.plot_windows.append(x)
     
     # get all the figures associated with these windows
     self.figures = []
     for x in self.plot_windows:
         self.figures.append(x.canvas.figure)
         
     # all items in the tree must have data associated with it 
     # we use a dictionary of important values for ease of coding
     # children, parents and selfs are all tree ID's
     T.SetItemData(self.tree_root, 
       wx.TreeItemData({"string":"Current Session", 
                        "type":"tree_root_title", 
                        "self":self.tree_root, 
                        "parent":None, 
                        "children":[],
                        "window":None,
                        "figure":None,
                        "axes":None,
                        "line":None}))
     
     # fill the tree items!
     
     # kill all the root's children
     T.DeleteChildren(self.tree_root)
     
     # now loop over the figures and add a branch for each
     for nf in range(0,len(self.figures)):
         f = self.figures[nf]
         w = self.plot_windows[nf]
         
         # add the tree item corresponding to the figure
         cf_title = self.plot_windows[nf].GetTitle()
         cf = T.AppendItem(self.tree_root, cf_title)
         
         # we need to append this to the children array in the root
         self.AppendTreeItemData(self.tree_root, "children", cf)
         
         # we also need to set the tree item data for this item
         T.SetItemData(cf, 
           wx.TreeItemData({"string":cf_title, 
                            "type":"figure_title", 
                            "self":cf, 
                            "parent":self.tree_root, 
                            "children":[],
                            "window":w,
                            "figure":f,
                            "axes":None,
                            "line":None}))
         
         # now loop over the axes
         for na in range(0,len(f.axes)):
             a = f.axes[na]
                             
             # add the axes tree item to the figure item
             ca_title = "axes "+str(na)
             ca = T.AppendItem(cf, ca_title)
             
             # now append this id to the children array of the figure
             self.AppendTreeItemData(cf, "children", ca)
         
             # we also need to set the tree item data for this item
             T.SetItemData(ca, 
               wx.TreeItemData({"string":ca_title, 
                                "type":"axes_tree_label", 
                                "self":ca, 
                                "parent":cf, 
                                "children":[],
                                "window":w,
                                "figure":f,
                                "axes":a,
                                "line":None}))
                             
             # add the "axes title" item to the tree and axes children list
             p = T.AppendItem(ca, "Axes Title")
             self.AppendTreeItemData(ca, "children", p)
             T.SetItemData(p, 
                 wx.TreeItemData({"string":a.title.get_text(),
                                  "type":"axes_title", 
                                  "self":p, 
                                  "parent":ca, 
                                  "children":[],
                                  "window":w,
                                  "figure":f,
                                  "axes":a,
                                  "line":None}))
             
             # add the "y-scale" item to the tree and axes children list
             p = T.AppendItem(ca, "y-scaling = 1.0")
             self.AppendTreeItemData(ca, "children", p)
             T.SetItemData(p, 
                 wx.TreeItemData({"type":"y_scale", 
                                  "string":"1.0",
                                  "last_value":1.0,
                                  "self":p, 
                                  "parent":ca, 
                                  "children":[],
                                  "window":w,
                                  "figure":f,
                                  "axes":a,
                                  "line":None}))
             
             
             
             # now loop over the lines
             lines = a.get_lines()
             for nl in range(0,len(lines)):
                 l = lines[nl]
                 
                 # add the axes tree item to the figure item
                 cl_title = "line "+str(nl)
                 cl = T.AppendItem(ca, cl_title)
                 
                 # now append this id to the children array of the figure
                 self.AppendTreeItemData(ca, "children", cl)
             
                 # we also need to set the tree item data for this item
                 T.SetItemData(cl, 
                   wx.TreeItemData({"string":cl_title, 
                                    "type":"line_title", 
                                    "self":cl, 
                                    "parent":ca, 
                                    "children":[],
                                    "window":w,
                                    "figure":f,
                                    "axes":a,
                                    "line":l}))
             
                 # now we set the individual line attributes
                 for x in self.line_attributes:
                     # make the tree branch
                     y = T.AppendItem(cl, x+": '"+str(pylab.getp(l,x))+"'")
                     
                     self.AppendTreeItemData(cl, "children", y)
                     
                     T.SetItemData(y,
                       wx.TreeItemData({"string": str(pylab.getp(l,x)),
                                        "type":x,
                                        "self":y,
                                        "parent":cl,
                                        "children":[],
                                        "window":w,
                                        "figure":f,
                                        "axes":a,
                                        "line":l}))
     
     # now expand the bitch
     T.Expand(self.tree_root)