Beispiel #1
0
def scale_mtx(M, normalize=False, dbscale=False, norm=False, bels=False):
    """
    ::

        Perform mutually-orthogonal scaling operations, otherwise return identity:
          normalize [False]
          dbscale  [False]
          norm      [False]        
    """
    if not (normalize or dbscale or norm or bels):
        return M
    else:
        X = M.copy()  # don't alter the original
        if norm:
            nz_idx = (X * X).sum(1) > 0
            X[nz_idx] = (X[nz_idx].T / np.sqrt(
                (X[nz_idx] * X[nz_idx]).sum(1))).T
        if normalize:
            X = X - np.min(X)
            X = X / np.max(X)
        if dbscale or bels:
            X = P.log10(P.clip(X, 0.0001, X.max()))
            if dbscale:
                X = 20 * X
    return X
Beispiel #2
0
    def _mfcc(self):
        """
        ::

            DCT of the Log magnitude CQFT
        """
        fp = self._check_feature_params()
        if not self._cqft():
            return False
        self._make_dct()
        AA = P.log10(P.clip(self.CQFT, 0.0001, self.CQFT.max()))
        self.MFCC = P.dot(self.DCT, AA)
        self._have_mfcc = True
        if self.verbosity:
            print("Extracted MFCC: lcoef=%d, ncoef=%d, intensified=%d" %
                  (self.lcoef, self.ncoef, self.intensify))
        n = self.ncoef
        l = self.lcoef
        self.X = self.MFCC[l:l + n, :]
        return True
Beispiel #3
0
def feature_scale(M, normalize=False, dbscale=False, norm=False, bels=False):
    """
    ::

        Perform mutually-orthogonal scaling operations, otherwise return identity:
          normalize [False]
          dbscale  [False]
          norm      [False]
    """
    if not (normalize or dbscale or norm or bels):
        return M
    else:
        X = M.copy()  # don't alter the original
        if norm:
            X = X / P.tile(P.sqrt((X * X).sum(0)), (X.shape[0], 1))
        if normalize:
            X = _normalize(X)
        if dbscale or bels:
            X = P.log10(P.clip(X, 0.0001, X.max()))
            if dbscale:
                X = 20 * X
    return X
