Exemplo n.º 1
0
    def plot(self):
        """
        Plotting function
        """
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.plot(self.radius, self.tcond-self.tcond[0], 'k--', label='Cond. temp.')
        xs, ys = mlab.poly_between(self.radius, self.temprmmean-self.temprmstd-self.temprmmean[0],\
                                   self.temprmmean+self.temprmstd-self.temprmmean[0])
        ax.fill(xs, ys, facecolor='#aec7e8', edgecolor='None')
        ax.plot(self.radius, self.temprmmean-self.temprmmean[0], ls='-', c='#1f77b4',\
                lw=2, label='Mean temp.')
        xs, ys = mlab.poly_between(self.radius, self.tempEqmean-self.tempEqstd-self.temprmmean[0],\
                                   self.tempEqmean+self.tempEqstd-self.temprmmean[0])
        ax.fill(xs, ys, facecolor='#ffbb78', edgecolor='None')
        ax.plot(self.radius, self.tempEqmean-self.temprmmean[0],
                ls='-.', c='#ff7f0e', lw=2, label='Temp. equat')
        xs, ys = mlab.poly_between(self.radius, self.tempPolmean-self.tempPolstd-self.temprmmean[0],\
                                   self.tempPolmean+self.tempPolstd-self.temprmmean[0])
        ax.fill(xs, ys, facecolor='#98df8a', edgecolor='None')
        ax.plot(self.radius, self.tempPolmean-self.temprmmean[0],
                ls='--', c='#2ca02c', lw=2, label='Temp. Pol')
        ax.set_xlim(self.ri, self.ro)
        ax.set_ylim(0., 1.)
        ax.set_ylabel('T')
        ax.set_xlabel('r')
        ax.legend(loc='upper right', frameon=False)

        fig1 = plt.figure()
        ax1 = fig1.add_subplot(111)
        xs, ys = mlab.poly_between(self.colat*180./np.pi, self.nusstopmean-self.nusstopstd,\
                                   self.nusstopmean+self.nusstopstd)
        ax1.fill(xs, ys, facecolor='#aec7e8', edgecolor='None')
        ax1.plot(self.colat*180./np.pi, self.nusstopmean, ls='-', color='#1f77b4',\
                 lw=2, label='Top Nu')

        xs, ys = mlab.poly_between(self.colat*180./np.pi, self.nussbotmean-self.nussbotstd,\
                                   self.nussbotmean+self.nussbotstd)
        ax1.fill(xs, ys, facecolor='#ffbb78', edgecolor='None')
        ax1.plot(self.colat*180./np.pi, self.nussbotmean, ls='--', c='#ff7f0e',\
                 lw=2, label='Bot Nu')
        ax1.set_xlim(0., 180.)
        ax1.set_ylabel('Nu')
        ax1.set_xlabel('Theta')
        ax1.legend(loc='upper right', frameon=False)
        ax1.axvline(180./np.pi*np.arcsin(self.ri/self.ro), color='k', linestyle='--')
        ax1.axvline(180-180./np.pi*np.arcsin(self.ri/self.ro), color='k', linestyle='--')
Exemplo n.º 2
0
    def create_snapshot_chart(self, filename: str = '') -> str:
        """
        Create chart that depicts the memory allocation over time apportioned
        to the tracked classes.
        """
        try:
            from pylab import (figure, title, xlabel, ylabel, plot, fill,
                               legend, savefig)
            import matplotlib.mlab as mlab
        except ImportError:
            return self.nopylab_msg % ("memory allocation")

        classlist = self.tracked_classes

        times = [snapshot.timestamp for snapshot in self.snapshots]
        base = [0.0] * len(self.snapshots)
        poly_labels = []
        polys = []
        for cn in classlist:
            pct = [
                snapshot.classes[cn]['pct'] for snapshot in self.snapshots
                if snapshot.classes is not None
            ]
            if pct and max(pct) > 3.0:
                sz = [
                    float(fp.classes[cn]['sum']) / (1024 * 1024)
                    for fp in self.snapshots if fp.classes is not None
                ]
                sz = [sx + sy for sx, sy in zip(base, sz)]
                xp, yp = mlab.poly_between(times, base, sz)
                polys.append(((xp, yp), {'label': cn}))
                poly_labels.append(cn)
                base = sz

        figure()
        title("Snapshot Memory")
        xlabel("Execution Time [s]")
        ylabel("Virtual Memory [MiB]")

        sizes = [
            float(fp.asizeof_total) / (1024 * 1024) for fp in self.snapshots
        ]
        plot(times, sizes, 'r--', label='Total')
        sizes = [
            float(fp.tracked_total) / (1024 * 1024) for fp in self.snapshots
        ]
        plot(times, sizes, 'b--', label='Tracked total')

        for (args, kwds) in polys:
            fill(*args, **kwds)
        legend(loc=2)
        savefig(filename)

        return self.chart_tag % (self.relative_path(filename))
Exemplo n.º 3
0
    def contourf(self, dir, var, **kwargs):
        """
        Plot a windrose in filled mode. For each var bins, a line will be
        draw on the axes, a segment between each sector (center to center).
        Each line can be formated (color, width, ...) like with standard plot
        pylab command.

        Mandatory:
         * dir : 1D array - directions the wind blows from, North centred
         * var : 1D array - values of the variable to compute. Typically the wind
           speeds

        Optional:
         * nsector: integer - number of sectors used to compute the windrose
           table. If not set, nsectors=16, then each sector will be 360/16=22.5°,
           and the resulting computed table will be aligned with the cardinals
           points.
         * bins : 1D array or integer- number of bins, or a sequence of
           bins variable. If not set, bins=6, then
           bins=linspace(min(var), max(var), 6)
         * blowto : bool. If True, the windrose will be pi rotated,
           to show where the wind blow to (usefull for pollutant rose).
         * colors : string or tuple - one string color ('k' or 'black'), in this
           case all bins will be plotted in this color; a tuple of matplotlib
           color args (string, float, rgb, etc), different levels will be plotted
           in different colors in the order specified.
         * cmap : a cm Colormap instance from matplotlib.cm.
           - if cmap == None and colors == None, a default Colormap is used.

        others kwargs :
         * see help(pylab.plot)

        """

        bins, nbins, nsector, colors, angles, kwargs = self._init_plot(dir, var,
                                                                       **kwargs)
        null = kwargs.pop('facecolor', None)
        null = kwargs.pop('edgecolor', None)

        #closing lines
        angles = np.hstack((angles, angles[-1]-2*np.pi/nsector))
        vals = np.hstack((self._info['table'],
                         np.reshape(self._info['table'][:,0],
                                   (self._info['table'].shape[0], 1))))
        offset = 0
        for i in range(nbins):
            val = vals[i,:] + offset
            offset += vals[i, :]
            zorder = ZBASE + nbins - i
            xs, ys = poly_between(angles, 0, val)
            patch = self.fill(xs, ys, facecolor=colors[i],
                              edgecolor=colors[i], zorder=zorder, **kwargs)
            self.patches_list.extend(patch)
    def create_snapshot_chart(self, filename=''):
        """
        Create chart that depicts the memory allocation over time apportioned
        to the tracked classes.
        """
        try:
            from pylab import (figure, title, xlabel, ylabel, plot, fill,
                               legend, savefig)
            import matplotlib.mlab as mlab
        except ImportError:
            return self.nopylab_msg % ("memory allocation")

        classlist = self.tracked_classes

        times = [snapshot.timestamp for snapshot in self.snapshots]
        base = [0] * len(self.snapshots)
        poly_labels = []
        polys = []
        for cn in classlist:
            pct = [snapshot.classes[cn]['pct'] for snapshot in self.snapshots]
            if max(pct) > 3.0:
                sz = [float(fp.classes[cn]['sum']) / (1024 * 1024)
                      for fp in self.snapshots]
                sz = [sx + sy for sx, sy in zip(base, sz)]
                xp, yp = mlab.poly_between(times, base, sz)
                polys.append(((xp, yp), {'label': cn}))
                poly_labels.append(cn)
                base = sz

        figure()
        title("Snapshot Memory")
        xlabel("Execution Time [s]")
        ylabel("Virtual Memory [MiB]")

        sizes = [float(fp.asizeof_total) / (1024 * 1024)
                 for fp in self.snapshots]
        plot(times, sizes, 'r--', label='Total')
        sizes = [float(fp.tracked_total) / (1024 * 1024)
                 for fp in self.snapshots]
        plot(times, sizes, 'b--', label='Tracked total')

        for (args, kwds) in polys:
            fill(*args, **kwds)
        legend(loc=2)
        savefig(filename)

        return self.chart_tag % (self.relative_path(filename))
