Ejemplo n.º 1
0
 def build(self, ctrlarr, listpars):
     """ Set full list of parameters. """
     for i in range(len(ctrlarr)):
         if i == 0:
             self.M = _phc.find_nearest(listpars[i], ctrlarr[i])
         if i == 1:
             self.ob = _phc.find_nearest(listpars[i], ctrlarr[i])
         if i == 2:
             self.Z = _phc.find_nearest(listpars[i], ctrlarr[i])
         if i == 3:
             self.H = _phc.find_nearest(listpars[i], ctrlarr[i])
         if i == 4:
             self.sig = _phc.find_nearest(listpars[i], ctrlarr[i])
         if i == 5:
             self.Rd = _phc.find_nearest(listpars[i], ctrlarr[i])
         if i == 6:
             self.h = _phc.find_nearest(listpars[i], ctrlarr[i])
         if len(listpars) == 9:
             if i == 7:
                 # print(_phc.find_nearest(listpars[i], ctrlarr[i]))
                 self.n = _phc.find_nearest(listpars[i], ctrlarr[i])
                 self.param = True
             if i == 8:
                 self.cosi = _phc.find_nearest(listpars[i], ctrlarr[i])
         else:
             if i == 7:
                 self.cosi = _phc.find_nearest(listpars[i], ctrlarr[i])
Ejemplo n.º 2
0
 def build(self, ctrlarr, listpars):
     """ Set full list of parameters. """
     for i in range(len(ctrlarr)):
         if i == 0:
             self.M = _phc.find_nearest(listpars[i], ctrlarr[i])
         if i == 1:
             self.ob = _phc.find_nearest(listpars[i], ctrlarr[i])
         if i == 2:
             self.Z = _phc.find_nearest(listpars[i], ctrlarr[i])
         if i == 3:
             self.H = _phc.find_nearest(listpars[i], ctrlarr[i])
         if i == 4:
             self.sig = _phc.find_nearest(listpars[i], ctrlarr[i])
         if i == 5:
             self.Rd = _phc.find_nearest(listpars[i], ctrlarr[i])
         if i == 6:
             self.h = _phc.find_nearest(listpars[i], ctrlarr[i])
         if len(listpars) == 9:
             if i == 7:
                 # print(_phc.find_nearest(listpars[i], ctrlarr[i]))
                 self.n = _phc.find_nearest(listpars[i], ctrlarr[i])
                 self.param = True
             if i == 8:
                 self.cosi = _phc.find_nearest(listpars[i], ctrlarr[i])
         else:
             if i == 7:
                 self.cosi = _phc.find_nearest(listpars[i], ctrlarr[i])
Ejemplo n.º 3
0
def find_max_peak(vl, nflx, idx=-1):
    """ Based on max flux. 
    """
    if idx == -1:
        idx = len(vl)/2
    idx_ = phc.find_nearest(nflx[:idx], np.max(nflx[:idx]), idx=True)
    nfV, vlV = nflx[idx_], vl[idx_]
    idx_ = phc.find_nearest(nflx[idx:], np.max(nflx[idx:]), idx=True)
    nfR, vlR = nflx[idx+idx_], vl[idx+idx_]
    return nfV, vlV, nfR, vlR
Ejemplo n.º 4
0
def find_max_peak(vl, nflx, idx=-1):
    """ Based on max flux. 
    """
    if idx == -1:
        idx = len(vl) / 2
    idx_ = phc.find_nearest(nflx[:idx], np.max(nflx[:idx]), idx=True)
    nfV, vlV = nflx[idx_], vl[idx_]
    idx_ = phc.find_nearest(nflx[idx:], np.max(nflx[idx:]), idx=True)
    nfR, vlR = nflx[idx + idx_], vl[idx + idx_]
    return nfV, vlV, nfR, vlR