Beispiel #4
0
def Make_Z_Plot(grbdict, z_key='grbox_z', Nbins=31, z_cutoff=4.0):
    '''Given any dictionary which has the redshift as one of the keywords, plot
    a histogram of those redshifts.
    '''
    z_list = []
    zname_list = []
    date_list = []

    # 'un'zip all_grbs (is there a better way to do this? just assign rather than a for loop?)
    for key, value in grbdict.iteritems():
        # date_list.append(value['date'])
        z_list.append(value[z_key])
        zname_list.append(key)
    print '***All***'
    print ' '
    print z_list
    print len(z_list)

    ### Print out the most distant GRB as a function of time
    zmax = 0.0
    rr = []
    for key, value in grbdict.iteritems():
        if value[z_key] > zmax:
            rr.append(key)
            zmax = value[z_key]
            # print value['date'].year + value['date'].timetuple().tm_yday/365.0, zmax, "#  ", key

    ax = plt.subplot(111)
    n, bins, patches = plt.hist(plt.log10(z_list),
                                bins=Nbins,
                                facecolor='grey',
                                edgecolor='grey')

    # Define pre-swift burst index as bursts before 041210
    # high_z_i = plt.where(plt.array(date_list) < datetime.date(2004,12,10))

    # high_z_list = [z_list[i] for i in list(high_z_i[0])]
    #print high_z_list
    # n, bins1, patches = plt.hist(plt.log10(high_z_list),bins=bins,facecolor='black',edgecolor='black',alpha=0.6)

    if overplot_high_z:
        high_z_list = [z for z in z_list if z > z_cutoff]
        n, bins1, patches = plt.hist(plt.log10(high_z_list),
                                     bins=bins,
                                     facecolor='black',
                                     edgecolor='black')

    ay = ax.twinx()

    argg = list(plt.ones(len(z_list)).cumsum().repeat(2))
    zz = copy.copy(z_list)
    zz.sort()
    tmp = list(plt.log10(zz).repeat(2))

    tmp.append(1)
    yy = [0]
    yy.extend(argg)

    ay.plot(tmp, yy, aa=True, linewidth=4, color='black')

    argg = list(plt.ones(len(high_z_list)).cumsum().repeat(2))
    zz = copy.copy(high_z_list)
    zz.sort()
    tmp = list(plt.log10(zz).repeat(2))

    tmp.append(1)
    yy = [0]
    yy.extend(argg)

    ay.plot(tmp, yy, aa=True, linewidth=2, color='grey')
    ay.set_ylim((0, len(z_list) * 1.05))
    ay.set_ylabel("Cumulative Number", fontsize=20)

    # formatter for bottom x axis
    def ff(x, pos=None):
        if x < -1:
            return "%.2f" % (10**x)
        elif x < 0:
            return "%.1f" % (10**x)
        elif 10**x == 8.5:
            return "%.1f" % (10**x)
        else:
            return "%i" % (10**x)

    formatter = FuncFormatter(ff)
    ax.set_xticks([
        -2, -1,
        plt.log10(0.3), 0,
        plt.log10(2),
        plt.log10(3),
        plt.log10(4),
        plt.log10(6),
        plt.log10(8.5)
    ])
    ax.xaxis.set_major_formatter(formatter)
    ax.set_xlabel("Redshift ($z$)", fontsize=20)
    ax.set_ylabel("Number", fontsize=20)

    ax.set_xlim((plt.log10(0.005), plt.log10(10)))

    ax2 = ax.twiny()
    xlim = ax.get_xlim()
    #ax2.set_xscale("log")
    ax2.set_xlim((xlim[0], xlim[1]))

    # Define function for plotting the top X axis; time since big bang in Gyr
    def rr(x, pos=None):
        g = cosmocalc.cosmocalc(10.0**x, H0=71.0)
        if g['zage_Gyr'] < 1:
            return "%.2f" % g[
                'zage_Gyr']  # Return 2 dec place if age < 1; e.g 0.62
        else:
            return "%.1f" % g[
                'zage_Gyr']  # Return 1 dec place if age > 1; e.g. 1.5

    ax2.set_xticks(
        [-1.91, -1.3, -0.752, -0.283, 0.102, 0.349, 0.62,
         plt.log10(8.3)])

    formatter1 = FuncFormatter(rr)
    ax2.xaxis.set_major_formatter(formatter1)
    ax2.set_xlabel("Time since Big Bang (Gyr)", fontsize=20)

    #plt.bar(l,a['yy'],width=w,log=False)
    #ax.set_xscale("log",nonposx='clip')

    ## Now plot inset plot of GRBs greater than z=z_cutoff

    axins = inset_axes(
        ax2,
        width="30%",  # width = 30% of parent_bbox
        height="30%")  # height : 1 inch)

    locator = axins.get_axes_locator()
    locator.set_bbox_to_anchor((-0.8, -0.45, 1.35, 1.35), ax.transAxes)
    locator.borderpad = 0.0

    high_z_list = [z for z in z_list if z > z_cutoff]
    if high_z_list:  # if there are any high-z's, plot them
        n, bins, patches = plt.hist(plt.array(high_z_list),
                                    facecolor='black',
                                    edgecolor='black')
    axins.set_xlim(z_cutoff, 8.5)
    axins.set_xlabel("z")
    axins.set_ylabel("N")

    # high_z_i = plt.where(plt.array(date_list) < datetime.date(2004,12,10))
    # high_z_list = [z_list[i] for i in list(high_z_i[0]) if z_list[i] > z_cutoff]

    n, bins, patches = plt.hist(plt.array(high_z_list),
                                bins=bins,
                                facecolor='black',
                                edgecolor='black')

    high_z_list = [z for z in z_list if z > z_cutoff]

    if high_z_list:  # if there are any high-z's, plot them
        n, bins, patches = plt.hist(plt.array(high_z_list),
                                    facecolor='black',
                                    edgecolor='black')

    axins.set_xlim(z_cutoff, 9.0)
    #mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")

    #axins2.set_xlabel("Time since Big Bang [Gyr]",fontsize=20)
    ylabels = ax.get_yticklabels()
    plt.setp(ylabels, size=14, name='times', weight='light', color='k')

    xlabels = ax.get_xticklabels()
    plt.setp(xlabels, size=14, name='times', weight='light', color='k')

    xlabels = ax2.get_xticklabels()
    plt.setp(xlabels, size=14, name='times', weight='light', color='k')

    xlabels = ay.get_yticklabels()
    plt.setp(xlabels, size=14, name='times', weight='light', color='k')

    plt.savefig('z_plot.eps')
    plt.draw()
    return z_list
