示例#1
0
def wtfromDR(fbase,fend='.ang'):
  """
  Quick hack, fill in options later.
  """

  fDD = fbase+'.DRopt1'+fend
  fDR = fbase+'.DRopt2'+fend
  fRR = fbase+'.DRopt3'+fend

  ximisc.getDRfactors(fbase,fend)

  t, DDg = np.loadtxt(fDD,skiprows=2,unpack=True)
  tchk, DRg = np.loadtxt(fDR,skiprows=2,unpack=True)
  assert (t==tchk).all()
  tchk, RRg = np.loadtxt(fRR,skiprows=2,unpack=True)
  assert (t==tchk).all()

  DRfac, fixRR = ximisc.getDRfactors(fbase,fend)

  wt = (DDg-DRg*DRfac)/RRg/DRfac**2/fixRR**2 + 1.

  return wtheta(wtfname=fbase,twlist = [t,wt])
示例#2
0
def xiellfromDR(fbase,nell=3,binfile=None,rperpcut=-1.,
                dfacs=1,dfacmu=1,icovfname=None,smincut=-1.,smaxcut=1.e12,\
                DRfacinfo=None,smallRRcut=-1.,periodicopt=0,printmaskopt=0,xiopt=0):
  """
  This function should supercede older codes with names like rebinxismugeneric*py
  input the base for the DR files, as well as optional bin files and small scale 
  cutoff for masking (rperpcut).  If you don't want to use a binfile to specify
  the downsampling, use dfacs and dfacmu inputs.
  smincut/smaxcut will only be used if binfile is None.
  DRfacinfo is used to pass [DRfac, fixRR] (dont get it from file headers in this case)
  That feature is necessary for computing covariance matrices from bootstrap, where that factor
  should be fixed by total N and/or S, it does not vary from bootstrap region to region.
  smallRRcut allows you to replace randoms(mu) with the average over mu where the total number of 
  randoms in the bin is smaller than smallRRcut, just to keep Poisson noise down.
  If periodicopt == 1, assume the input is file containing [rg, mug, Vg, Ng] as currently output
  by correlationfxnMASTERv4.
  xiopt introduced on May 13 2014 to input xi(s,mu) and simply rebin (for comparison with Hong).
  """
  if periodicopt == 1: # periodic box.
    rg, mug, Vg, Ng = np.loadtxt(fbase,unpack=True)
    Vzerochk = Vg.min()*0.1
    fDR = fbase ## just for the return xiell purposes.
  elif xiopt == 1:
    rg, mug, xig = np.loadtxt(fbase,unpack=True,usecols=[0,1,2])  ## Hong format.
    fDR = fbase
    if binfile is None:
      ikeep = np.where((rg >= smincut) & (rg <= smaxcut))[0]
      rg = rg[ikeep]
      mug = mug[ikeep]
      xig = xig[ikeep]
  else: # DD,RR counts.
    fDD = fbase+'.DRopt1'
    fDR = fbase+'.DRopt2'
    fRR = fbase+'.DRopt3'
    rg, mug, DDg = np.loadtxt(fDD,skiprows=3,unpack=True)
    rg, mug, DRg = np.loadtxt(fDR,skiprows=3,unpack=True)
    rg, mug, RRg = np.loadtxt(fRR,skiprows=3,unpack=True)
    if binfile is None:
      ikeep = np.where((rg >= smincut) & (rg <= smaxcut))[0]
      rg = rg[ikeep]
      mug = mug[ikeep]
      DDg = DDg[ikeep]
      DRg = DRg[ikeep]
      RRg = RRg[ikeep]

    if DRfacinfo is None:
      DRfac, fixRR = ximisc.getDRfactors(fbase)
    else:
      DRfac = DRfacinfo[0]
      fixRR = DRfacinfo[1]


  nmu = len(np.where(rg == rg[0])[0])
  dmu  = 1./float(nmu)
  nr = len(np.where(mug == mug[0])[0])
  if nmu*nr != len(rg):
    return None

  ## is s (called r here) log or linear binning?
  s1d = rg.reshape([nr,nmu])[:,0]
  mu1d = rg.reshape([nr,nmu])[0,:]
  ## compute linear spacings.
  dmutmp = (mu1d[1:]-mu1d[:-1]).mean()
  ds = (s1d[1:]-s1d[:-1]).mean()
  dlogs = (np.log(s1d[1:]/s1d[:-1])).mean()
  if (np.fabs(mu1d[1:]-mu1d[:-1] - dmutmp) > 0.0001*dmutmp).any():
    ## not linear binning!
    ## this shouldn't be the case for a s,mu grid.
    assert 0==1
    assert np.fabs(dmutmp - dmu) < 1.0e-4

  if (np.fabs(s1d[1:]-s1d[:-1] - ds) < 0.0001*ds).all():
    logsopt = 0
    rglowedge = rg.copy()
    rglowedge = rglowedge-0.5*ds
    ## added specifically for xiopt
    rghighedge = rg.copy()
    rghighedge = rghighedge+0.5*ds
  if (np.fabs(np.log(s1d[1:])-np.log(s1d[:-1]) - dlogs) < 0.0001*dlogs).all():
    logsopt = 1
    rglowedge = rg.copy()
    rglowedge = rglowedge*np.exp(-0.5*dlogs)
    ## added specifically for xiopt
    rghighedge = rg.copy()
    rghighedge = rghighedge*np.exp(0.5*dlogs)

  assert logsopt == 0 or logsopt == 1
  if xiopt == 1:
    Vg = rghighedge**3 - rglowedge**3  ## just need something proportional to volume.
    Vzerochk = Vg.min()*0.1

  ## cut at edge of bin.
  xx = np.where(rglowedge*(1-(mug+0.5*dmu)**2)**0.5 < rperpcut)[0]
  if(rperpcut < 0.):  assert len(xx) == 0
  if len(xx) > 0:
    if periodicopt == 1:
      Vg[xx] = 0.
      Ng[xx] = 0.
    elif xiopt == 1:
      Vg[xx] = 0.
      xig[xx] = 0.

    else:
      DDg[xx] = 0.
      DRg[xx] = 0.
      RRg[xx] = 0.

  mymask = np.zeros(len(rg),dtype='int')
  mymask[xx] = 1

  ## tmp!  print a mask file.
  if(printmaskopt == 1):
    print 'yoyoyo opening masktmp.dat'
    ofpmask = open('masktmp.dat','w')
    for i in range(len(mymask)):
      ofpmask.write('%d\n' % (mymask[i]))
    ofpmask.close()

  if(printmaskopt == 2):
#### nevermind, let's print below the boundaries of each s,mu bin.
#    print 'yoyoyo opening masktmp2.dat'
#    ofpmask = open('masktmp2.dat','w')
    mumaxlist = np.zeros(len(s1d)) + 1.
    for qi in range(len(s1d)):
      rgval = s1d[qi]
      qq = np.where((rg == rgval) & (mymask == 1))[0]
      ww = np.where((rg == rgval))[0]
      assert len(ww) > 0
      if(len(qq) == 0):
        pass
#        ofpmask.write('%e %e %e\n' % (rgval,rglowedge[ww[0]],1.0))
      else:
#        ofpmask.write('%e %e %e\n' % (rgval,rglowedge[ww[0]],mug[qq].max()))
        mumaxlist[qi] = mug[qq].min()-0.5*dmu
### testing.
#      print s1d[qi], mumaxlist[qi]
      #ofpmask.write('%d\n' % (mymask[i]))
#    ofpmask.close()
    
  
  if binfile is not None:
    ## specifies how many rbins to join together for first bin, next bin, etc.
    rjoin, mujoin = np.loadtxt(binfile,unpack=True,dtype='int')
    nrcut = len(rjoin)
    ### use later.
    #bintag = binfile.split('.')[0]
  else:
#    dfacs = dfacsin
#    dfacmu = dfacmuin
    nrcut = len(s1d)/dfacs
    dmudown = dfacmu*dmu

  if printmaskopt == 2:
    ofpmask = open('masktmp2.dat','w')

  ## check mask if I'm going to cut more.
  ristart = 0
  badlist = np.zeros(nrcut,dtype='int')
  for i in range(nrcut):
    if binfile is not None:
      dfacs = rjoin[i]
    if (mymask[ristart*nmu:(ristart+dfacs)*nmu] == 1).all():
      badlist[i] = 1
    ristart = ristart + dfacs

  nrcutkeep = nrcut-len(np.where(badlist == 1)[0])

  xi = np.zeros([nell,nrcutkeep],dtype=float)
  svec = np.zeros([nell,nrcutkeep],dtype=float)

  rcen = np.zeros(nrcut,dtype=float)
  ristart = 0
  xiindx = 0
  for i in range(nrcut):
    if binfile is not None:
      dfacs = rjoin[i]
      dfacmu = mujoin[i]
      dmudown = dfacmu*dmu
    riend = ristart + dfacs - 1
    if logsopt == 0:
      rcen[i] = 0.5*(s1d[ristart] + s1d[riend])
    if logsopt == 1:
      rcen[i] = np.exp(0.5*np.log(s1d[ristart]*s1d[riend]))
    for ishort in range(dfacs):
      i1 = (ristart+ishort)*nmu
      i2 = (ristart+ishort+1)*nmu
      if periodicopt == 1:
        if(ishort == 0):
          mymu = ximisc.downsample1d(mug[i1:i2],dfacmu)
          myVg = ximisc.downsample1dsum(Vg[i1:i2],dfacmu)
          myNg = ximisc.downsample1dsum(Ng[i1:i2],dfacmu)
        else:
          myVg = myVg + ximisc.downsample1dsum(Vg[i1:i2],dfacmu)
          myNg = myNg + ximisc.downsample1dsum(Ng[i1:i2],dfacmu)
      elif xiopt == 1:
        if(ishort == 0):
          mymu = ximisc.downsample1d(mug[i1:i2],dfacmu)
          myxig = ximisc.downsample1dvweight(xig[i1:i2],Vg[i1:i2],dfacmu)  #perform volume weighted sum. 
          myVg = ximisc.downsample1dsum(Vg[i1:i2],dfacmu)
        else:
          myxig = myxig + ximisc.downsample1dvweight(xig[i1:i2],Vg[i1:i2],dfacmu) # perform volume weighted sum, divide out at the end.
          myVg = myVg + ximisc.downsample1dsum(Vg[i1:i2],dfacmu)

      else:
        if(ishort == 0):
          mymu = ximisc.downsample1d(mug[i1:i2],dfacmu)
          mydd = ximisc.downsample1dsum(DDg[i1:i2],dfacmu)
          mydr = ximisc.downsample1dsum(DRg[i1:i2],dfacmu)
          myrr = ximisc.downsample1dsum(RRg[i1:i2],dfacmu)
        else:
          mydd = mydd + ximisc.downsample1dsum(DDg[i1:i2],dfacmu)
          mydr = mydr + ximisc.downsample1dsum(DRg[i1:i2],dfacmu)
          myrr = myrr + ximisc.downsample1dsum(RRg[i1:i2],dfacmu)

    if periodicopt == 1:
      yy = np.where(myVg < Vzerochk)[0]
      xitmp = myNg/myVg-1.
      xitmp[yy] = 0.

    elif xiopt == 1:
      yy = np.where(myVg < Vzerochk)[0]
      xitmp = myxig/myVg
      xitmp[yy] = 0.
      ## for now, nothing to 0 out (?)

    else:  ##DR stuff
      zz = np.where(myrr < smallRRcut)[0]
      if(len(zz) > 0):
        print 'using smallRRcut!  here are details',i,rcen[i],smallRRcut
        myrr = myrr.mean()

      yy = np.where(myrr < 0.01)[0]
      xitmp = (mydd-mydr*DRfac)/myrr/DRfac**2/fixRR**2+1.
      xitmp[yy] = 0.  ## fix 0'd out regions

      if(len(yy) > 0 and 0==1):
        print 'ack why zerod out regions?'
        print len(yy)
        print i, dfacs, dfacmu
        print myrr
        print mymu

    for ell in np.arange(0,nell*2,2):
      if(badlist[i] == 0):
        xi[ell/2,xiindx] = (xitmp*ximisc.legendre(ell,mymu)).sum()*dmudown*(2.*ell+1.)
        svec[ell/2,xiindx] = rcen[i]

    if printmaskopt == 2:
      ofpmask.write('%e %e %e %e %e ' % (rcen[i], s1d[ristart]*np.exp(-0.5*dlogs), s1d[riend]*np.exp(0.5*dlogs), mumaxlist[ristart],mumaxlist[riend]))
      for ell in np.arange(0,nell*2,2):
        if badlist[i] == 0:
          ofpmask.write('%e ' % (xi[ell/2,xiindx]))
        else:
          ofpmask.write('%e ' % (0.0))

      ofpmask.write('\n')

    ristart = ristart + dfacs

    if(badlist[i] == 0):
      xiindx += 1

  return xiell(xiellfname=fDR,sxilist=[svec, xi],icovfname=icovfname)