Ejemplo n.º 5
0
def interpolBA(params, ctrlarr, lparams, minfo, models, param=True):
    """ Interpola os `modelos` para os parametros `params` 

    | -params = from emcee minimization
    | -ctrlarr = the fixed value of M, ob(W), Z, H, sig, Rd, h, *n*, cos(i).
    |            If it is not fixed, use np.NaN.
    | -Parametric disk model default (`param` == True).

    This function always returns a valid result (i.e., extrapolations from the
    nearest values are always on).

    If it is a 'Non-squared grid' (asymmetric), it will return a zero array if
    a given model is not found.
    """
    nq = 9
    if not param:
        nq = 8
    if len(ctrlarr) != nq:
        raise ValueError('# Wrong ctrlarr format!!')
    params = params[:_np.sum(_np.isnan(ctrlarr))]
    nlb = len(models[0])
    outmodels = _np.empty((2**len(params), nlb))
    mod = BAmod('')
    parlims = _np.zeros((len(params), 2))
    j = 0
    for i in range(nq):
        if ctrlarr[i] is _np.NaN:
            parlims[j] = [
                _phc.find_nearest(lparams[i], params[j], bigger=False),
                _phc.find_nearest(lparams[i], params[j], bigger=True)
            ]
            j += 1
    j = 0
    for prod in _product(*parlims):
        allpars = _np.array(ctrlarr)
        idx = _np.isnan(allpars)
        allpars[idx] = prod
        mod.build(allpars, lparams)
        idx = mod.getidx(minfo)
        if _np.sum(idx) == 0:
            return _np.zeros(nlb)
        outmodels[j] = models[idx]
        j += 1
    X0 = parlims[:, 0]
    X1 = parlims[:, 1]
    return _phc.interLinND(params, X0, X1, outmodels)
Ejemplo n.º 6
0
def interpolBA(params, ctrlarr, lparams, minfo, models, param=True):
    """ Interpola os `modelos` para os parametros `params` 

    | -params = from emcee minimization
    | -ctrlarr = the fixed value of M, ob(W), Z, H, sig, Rd, h, *n*, cos(i).
    |            If it is not fixed, use np.NaN.
    | -Parametric disk model default (`param` == True).

    This function always returns a valid result (i.e., extrapolations from the
    nearest values are always on).

    If it is a 'Non-squared grid' (asymmetric), it will return a zero array if
    a given model is not found.
    """
    nq = 9
    if not param:
        nq = 8
    if len(ctrlarr) != nq:
        raise ValueError('# Wrong ctrlarr format!!')
    params = params[:_np.sum(_np.isnan(ctrlarr))]
    nlb = len(models[0])
    outmodels = _np.empty((2**len(params), nlb))
    mod = BAmod('')
    parlims = _np.zeros((len(params), 2))
    j = 0
    for i in range(nq):
        if ctrlarr[i] is _np.NaN:
            parlims[j] = [_phc.find_nearest(lparams[i], params[j], 
            bigger=False), _phc.find_nearest(lparams[i], params[j], 
            bigger=True)]
            j += 1
    j = 0
    for prod in _product(*parlims):
        allpars = _np.array(ctrlarr)
        idx = _np.isnan(allpars)
        allpars[idx] = prod
        mod.build(allpars, lparams)
        idx = mod.getidx(minfo)
        if _np.sum(idx) == 0:
            return _np.zeros(nlb)
        outmodels[j] = models[idx]
        j += 1
    X0 = parlims[:, 0]
    X1 = parlims[:, 1]
    return _phc.interLinND(params, X0, X1, outmodels)
Ejemplo n.º 7
0
def griddataBA(minfo, models, params, listpar, dims):
    '''
    Moser's routine to interpolate BeAtlas models
    obs: last argument ('listpar') had to be included here
    '''

    # print(params[0])
    idx = np.arange(len(minfo))
    lim_vals = len(params) * [
        [],
    ]
    for i in range(len(params)):
        #print(i, listpar[i], params[i], minfo[:, i])
        lim_vals[i] = [
            phc.find_nearest(listpar[i], params[i], bigger=False),
            phc.find_nearest(listpar[i], params[i], bigger=True)
        ]

        tmp = np.where((minfo[:, i] == lim_vals[i][0])
                       | (minfo[:, i] == lim_vals[i][1]))

        idx = np.intersect1d(idx, tmp[0])

    #print(idx)
    out_interp = griddata(minfo[idx], models[idx], params)[0]

    if (np.sum(out_interp) == 0 or np.sum(np.isnan(out_interp)) > 0):

        mdist = np.zeros(np.shape(minfo))
        ichk = range(len(params))
        for i in ichk:
            mdist[:, i] = np.abs(minfo[:, i] - params[i]) /\
                (np.max(listpar[i]) - np.min(listpar[i]))
        idx = np.where(np.sum(mdist, axis=1) == np.min(np.sum(mdist, axis=1)))
        if len(idx[0]) != 1:
            out_interp = griddata(minfo[idx], models[idx], params)[0]
        else:
            out_interp = models[idx][0]

    # if (np.sum(out_interp) == 0 or np.sum(np.isnan(out_interp)) > 0) or\
    #    bool(np.isnan(np.sum(out_interp))) is True:
    #     print("# Houve um problema na grade e eu nao consegui arrumar...")

    return out_interp