Beispiel #5
0
def Make_Z_Plot(grbdict, z_key="grbox_z", Nbins=31, z_cutoff=4.0):
    """Given any dictionary which has the redshift as one of the keywords, plot
    a histogram of those redshifts.
    """
    z_list = []
    zname_list = []
    date_list = []

    # 'un'zip all_grbs (is there a better way to do this? just assign rather than a for loop?)
    for key, value in grbdict.iteritems():
        # date_list.append(value['date'])
        z_list.append(value[z_key])
        zname_list.append(key)
    print "***All***"
    print " "
    print z_list
    print len(z_list)

    ### Print out the most distant GRB as a function of time
    zmax = 0.0
    rr = []
    for key, value in grbdict.iteritems():
        if value[z_key] > zmax:
            rr.append(key)
            zmax = value[z_key]
            # print value['date'].year + value['date'].timetuple().tm_yday/365.0, zmax, "#  ", key

    ax = plt.subplot(111)
    n, bins, patches = plt.hist(plt.log10(z_list), bins=Nbins, facecolor="grey", edgecolor="grey")

    # Define pre-swift burst index as bursts before 041210
    # high_z_i = plt.where(plt.array(date_list) < datetime.date(2004,12,10))

    # high_z_list = [z_list[i] for i in list(high_z_i[0])]
    # print high_z_list
    # n, bins1, patches = plt.hist(plt.log10(high_z_list),bins=bins,facecolor='black',edgecolor='black',alpha=0.6)

    if overplot_high_z:
        high_z_list = [z for z in z_list if z > z_cutoff]
        n, bins1, patches = plt.hist(plt.log10(high_z_list), bins=bins, facecolor="black", edgecolor="black")

    ay = ax.twinx()

    argg = list(plt.ones(len(z_list)).cumsum().repeat(2))
    zz = copy.copy(z_list)
    zz.sort()
    tmp = list(plt.log10(zz).repeat(2))

    tmp.append(1)
    yy = [0]
    yy.extend(argg)

    ay.plot(tmp, yy, aa=True, linewidth=4, color="black")

    argg = list(plt.ones(len(high_z_list)).cumsum().repeat(2))
    zz = copy.copy(high_z_list)
    zz.sort()
    tmp = list(plt.log10(zz).repeat(2))

    tmp.append(1)
    yy = [0]
    yy.extend(argg)

    ay.plot(tmp, yy, aa=True, linewidth=2, color="grey")
    ay.set_ylim((0, len(z_list) * 1.05))
    ay.set_ylabel("Cumulative Number", fontsize=20)
    # formatter for bottom x axis
    def ff(x, pos=None):
        if x < -1:
            return "%.2f" % (10 ** x)
        elif x < 0:
            return "%.1f" % (10 ** x)
        elif 10 ** x == 8.5:
            return "%.1f" % (10 ** x)
        else:
            return "%i" % (10 ** x)

    formatter = FuncFormatter(ff)
    ax.set_xticks([-2, -1, plt.log10(0.3), 0, plt.log10(2), plt.log10(3), plt.log10(4), plt.log10(6), plt.log10(8.5)])
    ax.xaxis.set_major_formatter(formatter)
    ax.set_xlabel("Redshift ($z$)", fontsize=20)
    ax.set_ylabel("Number", fontsize=20)

    ax.set_xlim((plt.log10(0.005), plt.log10(10)))

    ax2 = ax.twiny()
    xlim = ax.get_xlim()
    # ax2.set_xscale("log")
    ax2.set_xlim((xlim[0], xlim[1]))

    # Define function for plotting the top X axis; time since big bang in Gyr
    def rr(x, pos=None):
        g = cosmocalc.cosmocalc(10.0 ** x, H0=71.0)
        if g["zage_Gyr"] < 1:
            return "%.2f" % g["zage_Gyr"]  # Return 2 dec place if age < 1; e.g 0.62
        else:
            return "%.1f" % g["zage_Gyr"]  # Return 1 dec place if age > 1; e.g. 1.5

    ax2.set_xticks([-1.91, -1.3, -0.752, -0.283, 0.102, 0.349, 0.62, plt.log10(8.3)])

    formatter1 = FuncFormatter(rr)
    ax2.xaxis.set_major_formatter(formatter1)
    ax2.set_xlabel("Time since Big Bang (Gyr)", fontsize=20)

    # plt.bar(l,a['yy'],width=w,log=False)
    # ax.set_xscale("log",nonposx='clip')

    ## Now plot inset plot of GRBs greater than z=z_cutoff

    axins = inset_axes(ax2, width="30%", height="30%")  # width = 30% of parent_bbox  # height : 1 inch)

    locator = axins.get_axes_locator()
    locator.set_bbox_to_anchor((-0.8, -0.45, 1.35, 1.35), ax.transAxes)
    locator.borderpad = 0.0

    high_z_list = [z for z in z_list if z > z_cutoff]
    if high_z_list:  # if there are any high-z's, plot them
        n, bins, patches = plt.hist(plt.array(high_z_list), facecolor="black", edgecolor="black")
    axins.set_xlim(z_cutoff, 8.5)
    axins.set_xlabel("z")
    axins.set_ylabel("N")

    # high_z_i = plt.where(plt.array(date_list) < datetime.date(2004,12,10))
    # high_z_list = [z_list[i] for i in list(high_z_i[0]) if z_list[i] > z_cutoff]

    n, bins, patches = plt.hist(plt.array(high_z_list), bins=bins, facecolor="black", edgecolor="black")

    high_z_list = [z for z in z_list if z > z_cutoff]

    if high_z_list:  # if there are any high-z's, plot them
        n, bins, patches = plt.hist(plt.array(high_z_list), facecolor="black", edgecolor="black")

    axins.set_xlim(z_cutoff, 9.0)
    # mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")

    # axins2.set_xlabel("Time since Big Bang [Gyr]",fontsize=20)
    ylabels = ax.get_yticklabels()
    plt.setp(ylabels, size=14, name="times", weight="light", color="k")

    xlabels = ax.get_xticklabels()
    plt.setp(xlabels, size=14, name="times", weight="light", color="k")

    xlabels = ax2.get_xticklabels()
    plt.setp(xlabels, size=14, name="times", weight="light", color="k")

    xlabels = ay.get_yticklabels()
    plt.setp(xlabels, size=14, name="times", weight="light", color="k")

    plt.savefig("z_plot.eps")
    plt.draw()
    return z_list