Exemplo n.º 5
0
from __future__ import division
import numpy as np
import matplotlib as mpl
import matplotlib.mlab as mlab
import pylab as pl


yoffs = np.arange(10)
nplots = len(yoffs)
x = np.arange(0, 1, 0.1)
npoints = len(x)
y = np.zeros((nplots, len(x)))
stdy = np.zeros((nplots, len(x)))
verts = np.zeros((nplots, 2 * npoints, 2))  # each timepoint has a +ve and a -ve value
for ploti, yoff in enumerate(yoffs):
    y[ploti] = np.random.random(len(x)) / 2 + 0.25 + yoff
    stdy[ploti] = 0.2 + np.random.random(len(x)) * 0.2
    vert = mlab.poly_between(x, y[ploti] - stdy[ploti], y[ploti] + stdy[ploti])
    vert = np.asarray(vert).T
    verts[ploti] = vert

# can also use axes.fill() instead of a poly collection, or directly use axes.fill_between()
pcol = mpl.collections.PolyCollection(verts, facecolors="r", edgecolors="none", alpha=0.2)
a = pl.gca()
# pcol = a.fill_between(x, y+stdy, y-stdy, facecolors='r', edgecolors='none', alpha=0.2)
a.add_collection(pcol)
for ploti in range(nplots):
    a.plot(x, y[ploti], "r-")
a.set_xlim((0, 1))
Exemplo n.º 6
0
#!/usr/bin/env python
import matplotlib.mlab as mlab
from pylab import figure, show
import numpy as npy

x = npy.arange(0, 2, 0.01)
y1 = npy.sin(2*npy.pi*x)
y2 = npy.sin(4*npy.pi*x) + 2

fig = figure()
ax = fig.add_subplot(311)
ax2 = fig.add_subplot(312)
ax3 = fig.add_subplot(313)


xs, ys = mlab.poly_between(x, 0, y1)
ax.fill(xs, ys)
ax.set_ylabel('between y1 and 0')

xs, ys = mlab.poly_between(x, y1, 1)
ax2.fill(xs, ys)
ax2.set_ylabel('between y1 and 1')

xs, ys = mlab.poly_between(x, y1, y2)
ax3.fill(xs, ys)
ax3.set_ylabel('between y1 and y2')
ax3.set_xlabel('x')
show()

Exemplo n.º 7
0
#!/usr/bin/env python
import matplotlib.mlab as mlab
from pylab import figure, show
import numpy as npy

x = npy.arange(0, 2, 0.01)
y1 = npy.sin(2 * npy.pi * x)
y2 = npy.sin(4 * npy.pi * x) + 2

fig = figure()
ax = fig.add_subplot(311)
ax2 = fig.add_subplot(312)
ax3 = fig.add_subplot(313)

xs, ys = mlab.poly_between(x, 0, y1)
ax.fill(xs, ys)
ax.set_ylabel('between y1 and 0')

xs, ys = mlab.poly_between(x, y1, 1)
ax2.fill(xs, ys)
ax2.set_ylabel('between y1 and 1')

xs, ys = mlab.poly_between(x, y1, y2)
ax3.fill(xs, ys)
ax3.set_ylabel('between y1 and y2')
ax3.set_xlabel('x')
show()
Exemplo n.º 8
0
def plot(ocd,
         calib,
         file_name = "test.jpg",
         interpolation = False):
    fig = plt.figure(figsize=(12,6))
    ax1 = plt.subplot(111)
    plt.xlabel("{} - Calibrated date (BC)".format(ocd.name), fontsize=18)
    plt.ylabel("Radiocarbon determination (BP)", fontsize=18)


    plt.text(0., 0.99,"pyC14 v0.1; Xtof; Bellevue 2008-2012",
         horizontalalignment='left',
         verticalalignment='bottom',
         transform = ax1.transAxes,
         size=9,
         bbox=dict(facecolor='white', alpha=1, lw=0))


    # Calendar Age
    ax2 = plt.twinx()

    calib_0 = (ocd.likelihood.array)
    calib_1 = (ocd.posterior.array)
    if(interpolation):
        calib_0 = interpolate(calib_0)
        calib_1 = interpolate(calib_1)

    max_prob_ref = max(calib_0[:,1])
    min_prob_ref = min(calib_0[:,1])
    max_prob_calib = max(calib_1[:,1])
    min_prob_calib = min(calib_1[:,1])

    beta = ocd.adjust_comparaison()

    ax2.fill(
        calib_0[:,0],
        calib_0[:,1] + max(max_prob_ref, max_prob_calib)*0.3,
        'k',
        alpha=0.2,
        )
    ax2.plot(
        calib_0[:,0],
        calib_0[:,1] + max(max_prob_ref, max_prob_calib)*0.3,
        'k:',
        alpha=0.5
        )

    # Calendar Age bis
    ax2b = plt.twinx()


    ax2b.fill(
        calib_1[:,0],
        calib_1[:,1]/beta + max(max_prob_ref, max_prob_calib)*0.3,
        'k',
        alpha=0.5,
        )
    ax2b.plot(
        calib_1[:,0],
        calib_1[:,1]/beta + max(max_prob_ref, max_prob_calib)*0.3,
        'k',
        alpha=0.5
        )

    #print(min_prob_ref, min_prob_calib)
    #print(max_prob_ref, max_prob_calib)

    ax2.set_ybound(
        min(min_prob_ref, min_prob_calib), 
        max(max_prob_ref, max_prob_calib)*3)
    ax2b.set_ybound(
        min(min_prob_ref, min_prob_calib), 
        max(max_prob_ref, max_prob_calib)*3)
    ax2.set_axis_off()
    ax2b.set_axis_off()

    # Radiocarbon Age
    sample_interval = np.arange(ocd.date-4*ocd.error, ocd.date+4*ocd.error,1.)
    sample_curve = normpdf(sample_interval, ocd.date, ocd.error)
    max_sample_curve = max(sample_curve)

    line_x = np.array([0, max_sample_curve*3])
    line_y = np.array([ocd.date, ocd.date])

    ax3 = plt.twiny(ax1)
    for i in range(-1,2,1):
        ax3.plot(
            line_x,
            line_y+i*ocd.error,
            'k--',
            alpha=0.5-0.2*abs(i),
            lw=2-abs(i)
            )
    ax3.fill(
        sample_curve,
        sample_interval,
        'r',
        alpha=0.4
        )
    ax3.plot(
        sample_curve,
        sample_interval,
        'r',
        alpha=0.5
        )
    ax3.set_xbound(0,max_sample_curve*4)
    ax3.set_axis_off()


    # Calibration Curve
    xs, ys = mlab.poly_between(calib.array[:,0],
                               calib.array[:,1] - calib.array[:,2],
                               calib.array[:,1] + calib.array[:,2])
    ax1.fill(xs, ys, 'b', alpha=0.3)
    ax1.plot(
        calib.array[:,0],
        calib.array[:,1],
        'b',
        alpha=0.5,
        lw=1
        )

    # Confidence intervals

    ymin=[0.075, 0.05, 0.025]
    if(ocd.posterior.used):
        calibrated = ocd.posterior
    else:
        calibrated = ocd.likelihood

    for j in range(2,-1,-1):
        for i in calibrated.range[j]:
            ax1.axvspan(
                i[0], i[1],
                ymin=ymin[j],
                ymax=ymin[j]+0.07,
                facecolor='none',
                alpha=0.8)
            ax1.axvspan(
                i[0], i[1],
                ymin=ymin[j]+0.02,
                ymax=ymin[j]+0.07,
                facecolor='w',
                edgecolor='w',
                lw=2)

    comments = ocd.ref + "\n"
    comments += calib.ref + "\n"

    plt.text(0.55, 0.90,'{}'.format(comments),
         horizontalalignment='left',
         verticalalignment='center',
         transform = ax1.transAxes,
         bbox=dict(facecolor='white', alpha=0.9, lw=0))

    plt.text(0.745, 0.68,'{}'.format(calibrated.get_meta("",False)),
         horizontalalignment='left',
         verticalalignment='center',
         transform = ax1.transAxes,
         bbox=dict(facecolor='white', alpha=0.9, lw=0))

    # FIXME the following values 10 and 5 are arbitrary and could be probably
    # drawn from the f_m value itself, while preserving their ratio
    tl = len(ocd.likelihood.array[:,0])
    ax1.set_ybound(ocd.date - ocd.error * 8, ocd.date + ocd.error * 8)
    ax1.set_xbound(ocd.likelihood.array[0,0],ocd.likelihood.array[-1,0])

    #plt.savefig('image_%d±%d.pdf' %(f_m, sigma_m))
    plt.savefig(file_name)
    fig = plt.gcf()
    fig.clear()
