########NONAXI
if addNonAxi:
    nonAxiFile= 'predict_l_vhelio_nonaxi.sav'
    if os.path.exists(nonAxiFile):
        nonaxi_file= open(nonAxiFile,'rb')
        nonaxils= pickle.load(nonaxi_file)
        nonaxiEl= pickle.load(nonaxi_file)
        nonaxiBar= pickle.load(nonaxi_file)
        nonaxi_file.close()
    else:
        print "Working on NonAxi ..."
        elfile= '/work/bovy/data/bovy/nonaximw/elliptical/el_rect_so_0.2_res_51_grid_101_tform_-150._tsteady_125._cp_0.05_nsigma_4.sav'
        print "Reading bar file ..."
        barfile= '/work/bovy/data/bovy/nonaximw/bar/bar_rect_vr_tform-150_tsteady-4pi_51_101.sav'
        #elliptical
        surfmass,meanvr,meanvt,sigmar2,sigmat2,sigmart,vertexdev,surfmass_init,meanvt_init,sigmar2_init,sigmat2_init,ii,jj,grid = read_output(elfile)
        xgrid, ygrid= marginalize_phasedist.phiR_input(51,0.5,2.)
        interpObj= marginalize_phasedist.interp_velocity_field(xgrid,ygrid,surfmass,meanvr,meanvt)
        interpObjAxi= marginalize_phasedist.interp_velocity_field(xgrid,ygrid,surfmass_init,0.,meanvt_init)
        nonaxils= numpy.linspace(30.,330.,501)
        nonaxiEl= numpy.zeros(len(nonaxils))
        phio=70.
        print "Calculating elliptical perturbation ..."
        print "WARNING: DOES NOT CORRECTLY USE SURFMASS"
        for ii in range(len(nonaxils)):
            print ii
            nonaxiEl[ii]= marginalize_phasedist.mvlos_l(nonaxils[ii],interpObj,degree=True,phio=phio)-marginalize_phasedist.mvlos_l(nonaxils[ii],interpObjAxi,degree=True,phio=phio)
        #Bar
        surfmass,meanvr,meanvt,sigmar2,sigmat2,sigmart,vertexdev,surfmass_init,meanvt_init,sigmar2_init,sigmat2_init,ii,jj,grid = read_output(barfile)
        interpObj= marginalize_phasedist.interp_velocity_field(xgrid,ygrid,surfmass,meanvr,meanvt)
        interpObjAxi= marginalize_phasedist.interp_velocity_field(xgrid,ygrid,surfmass_init,0.,meanvt_init)
def calc_nonaxi(params, barfile, options, data, logpiso, nlocs, locations,
                phio):
    #Average over data and integrate over distance
    surfmass, meanvr, meanvt, sigmar2, sigmat2, sigmart, vertexdev, surfmass_init, meanvt_init, sigmar2_init, sigmat2_init, ii, jj, grid = read_output(
        barfile)
    xgrid, ygrid = marginalize_phasedist.phiR_input(51, 0.5, 2.)
    interpObj = marginalize_phasedist.interp_velocity_field(
        xgrid, ygrid, surfmass, meanvr, meanvt)
    interpObjAxi = marginalize_phasedist.interp_velocity_field(
        xgrid, ygrid, surfmass_init, 0., meanvt_init)
    avg_plate_model = numpy.zeros(nlocs)
    for ii in range(nlocs):
        #Calculate vlos | los
        indx = (data['LOCATION'] == locations[ii])
        thesedata = data[indx]
        thislogpiso = logpiso[indx, :]
        if not options.multi is None:
            mvlos = multi.parallel_map((lambda x: mvlosnonaxi(
                params, interpObj, interpObjAxi, thesedata[x], options,
                thislogpiso[x, :], phio)),
                                       range(len(thesedata)),
                                       numcores=numpy.amin([
                                           len(thesedata),
                                           multiprocessing.cpu_count(),
                                           options.multi
                                       ]))
        else:
            mvlos = numpy.zeros(len(data))
            for jj in range(len(thesedata)):
                print jj
                mvlos[jj] = mvlosnonaxi(params, interpObj, interpObjAxi,
                                        thesedata[jj], options,
                                        thislogpiso[jj, :], phio)
        #Calculate mean and velocity dispersion
        avg_plate_model[ii] = numpy.mean(mvlos)
    return avg_plate_model * _REFV0 * params[0]
