Пример #1
0
    def gaussfit(self):
        for idx, columnx in enumerate(df):
            if boxDict[columnx + str(1)].isChecked():
                pa = df[columnx].tolist()
                for idy, columny in enumerate(df):
                    variablefit = str(idx) + str(idy) + "gauss_fit"
                    if boxDict[columny + str(2)].isChecked():
                        try:
                            fitDict[variablefit][0].remove()
                        except:
                            pass
                        pb = df[columny].tolist()
                        pstart = [1., 0., 1.]
                        coeff, var_matrix = cf(functions.gauss,
                                               pa,
                                               pb,
                                               p0=pstart)
                        fitDict[variablefit] = plt.plot(
                            np.linspace(pa[0], pa[-1], 1000),
                            functions.gauss(np.linspace(pa[0], pa[-1], 1000),
                                            coeff[0], coeff[1], coeff[2]),
                            "-",
                            color="red")
                        self.textBrowser.append("Line fit: " + "a = " +
                                                str(coeff[0]) + ", mu = " +
                                                str(coeff[1]) + ", sigma = " +
                                                str(coeff[2]) + " for " +
                                                str(columnx) + " x " +
                                                str(columny))

        self.reloadpictrue()
Пример #2
0
def test_gauss_x_mu_zero():
    """
    If $\mu=0$, $x=0$, and $\sigma=1$ the value of the Gaussian should
    be $1/\sqrt{2\pi}$. Check that it is.
    """
    tolerance = 1e-8
    x = 0
    mu = 0
    sigma = 1
    assert np.abs(gauss(x, mu, sigma) - 1 / np.sqrt(2 * np.pi)) <= tolerance
Пример #3
0
def sym_gauss_int_sqr(xb, n=10):
    """  
    This function calculates the area underneath the gaussian function (imported
    through functions.py) for constant c= sqrt(0.5) using the trapezoidal rule.
    
    Returns the area squared.
    paramters:
    xb -- the upper bound for the interval to be integrated over. Assumed the number 
            being passed through is positive. the negative of this variable will 
            be the lower bound of the interval
    n -- constant, represents the number of grid cells in direction x to be used
            in the numberical integration. optional argument, default is 10.
    
    """
    y = np.linspace(-xb, xb, n)
    trapezoids = 0
    for i in y:
        h1 = f.gauss(i, c=np.sqrt(0.5))
        h2 = f.gauss(i + 1, c=np.sqrt(0.5))
        trapezoids += (((xb) / (n - 1)) * ((h1 + h2)))
    return (trapezoids**2)
Пример #4
0
def test_gauss_x_zero_mu_is_2_sigma():
    """
    If $x=0$ and $\mu = \sqrt{2} \sigma$ then the Gaussian should have value
    $\frac{1}{e\sqrt{2\pi\sigma^2}}$. Make sure it does.
    """
    tolerance = 1e-8
    x = 0
    # Pick a value of sigma
    sigma = 2.5
    mu = np.sqrt(2) * sigma
    expected_result = 1 / (np.e * np.sqrt(2 * np.pi * sigma**2))
    assert np.abs(gauss(x, mu, sigma) - expected_result) <= tolerance
Пример #5
0
def test_gauss_value_at_mu():
    """
    The value of the Gaussian at ``x=mu`` should be $1/sqrt(2 * pi * sigma**2)$; check
    that that is the case for a couple non-zero values of sigma to within a tolerance.
    """
    # Nothing particularly special about this value of tolerance
    tolerance = 1e-8

    # choose x and mu; they need to be the same for this test
    x = 4
    mu = 4
    sig1 = 2.3
    norm1 = 1 / np.sqrt(2 * np.pi * sig1**2)
    assert np.abs(gauss(x, mu, sig1) - norm1) <= tolerance
Пример #6
0
    ax4.set_xscale("log")

    fig4 = plt.figure(4, figsize=(10, 7))
    ax5 = fig4.add_subplot(2, 1, 1)
    ax6 = fig4.add_subplot(2, 1, 2)

    fig5 = plt.figure(5, figsize=(10, 7))
    ax7 = fig5.add_subplot(2, 1, 1)
    ax8 = fig5.add_subplot(2, 1, 2)
    ax7.set_title("volitility test")

    #plots
    ax.plot(t, y, color="r")
    ax.plot(t, f.line(np.array(t), *linepara))
    ax2.plot(t2, y2)
    values, bounds, patches = ax3.hist(brownianhist, 100)
    gausspara = f.fitgauss(f.bincenters(bounds), values)
    ax3.plot(f.bincenters(bounds), f.gauss(f.bincenters(bounds), *gausspara))
    ax4.plot(f1, s1, "o", markerfacecolor="None")
    ax4.plot(f1[:2000], f.logline(f1, *linepara2)[:2000])
    ax5.plot(t3, noise)
    ax6.plot(f3, s3, "o", markerfacecolor="None")
    ax6.set_yscale("log")
    ax6.set_xscale("log")
    ax7.plot(t2, y2, color="black")
    ax7.plot(t5, avg, color="blue")
    ax7.plot(t6, avg2, color="green")
    ax8.plot(t4, vol, color="red")

    plt.show()