Exemplo n.º 9
0
def plot(ocd,
        calib,
        file_name = "test.jpg",
        use_model = True):

    fig = plt.figure(figsize=(8,2))
    ax1 = plt.subplot(111)
    plt.ylabel("C14 age (BP)", fontsize=11)

    plt.text(-0.14, -0.11,"Date (BC)",
         horizontalalignment='left',
         verticalalignment='bottom',
         transform = ax1.transAxes,
         size=11)

    plt.text(0.0, 0.97,"pyC14 v0.1; Xtof; Ard-team",
         horizontalalignment='left',
         verticalalignment='bottom',
         transform = ax1.transAxes,
         size=7,
         bbox=dict(facecolor='white', alpha=1, lw=0))

    comments = ""
    comments += ocd.ref + "\n"
    comments += calib.ref + "\n"

    plt.text(0.55, 0.85,'{}'.format(comments),
         horizontalalignment='left',
         verticalalignment='center',
         transform = ax1.transAxes,
         size=8,
         bbox=dict(facecolor='white', alpha=0.9, lw=0))


    alphaY = 8
    if(ocd.posterior.used and use_model):
        calibrated = ocd.posterior
        alphaY = 6
    else:
        calibrated = ocd.likelihood

    # Calendar Age
    # imitate OxCal
    ax2 = plt.twinx()

    ax2.fill(
        calibrated.calibAxis,
        calibrated.prob + max(calibrated.prob)*0.3,
        'k',
        alpha=0.3
        )
    ax2.plot(
        calibrated.calibAxis,
        calibrated.prob + max(calibrated.prob)*0.3,
        'k',
        alpha=0.8
        )

    ax2.set_ybound(min(calibrated.prob),max(calibrated.prob)*1.7)
    tl = len(calibrated.calibAxis)
    ax2.set_xbound(calibrated.array[0,0],calibrated.array[-1,0])
    ax2.set_axis_off()

    # Radiocarbon Age
    sample_interval = np.arange(ocd.date-4*ocd.error, ocd.date+4*ocd.error,1.)
    sample_curve = normpdf(sample_interval, ocd.date, ocd.error)
    line_x = np.array([0, 1])
    line_y = np.array([ocd.date, ocd.date])

    ax3 = plt.twiny(ax1)
    for i in range(-1,2,1):
        ax3.plot(
            line_x,
            line_y+i*ocd.error,
            'k--',
            alpha=0.5-0.2*abs(i),
            lw=1.5-abs(i)
            )
    ax3.fill(
        sample_curve,
        sample_interval,
        'r',
        alpha=0.3
        )
    ax3.plot(
        sample_curve,
        sample_interval,
        'r',
        alpha=0.3,
        label='Radiocarbon determination (BP)'
        )
    ax3.set_xbound(0,max(sample_curve)*4)
    ax3.set_axis_off()

    # Calibration Curve
    xs, ys = mlab.poly_between(calib.array[:,0],
                               calib.array[:,1] - calib.array[:,2],
                               calib.array[:,1] + calib.array[:,2])
    ax1.fill(xs, ys, 'b', alpha=0.3)

    # Confidence intervals
    ymin=[0.14, 0.10, 0.06]

    for j in range(2,-1,-1):
        for i in calibrated.range[j]:
            ax1.axvspan(
                i[0], i[1],
                ymin=ymin[j],
                ymax=ymin[j]+0.07,
                facecolor='none',
                alpha=0.8)
            ax1.axvspan(
                i[0], i[1],
                ymin=ymin[j]+0.03,
                ymax=ymin[j]+0.07,
                facecolor='w',
                edgecolor='w',
                lw=2)

    # FIXME the following values 10 and 5 are arbitrary and could be probably
    # drawn from the f_m value itself, while preserving their ratio
    detla_BP = ocd.likelihood.mean - calibrated.mean
    ax1.set_ybound(ocd.date - ocd.error*alphaY + detla_BP, ocd.date + ocd.error*alphaY + detla_BP)
    ax1.set_xbound(calibrated.array[0,0],calibrated.array[-1,0])

    #plt.savefig('image_%d±%d.pdf' %(f_m, sigma_m))
    plt.savefig(file_name)
    fig = plt.gcf()
    fig.clear()