示例#3
0
def getbootcov(
    bootfile,
    workingdir,
    covtag=None,
    NSortot=2,
    nboot=5000000,
    fbaseend="_rmax48deltalog10r",
    xiellorwp=0,
    rpimax=80.0,
    splitwp=7,
    wpstart=1,
    wpend=19,
    nell=3,
    binfile=None,
    rperpcut=-1.0,
    smallRRcut=-1.0,
    dfacs=1,
    dfacmu=1,
    icovfname=None,
    smincut=-1.0,
    smaxcut=1.0e12,
    splitxi0=5,
    splitxi2=6,
    fbaseendxiell="_rmax48deltalog10r",
    fbaseendwp="_xigrid",
):
    """
  Get covariance matrix.
  fbaseend = '_rmax48deltalog10r' for xiell or '_xigrid' for wp.
  Third tier of stuff goes directly to xiellfromDR
  expect splitxi0/splitxi2 [those go to xicorrect; values determined in
  comparetiledcmockstotruthv0
  Added functionality for wp: xiellorwp = 1, splitwp = where to go from ang to NN.
  rpimax is for wp, default is 80.
  Leaving variable fbaseend for backward compatibility,  but if xiellorwp == 2, defaults to 
  using fbaseendxiell and fbaseendwp
  """
    # NNorang = 0 [NN] or 1 [ang] or 2 [optimal unbiased combination, not yet written]
    ## nevermind, that doesnt get used anywhere!!?? deleted, was the 4th elt in the list.

    assert xiellorwp >= 0 and xiellorwp <= 2

    nsub, pixelfname, fbaseNNstart, fbaseangstart, fbaseNNtotN, fbaseNNtotS, fbaseangtotN, fbaseangtotS = parsebootinfo(
        bootfile, workingdir
    )

    if nsub is None or pixelfname is None or fbaseNNstart is None or fbaseangstart is None:
        print "bad boot file, getbootcov returning None!"
        return None
    pixlist = getpixlist(pixelfname, nsub)

    myfbase_NN = fbaseNNstart
    myfbase_ang = fbaseangstart

    if xiellorwp == 0 or xiellorwp == 1:
        DRfacN_NN, fixRRdownN_NN = ximisc.getDRfactors(fbaseNNtotN + fbaseend)
        DRfacS_NN, fixRRdownS_NN = ximisc.getDRfactors(fbaseNNtotS + fbaseend)
        DRfacN_ang, fixRRdownN_ang = ximisc.getDRfactors(fbaseangtotN + fbaseend)
        DRfacS_ang, fixRRdownS_ang = ximisc.getDRfactors(fbaseangtotS + fbaseend)
    else:  ##xiwp statistic.  xiellorwp == 2
        ## xiell
        DRfacN_NNxiell, fixRRdownN_NNxiell = ximisc.getDRfactors(fbaseNNtotN + fbaseendxiell)
        DRfacS_NNxiell, fixRRdownS_NNxiell = ximisc.getDRfactors(fbaseNNtotS + fbaseendxiell)
        DRfacN_angxiell, fixRRdownN_angxiell = ximisc.getDRfactors(fbaseangtotN + fbaseendxiell)
        DRfacS_angxiell, fixRRdownS_angxiell = ximisc.getDRfactors(fbaseangtotS + fbaseendxiell)
        ## wp
        DRfacN_NNwp, fixRRdownN_NNwp = ximisc.getDRfactors(fbaseNNtotN + fbaseendwp)
        DRfacS_NNwp, fixRRdownS_NNwp = ximisc.getDRfactors(fbaseNNtotS + fbaseendwp)
        DRfacN_angwp, fixRRdownN_angwp = ximisc.getDRfactors(fbaseangtotN + fbaseendwp)
        DRfacS_angwp, fixRRdownS_angwp = ximisc.getDRfactors(fbaseangtotS + fbaseendwp)

    if xiellorwp == 0:
        splittag = "splits%d_%d" % (splitxi0, splitxi2)
    if xiellorwp == 1:
        splittag = "splitswp%d_%d_%d" % (splitwp, wpstart, wpend)
    if xiellorwp == 2:
        splittagxiell = "splits%d_%d" % (splitxi0, splitxi2)
        splittagwp = "splitswp%d_%d_%d" % (splitwp, wpstart, wpend)
        splittag = splittagxiell + "_" + splittagwp

    if binfile is not None:
        bintag = binfile.split("/")[-1].split(".")[0]
        covoutNN = "covtotv7NN_b%d_N%d_rebin-%s" % (nboot, nsub, bintag)
        covoutang = "covtotv7ang_b%d_N%d_rebin-%s" % (nboot, nsub, bintag)
        covoutcorr = "covtotv7corr_b%d_N%d_rebin-%s_%s" % (nboot, nsub, bintag, splittag)
    else:
        covoutNN = "covtotv7NN_b%d_N%d" % (nboot, nsub)
        covoutang = "covtotv7ang_b%d_N%d" % (nboot, nsub)
        covoutcorr = "covtotv7corr_b%d_N%d_%s" % (nboot, nsub, splittag)

    if covtag is not None:
        covoutNN = covoutNN + "_%s" % covtag
        covoutang = covoutang + "_%s" % covtag
        covoutcorr = covoutcorr + "_%s" % covtag

    icovoutNN = "i" + covoutNN
    icovoutang = "i" + covoutang
    icovoutcorr = "i" + covoutcorr

    if xiellorwp == 0 or xiellorwp == 1:
        DRinfoN_NN = [DRfacN_NN, fixRRdownN_NN]
        DRinfoS_NN = [DRfacS_NN, fixRRdownS_NN]
        DRinfoN_ang = [DRfacN_ang, fixRRdownN_ang]
        DRinfoS_ang = [DRfacS_ang, fixRRdownS_ang]
    else:
        # xiell
        DRinfoN_NNxiell = [DRfacN_NNxiell, fixRRdownN_NNxiell]
        DRinfoS_NNxiell = [DRfacS_NNxiell, fixRRdownS_NNxiell]
        DRinfoN_angxiell = [DRfacN_angxiell, fixRRdownN_angxiell]
        DRinfoS_angxiell = [DRfacS_angxiell, fixRRdownS_angxiell]
        # wp
        DRinfoN_NNwp = [DRfacN_NNwp, fixRRdownN_NNwp]
        DRinfoS_NNwp = [DRfacS_NNwp, fixRRdownS_NNwp]
        DRinfoN_angwp = [DRfacN_angwp, fixRRdownN_angwp]
        DRinfoS_angwp = [DRfacS_angwp, fixRRdownS_angwp]

    for ns in range(nsub):
        print ns
        fbase_NN = myfbase_NN + ("-%03d" % (ns)) + fbaseend
        fbase_ang = myfbase_ang + ("-%03d" % (ns)) + fbaseend
        if xiellorwp == 2:
            fbase_NNxiell = myfbase_NN + ("-%03d" % (ns)) + fbaseendxiell
            fbase_angxiell = myfbase_ang + ("-%03d" % (ns)) + fbaseendxiell
            fbase_NNwp = myfbase_NN + ("-%03d" % (ns)) + fbaseendwp
            fbase_angwp = myfbase_ang + ("-%03d" % (ns)) + fbaseendwp

        xx = np.where(pixlist["PID"] == ns)[0]
        assert len(xx) == 1
        assert xx[0] == ns
        NorSval = pixlist["NorS"][xx[0]]
        if NorSval == 0:
            if xiellorwp == 0 or xiellorwp == 1:
                DRinfo_NN = DRinfoN_NN
                DRinfo_ang = DRinfoN_ang
            else:
                DRinfo_NNxiell = DRinfoN_NNxiell
                DRinfo_angxiell = DRinfoN_angxiell
                DRinfo_NNwp = DRinfoN_NNwp
                DRinfo_angwp = DRinfoN_angwp

        else:  # south
            if xiellorwp == 0 or xiellorwp == 1:
                DRinfo_NN = DRinfoS_NN
                DRinfo_ang = DRinfoS_ang
            else:
                DRinfo_NNxiell = DRinfoS_NNxiell
                DRinfo_angxiell = DRinfoS_angxiell
                DRinfo_NNwp = DRinfoS_NNwp
                DRinfo_angwp = DRinfoS_angwp

        if xiellorwp == 0:
            xiinNN = xiell.xiellfromDR(
                fbase_NN, nell, binfile, rperpcut, dfacs, dfacmu, icovfname, smincut, smaxcut, DRinfo_NN, smallRRcut
            )
            xiinang = xiell.xiellfromDR(
                fbase_ang, nell, binfile, rperpcut, dfacs, dfacmu, icovfname, smincut, smaxcut, DRinfo_ang, smallRRcut
            )
            xicorr = xicorrect(xiinNN, xiinang, splitxi0, splitxi2)
        if xiellorwp == 1:  ## doing wp
            xiinNNtmp = wp.wpfromDR(fbase_NN, DRfacinfo=DRinfo_NN, rpimax=rpimax, icovfname=icovfname)
            xiinangtmp = wp.wpfromDR(fbase_ang, DRfacinfo=DRinfo_ang, rpimax=rpimax, icovfname=icovfname)

            ## these are for later, saving cov of NN and ang separately.
            xiinNN = wp.wpfromDR(
                fbase_NN, DRfacinfo=DRinfo_NN, rpimax=rpimax, icovfname=icovfname, wpstart=wpstart, wpend=wpend
            )
            xiinang = wp.wpfromDR(
                fbase_ang, DRfacinfo=DRinfo_ang, rpimax=rpimax, icovfname=icovfname, wpstart=wpstart, wpend=wpend
            )

            ##wpstart,end not already applied to this NN and ang!
            xicorr = wpcorrect(xiinNNtmp, xiinangtmp, splitwp, wpstart, wpend)

        if xiellorwp == 2:  ##doing xiwp
            xiinNNxiell = xiell.xiellfromDR(
                fbase_NNxiell,
                nell,
                binfile,
                rperpcut,
                dfacs,
                dfacmu,
                icovfname,
                smincut,
                smaxcut,
                DRinfo_NNxiell,
                smallRRcut,
            )
            xiinangxiell = xiell.xiellfromDR(
                fbase_angxiell,
                nell,
                binfile,
                rperpcut,
                dfacs,
                dfacmu,
                icovfname,
                smincut,
                smaxcut,
                DRinfo_angxiell,
                smallRRcut,
            )

            xiinNNwptmp = wp.wpfromDR(fbase_NNwp, DRfacinfo=DRinfo_NNwp, rpimax=rpimax, icovfname=icovfname)
            xiinangwptmp = wp.wpfromDR(fbase_angwp, DRfacinfo=DRinfo_angwp, rpimax=rpimax, icovfname=icovfname)

            xiinNNwp = wp.wpfromDR(
                fbase_NNwp, DRfacinfo=DRinfo_NNwp, rpimax=rpimax, icovfname=icovfname, wpstart=wpstart, wpend=wpend
            )
            xiinangwp = wp.wpfromDR(
                fbase_angwp, DRfacinfo=DRinfo_angwp, rpimax=rpimax, icovfname=icovfname, wpstart=wpstart, wpend=wpend
            )
            xiinNN = xiwp.xiwp(xiinNNxiell, xiinNNwp)
            xiinang = xiwp.xiwp(xiinangxiell, xiinangwp)
            xicorr = xiwpcorrect(
                xiinNNxiell, xiinangxiell, splitxi0, splitxi2, xiinNNwptmp, xiinangwptmp, splitwp, wpstart, wpend
            )

        ## tmp!  we tested to make sure we recovered the same correlation fxns as with old code.  Good!
        # tmpfname = "testing/testo%d" % ns
        # xiin.printxiellshort(tmpfname)
        if ns == 0:
            if xiellorwp == 0:
                ndata = xiinNN.ndata
                ndatacorr = ndata
            if xiellorwp == 1:
                ndata = len(xiinNN.wp)
                ndatacorr = len(xicorr.wp)
            if xiellorwp == 2:
                ndata = xiinNN.ntot
                ndatacorr = ndata

            xilistNN = np.zeros([nsub, ndata], dtype="float128")
            xilistang = np.zeros([nsub, ndata], dtype="float128")
            xilistcorr = np.zeros([nsub, ndatacorr], dtype="float128")
        if xiellorwp == 0:
            xilistNN[ns, :] = xiinNN.xilong
            xilistang[ns, :] = xiinang.xilong
            xilistcorr[ns, :] = xicorr.xilong
        if xiellorwp == 1:
            xilistNN[ns, :] = xiinNN.wp
            xilistang[ns, :] = xiinang.wp
            xilistcorr[ns, :] = xicorr.wp
        if xiellorwp == 2:
            xilistNN[ns, :] = xiinNN.xiwp
            xilistang[ns, :] = xiinang.xiwp
            xilistcorr[ns, :] = xicorr.xiwp

    ## check means with total counts.
    nindx = np.where(pixlist["NorS"] == 0)[0]
    sindx = np.where(pixlist["NorS"] == 1)[0]
    print "N/S: ", len(nindx), len(sindx)

    ## now compute mean and bootstrap errors:
    if NSortot == 0:
        ximeanNN = (xilistNN[nindx, :]).sum(axis=0) / float(len(nindx))
        ximeanang = (xilistang[nindx, :]).sum(axis=0) / float(len(nindx))
        ximeancorr = (xilistcorr[nindx, :]).sum(axis=0) / float(len(nindx))
        ntot = len(nindx)
        ## restrict xilist to N only
        xilistNN = xlistNN[nindx, :]
        xilistang = xlistang[nindx, :]
        xilistcorr = xlistcorr[nindx, :]

    if NSortot == 1:
        ximeanNN = (xilistNN[sindx, :]).sum(axis=0) / float(len(sindx))
        ximeanang = (xilistang[sindx, :]).sum(axis=0) / float(len(sindx))
        ximeancorr = (xilistcorr[sindx, :]).sum(axis=0) / float(len(sindx))
        ntot = len(sindx)
        ## restrict xilist to S only
        xilistNN = xlistNN[sindx, :]
        xilistang = xlistang[sindx, :]
        xilistcorr = xlistcorr[sindx, :]

    if NSortot == 2:
        ximeanNN = xilistNN.sum(axis=0) / float(nsub)
        ximeanang = xilistang.sum(axis=0) / float(nsub)
        ximeancorr = xilistcorr.sum(axis=0) / float(nsub)
        ntot = nsub

    xitotNN = np.zeros(ndata, dtype="float128")
    xitotang = np.zeros(ndata, dtype="float128")
    xitotcorr = np.zeros(ndatacorr, dtype="float128")
    CguessNN = np.zeros([ndata, ndata], dtype="float128")
    Cguessang = np.zeros([ndata, ndata], dtype="float128")
    Cguesscorr = np.zeros([ndatacorr, ndatacorr], dtype="float128")

    for b in range(nboot):
        rr = np.random.random_integers(0, ntot - 1, ntot)
        xitrialNN = (xilistNN[rr, :]).sum(axis=0) / float(ntot)
        xitrialang = (xilistang[rr, :]).sum(axis=0) / float(ntot)
        xitrialcorr = (xilistcorr[rr, :]).sum(axis=0) / float(ntot)
        xvecNN = np.matrix([xitrialNN - ximeanNN])
        xvecang = np.matrix([xitrialang - ximeanang])
        xveccorr = np.matrix([xitrialcorr - ximeancorr])
        CguessNN += xvecNN.T * xvecNN
        Cguessang += xvecang.T * xvecang
        Cguesscorr += xveccorr.T * xveccorr

    CguessNN = CguessNN / float(nboot - 1)
    Cguessang = Cguessang / float(nboot - 1)
    Cguesscorr = Cguesscorr / float(nboot - 1)

    ## put this back in after tests.
    #### now let's compute icov for all these.
    ## eqn 17 of 0608064:
    p = len(CguessNN[:, 0])
    unbiasicov = float(ntot - p - 2) / float(ntot - 1)

    CguessNN = np.matrix(CguessNN, dtype="float64")
    invCguessNN = CguessNN.I * unbiasicov
    printcov(CguessNN, covoutNN)
    printcov(invCguessNN, icovoutNN)

    Cguessang = np.matrix(Cguessang, dtype="float64")
    invCguessang = Cguessang.I * unbiasicov
    printcov(Cguessang, covoutang)
    printcov(invCguessang, icovoutang)

    Cguesscorr = np.matrix(Cguesscorr, dtype="float64")
    invCguesscorr = Cguesscorr.I * unbiasicov
    printcov(Cguesscorr, covoutcorr)
    printcov(invCguesscorr, icovoutcorr)

    return CguessNN, invCguessNN, Cguessang, invCguessang, Cguesscorr, invCguesscorr