Ejemplo n.º 8
0
def griddataBAtlas(minfo, models, params, listpar, dims, isig):
    
    import pyhdust.phc as phc
    from scipy.interpolate import griddata
    
    idx = range(len(minfo))
    lim_vals = len(params)*[ [], ]
    for i in [i for i in range(len(params)) if i != isig]:
        lim_vals[i] = [
            phc.find_nearest(listpar[i], params[i], bigger=False), 
            phc.find_nearest(listpar[i], params[i], bigger=True)]
        tmp = np.where((minfo[:, i] == lim_vals[i][0]) | 
                (minfo[:, i] == lim_vals[i][1]))
        idx = np.intersect1d(idx, tmp)
        #
    out_interp = griddata(minfo[idx], models[idx], params)[0]
    #
    if (np.sum(out_interp) == 0 or np.sum(np.isnan(out_interp)) > 0):
        print("# Houve um problema na grade. Tentando arrumar...")
        print(params)
        idx = np.arange(len(minfo))
        for i in [i for i in range(len(params)) if i != dims["sig0"]]:
            imin = lim_vals[i][0]
            if lim_vals[i][0] != np.min(listpar[i]):
                imin = phc.find_nearest(listpar[i], lim_vals[i][0], 
                    bigger=False)
            imax = lim_vals[i][1]
            if lim_vals[i][1] != np.max(listpar[i]):
                imax = phc.find_nearest(listpar[i], lim_vals[i][1], 
                    bigger=True)
            lim_vals[i] = [imin, imax]
            tmp = np.where((minfo[:, i] >= lim_vals[i][0]) & 
                (minfo[:, i] <= lim_vals[i][1]))
            idx = np.intersect1d(idx, phc.flatten(tmp))
        out_interp = griddata(minfo[idx], models[idx], params)[0]
    #
    if (np.sum(out_interp) == 0 or np.sum(np.isnan(out_interp)) > 0):
        print("# Houve um problema na grade e eu nao conseguir arrumar...")
    #
    return out_interp
Ejemplo n.º 9
0
def angQU(Q, U, filter=True):
    """ Calculate [Q, U] angles with filters* (avg-180 < degs > avg+180) """
    Q = _np.array(Q)
    U = _np.array(U)
    ind = _np.where(Q == 0)
    Q[ind] = 1e-34
    ang = _np.arctan(U / Q)
    #
    ind = _np.where(Q <= 0.)
    ang[ind] = ang[ind] + _np.pi
    ind = _np.where((Q > 0) & (U < 0))
    ang[ind] = ang[ind] + 2 * _np.pi
    ang = ang / 2.
    # ind = _np.where(ang >= _np.pi)
    # ang[ind] = ang[ind] - _np.pi
    if filter:
        avg = _np.median(ang)
        avg = _phc.find_nearest([0, _np.pi / 4, _np.pi / 2, _np.pi * 3. / 4],
                                avg)
        ind = _np.where((ang - avg) > 1. / 2 * _np.pi)
        ang[ind] = ang[ind] - _np.pi
        ind = _np.where((ang - avg) < -1. / 2 * _np.pi)
        ang[ind] = ang[ind] + _np.pi
    return ang