Beispiel #6
0
                # Get pixel coordinates of SN
                wcs = pywcs.WCS(prihdr)
                try:
                    target_pix = wcs.wcs_sky2pix([(np.array([ra,dec], np.float_))], 1)[0]
                except:
                    print "ERROR when converting sky to wcs. Is astrometry in place? Default coordinates assigned."
                    target_pix = [+nx/2., ny/2.]
    
                print target_pix
            else:
                target_pix = [+nx/2., ny/2.]
               
            img = img - np.nanmin(img)
            av = np.median(img.flatten())
            mi, ma = zscale.zscale(img)
            im = plt.imshow(plt.log10(img), aspect="equal", extent=(0, ny, 0, nx), \
            origin="lower", cmap=matplotlib.cm.gray_r, interpolation="none", vmin=np.log10(av), vmax=np.log10(3*av)) #, interpolation="lanczos")
            plt.scatter(target_pix[0], target_pix[1], marker="x", s=10, c="red")
            plt.colorbar(im)
            filename = os.path.basename(f)
            plt.savefig(os.path.join(plot_dir, filename.replace("."+filename.split(".")[-1], "_{:}.png".format(i))), dpi=200)
            plt.clf()
    
def move_to_discarded(mydir, myfilter, ra, dec):
    import shutil
    
    for f in glob.glob(os.path.join(mydir, myfilter)):
        frames_with_target = get_frames_with_target(f, ra, dec)
        if len(frames_with_target) == 0:
            discarddir = os.path.join(mydir, "discarded")
            if (not os.path.isdir(discarddir)):