########NONAXI
if addNonAxi:
    nonAxiFile = 'predict_l_vhelio_nonaxi.sav'
    if os.path.exists(nonAxiFile):
        nonaxi_file = open(nonAxiFile, 'rb')
        nonaxils = pickle.load(nonaxi_file)
        nonaxiEl = pickle.load(nonaxi_file)
        nonaxiBar = pickle.load(nonaxi_file)
        nonaxi_file.close()
    else:
        print "Working on NonAxi ..."
        elfile = '/work/bovy/data/bovy/nonaximw/elliptical/el_rect_so_0.2_res_51_grid_101_tform_-150._tsteady_125._cp_0.05_nsigma_4.sav'
        print "Reading bar file ..."
        barfile = '/work/bovy/data/bovy/nonaximw/bar/bar_rect_vr_tform-150_tsteady-4pi_51_101.sav'
        #elliptical
        surfmass, meanvr, meanvt, sigmar2, sigmat2, sigmart, vertexdev, surfmass_init, meanvt_init, sigmar2_init, sigmat2_init, ii, jj, grid = read_output(
            elfile)
        xgrid, ygrid = marginalize_phasedist.phiR_input(51, 0.5, 2.)
        interpObj = marginalize_phasedist.interp_velocity_field(
            xgrid, ygrid, surfmass, meanvr, meanvt)
        interpObjAxi = marginalize_phasedist.interp_velocity_field(
            xgrid, ygrid, surfmass_init, 0., meanvt_init)
        nonaxils = numpy.linspace(30., 330., 501)
        nonaxiEl = numpy.zeros(len(nonaxils))
        phio = 70.
        print "Calculating elliptical perturbation ..."
        print "WARNING: DOES NOT CORRECTLY USE SURFMASS"
        for ii in range(len(nonaxils)):
            print ii
            nonaxiEl[ii] = marginalize_phasedist.mvlos_l(
                nonaxils[ii], interpObj, degree=True,
                phio=phio) - marginalize_phasedist.mvlos_l(
def calc_nonaxi(params, barfile, options, data, logpiso, nlocs, locations, phio):
    # Average over data and integrate over distance
    surfmass, meanvr, meanvt, sigmar2, sigmat2, sigmart, vertexdev, surfmass_init, meanvt_init, sigmar2_init, sigmat2_init, ii, jj, grid = read_output(
        barfile
    )
    xgrid, ygrid = marginalize_phasedist.phiR_input(51, 0.5, 2.0)
    interpObj = marginalize_phasedist.interp_velocity_field(xgrid, ygrid, surfmass, meanvr, meanvt)
    interpObjAxi = marginalize_phasedist.interp_velocity_field(xgrid, ygrid, surfmass_init, 0.0, meanvt_init)
    avg_plate_model = numpy.zeros(nlocs)
    for ii in range(nlocs):
        # Calculate vlos | los
        indx = data["LOCATION"] == locations[ii]
        thesedata = data[indx]
        thislogpiso = logpiso[indx, :]
        if not options.multi is None:
            mvlos = multi.parallel_map(
                (
                    lambda x: mvlosnonaxi(
                        params, interpObj, interpObjAxi, thesedata[x], options, thislogpiso[x, :], phio
                    )
                ),
                range(len(thesedata)),
                numcores=numpy.amin([len(thesedata), multiprocessing.cpu_count(), options.multi]),
            )
        else:
            mvlos = numpy.zeros(len(data))
            for jj in range(len(thesedata)):
                print jj
                mvlos[jj] = mvlosnonaxi(
                    params, interpObj, interpObjAxi, thesedata[jj], options, thislogpiso[jj, :], phio
                )
        # Calculate mean and velocity dispersion
        avg_plate_model[ii] = numpy.mean(mvlos)
    return avg_plate_model * _REFV0 * params[0]
     V= numpy.array([[l[2],l[4]],[l[4],l[3]]])
     return -numpy.sum(logmultiskewnormal(x,m,V,[0.,0.]))
 def altoptm(l,df,zs):
     m= numpy.array([l[0],l[1]])
     V= numpy.array([[l[2],l[4]],[l[4],l[3]]])
     a= numpy.array([l[5],l[6]])
     return numpy.sum((multiskewnormal(zs,m,V,a)-df)**2.)
 savefilename= 'testMultiSkews2.sav'
 dfstr= 'dehnen'
 s= numpy.exp(numpy.linspace(numpy.log(0.0125),numpy.log(0.2),21))
 so= s[-1]
 #so= 0.2
 elsavefilename= os.path.join(OUTDIR,
                              'el_rect_so_%.6f_res_%i_grid_%i_tform_%.5f_tsteady_%.5f_cp_%.5f_nsigma_%.1f' % (so,101,101,-150.,125.,0.05,5) + 
                              '_'+dfstr+'_%.6f_%.6f_%.6f.sav'  % (1./3.,1.,0.))
 surfmass,meanvr,meanvt,sigmar2,sigmat2,sigmart,vertexdev,surfmass_init,meanvt_init,sigmar2_init,sigmat2_init,ii,jj,grid = read_output(elsavefilename)
 indx= int(long(numpy.floor(45./180.*101)))
 grid= grid[indx]
 if os.path.exists(savefilename):
     savefile= open(savefilename,'rb')
     vs= pickle.load(savefile)
     savefile.close()
 else:
     #Set up everything up for sampling
     sortindx= numpy.argsort(grid.df.flatten())[::-1]
     cumul= numpy.cumsum(numpy.sort(grid.df.flatten())[::-1])/numpy.sum(grid.df.flatten())
     vrs= numpy.zeros(grid.df.shape)
     vts= numpy.zeros(grid.df.shape)
     for ii in range(grid.df.shape[1]):
         vrs[:,ii]= grid.vRgrid.reshape((101,1))
     for ii in range(grid.df.shape[0]):