示例#4
0
def getbootcov(bootfile, basedir, outdirbase = 'outputdr12', covoutfname=None, NSortot=2, nboot = 5000000, \
               rpimax=80.,wpstart=1,wpend=19,\
               nell=3,rperpcut=-1.,smallRRcut=-1.,\
               dfacs=1,dfacmu=1,icovfname=None,smincut=-1.,smaxcut=1.e12,\
               binfname_xiell='xibinfiles/bin1fineMU.txt',\
               nbar2d=[-1.,-1.],nbar3d=[-1.,-1],\
               whichtask=4):
## resurrect these later.
#               splitxi0=5,splitxi2=6,splitwp=7):
  """
  Get covariance matrix.
  We're going to do all tasks at once by default (4).
  whichtask = 0: xiell
  whichtask = 1: wp (compute xi(rp,rpi))
  whichtask = 2: wtheta
  whichtask = 3: Hogg spec-im cross-correlation.
  whichtask = 4: combine xiell and wp in usual way.

  Third tier of stuff goes directly to xiellfromDR
  rpimax is for wp, default is 80.
  nbar2d,nbar3d needs to be computed separately for N and S.
  """

  nsub, nsubdir, pixelfname, fbase, fbasetotN, fbasetotS = parsebootinfo(bootfile=basedir+bootfile)

  NSlist = [0,1]
  NStaglist = ['N','S']

  for xx in [nsub, nsubdir, pixelfname, fbase, fbasetotN, fbasetotS]:
    if xx is None:
      print 'bad bootfile!'
      return None

  b = boot.bootpix()
  b.readregions(basedir + pixelfname)
  assert b.nsub == nsub

  ## this list will be filled
  DRinfolist = [-1,-1,-1,-1]

  taglist= ['-xiell','-xigrid','-wtheta','-wpcross']

  ## get global DR factors for taglist.
  for ii in range(len(taglist)-1):
    tag = taglist[ii]
    tmp = np.zeros([2,2]) # first index is N or S.  DRfac, fixRR stored for each.

    for NS, NStag, ff in zip(NSlist, NStaglist,[fbasetotN,fbasetotS]):
      try:
      #if 0==0:
        tmp[NS,0], tmp[NS,1] = ximisc.getDRfactors(basedir + '/'+outdirbase + tag +'/'+ff)
      except:
        tmp[NS,:] = -1.
    DRinfolist[ii] = tmp.copy()

  ## now get DR info for wpcross.
  ### nevermind! we reduce this to two ratios.
  ## DRinfolist[3] = np.zeros([2,4,2])
  DRinfolist[3] = np.zeros([2,2])
  tag = taglist[3]
  for NS, NStag, ff in zip(NSlist, NStaglist,[fbasetotN,fbasetotS]):
    try:
      normfac = ximisc.getDRnormswpcross(basedir + '/'+outdirbase + tag +'/'+ff) 
      DRinfolist[3][NS][0] = normfac[0,0]/normfac[2,0]
      DRinfolist[3][NS][1] = normfac[0,1]/normfac[1,1]
    except:
      DRinfolist[3][NS][:] = -1.

  tasklist = np.zeros(4,dtype='int')
  if whichtask == 4:
    tasklist = np.array([1,1,0,1],dtype='int')
  else:
    tasklist[whichtask] = 1

  if tasklist[3] > 0:
    assert (nbar2d[:] > 0).all()
    assert (nbar3d[:] > 0).all()
    assert (DRinfolist[3][:,:].flatten() > 0).all()

  for ns in range(nsub):
    xx = np.where(b.pixlist['PID'] == ns)[0]
    assert len(xx) == 1
    assert xx[0] == ns
    NorSval = b.pixlist['NorS'][xx[0]]
    for tt in range(len(tasklist)):
      if tasklist[tt] == 0: continue
      tag = taglist[tt]
      ff = basedir+'/'+outdirbase + tag +'/' + nsubdir + '/' + fbase + '.%04d.Np' % (ns) 
      if tt == 0: #xiell
        xitmp = xiell.xiellfromDR(ff,binfile=binfname_xiell,rperpcut=rperpcut,nell=nell,smallRRcut=smallRRcut,dfacs=dfacs,dfacmu=dfacmu,smincut=smincut,smaxcut=smaxcut,DRfacinfo=DRinfolist[tt][NorSval]) 
        dvec = xitmp.xilong
      if tt == 1: #wp
        wptmp = wp.wpfromDR(ff,DRfacinfo=DRinfolist[tt][NorSval],rpimax=rpimax)
        dvec = wptmp.wp

      if tt == 2: #wtheta
        wttmp = wtheta.wthetafromDR(ff,DRfacinfo=DRinfolist[tt][NorSval])
        dvec = wttmp.wtheta

      if tt == 3: #wpcross
        wpcrosstmp = wp.wpcrossHogg(ff,DRfacinfo=DRinfolist[tt][NorSval],nbar2d=nbar2d[NorSval],nbar3d=nbar3d[NorSval])
        dvec = wpcrosstmp.wp

    if whichtask == 4:
      dvec = xiwpvec(xitmp,wptmp,wpcrosstmp,wpstart,wpend)

    if ns == 0:  ## allocate!
      ndata = len(dvec)
      dveclist = np.zeros([nsub,ndata],dtype='float128')
    dveclist[ns,:] = dvec[:]

  ## check means with total counts.
  nindx = np.where(b.pixlist['NorS'] == 0)[0]
  sindx = np.where(b.pixlist['NorS'] == 1)[0]
  nsindx = np.where((b.pixlist['NorS'] == 0) | (b.pixlist['NorS'] == 1))[0]
  print 'N/S: ',len(nindx), len(sindx), len(nsindx)
  assert len(nsindx) == nsub
  assert (nsindx == np.arange(0,nsub,1,dtype='int')).all()
  myindx= nsindx
  ## assume we want nsindx for this, but can restore N/S option later if I want.

  dmean = (dveclist[myindx,:]).sum(axis=0)/float(len(myindx))
  ntot = len(myindx)
  ntotflt = float(ntot)

  print 'hi beth'
  print dmean

  Cmat = np.zeros([ndata,ndata],dtype='float128')
  for b in range(nboot):
    rr = np.random.random_integers(0,ntot-1,ntot)
    dtrial = (dveclist[rr,:]).sum(axis=0)/ntotflt
    xvec = np.matrix([dtrial-dmean])
    Cmat += (xvec.T*xvec)

  Cmat = Cmat/float(nboot-1)
  Cmat = np.matrix(Cmat,dtype='float64')
  iCmat = Cmat.I ##
  print 'not assuming any bootstrap unbias factor for now!'
  if covoutfname is not None:
    printcov(Cmat,covoutfname)
    printcov(iCmat,covoutfname+'.inv')
    printmean(dmean,covoutfname+'.mean')
  return Cmat, iCmat, dmean