Beispiel #7
0
                wcs = pywcs.WCS(prihdr)
                try:
                    target_pix = wcs.wcs_sky2pix(
                        [(np.array([ra, dec], np.float_))], 1)[0]
                except:
                    print "ERROR when converting sky to wcs. Is astrometry in place? Default coordinates assigned."
                    target_pix = [+nx / 2., ny / 2.]

                print target_pix
            else:
                target_pix = [+nx / 2., ny / 2.]

            img = img - np.nanmin(img)
            av = np.median(img.flatten())
            mi, ma = zscale.zscale(img)
            im = plt.imshow(plt.log10(img), aspect="equal", extent=(0, ny, 0, nx), \
            origin="lower", cmap=matplotlib.cm.gray_r, interpolation="none", vmin=np.log10(av), vmax=np.log10(3*av)) #, interpolation="lanczos")
            plt.scatter(target_pix[0],
                        target_pix[1],
                        marker="x",
                        s=10,
                        c="red")
            plt.colorbar(im)
            filename = os.path.basename(f)
            plt.savefig(os.path.join(
                plot_dir,
                filename.replace("." + filename.split(".")[-1],
                                 "_{:}.png".format(i))),
                        dpi=200)
            plt.clf()
Beispiel #8
0
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.pylab as plb
from scipy.stats import linregress

labels, values = zip(*aggCount.most_common(50))

indexes = np.arange(len(labels))
width = 1

plt.bar(indexes, values, width)

plt.xticks(indexes + width * 0.5, labels)
plt.show()

X = indexes + 1
Y = values
plt.plot(X, Y, 'bo')
plt.savefig('rawplot.png')

plt.loglog(X, Y, 'bo')
plt.savefig('loglogplot.png')

m, b = plb.polyfit(plb.log10(X), plb.log10(Y), 1)
slope, intercept, r_value, p_value, std_err = linregress(
    plb.log10(X), plb.log10(Y))
rsquared = r_value**2
plt.plot(plb.log10(X), plb.log10(Y), 'bo', plb.log10(X),
         plb.log10(X) * slope + intercept, '--k')
plt.savefig('loglogplot_fitted.png')
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.pylab as plb
from scipy.stats import linregress

labels, values = zip(*aggCount.most_common(50))

indexes = np.arange(len(labels))
width = 1

plt.bar(indexes, values, width)

plt.xticks(indexes + width * 0.5, labels)
plt.show()

X=indexes +1
Y=values
plt.plot(X,Y, 'bo')
plt.savefig('rawplot.png')

plt.loglog(X,Y,'bo')
plt.savefig('loglogplot.png')

m,b=plb.polyfit(plb.log10(X),plb.log10(Y),1)
slope, intercept, r_value, p_value, std_err=linregress(plb.log10(X),plb.log10(Y))
rsquared=r_value**2
plt.plot(plb.log10(X),plb.log10(Y),'bo',plb.log10(X), plb.log10(X)*slope +intercept, '--k')
plt.savefig('loglogplot_fitted.png')
#!/usr/bin/env python
# coding: utf-8
import pickle
from pylab import *
import random
from matplotlib import pylab as pl
file = open('table_data.bin', 'rb')
table = pickle.load(file)
file.close()

chen_f = lambda Ree, jdd: (-2.0 * pl.log10(
    jdd / 3.7065 - 5.0452 / Ree * pl.log10((jdd**1.1098) / 2.8257 + 5.8506 /
                                           (Ree**0.8981))))**-2  #Re>2100일경우

minor_loss = {
    'edged inlet': 0.5,
    'Re-entrant inlet': 1,
    'Well rounded inlet': 0.05,
    'Exit': 1,
    '90º Elbow': 1.4,
    '45º Elbow': 0.35,
    'Globe valve': 10,
    'Gate valve': 0.15,
    'Basket strainer': 1.3
}


# -------------------------------- 압력차 ---------------------------------------------
def Pressure_drop(Q, L, dz, liquid_type, pipe_standard, merterial, loss):

    Q = float(Q)