array_original = fc.convertToArray(image_original, col, row)

#Vetor com as expanções laterais
array_completo = fc.completaVetor(array_original, total)
for i in range(0, total + 18):
    array_completo[i] = int(array_completo[i] * 256)
#print(array_completo)

# =============================================================================#
#               Bloco do primeiro filtro gaussiano
# =============================================================================#
#Aplicação do primeiro filtro de gauss
#Primeira passagem
for i in range(len(array_original)):
    array_analise = array_completo[i:i + 19]
    pixel = fc.gauss(array_analise, curva)
    array_result = array_result + [pixel]

#Segunda Passagem do filtro gaussiano na primeira etapa .
#Por reutilizar a função completaVetor necessita que seus parâmetros sejam em array
#e não list. Assim, é necessário passar array_result pra array para que seja possível
#a concatenação do preambulo e do posambulo.

array_teste = np.zeros(total)

for i in range(0, total):
    array_teste[i] = array_result[i]

#Aplica o segundo filtro gaussiano na primeira parte
array_completo_b = fc.completaVetor(array_teste, total)
for i in range(len(array_result)):
Пример #8
0
def redoclean():
    #from datasource import DataSource
    #wifsip = DataSource(database='stella', user='******', host='pera.aip.de')
    #query = """SELECT tab FROM m48stars WHERE good;"""
    #result = wifsip.query(query)
    from starids import starids
    from matplotlib import pyplot as plt
    from functions import gauss, gauss_fit

    for starid in starids.split('\n'):
        doplot = False
        star = M48Star(starid)
        f, a = star.cleanspectrum()
        p = 1. / f
        i = np.where((p > 1.3) & (p < 20.0))
        pi = p[i]
        fi = f[i]
        ai = a[i]
        j = np.argmax(ai)
        pnew = pi[j]
        anew = ai[j]
        pman = star['pman']
        diff = abs(pnew - pman)
        if diff > 0.5:
            k = np.where((p > pman - 1.0) & (p < pman + 1.0))
            pk = p[k]
            fk = f[k]
            ak = a[k]
            j = np.argmax(ak)
            pnew = pk[j]
            anew = ak[j]
            diff = abs(pnew - pman)
            doplot = True

        # find local minima
        h = np.argwhere(pi == pnew)[0][0]
        h0 = h
        while ai[h0 - 1] <= ai[h0] and h0 > 0:
            h0 -= 1
        h1 = h
        while ai[h1 + 1] <= ai[h1] and h1 < len(ai):
            h1 += 1
        # perform gauss fit
        par = gauss_fit(pi[h0:h1],
                        ai[h0:h1] - min(ai[h0:h1]),
                        amp=anew,
                        mean=pnew,
                        sigma=0.5)
        #print p
        pgauss = par[1]
        perr = par[2]
        if perr > 1.0:
            doplot = True
        # update database
        x = np.linspace(pi[0], pi[-1], 500)
        #gauss(x, a, x0, sigma):
        diff = abs(pnew - pman)

        print '%25s %4d %6.3f %5.2f %6.3f %6.3f' % (starid, star['tab'], pman,
                                                    diff, pgauss, perr)
        star['clean_period'] = pgauss
        star['clean_sigma'] = perr
        if doplot:
            plt.plot(pi, ai)
            plt.axvline(pnew, linestyle='--')
            plt.plot(x, gauss(x, par[0], par[1], par[2]), 'r')
            plt.title('#%d' % star['tab'])
            plt.xlabel('period = %.3f days' % pnew)
            plt.show()
Пример #9
0
#Bohdan Shybetskyi, 4th variant

import functions as fn

koef = 0.5 * 3
a = [[3.81, 0.25, 1.28, 0.75 + koef], [2.25, 1.32, 4.58 + koef, 0.49],
     [5.31, 6.28 + koef, 0.98, 1.04], [9.39 + koef, 2.45, 3.35, 2.28]]

b = [4.21, 6.47 + koef, 2.38, 10.48 + koef]