示例#5
0
def getbootcov(bootfile, workingdir, covtag, NNorang=0, NSortot=2, nboot = 5000000, fbaseend='_rmax48deltalog10r',\
               nell=3,binfile=None,rperpcut=-1.,smallRRcut=-1.,
               dfacs=1,dfacmu=1,icovfname=None,smincut=-1.,smaxcut=1.e12):
    """
  Get covariance matrix.
  fbaseend = '_rmax48deltalog10r' for xiell or '_xigrid' for wp.
  NNorang = 0 [NN] or 1 [ang] or 2 [optimal unbiased combination, not yet written]
  Third tier of stuff goes directly to xiellfromDR
  """
    print 'this is not up to date!  i am using bootcov.py for this job'
    print 'BETH, you should edit/delete/merge for consistency and reduce defns of same functions in two places!!'
    return 0

    nsub, pixelfname, fbaseNNstart, fbaseangstart, \
    fbaseNNtotN, fbaseNNtotS, fbaseangtotN, fbaseangtotS =  parsebootinfo(bootfile,workingdir)

    if nsub is None or pixelfname is None or fbaseNNstart is None or fbaseangstart is None:
        print 'bad boot file, getbootcov returning None!'
        return None
    pixlist = getpixlist(pixelfname, nsub)

    if NNorang == 0:
        myfbase = fbaseNNstart
        DRfacN, fixRRdownN = ximisc.getDRfactors(fbaseNNtotN + fbaseend)
        DRfacS, fixRRdownS = ximisc.getDRfactors(fbaseNNtotS + fbaseend)

    elif NNorang == 1:
        myfbase = fbaseangstart
        DRfacN, fixRRdownN = ximisc.getDRfactors(fbaseangtotN + fbaseend)
        DRfacS, fixRRdownS = ximisc.getDRfactors(fbaseangtotS + fbaseend)
    else:
        print 'NNorang = ', NNorang, 'not supported.'
        return None

    DRinfoN = [DRfacN, fixRRdownN]
    DRinfoS = [DRfacS, fixRRdownS]

    for ns in range(nsub):
        fbase = myfbase + ('-%03d' % (ns)) + fbaseend
        xx = np.where(pixlist['PID'] == ns)[0]
        assert len(xx) == 1
        assert xx[0] == ns
        NorSval = pixlist['NorS'][xx[0]]
        if (NorSval == 0):
            DRinfo = DRinfoN
        else:
            DRinfo = DRinfoS
        xiin = xiell.xiellfromDR(fbase, nell, binfile, rperpcut, dfacs, dfacmu,
                                 icovfname, smincut, smaxcut, DRinfo,
                                 smallRRcut)
        ## tmp!  we tested to make sure we recovered the same correlation fxns as with old code.  Good!
        tmpfname = "testing/testo%d" % ns
        xiin.printxiellshort(tmpfname)
        if (ns == 0):
            ndata = xiin.ndata
            xilist = np.zeros([nsub, ndata], dtype='float128')
        xilist[ns, :] = xiin.xilong

    ## check means with total counts.
    nindx = np.where(pixlist['NorS'] == 0)[0]
    sindx = np.where(pixlist['NorS'] == 1)[0]
    print 'N/S: ', len(nindx), len(sindx)

    ## now compute mean and bootstrap errors:
    if (NSortot == 0):
        ximean = (xilist[nindx, :]).sum(axis=0) / float(len(nindx))
        ntot = len(nindx)
        ## restrict xilist to N only
        xilist = xlist[nindx, :]
    if (NSortot == 1):
        ximean = (xilist[sindx, :]).sum(axis=0) / float(len(sindx))
        ntot = len(sindx)
        xilist = xlist[sindx, :]
    if (NSortot == 2):
        ximean = xilist.sum(axis=0) / float(nsub)
        ntot = nsub

    xitot = np.zeros(ndata, dtype='float128')
    Cguess = np.zeros([ndata, ndata], dtype='float128')

    for b in range(nboot):
        rr = np.random.random_integers(0, ntot - 1, ntot)
        xitrial = (xilist[rr, :]).sum(axis=0) / float(ntot)
        xvec = np.matrix([xitrial - ximean])
        Cguess += (xvec.T * xvec)

    Cguess = Cguess / float(nboot - 1)

    #### now let's compute icov for all these.
    ## eqn 17 of 0608064:
    p = len(Cguess[:, 0])
    unbiasicov = float(ntot - p - 2) / float(ntot - 1)
    Cguess = np.matrix(Cguess, dtype='float64')
    invCguess = Cguess.I * unbiasicov

    #  printcov(Cguess,"cov.tmp")
    #  printcov(invCguess,"icov.tmp")
    return Cguess, invCguess