Exemplo n.º 10
0
    def on_draw(self):
        yup = self.ui.sigTop.value()
        ydown = self.ui.sigBottom.value()
        yrefup = self.ui.ref1Top.value()
        yrefdown = self.ui.ref1Bottom.value()
        yref2up = self.ui.ref2Top.value()
        yref2down = self.ui.ref2Bottom.value()
        n = self.ui.NumSignals.value()
        if n == 0:
            n = 1
        dh = self.ui.SigSpacing.value()

        self.lup[0].set_data([0, self.data["var"]["nx"]], [yup, yup])
        self.ldown[0].set_data([0, self.data["var"]["nx"]], [ydown, ydown])
        self.lref1up.set_data([0, self.data["var"]["nx"]], [yrefup, yrefup])
        self.lref1down.set_data([0, self.data["var"]["nx"]], [yrefdown, yrefdown])
        self.lref2up.set_data([0, self.data["var"]["nx"]], [yref2up, yref2up])
        self.lref2down.set_data([0, self.data["var"]["nx"]], [yref2down, yref2down])

        self.plt.clear()
        self.ref.clear()
        self.raw.clear()
        self.ref.clear()

        # Signals
        data = [np.mean(self.data["rawdata"][yup:ydown], 0)]
        self.raw.plot(self.data["wavelength"], data[0], color="black")
        if self.ui.multisig.checkState() == QtCore.Qt.Checked:
            if len(self.lup) > n:
                for i in range(n + 1, len(self.lup)):
                    self.axes.remove(self.lup[i])
                    self.axes.remove(self.ldown[i])
                self.lup = self.lup[:n]
                self.ldown = self.ldown[:n]
            if n > 1:
                if len(self.lup) < n:
                    for i in range(len(self.lup), n):
                        self.lup.append(mpl.lines.Line2D([0, self.data["var"]["nx"]], [0, 0], color="red"))
                        self.ldown.append(mpl.lines.Line2D([0, self.data["var"]["nx"]], [0, 0], color="red"))
                        self.axes.add_line(self.lup[i])
                        self.axes.add_line(self.ldown[i])
                for i in range(1, n):
                    data.append(np.mean(self.data["rawdata"][int(yup - dh * i) : int(ydown - dh * i)], 0))
                    self.raw.plot(self.data["wavelength"], data[i])
                    self.lup[i].set_data([0, self.data["var"]["nx"]], [int(yup - dh * i), int(yup - dh * i)])
                    self.ldown[i].set_data([0, self.data["var"]["nx"]], [int(ydown - dh * i), int(ydown - dh * i)])

                    # Sig StdDev
        drs = np.sqrt(np.var(self.data["rawdata"][yup:ydown], 0))
        if self.ui.rawsigStdDev.checkState() == QtCore.Qt.Checked:
            vx, vy = mlab.poly_between(self.data["wavelength"], data[0] - drs, data[0] + drs)
            self.raw.fill(vx, vy, color="red")

            # Reference Signal
        if yrefup != yrefdown:
            ref = np.mean(self.data["rawdata"][yrefup:yrefdown], 0)
            self.ref.plot(self.data["wavelength"], ref, color="black")
            # Std Dev
            delta = np.sqrt(np.var(self.data["rawdata"][yrefup:yrefdown], 0))
            if self.ui.refStdDev.checkState() == QtCore.Qt.Checked:
                vx, vy = mlab.poly_between(self.data["wavelength"], ref - delta, ref + delta)
                self.ref.fill(vx, vy, color="blue")
                DS = np.sqrt((drs / ref) ** 2 + ((data[0] * delta) / (ref ** 2)) ** 2)
                data[0] = data[0] / ref
                self.plt.plot(self.data["wavelength"], data[0], color="black")
            if self.ui.multisig.checkState() == QtCore.Qt.Checked:
                if n > 1:
                    for i in range(1, n):
                        data[i] = data[i] - ref
                        self.plt.plot(self.data["wavelength"], data[i])
            if self.ui.sigStdDev.checkState() == QtCore.Qt.Checked:
                vx, vy = mlab.poly_between(self.data["wavelength"], data[0] - DS, data[0] + DS)
                self.plt.fill(vx, vy)
        self.canvas.draw()
Exemplo n.º 11
0
    def on_draw(self):
        yup = self.ui.sigTop.value()
        ydown = self.ui.sigBottom.value()
        yrefup = self.ui.ref1Top.value()
        yrefdown = self.ui.ref1Bottom.value()
        yref2up = self.ui.ref2Top.value()
        yref2down = self.ui.ref2Bottom.value()
        n = self.ui.NumSignals.value()
        if n == 0: n = 1
        dh = self.ui.SigSpacing.value()

        self.lup[0].set_data([0, self.data["var"]['nx']], [yup, yup])
        self.ldown[0].set_data([0, self.data["var"]['nx']], [ydown, ydown])
        self.lref1up.set_data([0, self.data["var"]['nx']], [yrefup, yrefup])
        self.lref1down.set_data([0, self.data["var"]['nx']],
                                [yrefdown, yrefdown])
        self.lref2up.set_data([0, self.data["var"]['nx']], [yref2up, yref2up])
        self.lref2down.set_data([0, self.data["var"]['nx']],
                                [yref2down, yref2down])

        self.plt.clear()
        self.ref.clear()
        self.raw.clear()
        self.ref.clear()

        # Signals
        data = [np.mean(self.data["rawdata"][yup:ydown], 0)]
        self.raw.plot(self.data["wavelength"], data[0], color="black")
        if self.ui.multisig.checkState() == QtCore.Qt.Checked:
            if len(self.lup) > n:
                for i in range(n + 1, len(self.lup)):
                    self.axes.remove(self.lup[i])
                    self.axes.remove(self.ldown[i])
                self.lup = self.lup[:n]
                self.ldown = self.ldown[:n]
            if n > 1:
                if len(self.lup) < n:
                    for i in range(len(self.lup), n):
                        self.lup.append(
                            mpl.lines.Line2D([0, self.data["var"]['nx']],
                                             [0, 0],
                                             color="red"))
                        self.ldown.append(
                            mpl.lines.Line2D([0, self.data["var"]['nx']],
                                             [0, 0],
                                             color="red"))
                        self.axes.add_line(self.lup[i])
                        self.axes.add_line(self.ldown[i])
                for i in range(1, n):
                    data.append(
                        np.mean(
                            self.data["rawdata"][int(yup -
                                                     dh * i):int(ydown -
                                                                 dh * i)], 0))
                    self.raw.plot(self.data["wavelength"], data[i])
                    self.lup[i].set_data(
                        [0, self.data["var"]['nx']],
                        [int(yup - dh * i),
                         int(yup - dh * i)])
                    self.ldown[i].set_data(
                        [0, self.data["var"]['nx']],
                        [int(ydown - dh * i),
                         int(ydown - dh * i)])

        # Sig StdDev
        drs = np.sqrt(np.var(self.data["rawdata"][yup:ydown], 0))
        if self.ui.rawsigStdDev.checkState() == QtCore.Qt.Checked:
            vx, vy = mlab.poly_between(self.data["wavelength"], data[0] - drs,
                                       data[0] + drs)
            self.raw.fill(vx, vy, color="red")

        # Reference Signal
        if yrefup != yrefdown:
            ref = np.mean(self.data["rawdata"][yrefup:yrefdown], 0)
            self.ref.plot(self.data["wavelength"], ref, color="black")
            # Std Dev
            delta = np.sqrt(np.var(self.data["rawdata"][yrefup:yrefdown], 0))
            if self.ui.refStdDev.checkState() == QtCore.Qt.Checked:
                vx, vy = mlab.poly_between(self.data["wavelength"],
                                           ref - delta, ref + delta)
                self.ref.fill(vx, vy, color="blue")
                DS = np.sqrt((drs / ref)**2 + ((data[0] * delta) /
                                               (ref**2))**2)
                data[0] = data[0] / ref
                self.plt.plot(self.data["wavelength"], data[0], color="black")
            if self.ui.multisig.checkState() == QtCore.Qt.Checked:
                if n > 1:
                    for i in range(1, n):
                        data[i] = data[i] - ref
                        self.plt.plot(self.data["wavelength"], data[i])
            if self.ui.sigStdDev.checkState() == QtCore.Qt.Checked:
                vx, vy = mlab.poly_between(self.data["wavelength"],
                                           data[0] - DS, data[0] + DS)
                self.plt.fill(vx, vy)
        self.canvas.draw()