Ejemplo n.º 10
0
def angQU(Q, U, filter=True):
    """ Calculate [Q, U] angles with filters* (avg-180 < degs > avg+180) """
    Q = _np.array(Q)
    U = _np.array(U)
    ind = _np.where(Q == 0)
    Q[ind] = 1e-34
    ang = _np.arctan(U / Q)
    #
    ind = _np.where(Q <= 0.)
    ang[ind] = ang[ind] + _np.pi
    ind = _np.where((Q > 0) & (U < 0))
    ang[ind] = ang[ind] + 2 * _np.pi
    ang = ang / 2.
    # ind = _np.where(ang >= _np.pi)
    # ang[ind] = ang[ind] - _np.pi
    if filter:
        avg = _np.median(ang)
        avg = _phc.find_nearest(
            [0, _np.pi / 4, _np.pi / 2, _np.pi * 3. / 4], avg)
        ind = _np.where((ang - avg) > 1. / 2 * _np.pi)
        ang[ind] = ang[ind] - _np.pi
        ind = _np.where((ang - avg) < -1. / 2 * _np.pi)
        ang[ind] = ang[ind] + _np.pi
    return ang
Ejemplo n.º 11
0
def kerncorner(xs, cmapn='gray_r', ncl=3, bestvals='perc', labels=[]):
    """ xs = (niteractions, ndim) 
    ncl = number os contour lines
    bestvals = None, 'peak' or 'perc'
    """
    ndim = _np.shape(xs)[1]
    if len(labels) < ndim:
        labels += [''] * (ndim - len(labels))

    fig = _plt.figure(figsize=(9, 9))
    gs = _gridspec.GridSpec(ndim, ndim)
    gs.update(hspace=0.01)
    fs = dict(_mpl.rcParams.viewitems())['font.size'] - 4

    axs = []
    xslim = []
    for i in range(ndim):
        ax = []
        xslim += [[_np.min(xs[:, i]), _np.max(xs[:, i])]]
        for j in range(i + 1):
            ax += [_plt.subplot(gs[i, j])]
        axs += [ax]

    for i in range(ndim):
        for j in range(i + 1):
            axs[i][j].locator_params(nbins=5)
            xmin, xmax = xslim[j]
            if i == j:
                kernel = _stats.gaussian_kde(xs[:, i])
                x = _np.linspace(xmin, xmax, 101)
                y = kernel(x)
                axs[i][j].plot(x, y / _np.max(y))
                axs[i][j].set_xlim([xmin, xmax])
                ymin, ymax = axs[i][j].get_ylim()
                if isinstance(bestvals, _strtypes):
                    if bestvals.startswith('perc'):
                        pc = _np.percentile(xs[:, i], [15.9, 50.0, 84.1])
                    elif bestvals.startswith('peak'):
                        mode = x[_phc.find_nearest(y, _np.max(y), idx=True)]
                        mad = _stt.mad(xs[:, i])
                        pc = mode + _np.array([-mad, 0, mad])
                    else:
                        _warn.warn('Invalid `bestvals` in kerncorner',
                                   stacklevel=2)
                    if 'pc' in locals():
                        dx = xmax - xmin
                        for p in pc:
                            if p < xmin + 0.015 * dx:
                                p = xmin + 0.015 * dx
                            if p > xmax - 0.015 * dx:
                                p = xmax - 0.015 * dx
                            axs[i][j].plot([p, p], [ymin, ymax], 'k--')
            else:
                y = xs[:, i]
                x = xs[:, j]
                ymin, ymax = xslim[i]
                #
                values = _np.vstack([x, y])
                kernel = _stats.gaussian_kde(values)
                X, Y = _np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
                positions = _np.vstack([X.ravel(), Y.ravel()])
                Z = _np.reshape(kernel(positions), X.shape)
                #
                # axs[i][j].plot(x, y, 'k.')
                axs[i][j].imshow(
                    Z.T,
                    cmap=_plt.get_cmap(cmapn),
                    extent=[xmin, xmax, ymin, ymax],
                    origin='lower',
                )
                if ncl > 0:
                    CS = axs[i][j].contour(X,
                                           Y,
                                           Z,
                                           ncl,
                                           colors=_phc.gradColor(
                                               range(ncl), cmapn='copper'))
                # axs[i][j].clabel(CS, inline=1, fontsize=fs)
            if j == 0:
                axs[i][j].set_ylabel(labels[i])
            if i == ndim - 1:
                axs[i][j].set_xlabel(labels[j])
            if (i == 0 and j == 0) or (j != 0):
                axs[i][j].set_yticklabels([])
            axs[i][j].set_aspect(abs(xmax - xmin) / abs(ymax - ymin))
            if i != ndim - 1:
                # axs[i][j].get_xaxis().set_visible(False)
                # axs[i][j].xaxis.set_visible(False)
                axs[i][j].set_xticklabels([])
            else:
                _plt.setp(axs[i][j].xaxis.get_majorticklabels(), rotation=50)

    _phc.savefig(fig)  # figname='outname')
    return