示例#6
0
def xiellfromDR(fbase,nell=3,binfile=None,rperpcut=-1.,
                dfacs=1,dfacmu=1,icovfname=None,smincut=-1.,smaxcut=1.e12,\
                DRfacinfo=None,smallRRcut=-1.,periodicopt=0,printmaskopt=0,xiopt=0):
    """
  This function should supercede older codes with names like rebinxismugeneric*py
  input the base for the DR files, as well as optional bin files and small scale 
  cutoff for masking (rperpcut).  If you don't want to use a binfile to specify
  the downsampling, use dfacs and dfacmu inputs.
  smincut/smaxcut will only be used if binfile is None.
  DRfacinfo is used to pass [DRfac, fixRR] (dont get it from file headers in this case)
  That feature is necessary for computing covariance matrices from bootstrap, where that factor
  should be fixed by total N and/or S, it does not vary from bootstrap region to region.
  smallRRcut allows you to replace randoms(mu) with the average over mu where the total number of 
  randoms in the bin is smaller than smallRRcut, just to keep Poisson noise down.
  If periodicopt == 1, assume the input is file containing [rg, mug, Vg, Ng] as currently output
  by correlationfxnMASTERv4.
  xiopt introduced on May 13 2014 to input xi(s,mu) and simply rebin (for comparison with Hong).
  """
    if periodicopt == 1:  # periodic box.
        rg, mug, Vg, Ng = np.loadtxt(fbase, unpack=True)
        Vzerochk = Vg.min() * 0.1
        fDR = fbase  ## just for the return xiell purposes.
    elif xiopt == 1:
        rg, mug, xig = np.loadtxt(fbase, unpack=True,
                                  usecols=[0, 1, 2])  ## Hong format.
        fDR = fbase
        if binfile is None:
            ikeep = np.where((rg >= smincut) & (rg <= smaxcut))[0]
            rg = rg[ikeep]
            mug = mug[ikeep]
            xig = xig[ikeep]
    else:  # DD,RR counts.
        fDD = fbase + '.DRopt1'
        fDR = fbase + '.DRopt2'
        fRR = fbase + '.DRopt3'
        rg, mug, DDg = np.loadtxt(fDD, skiprows=3, unpack=True)
        rg, mug, DRg = np.loadtxt(fDR, skiprows=3, unpack=True)
        rg, mug, RRg = np.loadtxt(fRR, skiprows=3, unpack=True)
        if binfile is None:
            ikeep = np.where((rg >= smincut) & (rg <= smaxcut))[0]
            rg = rg[ikeep]
            mug = mug[ikeep]
            DDg = DDg[ikeep]
            DRg = DRg[ikeep]
            RRg = RRg[ikeep]

        if DRfacinfo is None:
            DRfac, fixRR = ximisc.getDRfactors(fbase)
        else:
            DRfac = DRfacinfo[0]
            fixRR = DRfacinfo[1]

    nmu = len(np.where(rg == rg[0])[0])
    dmu = 1. / float(nmu)
    nr = len(np.where(mug == mug[0])[0])
    if nmu * nr != len(rg):
        return None

    ## is s (called r here) log or linear binning?
    s1d = rg.reshape([nr, nmu])[:, 0]
    mu1d = rg.reshape([nr, nmu])[0, :]
    ## compute linear spacings.
    dmutmp = (mu1d[1:] - mu1d[:-1]).mean()
    ds = (s1d[1:] - s1d[:-1]).mean()
    dlogs = (np.log(s1d[1:] / s1d[:-1])).mean()
    if (np.fabs(mu1d[1:] - mu1d[:-1] - dmutmp) > 0.0001 * dmutmp).any():
        ## not linear binning!
        ## this shouldn't be the case for a s,mu grid.
        assert 0 == 1
        assert np.fabs(dmutmp - dmu) < 1.0e-4

    if (np.fabs(s1d[1:] - s1d[:-1] - ds) < 0.0001 * ds).all():
        logsopt = 0
        rglowedge = rg.copy()
        rglowedge = rglowedge - 0.5 * ds
        ## added specifically for xiopt
        rghighedge = rg.copy()
        rghighedge = rghighedge + 0.5 * ds
    if (np.fabs(np.log(s1d[1:]) - np.log(s1d[:-1]) - dlogs) <
            0.0001 * dlogs).all():
        logsopt = 1
        rglowedge = rg.copy()
        rglowedge = rglowedge * np.exp(-0.5 * dlogs)
        ## added specifically for xiopt
        rghighedge = rg.copy()
        rghighedge = rghighedge * np.exp(0.5 * dlogs)

    assert logsopt == 0 or logsopt == 1
    if xiopt == 1:
        Vg = rghighedge**3 - rglowedge**3  ## just need something proportional to volume.
        Vzerochk = Vg.min() * 0.1

    ## cut at edge of bin.
    xx = np.where(rglowedge * (1 - (mug + 0.5 * dmu)**2)**0.5 < rperpcut)[0]
    if (rperpcut < 0.): assert len(xx) == 0
    if len(xx) > 0:
        if periodicopt == 1:
            Vg[xx] = 0.
            Ng[xx] = 0.
        elif xiopt == 1:
            Vg[xx] = 0.
            xig[xx] = 0.

        else:
            DDg[xx] = 0.
            DRg[xx] = 0.
            RRg[xx] = 0.

    mymask = np.zeros(len(rg), dtype='int')
    mymask[xx] = 1

    ## tmp!  print a mask file.
    if (printmaskopt == 1):
        print 'yoyoyo opening masktmp.dat'
        ofpmask = open('masktmp.dat', 'w')
        for i in range(len(mymask)):
            ofpmask.write('%d\n' % (mymask[i]))
        ofpmask.close()

    if (printmaskopt == 2):
        #### nevermind, let's print below the boundaries of each s,mu bin.
        #    print 'yoyoyo opening masktmp2.dat'
        #    ofpmask = open('masktmp2.dat','w')
        mumaxlist = np.zeros(len(s1d)) + 1.
        for qi in range(len(s1d)):
            rgval = s1d[qi]
            qq = np.where((rg == rgval) & (mymask == 1))[0]
            ww = np.where((rg == rgval))[0]
            assert len(ww) > 0
            if (len(qq) == 0):
                pass
#        ofpmask.write('%e %e %e\n' % (rgval,rglowedge[ww[0]],1.0))
            else:
                #        ofpmask.write('%e %e %e\n' % (rgval,rglowedge[ww[0]],mug[qq].max()))
                mumaxlist[qi] = mug[qq].min() - 0.5 * dmu
### testing.
#      print s1d[qi], mumaxlist[qi]
#ofpmask.write('%d\n' % (mymask[i]))
#    ofpmask.close()

    if binfile is not None:
        ## specifies how many rbins to join together for first bin, next bin, etc.
        rjoin, mujoin = np.loadtxt(binfile, unpack=True, dtype='int')
        nrcut = len(rjoin)
        ### use later.
        #bintag = binfile.split('.')[0]
    else:
        #    dfacs = dfacsin
        #    dfacmu = dfacmuin
        nrcut = len(s1d) / dfacs
        dmudown = dfacmu * dmu

    if printmaskopt == 2:
        ofpmask = open('masktmp2.dat', 'w')

    ## check mask if I'm going to cut more.
    ristart = 0
    badlist = np.zeros(nrcut, dtype='int')
    for i in range(nrcut):
        if binfile is not None:
            dfacs = rjoin[i]
        if (mymask[ristart * nmu:(ristart + dfacs) * nmu] == 1).all():
            badlist[i] = 1
        ristart = ristart + dfacs

    nrcutkeep = nrcut - len(np.where(badlist == 1)[0])

    xi = np.zeros([nell, nrcutkeep], dtype=float)
    svec = np.zeros([nell, nrcutkeep], dtype=float)

    rcen = np.zeros(nrcut, dtype=float)
    ristart = 0
    xiindx = 0
    for i in range(nrcut):
        if binfile is not None:
            dfacs = rjoin[i]
            dfacmu = mujoin[i]
            dmudown = dfacmu * dmu
        riend = ristart + dfacs - 1
        if logsopt == 0:
            rcen[i] = 0.5 * (s1d[ristart] + s1d[riend])
        if logsopt == 1:
            rcen[i] = np.exp(0.5 * np.log(s1d[ristart] * s1d[riend]))
        for ishort in range(dfacs):
            i1 = (ristart + ishort) * nmu
            i2 = (ristart + ishort + 1) * nmu
            if periodicopt == 1:
                if (ishort == 0):
                    mymu = ximisc.downsample1d(mug[i1:i2], dfacmu)
                    myVg = ximisc.downsample1dsum(Vg[i1:i2], dfacmu)
                    myNg = ximisc.downsample1dsum(Ng[i1:i2], dfacmu)
                else:
                    myVg = myVg + ximisc.downsample1dsum(Vg[i1:i2], dfacmu)
                    myNg = myNg + ximisc.downsample1dsum(Ng[i1:i2], dfacmu)
            elif xiopt == 1:
                if (ishort == 0):
                    mymu = ximisc.downsample1d(mug[i1:i2], dfacmu)
                    myxig = ximisc.downsample1dvweight(
                        xig[i1:i2], Vg[i1:i2],
                        dfacmu)  #perform volume weighted sum.
                    myVg = ximisc.downsample1dsum(Vg[i1:i2], dfacmu)
                else:
                    myxig = myxig + ximisc.downsample1dvweight(
                        xig[i1:i2], Vg[i1:i2], dfacmu
                    )  # perform volume weighted sum, divide out at the end.
                    myVg = myVg + ximisc.downsample1dsum(Vg[i1:i2], dfacmu)

            else:
                if (ishort == 0):
                    mymu = ximisc.downsample1d(mug[i1:i2], dfacmu)
                    mydd = ximisc.downsample1dsum(DDg[i1:i2], dfacmu)
                    mydr = ximisc.downsample1dsum(DRg[i1:i2], dfacmu)
                    myrr = ximisc.downsample1dsum(RRg[i1:i2], dfacmu)
                else:
                    mydd = mydd + ximisc.downsample1dsum(DDg[i1:i2], dfacmu)
                    mydr = mydr + ximisc.downsample1dsum(DRg[i1:i2], dfacmu)
                    myrr = myrr + ximisc.downsample1dsum(RRg[i1:i2], dfacmu)

        if periodicopt == 1:
            yy = np.where(myVg < Vzerochk)[0]
            xitmp = myNg / myVg - 1.
            xitmp[yy] = 0.

        elif xiopt == 1:
            yy = np.where(myVg < Vzerochk)[0]
            xitmp = myxig / myVg
            xitmp[yy] = 0.
            ## for now, nothing to 0 out (?)

        else:  ##DR stuff
            zz = np.where(myrr < smallRRcut)[0]
            if (len(zz) > 0):
                print 'using smallRRcut!  here are details', i, rcen[
                    i], smallRRcut
                myrr = myrr.mean()

            yy = np.where(myrr < 0.01)[0]
            xitmp = (mydd - mydr * DRfac) / myrr / DRfac**2 / fixRR**2 + 1.
            xitmp[yy] = 0.  ## fix 0'd out regions

            if (len(yy) > 0 and 0 == 1):
                print 'ack why zerod out regions?'
                print len(yy)
                print i, dfacs, dfacmu
                print myrr
                print mymu

        for ell in np.arange(0, nell * 2, 2):
            if (badlist[i] == 0):
                xi[ell / 2, xiindx] = (xitmp * ximisc.legendre(
                    ell, mymu)).sum() * dmudown * (2. * ell + 1.)
                svec[ell / 2, xiindx] = rcen[i]

        if printmaskopt == 2:
            ofpmask.write(
                '%e %e %e %e %e ' %
                (rcen[i], s1d[ristart] * np.exp(-0.5 * dlogs), s1d[riend] *
                 np.exp(0.5 * dlogs), mumaxlist[ristart], mumaxlist[riend]))
            for ell in np.arange(0, nell * 2, 2):
                if badlist[i] == 0:
                    ofpmask.write('%e ' % (xi[ell / 2, xiindx]))
                else:
                    ofpmask.write('%e ' % (0.0))

            ofpmask.write('\n')

        ristart = ristart + dfacs

        if (badlist[i] == 0):
            xiindx += 1

    return xiell(xiellfname=fDR, sxilist=[svec, xi], icovfname=icovfname)