Exemplo n.º 12
0
    def __init__(self, ax, orbit_collection, ensemble_mean=True, calval=True):

        # Prepare Input
        orbit_ensemble = orbit_collection.orbit_ensemble
        orbit_ensemble_mean = orbit_ensemble.get_ensemble_mean()
        calval_ensemble = orbit_collection.calval_ensemble

        # Plot all datasets
        for dataset_id in orbit_ensemble.dataset_ids:

            color = DATASET_COLOR[dataset_id]
            marker = DATASET_MARKER[dataset_id]

            # Get statistics for each dataset
            dataset_mean = orbit_ensemble.get_member_mean(dataset_id)

            # Plot the mean as lines and symbols
            #            ax.plot(orbit_ensemble.time[is_valid], dataset_mean[is_valid],
            #                    color=color, **self.datasetl_props)
            ax.scatter(orbit_ensemble.time,
                       dataset_mean,
                       color=color,
                       marker=marker,
                       **self.datasets_props)

        # Plot ensemble means
        if ensemble_mean:
            ax.plot(orbit_ensemble.time,
                    orbit_ensemble_mean,
                    label="Ensemble Mean Thickness",
                    **self.ensemble_mean_props)

            # Fill in between ensemble min/max
            emin, emax = orbit_ensemble.get_ensemble_minmax()
            is_valid = np.where(np.isfinite(dataset_mean))

            # Plot standard deviation envelope in the background
            is_valid = np.where(np.isfinite(emin))
            xs, ys = poly_between(orbit_ensemble.time[is_valid],
                                  emin[is_valid], emax[is_valid])
            ax.fill(xs, ys, **self.sdev_fill_props)

        # Plot the calval ensembles
        if calval:
            calval_props = dict(aem=self.calval_props_aem,
                                oib=self.calval_props_oib)
            shadow = [
                path_effects.SimpleLineShadow(offset=(1, -1)),
                path_effects.Normal()
            ]
            for calval_id in calval_ensemble.dataset_ids:
                dataset_mean = calval_ensemble.get_member_mean(calval_id)
                source_id = calval_id[-3:]
                ax.scatter(calval_ensemble.time,
                           dataset_mean,
                           path_effects=shadow,
                           label=source_id.upper(),
                           **calval_props[source_id])

        ax.set_xlim(orbit_collection.time_range)
        leg = ax.legend(**self.legend_props)
        leg.set_zorder(300)
Exemplo n.º 13
0
	def on_draw(self):
		yup = self.ui.sigTop.value()
		ydown = self.ui.sigBottom.value()
		yrefup= self.ui.ref1Top.value()
		yrefdown = self.ui.ref1Bottom.value()
		yref2up = self.ui.ref2Top.value()
		yref2down = self.ui.ref2Bottom.value()
		n=self.ui.NumSignals.value()
		if n==0: n=1
		dh=self.ui.SigSpacing.value()
		
		if self.ui.Smin.value()!=self.lmin or self.ui.Smax.value()!=self.lmax:
			mmin=np.min(self.data["sig"])
			mmax=np.max(self.data["sig"])
			md=mmax-mmin
			dd=(self.ui.Smin.maximum()-self.ui.Smin.minimum())
			self.lmin=self.ui.Smin.value()
			self.lmax=self.ui.Smax.value()
			cmin=mmin+(md*self.lmin)/dd
			cmax=mmin+(md*self.lmax)/dd
			self.axes.imshow(self.data["sig"],vmin=cmin,vmax=cmax)

		self.lup[0].set_data([0,self.ds[0]],[yup,yup])
		self.ldown[0].set_data([0,self.ds[0]],[ydown,ydown])
		self.lref1up[0].set_data([0,self.ds[0]],[yrefup,yrefup])
		self.lref1down[0].set_data([0,self.ds[0]],[yrefdown,yrefdown])
		self.lref2up.set_data([0,self.ds[0]],[yref2up,yref2up])
		self.lref2down.set_data([0,self.ds[0]],[yref2down,yref2down])
			

		self.plt.clear()
		self.ref.clear()
		self.raw.clear()
		self.ref.clear()

	# Signals
		data=[np.mean(self.data["sig"][yup:ydown],0)]
		self.raw.plot(self.wavelength,data[0],color="black")
		if self.ui.multisig.checkState()==QtCore.Qt.Checked:
			if len(self.lup)>n:
				for i in range(n+1,len(self.lup)):
					del self.lup[i]
					del self.ldown[i]
				self.lup=self.lup[:n]
				self.ldown=self.ldown[:n]
			if n>1:
				if len(self.lup)>n:
					for i in range(n,len(self.lup)):
						del self.lup[i]
						del self.ldown[i]
				if len(self.lup)<n:
					for i in range(len(self.lup),n):
						self.lup.append(mpl.lines.Line2D([0,self.ds[0]],[0,0],color="red"))
						self.ldown.append(mpl.lines.Line2D([0,self.ds[0]],[0,0],color="red"))
						self.axes.add_line(self.lup[i])
						self.axes.add_line(self.ldown[i])
				for i in range(1,n):
					data.append(np.mean(self.data["sig"][int(yup-dh*i):int(ydown-dh*i)],0))
					self.raw.plot(self.wavelength,data[i])
					self.lup[i].set_data([0,self.ds[0]],[int(yup-dh*i),int(yup-dh*i)])
					self.ldown[i].set_data([0,self.ds[0]],[int(ydown-dh*i),int(ydown-dh*i)])
	
		# Sig StdDev
		DS2=0
		drs=np.sqrt(np.var(self.data["sig"][yup:ydown],0))
		if self.ui.rawsigStdDev.checkState()==QtCore.Qt.Checked:
				vx,vy = mlab.poly_between(self.wavelength,data[0]-drs,data[0]+drs)
				self.raw.fill(vx,vy,color="red")
				DS2+=(drs)**2

		# Reference Signal
		if yrefup!=yrefdown:
			ref=[np.mean(self.data["sig"][yrefup:yrefdown],0)]
			self.ref.plot(self.wavelength,ref[0],color="black")
			# Std Dev
			delta=np.sqrt(np.var(self.data["sig"][yrefup:yrefdown],0))
			if self.ui.refStdDev.checkState()==QtCore.Qt.Checked:
				vx,vy = mlab.poly_between(self.wavelength,ref[0]-delta,ref[0]+delta)
				self.ref.fill(vx,vy,color="blue")
				DS2+=(delta)**2
				DS=np.sqrt(DS2)
				data[0]=data[0]-ref[0]
				self.plt.plot(self.wavelength,data[0],color="black")
			if self.ui.multisig.checkState()==QtCore.Qt.Checked:
				if n>1:
					if self.ui.MultiRef.checkState()==QtCore.Qt.Checked:
						if len(self.lref1up)>n:
							for i in range(n,len(self.lref1up)):
								del self.lref1up[i]
								del self.lref1down[i]
						if len(self.lref1up)<n:
							for i in range(len(self.lref1up),n):
								self.lref1up.append(mpl.lines.Line2D([0,self.ds[0]],[0,0],color="green"))
								self.lref1down.append(mpl.lines.Line2D([0,self.ds[0]],[0,0],color="green"))
								self.axes.add_line(self.lref1up[i])
								self.axes.add_line(self.lref1down[i])
								if self.debug: print "++",i
						for i in range(1,n):
							ref.append(np.mean(self.data["sig"][int(yrefup-dh*i):int(yrefdown-dh*i)],0))
							data[i]=data[i]-ref[i]
							self.lref1up[i].set_data([0,self.ds[0]],[int(yrefup-dh*i),int(yrefup-dh*i)])
							self.lref1down[i].set_data([0,self.ds[0]],[int(yrefdown-dh*i),int(yrefdown-dh*i)])
					else:
						if len(self.lref1up)>1:
							for i in range(len(self.lref1up)-1,0,-1):
								if self.debug: print "-",i
								self.lref1up[i].set_data([0,self.ds[0]],[0,0])
								self.lref1down[i].set_data([0,self.ds[0]],[0,0])
								del self.lref1up[i]
								del self.lref1down[i]
						for i in range(1,n):
							data[i]=data[i]-ref[0]
					for i in range(1,n):
						self.plt.plot(self.wavelength,data[i])
			if self.ui.sigStdDev.checkState()==QtCore.Qt.Checked:
					vx,vy = mlab.poly_between(self.wavelength,data[0]-DS,data[0]+DS)
					self.plt.fill(vx,vy)
		self.canvas.draw()