fn.print_matr(a, b)
print(fn.gauss(a, b))
Пример #10
0
    def priorities(self, verbose=False):
        """updates the priorities in the ngc2236 table"""
        import numpy as np
        from functions import scaleto

        def makeplot(bv, v, p, filename=None, isobv=None, isov=None):
            """plot the priorities"""
            from matplotlib import pyplot
            pyplot.scatter(bv, v, c=p, edgecolor='none', alpha=0.75)
            if not isobv is None:
                pyplot.plot(isobv, isov, 'k')
            pyplot.xlim(-0.2, 2.0)
            pyplot.ylim(16.5, 7.5)
            pyplot.title('NGC 2236')
            pyplot.xlabel('B - V')
            pyplot.ylabel('V mag')

            if filename is None:
                pyplot.show()
            else:
                pyplot.savefig(filename, dpi=300)
            pyplot.close()

        def plotradec(ra, dec, p, filename=None):
            """plot the priorities"""
            from matplotlib import pyplot
            pyplot.scatter(ra, dec, c=p, edgecolor='none', alpha=0.75)
            pyplot.title('NGC 2236')
            pyplot.xlabel('R.A.')
            pyplot.ylabel('Dec')

            if filename is None:
                pyplot.show()
            else:
                pyplot.savefig(filename, dpi=300)
            pyplot.close()

        print 'calculate priorities ...'
        self.wifsip.execute("UPDATE ngc2236 SET priority=NULL, pointing=NULL;")
        self.wifsip.execute("""UPDATE ngc2236 
            SET priority=1.0 
            WHERE vmag<16.5 
            AND NOT tab IS NULL;""")

        data = self.wifsip.query("""SELECT tab, vmag, bv 
                               FROM ngc2236
                               WHERE not bv is null AND vmag<16.5
                               ORDER BY tab;""")
        tab = [d[0] for d in data]
        v = np.array([d[1] for d in data])
        bv = np.array([d[2] for d in data])
        p1 = scaleto(v, [1.0, 0.8])
        makeplot(bv, v, p1, filename=config.plotpath + 'vmag_priorities.pdf')

        print len(tab), 'stars brighter V<16.5'
        for i in range(len(tab)):
            if verbose: print '%4d: %.3f --> %.3f' % (tab[i], v[i], p1[i])
            self.wifsip.execute("""UPDATE ngc2236
                          SET priority = priority * %f
                          WHERE tab = %d;""" % (p1[i], tab[i]),
                                commit=False)
        self.wifsip.commit()

        lengood = self.wifsip.query(
            "select count(starid) from ngc2236 where good;")
        print lengood[0][0], 'stars with periods'

        self.wifsip.execute("""UPDATE ngc2236
                          SET priority = priority * 0.8
                          WHERE NOT good;""")
        self.wifsip.commit()

        self.wifsip.execute("""UPDATE ngc2236
                          SET priority = priority * 0.5
                          WHERE period IS NULL;""")
        self.wifsip.commit()

        iso = IsoChrone(config.datapath + 'output885516794937.dat')
        x = iso['V'] + self.dm
        y = iso['B-V'] + self.ebv
        data = self.wifsip.query("""SELECT tab, vmag, bv 
                               FROM ngc2236 
                               WHERE not bv is null AND vmag<16.5
                               ORDER BY tab;""")
        tab = [d[0] for d in data]
        v = np.array([d[1] for d in data])
        bv = np.array([d[2] for d in data])
        p = np.zeros(len(tab))
        print len(tab), 'stars for isochrone priority'

        for i in range(len(tab)):
            p[i] = np.min(abs(x - v[i]) + abs(y - bv[i]))

        #p[p > 0.4] = 0.4
        p = scaleto(p, [1.0, 0.1])
        makeplot(bv,
                 v,
                 p,
                 filename=config.plotpath + 'iso_priorities.pdf',
                 isobv=y,
                 isov=x)
        for t in tab:
            i = tab.index(t)
            if verbose:
                print '%d: V=%.3f B-V=%.3f p=%.3f' % (t, v[i], bv[i], p[i])
            self.wifsip.execute("""UPDATE ngc2236
                              SET priority = priority * %f
                              WHERE tab = %d;""" % (p[i], t),
                                commit=False)
        self.wifsip.commit()

        data = self.wifsip.query("""SELECT tab, ra, dec
                               FROM ngc2236
                               WHERE not ra is NULL AND not dec is NULL
                               AND priority > 0.0
                               ORDER BY TAB;""")
        tab = [d[0] for d in data]
        print len(tab), 'stars for distance priority'
        ra = np.array([d[1] for d in data])
        dec = np.array([d[2] for d in data])
        dist = np.sqrt((ra - self.center[0])**2 + (dec - self.center[1])**2)
        from functions import gauss
        p = gauss(dist, 1.0, 0.0, 7.0 / 60.)
        #p = scaleto(dist, [1.0, 0.0])
        plotradec(ra,
                  dec,
                  p,
                  filename=config.plotpath + 'coord_priorities.pdf')
        for t in tab:
            i = tab.index(t)
            try:
                if verbose:
                    print '%d: d=%.3f p=%.3f' % (t, dist[i], p[i])
                self.wifsip.execute("""UPDATE ngc2236
                              SET priority = priority * %f
                              WHERE tab = %d;""" % (p[i], t),
                                    commit=False)
            except TypeError:
                print t
        self.wifsip.commit()

        data = self.wifsip.query("""SELECT bv,vmag, priority
                               FROM ngc2236
                               WHERE priority > 0.0
                               ORDER BY tab;""")

        bv = np.array([d[0] for d in data])
        vmag = np.array([d[1] for d in data])
        p = np.array([d[2] for d in data])
        makeplot(bv, vmag, p, filename=config.plotpath + 'priorities.pdf')