示例#7
0
def getbootcov(bootfile, workingdir, covtag=None, NSortot=2, nboot = 5000000, fbaseend='_rmax48deltalog10r',\
               xiellorwp=0,rpimax=80.,splitwp=7,wpstart=1,wpend=19,\
               nell=3,binfile=None,rperpcut=-1.,smallRRcut=-1.,\
               dfacs=1,dfacmu=1,icovfname=None,smincut=-1.,smaxcut=1.e12,\
               splitxi0=5,splitxi2=6,fbaseendxiell='_rmax48deltalog10r',fbaseendwp='_xigrid'):
    """
  Get covariance matrix.
  fbaseend = '_rmax48deltalog10r' for xiell or '_xigrid' for wp.
  Third tier of stuff goes directly to xiellfromDR
  expect splitxi0/splitxi2 [those go to xicorrect; values determined in
  comparetiledcmockstotruthv0
  Added functionality for wp: xiellorwp = 1, splitwp = where to go from ang to NN.
  rpimax is for wp, default is 80.
  Leaving variable fbaseend for backward compatibility,  but if xiellorwp == 2, defaults to 
  using fbaseendxiell and fbaseendwp
  """
    #NNorang = 0 [NN] or 1 [ang] or 2 [optimal unbiased combination, not yet written]
    ## nevermind, that doesnt get used anywhere!!?? deleted, was the 4th elt in the list.

    assert xiellorwp >= 0 and xiellorwp <= 2

    nsub, pixelfname, fbaseNNstart, fbaseangstart, \
    fbaseNNtotN, fbaseNNtotS, fbaseangtotN, fbaseangtotS =  parsebootinfo(bootfile,workingdir)

    if nsub is None or pixelfname is None or fbaseNNstart is None or fbaseangstart is None:
        print 'bad boot file, getbootcov returning None!'
        return None
    pixlist = getpixlist(pixelfname, nsub)

    myfbase_NN = fbaseNNstart
    myfbase_ang = fbaseangstart

    if xiellorwp == 0 or xiellorwp == 1:
        DRfacN_NN, fixRRdownN_NN = ximisc.getDRfactors(fbaseNNtotN + fbaseend)
        DRfacS_NN, fixRRdownS_NN = ximisc.getDRfactors(fbaseNNtotS + fbaseend)
        DRfacN_ang, fixRRdownN_ang = ximisc.getDRfactors(fbaseangtotN +
                                                         fbaseend)
        DRfacS_ang, fixRRdownS_ang = ximisc.getDRfactors(fbaseangtotS +
                                                         fbaseend)
    else:  ##xiwp statistic.  xiellorwp == 2
        ## xiell
        DRfacN_NNxiell, fixRRdownN_NNxiell = ximisc.getDRfactors(fbaseNNtotN +
                                                                 fbaseendxiell)
        DRfacS_NNxiell, fixRRdownS_NNxiell = ximisc.getDRfactors(fbaseNNtotS +
                                                                 fbaseendxiell)
        DRfacN_angxiell, fixRRdownN_angxiell = ximisc.getDRfactors(
            fbaseangtotN + fbaseendxiell)
        DRfacS_angxiell, fixRRdownS_angxiell = ximisc.getDRfactors(
            fbaseangtotS + fbaseendxiell)
        ## wp
        DRfacN_NNwp, fixRRdownN_NNwp = ximisc.getDRfactors(fbaseNNtotN +
                                                           fbaseendwp)
        DRfacS_NNwp, fixRRdownS_NNwp = ximisc.getDRfactors(fbaseNNtotS +
                                                           fbaseendwp)
        DRfacN_angwp, fixRRdownN_angwp = ximisc.getDRfactors(fbaseangtotN +
                                                             fbaseendwp)
        DRfacS_angwp, fixRRdownS_angwp = ximisc.getDRfactors(fbaseangtotS +
                                                             fbaseendwp)

    if xiellorwp == 0:
        splittag = 'splits%d_%d' % (splitxi0, splitxi2)
    if xiellorwp == 1:
        splittag = 'splitswp%d_%d_%d' % (splitwp, wpstart, wpend)
    if xiellorwp == 2:
        splittagxiell = 'splits%d_%d' % (splitxi0, splitxi2)
        splittagwp = 'splitswp%d_%d_%d' % (splitwp, wpstart, wpend)
        splittag = splittagxiell + '_' + splittagwp

    if binfile is not None:
        bintag = binfile.split('/')[-1].split('.')[0]
        covoutNN = 'covtotv7NN_b%d_N%d_rebin-%s' % (nboot, nsub, bintag)
        covoutang = 'covtotv7ang_b%d_N%d_rebin-%s' % (nboot, nsub, bintag)
        covoutcorr = 'covtotv7corr_b%d_N%d_rebin-%s_%s' % (nboot, nsub, bintag,
                                                           splittag)
    else:
        covoutNN = 'covtotv7NN_b%d_N%d' % (nboot, nsub)
        covoutang = 'covtotv7ang_b%d_N%d' % (nboot, nsub)
        covoutcorr = 'covtotv7corr_b%d_N%d_%s' % (nboot, nsub, splittag)

    if covtag is not None:
        covoutNN = covoutNN + '_%s' % covtag
        covoutang = covoutang + '_%s' % covtag
        covoutcorr = covoutcorr + '_%s' % covtag

    icovoutNN = 'i' + covoutNN
    icovoutang = 'i' + covoutang
    icovoutcorr = 'i' + covoutcorr

    if xiellorwp == 0 or xiellorwp == 1:
        DRinfoN_NN = [DRfacN_NN, fixRRdownN_NN]
        DRinfoS_NN = [DRfacS_NN, fixRRdownS_NN]
        DRinfoN_ang = [DRfacN_ang, fixRRdownN_ang]
        DRinfoS_ang = [DRfacS_ang, fixRRdownS_ang]
    else:
        #xiell
        DRinfoN_NNxiell = [DRfacN_NNxiell, fixRRdownN_NNxiell]
        DRinfoS_NNxiell = [DRfacS_NNxiell, fixRRdownS_NNxiell]
        DRinfoN_angxiell = [DRfacN_angxiell, fixRRdownN_angxiell]
        DRinfoS_angxiell = [DRfacS_angxiell, fixRRdownS_angxiell]
        # wp
        DRinfoN_NNwp = [DRfacN_NNwp, fixRRdownN_NNwp]
        DRinfoS_NNwp = [DRfacS_NNwp, fixRRdownS_NNwp]
        DRinfoN_angwp = [DRfacN_angwp, fixRRdownN_angwp]
        DRinfoS_angwp = [DRfacS_angwp, fixRRdownS_angwp]

    for ns in range(nsub):
        print ns
        fbase_NN = myfbase_NN + ('-%03d' % (ns)) + fbaseend
        fbase_ang = myfbase_ang + ('-%03d' % (ns)) + fbaseend
        if xiellorwp == 2:
            fbase_NNxiell = myfbase_NN + ('-%03d' % (ns)) + fbaseendxiell
            fbase_angxiell = myfbase_ang + ('-%03d' % (ns)) + fbaseendxiell
            fbase_NNwp = myfbase_NN + ('-%03d' % (ns)) + fbaseendwp
            fbase_angwp = myfbase_ang + ('-%03d' % (ns)) + fbaseendwp

        xx = np.where(pixlist['PID'] == ns)[0]
        assert len(xx) == 1
        assert xx[0] == ns
        NorSval = pixlist['NorS'][xx[0]]
        if (NorSval == 0):
            if xiellorwp == 0 or xiellorwp == 1:
                DRinfo_NN = DRinfoN_NN
                DRinfo_ang = DRinfoN_ang
            else:
                DRinfo_NNxiell = DRinfoN_NNxiell
                DRinfo_angxiell = DRinfoN_angxiell
                DRinfo_NNwp = DRinfoN_NNwp
                DRinfo_angwp = DRinfoN_angwp

        else:  #south
            if xiellorwp == 0 or xiellorwp == 1:
                DRinfo_NN = DRinfoS_NN
                DRinfo_ang = DRinfoS_ang
            else:
                DRinfo_NNxiell = DRinfoS_NNxiell
                DRinfo_angxiell = DRinfoS_angxiell
                DRinfo_NNwp = DRinfoS_NNwp
                DRinfo_angwp = DRinfoS_angwp

        if xiellorwp == 0:
            xiinNN = xiell.xiellfromDR(fbase_NN, nell, binfile, rperpcut,
                                       dfacs, dfacmu, icovfname, smincut,
                                       smaxcut, DRinfo_NN, smallRRcut)
            xiinang = xiell.xiellfromDR(fbase_ang, nell, binfile, rperpcut,
                                        dfacs, dfacmu, icovfname, smincut,
                                        smaxcut, DRinfo_ang, smallRRcut)
            xicorr = xicorrect(xiinNN, xiinang, splitxi0, splitxi2)
        if xiellorwp == 1:  ## doing wp
            xiinNNtmp = wp.wpfromDR(fbase_NN,
                                    DRfacinfo=DRinfo_NN,
                                    rpimax=rpimax,
                                    icovfname=icovfname)
            xiinangtmp = wp.wpfromDR(fbase_ang,
                                     DRfacinfo=DRinfo_ang,
                                     rpimax=rpimax,
                                     icovfname=icovfname)

            ## these are for later, saving cov of NN and ang separately.
            xiinNN = wp.wpfromDR(fbase_NN,
                                 DRfacinfo=DRinfo_NN,
                                 rpimax=rpimax,
                                 icovfname=icovfname,
                                 wpstart=wpstart,
                                 wpend=wpend)
            xiinang = wp.wpfromDR(fbase_ang,
                                  DRfacinfo=DRinfo_ang,
                                  rpimax=rpimax,
                                  icovfname=icovfname,
                                  wpstart=wpstart,
                                  wpend=wpend)

            ##wpstart,end not already applied to this NN and ang!
            xicorr = wpcorrect(xiinNNtmp, xiinangtmp, splitwp, wpstart, wpend)

        if xiellorwp == 2:  ##doing xiwp
            xiinNNxiell = xiell.xiellfromDR(fbase_NNxiell, nell, binfile,
                                            rperpcut, dfacs, dfacmu, icovfname,
                                            smincut, smaxcut, DRinfo_NNxiell,
                                            smallRRcut)
            xiinangxiell = xiell.xiellfromDR(fbase_angxiell, nell, binfile,
                                             rperpcut, dfacs, dfacmu,
                                             icovfname, smincut, smaxcut,
                                             DRinfo_angxiell, smallRRcut)

            xiinNNwptmp = wp.wpfromDR(fbase_NNwp,
                                      DRfacinfo=DRinfo_NNwp,
                                      rpimax=rpimax,
                                      icovfname=icovfname)
            xiinangwptmp = wp.wpfromDR(fbase_angwp,
                                       DRfacinfo=DRinfo_angwp,
                                       rpimax=rpimax,
                                       icovfname=icovfname)

            xiinNNwp = wp.wpfromDR(fbase_NNwp,
                                   DRfacinfo=DRinfo_NNwp,
                                   rpimax=rpimax,
                                   icovfname=icovfname,
                                   wpstart=wpstart,
                                   wpend=wpend)
            xiinangwp = wp.wpfromDR(fbase_angwp,
                                    DRfacinfo=DRinfo_angwp,
                                    rpimax=rpimax,
                                    icovfname=icovfname,
                                    wpstart=wpstart,
                                    wpend=wpend)
            xiinNN = xiwp.xiwp(xiinNNxiell, xiinNNwp)
            xiinang = xiwp.xiwp(xiinangxiell, xiinangwp)
            xicorr = xiwpcorrect(xiinNNxiell, xiinangxiell, splitxi0, splitxi2,
                                 xiinNNwptmp, xiinangwptmp, splitwp, wpstart,
                                 wpend)

        ## tmp!  we tested to make sure we recovered the same correlation fxns as with old code.  Good!
        #tmpfname = "testing/testo%d" % ns
        #xiin.printxiellshort(tmpfname)
        if (ns == 0):
            if (xiellorwp == 0):
                ndata = xiinNN.ndata
                ndatacorr = ndata
            if (xiellorwp == 1):
                ndata = len(xiinNN.wp)
                ndatacorr = len(xicorr.wp)
            if (xiellorwp == 2):
                ndata = xiinNN.ntot
                ndatacorr = ndata

            xilistNN = np.zeros([nsub, ndata], dtype='float128')
            xilistang = np.zeros([nsub, ndata], dtype='float128')
            xilistcorr = np.zeros([nsub, ndatacorr], dtype='float128')
        if (xiellorwp == 0):
            xilistNN[ns, :] = xiinNN.xilong
            xilistang[ns, :] = xiinang.xilong
            xilistcorr[ns, :] = xicorr.xilong
        if (xiellorwp == 1):
            xilistNN[ns, :] = xiinNN.wp
            xilistang[ns, :] = xiinang.wp
            xilistcorr[ns, :] = xicorr.wp
        if (xiellorwp == 2):
            xilistNN[ns, :] = xiinNN.xiwp
            xilistang[ns, :] = xiinang.xiwp
            xilistcorr[ns, :] = xicorr.xiwp

    ## check means with total counts.
    nindx = np.where(pixlist['NorS'] == 0)[0]
    sindx = np.where(pixlist['NorS'] == 1)[0]
    print 'N/S: ', len(nindx), len(sindx)

    ## now compute mean and bootstrap errors:
    if (NSortot == 0):
        ximeanNN = (xilistNN[nindx, :]).sum(axis=0) / float(len(nindx))
        ximeanang = (xilistang[nindx, :]).sum(axis=0) / float(len(nindx))
        ximeancorr = (xilistcorr[nindx, :]).sum(axis=0) / float(len(nindx))
        ntot = len(nindx)
        ## restrict xilist to N only
        xilistNN = xlistNN[nindx, :]
        xilistang = xlistang[nindx, :]
        xilistcorr = xlistcorr[nindx, :]

    if (NSortot == 1):
        ximeanNN = (xilistNN[sindx, :]).sum(axis=0) / float(len(sindx))
        ximeanang = (xilistang[sindx, :]).sum(axis=0) / float(len(sindx))
        ximeancorr = (xilistcorr[sindx, :]).sum(axis=0) / float(len(sindx))
        ntot = len(sindx)
        ## restrict xilist to S only
        xilistNN = xlistNN[sindx, :]
        xilistang = xlistang[sindx, :]
        xilistcorr = xlistcorr[sindx, :]

    if (NSortot == 2):
        ximeanNN = xilistNN.sum(axis=0) / float(nsub)
        ximeanang = xilistang.sum(axis=0) / float(nsub)
        ximeancorr = xilistcorr.sum(axis=0) / float(nsub)
        ntot = nsub

    xitotNN = np.zeros(ndata, dtype='float128')
    xitotang = np.zeros(ndata, dtype='float128')
    xitotcorr = np.zeros(ndatacorr, dtype='float128')
    CguessNN = np.zeros([ndata, ndata], dtype='float128')
    Cguessang = np.zeros([ndata, ndata], dtype='float128')
    Cguesscorr = np.zeros([ndatacorr, ndatacorr], dtype='float128')

    for b in range(nboot):
        rr = np.random.random_integers(0, ntot - 1, ntot)
        xitrialNN = (xilistNN[rr, :]).sum(axis=0) / float(ntot)
        xitrialang = (xilistang[rr, :]).sum(axis=0) / float(ntot)
        xitrialcorr = (xilistcorr[rr, :]).sum(axis=0) / float(ntot)
        xvecNN = np.matrix([xitrialNN - ximeanNN])
        xvecang = np.matrix([xitrialang - ximeanang])
        xveccorr = np.matrix([xitrialcorr - ximeancorr])
        CguessNN += (xvecNN.T * xvecNN)
        Cguessang += (xvecang.T * xvecang)
        Cguesscorr += (xveccorr.T * xveccorr)

    CguessNN = CguessNN / float(nboot - 1)
    Cguessang = Cguessang / float(nboot - 1)
    Cguesscorr = Cguesscorr / float(nboot - 1)

    ## put this back in after tests.
    #### now let's compute icov for all these.
    ## eqn 17 of 0608064:
    p = len(CguessNN[:, 0])
    unbiasicov = float(ntot - p - 2) / float(ntot - 1)

    CguessNN = np.matrix(CguessNN, dtype='float64')
    invCguessNN = CguessNN.I * unbiasicov
    printcov(CguessNN, covoutNN)
    printcov(invCguessNN, icovoutNN)

    Cguessang = np.matrix(Cguessang, dtype='float64')
    invCguessang = Cguessang.I * unbiasicov
    printcov(Cguessang, covoutang)
    printcov(invCguessang, icovoutang)

    Cguesscorr = np.matrix(Cguesscorr, dtype='float64')
    invCguesscorr = Cguesscorr.I * unbiasicov
    printcov(Cguesscorr, covoutcorr)
    printcov(invCguesscorr, icovoutcorr)

    return CguessNN, invCguessNN, Cguessang, invCguessang, Cguesscorr, invCguesscorr