Exemplo n.º 14
0
def single_plot(calibrated_age, oxcal=False, output=None, BP=True):

    calibrated_age = calibrated_age
    f_m = calibrated_age.radiocarbon_sample.date
    sigma_m = calibrated_age.radiocarbon_sample.sigma
    radiocarbon_sample_id = calibrated_age.radiocarbon_sample.id
    calibration_curve = calibrated_age.calibration_curve
    calibration_curve_title = calibrated_age.calibration_curve.title
    intervals68 = calibrated_age.intervals68
    intervals95 = calibrated_age.intervals95
    sample_interval = 1950 - calibration_curve[:,0].copy() # for determination plot

    min_year, max_year = (50000, -50000)

    minx = min(calibrated_age[:,0])
    maxx = max(calibrated_age[:,0])

    if min_year < minx:
        pass
    else:
        min_year = minx
    if max_year > maxx:
        pass
    else:
        max_year = maxx

    # do not plot the part of calibration curve that is not visible
    # greatly reduces execution time \o/
    cutmin = calibration_curve[calibration_curve[:,0]>minx]
    cutmax = cutmin[cutmin[:,0]<maxx]
    calibration_curve = cutmax

    if BP is False:
        if min_year < 0 and max_year > 0:
            ad_bp_label = "BC/AD"
        elif min_year < 0 and max_year < 0:
            ad_bp_label = "BC"
        elif min_year > 0 and max_year > 0:
            ad_bp_label = "AD"
    else:
        ad_bp_label = "BP"

    string68 = "".join(
        util.interval_to_string(
            itv, calibrated_age, BP
            ) for itv in intervals68
        )
    string95 = "".join(
        util.interval_to_string(
            itv, calibrated_age, BP
            ) for itv in intervals95
        )

    fig = plt.figure(figsize=(12,8))
    ax1 = plt.subplot(111)
    ax1.set_axis_bgcolor(COLORS['bgcolor'])
    plt.xlabel("Calibrated age (%s)" % ad_bp_label)
    plt.ylabel("Radiocarbon determination (BP)")
    plt.text(0.5, 0.95,r'%s: $%d \pm %d BP$' % (radiocarbon_sample_id, f_m, sigma_m),
         horizontalalignment='center',
         verticalalignment='center',
         transform = ax1.transAxes,
         bbox=dict(facecolor='white', alpha=0.9, lw=0))
    plt.text(0.75, 0.80,'68.2%% probability\n%s\n95.4%% probability\n%s' \
                 % (string68, string95),
         horizontalalignment='left',
         verticalalignment='center',
         transform = ax1.transAxes,
         bbox=dict(facecolor='white', alpha=0.9, lw=0))
    plt.text(0.0, 1.0,'IOSACal v0.1; %s' % calibration_curve_title,
         horizontalalignment='left',
         verticalalignment='bottom',
         transform = ax1.transAxes,
         size=7,
         bbox=dict(facecolor='white', alpha=0.9, lw=0))

    # Calendar Age

    ax2 = plt.twinx()

    if oxcal is True:
        # imitate OxCal
        ax2.fill(
            calibrated_age[:,0],
            calibrated_age[:,1] + max(calibrated_age[:,1])*0.3,
            'k',
            alpha=0.3,
            label='Calendar Age'
            )
        ax2.plot(
            calibrated_age[:,0],
            calibrated_age[:,1],
            'k',
            alpha=0
            )
    else:
        ax2.fill(
            calibrated_age[:,0],
            calibrated_age[:,1],
            'k',
            alpha=0.3,
            label='Calendar Age'
            )
        ax2.plot(
            calibrated_age[:,0],
            calibrated_age[:,1],
            'k',
            alpha=0
            )

    ax2.set_ybound(min(calibrated_age[:,1]),max(calibrated_age[:,1])*3)
    ax2.set_xbound(min(calibrated_age[:,0]),max(calibrated_age[:,0]))
    ax2.set_axis_off()

    # Radiocarbon Age
    sample_curve = normpdf(sample_interval, f_m, sigma_m)

    ax3 = plt.twiny(ax1)
    ax3.fill(
        sample_curve,
        sample_interval,
        'r',
        alpha=0.3
        )
    ax3.set_xbound(0,max(sample_curve)*4)
    ax3.set_axis_off()

    # Calibration Curve

    mlab_low = calibration_curve[:,1] - calibration_curve[:,2]
    mlab_high = calibration_curve[:,1] + calibration_curve[:,2]

    xs, ys = mlab.poly_between(calibration_curve[:,0],
                               mlab_low,
                               mlab_high)
    ax1.fill(xs, ys, fc='#000000', ec='none', alpha=0.15)
    ax1.plot(calibration_curve[:,0], calibration_curve[:,1], '#000000', alpha=0.5)

    # Confidence intervals

    if oxcal is True:
        for i in intervals68:
            ax1.axvspan(
                min(i),
                max(i),
                ymin=0.05,
                ymax=0.07,
                facecolor='none',
                alpha=0.8)
            ax1.axvspan(
                min(i),
                max(i),
                ymin=0.068,
                ymax=0.072,
                facecolor='w',
                edgecolor='w',
                lw=2)
        for i in intervals95:
            ax1.axvspan(
                min(i),
                max(i),
                ymin=0.025,
                ymax=0.045,
                facecolor='none',
                alpha=0.8)
            ax1.axvspan(
                min(i),
                max(i),
                ymin=0.043,
                ymax=0.047,
                facecolor='w',
                edgecolor='w',
                lw=2)
    else:
        for i in intervals68:
            ax1.axvspan(
                min(i),
                max(i),
                ymin=0,
                ymax=0.02,
                facecolor='k',
                alpha=0.5)
        for i in intervals95:
            ax1.axvspan(
                min(i),
                max(i),
                ymin=0,
                ymax=0.02,
                facecolor='k',
                alpha=0.5)

    # FIXME the following values 10 and 5 are arbitrary and could be probably
    # drawn from the f_m value itself, while preserving their ratio
    ax1.set_ybound(f_m - sigma_m * 15, f_m + sigma_m * 5)
    ax1.set_xbound(min(calibrated_age[:,0]),max(calibrated_age[:,0]))
    ax1.invert_xaxis()          # if BP == True

    #plt.savefig('image_%d±%d.pdf' %(f_m, sigma_m))
    if output:
        plt.savefig(output)
    fig = plt.gcf()
    fig.clear()