Ejemplo n.º 12
0
def kerncorner(xs, cmapn='gray_r', ncl=3, bestvals='perc', labels=[]):
    """ xs = (niteractions, ndim) 
    ncl = number os contour lines
    bestvals = None, 'peak' or 'perc'
    """
    ndim = _np.shape(xs)[1]
    if len(labels) < ndim:
        labels += ['']*(ndim-len(labels))

    fig = _plt.figure(figsize=(9, 9))
    gs = _gridspec.GridSpec(ndim, ndim)
    gs.update(hspace=0.01)
    fs = dict(_mpl.rcParams.viewitems())['font.size']-4

    axs = []
    xslim = []
    for i in range(ndim):
        ax = []
        xslim += [[_np.min(xs[:, i]), _np.max(xs[:, i])]]
        for j in range(i+1):
            ax += [_plt.subplot(gs[i, j])]
        axs += [ax]

    for i in range(ndim):
        for j in range(i+1):
            axs[i][j].locator_params(nbins=5)
            xmin, xmax = xslim[j]
            if i == j:
                kernel = _stats.gaussian_kde(xs[:, i])
                x = _np.linspace(xmin, xmax, 101)
                y = kernel(x)
                axs[i][j].plot(x, y/_np.max(y))
                axs[i][j].set_xlim([xmin, xmax])
                ymin, ymax = axs[i][j].get_ylim()
                if isinstance(bestvals, _strtypes):
                    if bestvals.startswith('perc'):
                        pc = _np.percentile(xs[:, i], [15.9, 50.0, 84.1])
                    elif bestvals.startswith('peak'): 
                        mode = x[_phc.find_nearest(y, _np.max(y), idx=True)]
                        mad = _stt.mad(xs[:, i])
                        pc = mode + _np.array([-mad, 0, mad])
                    else:
                        _warn.warn('Invalid `bestvals` in kerncorner', 
                            stacklevel=2)
                    if 'pc' in locals():
                        dx = xmax-xmin
                        for p in pc:
                            if p < xmin+0.015*dx:
                                p = xmin+0.015*dx
                            if p > xmax-0.015*dx:
                                p = xmax-0.015*dx
                            axs[i][j].plot([p, p], [ymin, ymax], 'k--')
            else:
                y = xs[:, i]
                x = xs[:, j]
                ymin, ymax = xslim[i]
                #
                values = _np.vstack([x, y])
                kernel = _stats.gaussian_kde(values)
                X, Y = _np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
                positions = _np.vstack([X.ravel(), Y.ravel()])
                Z = _np.reshape(kernel(positions), X.shape)
                #
                # axs[i][j].plot(x, y, 'k.')
                axs[i][j].imshow(Z.T, cmap=_plt.get_cmap(cmapn), 
                    extent=[xmin, xmax, ymin, ymax], 
                    origin='lower',
                )
                if ncl > 0:
                    CS = axs[i][j].contour(X, Y, Z, ncl, 
                    colors=_phc.gradColor(range(ncl), cmapn='copper'))
                # axs[i][j].clabel(CS, inline=1, fontsize=fs)
            if j == 0:
                axs[i][j].set_ylabel(labels[i])
            if i == ndim-1:
                axs[i][j].set_xlabel(labels[j])
            if (i == 0 and j == 0) or (j != 0):
                axs[i][j].set_yticklabels([])
            axs[i][j].set_aspect(abs(xmax-xmin)/abs(ymax-ymin))
            if i != ndim-1:
                # axs[i][j].get_xaxis().set_visible(False)
                # axs[i][j].xaxis.set_visible(False)
                axs[i][j].set_xticklabels([])
            else:
                _plt.setp( axs[i][j].xaxis.get_majorticklabels(), rotation=50 )

    _phc.savefig(fig)  # figname='outname')
    return