示例#8
0
文件: cov.py 项目: bareid/LSSanalysis
def getbootcov(bootfile, workingdir, covtag, NNorang=0, NSortot=2, nboot = 5000000, fbaseend='_rmax48deltalog10r',\
               nell=3,binfile=None,rperpcut=-1.,smallRRcut=-1.,
               dfacs=1,dfacmu=1,icovfname=None,smincut=-1.,smaxcut=1.e12):
  """
  Get covariance matrix.
  fbaseend = '_rmax48deltalog10r' for xiell or '_xigrid' for wp.
  NNorang = 0 [NN] or 1 [ang] or 2 [optimal unbiased combination, not yet written]
  Third tier of stuff goes directly to xiellfromDR
  """
  print 'this is not up to date!  i am using bootcov.py for this job'
  print 'BETH, you should edit/delete/merge for consistency and reduce defns of same functions in two places!!'
  return 0

  nsub, pixelfname, fbaseNNstart, fbaseangstart, \
  fbaseNNtotN, fbaseNNtotS, fbaseangtotN, fbaseangtotS =  parsebootinfo(bootfile,workingdir)

  if nsub is None or pixelfname is None or fbaseNNstart is None or fbaseangstart is None:
    print 'bad boot file, getbootcov returning None!'
    return None
  pixlist = getpixlist(pixelfname,nsub)

  if NNorang == 0:
    myfbase = fbaseNNstart
    DRfacN, fixRRdownN = ximisc.getDRfactors(fbaseNNtotN+fbaseend)
    DRfacS, fixRRdownS = ximisc.getDRfactors(fbaseNNtotS+fbaseend)

  elif NNorang == 1:
    myfbase = fbaseangstart
    DRfacN, fixRRdownN = ximisc.getDRfactors(fbaseangtotN+fbaseend)
    DRfacS, fixRRdownS = ximisc.getDRfactors(fbaseangtotS+fbaseend)
  else:
    print 'NNorang = ',NNorang,'not supported.'
    return None

  DRinfoN = [DRfacN, fixRRdownN]
  DRinfoS = [DRfacS, fixRRdownS]

  for ns in range(nsub):
    fbase = myfbase + ('-%03d' % (ns))+fbaseend
    xx = np.where(pixlist['PID'] == ns)[0]
    assert len(xx) == 1
    assert xx[0] == ns
    NorSval = pixlist['NorS'][xx[0]]
    if(NorSval == 0):
      DRinfo = DRinfoN
    else:
      DRinfo = DRinfoS
    xiin = xiell.xiellfromDR(fbase,nell,binfile,rperpcut,dfacs,dfacmu,icovfname,smincut,smaxcut,DRinfo,smallRRcut)
    ## tmp!  we tested to make sure we recovered the same correlation fxns as with old code.  Good!
    tmpfname = "testing/testo%d" % ns
    xiin.printxiellshort(tmpfname)
    if(ns == 0):
      ndata = xiin.ndata
      xilist = np.zeros([nsub,ndata],dtype='float128')
    xilist[ns,:] = xiin.xilong

  ## check means with total counts.
  nindx = np.where(pixlist['NorS'] == 0)[0]
  sindx = np.where(pixlist['NorS'] == 1)[0]
  print 'N/S: ',len(nindx), len(sindx)

  ## now compute mean and bootstrap errors:
  if(NSortot == 0):
    ximean = (xilist[nindx,:]).sum(axis=0)/float(len(nindx))
    ntot = len(nindx)
    ## restrict xilist to N only
    xilist = xlist[nindx,:]
  if(NSortot == 1):
    ximean = (xilist[sindx,:]).sum(axis=0)/float(len(sindx))
    ntot = len(sindx)
    xilist = xlist[sindx,:]
  if(NSortot == 2):
    ximean = xilist.sum(axis=0)/float(nsub)
    ntot = nsub

  xitot = np.zeros(ndata,dtype='float128')
  Cguess = np.zeros([ndata,ndata],dtype='float128')

  for b in range(nboot):
    rr = np.random.random_integers(0,ntot-1,ntot)
    xitrial = (xilist[rr,:]).sum(axis=0)/float(ntot)
    xvec = np.matrix([xitrial-ximean])
    Cguess += (xvec.T*xvec)

  Cguess = Cguess/float(nboot-1)

  #### now let's compute icov for all these.
  ## eqn 17 of 0608064:
  p = len(Cguess[:,0])
  unbiasicov = float(ntot - p - 2)/float(ntot-1)
  Cguess = np.matrix(Cguess,dtype='float64')
  invCguess = Cguess.I*unbiasicov 