Exemplo n.º 15
0
sensorHalfDiagonal = d/2

X = np.linspace(0, sensorHalfDiagonal, 100)
Xscaled = X/sensorHalfHeight

fig, ax = drawLinePlot(X, 
                       (rd(Xscaled)-Xscaled)/Xscaled*100,
                       xlim=[0, sensorHalfDiagonal],
                       xlabel='$h\;(\mathrm{mm})$',
                       ylabel='distortion $D\;(\%)$',
                       )
saveFig(os.path.join(plotsPath, 'dist_relative_1d.svg'), fig)

fig, ax = drawLinePlot(X, 
                       rd1(Xscaled)*sensorHalfHeight,
                       xlim=[0, sensorHalfDiagonal], 
                       xlabel='$h\;(\mathrm{mm})$',
                       ylabel='$dD/dh\;(\mathrm{mm}^{-1})$',
                       )
# shade y>0 and y<0 with colors, to indicate pincushion vs. barrel distortion
alpha = 0.3
ymin, ymax = ax.get_ylim()
ax.autoscale(False)
polyPincushion = poly_between([0,sensorHalfDiagonal], 0, ymax)
ax.fill(*polyPincushion, alpha=alpha, facecolor='orange')
polyBarrel = poly_between([0,sensorHalfDiagonal], ymin, 0)
ax.fill(*polyBarrel, alpha=alpha, facecolor='blue')

saveFig(os.path.join(plotsPath, 'dist_derivative_1d.svg'), fig)

Exemplo n.º 16
0
    def on_draw(self):
        yup = self.ui.sigTop.value()
        ydown = self.ui.sigBottom.value()
        yrefup = self.ui.ref1Top.value()
        yrefdown = self.ui.ref1Bottom.value()
        yref2up = self.ui.ref2Top.value()
        yref2down = self.ui.ref2Bottom.value()
        n = self.ui.NumSignals.value()
        if n == 0: n = 1
        dh = self.ui.SigSpacing.value()

        if self.ui.Smin.value() != self.lmin or self.ui.Smax.value(
        ) != self.lmax:
            mmin = np.min(self.data["sig"])
            mmax = np.max(self.data["sig"])
            md = mmax - mmin
            dd = (self.ui.Smin.maximum() - self.ui.Smin.minimum())
            self.lmin = self.ui.Smin.value()
            self.lmax = self.ui.Smax.value()
            cmin = mmin + (md * self.lmin) / dd
            cmax = mmin + (md * self.lmax) / dd
            self.axes.imshow(self.data["sig"], vmin=cmin, vmax=cmax)

        self.lup[0].set_data([0, self.ds[0]], [yup, yup])
        self.ldown[0].set_data([0, self.ds[0]], [ydown, ydown])
        self.lref1up[0].set_data([0, self.ds[0]], [yrefup, yrefup])
        self.lref1down[0].set_data([0, self.ds[0]], [yrefdown, yrefdown])
        self.lref2up.set_data([0, self.ds[0]], [yref2up, yref2up])
        self.lref2down.set_data([0, self.ds[0]], [yref2down, yref2down])

        self.plt.clear()
        self.ref.clear()
        self.raw.clear()
        self.ref.clear()

        # Signals
        data = [np.mean(self.data["sig"][yup:ydown], 0)]
        self.raw.plot(self.wavelength, data[0], color="black")
        if self.ui.multisig.checkState() == QtCore.Qt.Checked:
            if len(self.lup) > n:
                for i in range(n + 1, len(self.lup)):
                    del self.lup[i]
                    del self.ldown[i]
                self.lup = self.lup[:n]
                self.ldown = self.ldown[:n]
            if n > 1:
                if len(self.lup) > n:
                    for i in range(n, len(self.lup)):
                        del self.lup[i]
                        del self.ldown[i]
                if len(self.lup) < n:
                    for i in range(len(self.lup), n):
                        self.lup.append(
                            mpl.lines.Line2D([0, self.ds[0]], [0, 0],
                                             color="red"))
                        self.ldown.append(
                            mpl.lines.Line2D([0, self.ds[0]], [0, 0],
                                             color="red"))
                        self.axes.add_line(self.lup[i])
                        self.axes.add_line(self.ldown[i])
                for i in range(1, n):
                    data.append(
                        np.mean(
                            self.data["sig"][int(yup - dh * i):int(ydown -
                                                                   dh * i)],
                            0))
                    self.raw.plot(self.wavelength, data[i])
                    self.lup[i].set_data(
                        [0, self.ds[0]],
                        [int(yup - dh * i),
                         int(yup - dh * i)])
                    self.ldown[i].set_data(
                        [0, self.ds[0]],
                        [int(ydown - dh * i),
                         int(ydown - dh * i)])

        # Sig StdDev
        DS2 = 0
        drs = np.sqrt(np.var(self.data["sig"][yup:ydown], 0))
        if self.ui.rawsigStdDev.checkState() == QtCore.Qt.Checked:
            vx, vy = mlab.poly_between(self.wavelength, data[0] - drs,
                                       data[0] + drs)
            self.raw.fill(vx, vy, color="red")
            DS2 += (drs)**2

        # Reference Signal
        if yrefup != yrefdown:
            ref = [np.mean(self.data["sig"][yrefup:yrefdown], 0)]
            self.ref.plot(self.wavelength, ref[0], color="black")
            # Std Dev
            delta = np.sqrt(np.var(self.data["sig"][yrefup:yrefdown], 0))
            if self.ui.refStdDev.checkState() == QtCore.Qt.Checked:
                vx, vy = mlab.poly_between(self.wavelength, ref[0] - delta,
                                           ref[0] + delta)
                self.ref.fill(vx, vy, color="blue")
                DS2 += (delta)**2
                DS = np.sqrt(DS2)
                data[0] = data[0] - ref[0]
                self.plt.plot(self.wavelength, data[0], color="black")
            if self.ui.multisig.checkState() == QtCore.Qt.Checked:
                if n > 1:
                    if self.ui.MultiRef.checkState() == QtCore.Qt.Checked:
                        if len(self.lref1up) > n:
                            for i in range(n, len(self.lref1up)):
                                del self.lref1up[i]
                                del self.lref1down[i]
                        if len(self.lref1up) < n:
                            for i in range(len(self.lref1up), n):
                                self.lref1up.append(
                                    mpl.lines.Line2D([0, self.ds[0]], [0, 0],
                                                     color="green"))
                                self.lref1down.append(
                                    mpl.lines.Line2D([0, self.ds[0]], [0, 0],
                                                     color="green"))
                                self.axes.add_line(self.lref1up[i])
                                self.axes.add_line(self.lref1down[i])
                                if self.debug: print "++", i
                        for i in range(1, n):
                            ref.append(
                                np.mean(
                                    self.data["sig"][int(yrefup -
                                                         dh * i):int(yrefdown -
                                                                     dh * i)],
                                    0))
                            data[i] = data[i] - ref[i]
                            self.lref1up[i].set_data(
                                [0, self.ds[0]],
                                [int(yrefup - dh * i),
                                 int(yrefup - dh * i)])
                            self.lref1down[i].set_data([0, self.ds[0]], [
                                int(yrefdown - dh * i),
                                int(yrefdown - dh * i)
                            ])
                    else:
                        if len(self.lref1up) > 1:
                            for i in range(len(self.lref1up) - 1, 0, -1):
                                if self.debug: print "-", i
                                self.lref1up[i].set_data([0, self.ds[0]],
                                                         [0, 0])
                                self.lref1down[i].set_data([0, self.ds[0]],
                                                           [0, 0])
                                del self.lref1up[i]
                                del self.lref1down[i]
                        for i in range(1, n):
                            data[i] = data[i] - ref[0]
                    for i in range(1, n):
                        self.plt.plot(self.wavelength, data[i])
            if self.ui.sigStdDev.checkState() == QtCore.Qt.Checked:
                vx, vy = mlab.poly_between(self.wavelength, data[0] - DS,
                                           data[0] + DS)
                self.plt.fill(vx, vy)
        self.canvas.draw()