#  printcov(Cguess,"cov.tmp")
#  printcov(invCguess,"icov.tmp")
  return Cguess, invCguess
示例#9
0
def wpfromDR(fbase,dfacr=1,periodicopt=0,DRfacinfo=None,rpimax=80.,testing=0,icovfname=None,wpstart=-1,wpend=-1,xiopt=0):
  """
  This function computes wp from DRopt[1-3] files.
  DRfacinfo is used to pass [DRfac, fixRR] (dont get it from file headers in this case)
  That feature is necessary for computing covariance matrices from bootstrap, where that factor
  should be fixed by total N and/or S, it does not vary from bootstrap region to region.
  xiopt added to input Hong's xi values rather than DR counts.
  """
  if(dfacr != 1):
    print 'dfacr not 1 is not coded up yet!'
    sys.exit(1)

  if(periodicopt == 1): # periodic box.
    fDR = fbase
    rpg, rpig, xi = np.loadtxt(fbase,unpack=True)
    nrpibins = len(np.where(rpg == rpg[0])[0])
    nrpbins = len(np.where(rpig == rpig[0])[0])
    if nrpibins*nrpbins != len(xi):
      return None

  elif xiopt == 1:
    rpg, rpig, xi, xigerr = np.loadtxt(fbase,unpack=True)
    nrpibins = len(np.where(rpg == rpg[0])[0])
    nrpbins = len(np.where(rpig == rpig[0])[0])
    if nrpibins*nrpbins != len(xi):
      return None
    fDR = fbase

  else:
    fDD = fbase+'.DRopt1'
    fDR = fbase+'.DRopt2'
    fRR = fbase+'.DRopt3'
    rpg, rpig, DDg = np.loadtxt(fDD,skiprows=3,unpack=True)
    rpg, rpig, DRg = np.loadtxt(fDR,skiprows=3,unpack=True)
    rpg, rpig, RRg = np.loadtxt(fRR,skiprows=3,unpack=True)

    if DRfacinfo is None:
      DRfac, fixRR = ximisc.getDRfactors(fbase)
    else:
      DRfac = DRfacinfo[0]
      fixRR = DRfacinfo[1]

    nrpibins = len(np.where(rpg == rpg[0])[0])
    nrpbins = len(np.where(rpig == rpig[0])[0])
    if nrpibins*nrpbins != len(DDg):
      return None

    xi = ((DDg-DRg*DRfac)/RRg/DRfac**2/fixRR**2 + 1.)

  rpi1d = rpig.reshape(nrpbins,nrpibins)[0]
  ## check that it's linearly spaced, get drpi
  drpi = rpi1d[1]-rpi1d[0]
  chk = rpi1d[1:] - rpi1d[:-1] - drpi
  aaa = np.where(np.fabs(chk) > 1.0e-5)[0]
  if(len(aaa) > 0):
    print 'error!'
    sys.exit(1)
  assert np.fabs(rpi1d[0]-drpi*0.5) < 1e-3
  rp1d = rpg.reshape(nrpbins,nrpibins)[:,0]

  mywp = np.zeros(len(rp1d),dtype='float')
  wpi = 0

  for rpval in rp1d:
    if(testing==1):
      print 'inside testing'
      xx = np.where(rpg == rpval)[0]
      assert len(xx) == nrpibins
      xicurr = xi[xx]
      assert (rpig[xx] == rpi1d).all()
      assert np.fabs(rpi1d[0]-drpi*0.5) < 1e-3

    ## ok, we're sure rpigrid is sane.
    xx = np.where((rpg == rpval) & (rpig < rpimax))[0]
    mywp[wpi] = (xi[xx]).sum()*drpi*2.
    wpi += 1

  return wp(wpfname=fDR,icovfname=icovfname,rpwplist=[rp1d,mywp],wpstart=wpstart,wpend=wpend)
示例#10
0
def getbootcov(bootfile, basedir, outdirbase = 'outputdr12', covoutfname=None, NSortot=2, nboot = 5000000, \
               rpimax=80.,wpstart=1,wpend=19,\
               nell=3,rperpcut=-1.,smallRRcut=-1.,\
               dfacs=1,dfacmu=1,icovfname=None,smincut=-1.,smaxcut=1.e12,\
               binfname_xiell='xibinfiles/bin1fineMU.txt',\
               nbar2d=[-1.,-1.],nbar3d=[-1.,-1],\
               whichtask=4):
    ## resurrect these later.
    #               splitxi0=5,splitxi2=6,splitwp=7):
    """
  Get covariance matrix.
  We're going to do all tasks at once by default (4).
  whichtask = 0: xiell
  whichtask = 1: wp (compute xi(rp,rpi))
  whichtask = 2: wtheta
  whichtask = 3: Hogg spec-im cross-correlation.
  whichtask = 4: combine xiell and wp in usual way.

  Third tier of stuff goes directly to xiellfromDR
  rpimax is for wp, default is 80.
  nbar2d,nbar3d needs to be computed separately for N and S.
  """

    nsub, nsubdir, pixelfname, fbase, fbasetotN, fbasetotS = parsebootinfo(
        bootfile=basedir + bootfile)

    NSlist = [0, 1]
    NStaglist = ['N', 'S']

    for xx in [nsub, nsubdir, pixelfname, fbase, fbasetotN, fbasetotS]:
        if xx is None:
            print 'bad bootfile!'
            return None

    b = boot.bootpix()
    b.readregions(basedir + pixelfname)
    assert b.nsub == nsub

    ## this list will be filled
    DRinfolist = [-1, -1, -1, -1]

    taglist = ['-xiell', '-xigrid', '-wtheta', '-wpcross']

    ## get global DR factors for taglist.
    for ii in range(len(taglist) - 1):
        tag = taglist[ii]
        tmp = np.zeros(
            [2, 2])  # first index is N or S.  DRfac, fixRR stored for each.

        for NS, NStag, ff in zip(NSlist, NStaglist, [fbasetotN, fbasetotS]):
            try:
                #if 0==0:
                tmp[NS, 0], tmp[NS, 1] = ximisc.getDRfactors(basedir + '/' +
                                                             outdirbase + tag +
                                                             '/' + ff)
            except:
                tmp[NS, :] = -1.
        DRinfolist[ii] = tmp.copy()

    ## now get DR info for wpcross.
    ### nevermind! we reduce this to two ratios.
    ## DRinfolist[3] = np.zeros([2,4,2])
    DRinfolist[3] = np.zeros([2, 2])
    tag = taglist[3]
    for NS, NStag, ff in zip(NSlist, NStaglist, [fbasetotN, fbasetotS]):
        try:
            normfac = ximisc.getDRnormswpcross(basedir + '/' + outdirbase +
                                               tag + '/' + ff)
            DRinfolist[3][NS][0] = normfac[0, 0] / normfac[2, 0]
            DRinfolist[3][NS][1] = normfac[0, 1] / normfac[1, 1]
        except:
            DRinfolist[3][NS][:] = -1.

    tasklist = np.zeros(4, dtype='int')
    if whichtask == 4:
        tasklist = np.array([1, 1, 0, 1], dtype='int')
    else:
        tasklist[whichtask] = 1

    if tasklist[3] > 0:
        assert (nbar2d[:] > 0).all()
        assert (nbar3d[:] > 0).all()
        assert (DRinfolist[3][:, :].flatten() > 0).all()

    for ns in range(nsub):
        xx = np.where(b.pixlist['PID'] == ns)[0]
        assert len(xx) == 1
        assert xx[0] == ns
        NorSval = b.pixlist['NorS'][xx[0]]
        for tt in range(len(tasklist)):
            if tasklist[tt] == 0: continue
            tag = taglist[tt]
            ff = basedir + '/' + outdirbase + tag + '/' + nsubdir + '/' + fbase + '.%04d.Np' % (
                ns)
            if tt == 0:  #xiell
                xitmp = xiell.xiellfromDR(ff,
                                          binfile=binfname_xiell,
                                          rperpcut=rperpcut,
                                          nell=nell,
                                          smallRRcut=smallRRcut,
                                          dfacs=dfacs,
                                          dfacmu=dfacmu,
                                          smincut=smincut,
                                          smaxcut=smaxcut,
                                          DRfacinfo=DRinfolist[tt][NorSval])
                dvec = xitmp.xilong
            if tt == 1:  #wp
                wptmp = wp.wpfromDR(ff,
                                    DRfacinfo=DRinfolist[tt][NorSval],
                                    rpimax=rpimax)
                dvec = wptmp.wp

            if tt == 2:  #wtheta
                wttmp = wtheta.wthetafromDR(ff,
                                            DRfacinfo=DRinfolist[tt][NorSval])
                dvec = wttmp.wtheta

            if tt == 3:  #wpcross
                wpcrosstmp = wp.wpcrossHogg(ff,
                                            DRfacinfo=DRinfolist[tt][NorSval],
                                            nbar2d=nbar2d[NorSval],
                                            nbar3d=nbar3d[NorSval])
                dvec = wpcrosstmp.wp

        if whichtask == 4:
            dvec = xiwpvec(xitmp, wptmp, wpcrosstmp, wpstart, wpend)

        if ns == 0:  ## allocate!
            ndata = len(dvec)
            dveclist = np.zeros([nsub, ndata], dtype='float128')
        dveclist[ns, :] = dvec[:]

    ## check means with total counts.
    nindx = np.where(b.pixlist['NorS'] == 0)[0]
    sindx = np.where(b.pixlist['NorS'] == 1)[0]
    nsindx = np.where((b.pixlist['NorS'] == 0) | (b.pixlist['NorS'] == 1))[0]
    print 'N/S: ', len(nindx), len(sindx), len(nsindx)
    assert len(nsindx) == nsub
    assert (nsindx == np.arange(0, nsub, 1, dtype='int')).all()
    myindx = nsindx
    ## assume we want nsindx for this, but can restore N/S option later if I want.

    dmean = (dveclist[myindx, :]).sum(axis=0) / float(len(myindx))
    ntot = len(myindx)
    ntotflt = float(ntot)

    print 'hi beth'
    print dmean

    Cmat = np.zeros([ndata, ndata], dtype='float128')
    for b in range(nboot):
        rr = np.random.random_integers(0, ntot - 1, ntot)
        dtrial = (dveclist[rr, :]).sum(axis=0) / ntotflt
        xvec = np.matrix([dtrial - dmean])
        Cmat += (xvec.T * xvec)

    Cmat = Cmat / float(nboot - 1)
    Cmat = np.matrix(Cmat, dtype='float64')
    iCmat = Cmat.I  ##
    print 'not assuming any bootstrap unbias factor for now!'
    if covoutfname is not None:
        printcov(Cmat, covoutfname)
        printcov(iCmat, covoutfname + '.inv')
        printmean(dmean, covoutfname + '.mean')
    return Cmat, iCmat, dmean