Exemplo n.º 17
0
    z = spstats.norm.ppf(0.95)
    # our position is 1000 shares of AAPL at the price
    # on 2014-22-31
    position = 1000 * aapl_closes.ix['2014-12-31'].AAPL
    # what is our VaR
    VaR = position * (z * returns.AAPL.std())

    ###### Misc ######
    # draw a 99% one-tail confidence interval
    x = np.linspace(-4, 4, 101)
    y = np.exp(-x**2 / 2) / np.sqrt(2 * np.pi)
    x2 = np.linspace(-4, -2.33, 101)
    y2 = np.exp(-x2**2 / 2) / np.sqrt(2 * np.pi)
    f = plt.figure(figsize=(12, 8))
    plt.plot(x, y * 100, linewidth=2)
    xf, yf = mlab.poly_between(x2, 0 * x2, y2 * 100)
    plt.fill(xf, yf, facecolor='g', alpha=0.5)
    plt.gca().set_xlabel('z-score')
    plt.gca().set_ylabel('Frequency %')
    plt.title("VaR based on the standard normal distribution")
    bbox_props = dict(boxstyle="rarrow,pad=0.3", fc="w", ec="b", lw=2)
    t = f.text(0.25,
               0.35,
               "99% VaR confidence level",
               ha="center",
               va="center",
               rotation=270,
               size=15,
               bbox=bbox_props)
    plt.savefig('5104OS_09_21.png', bbox_inches='tight', dpi=300)
Exemplo n.º 18
0
from __future__ import division
import numpy as np
import matplotlib as mpl
import matplotlib.mlab as mlab
import pylab as pl


yoffs = np.arange(10)
nplots = len(yoffs)
x = np.arange(0, 1, 0.1)
npoints = len(x)
y = np.zeros((nplots, len(x)))
stdy = np.zeros((nplots, len(x)))
verts = np.zeros((nplots, 2*npoints, 2)) # each timepoint has a +ve and a -ve value
for ploti, yoff in enumerate(yoffs):
    y[ploti] = np.random.random(len(x)) / 2 + 0.25 + yoff
    stdy[ploti] = 0.2 + np.random.random(len(x)) * 0.2
    vert = mlab.poly_between(x, y[ploti]-stdy[ploti], y[ploti]+stdy[ploti])
    vert = np.asarray(vert).T
    verts[ploti] = vert

# can also use axes.fill() instead of a poly collection, or directly use axes.fill_between()
pcol = mpl.collections.PolyCollection(verts, facecolors='r', edgecolors='none', alpha=0.2)
a = pl.gca()
#pcol = a.fill_between(x, y+stdy, y-stdy, facecolors='r', edgecolors='none', alpha=0.2)
a.add_collection(pcol)
for ploti in range(nplots):
    a.plot(x, y[ploti], 'r-')
a.set_xlim((0, 1))
Exemplo n.º 19
0
    def __init__(self, ensbl, month, output_path):
        super(GridRegionEnsembleGraph, self).__init__(self.__class__.__name__)

        # Save input parameter
        self._ensbl = ensbl
        self._month = month
        self._output_path = output_path
        self.output_filename = os.path.join(
            output_path, "%s_%02g.png" % (ensbl.region_id, month))

        plt.ioff()

        label = "%s - %s" % (REGION_ID_NAME[ensbl.region_id],
                             MONTH_NAME[month])

        # Make the plot
        fig = plt.figure(figsize=(8, 5))
        ax = plt.gca()
        ax.set_position([0.1, 0.1, 0.65, 0.8])

        dataset_color = []
        for i, dataset_id in enumerate(ensbl.dataset_ids):

            color = DATASET_COLOR[dataset_id]
            dataset_color.append(color)
            marker = DATASET_MARKER.get(dataset_id, "o")
            dataset_name = DATASET_ID_NAME[dataset_id]

            mean = ensbl.get_dataset_mean(dataset_id)
            ax.plot(ensbl.period_dts,
                    mean,
                    "-" + marker,
                    label=dataset_name,
                    color=color,
                    **self.dataset_props)

        # Plot ensemble mean
        ax.plot(ensbl.period_dts,
                ensbl.ensemble_mean,
                label="Ensemble Mean",
                **self.ensemble_mean_props)

        # Fill in between ensemble min/max
        emin, emax = ensbl.get_ensemble_minmax()
        is_valid = np.where(np.isfinite(ensbl.ensemble_mean))

        # Plot standard deviation envelope in the background
        is_valid = np.where(np.isfinite(emin))
        xs, ys = poly_between(ensbl.period_dts[is_valid], emin[is_valid],
                              emax[is_valid])
        ax.fill(xs, ys, **self.sdev_fill_props)

        # Plot legend outside the axes and color text
        leg = plt.legend(loc="lower left",
                         bbox_to_anchor=(1.0, 0.0),
                         fontsize=12)
        for i, text in enumerate(leg.get_texts()):
            if i < len(dataset_color) - 1:
                plt.setp(text, color=dataset_color[i])

        # Plot Properties
        plt.title(label, fontsize=16)
        plt.xticks(ensbl.period_dts)
        plt.ylabel("Mean Sea Ice Thickness (m)")
        ax.set_ylim(0, 5)

        # Plot style
        set_axes_style(fig, ax)

        # save plot
        self._save_to_file()
        plt.close(fig)