示例#1
0
    # output various profiles (only for stellar components)
    print("\033[1;33mComputing density profiles and velocity distribution\033[0m")
    modelStars = agama.GalaxyModel(model.potential, dfStellar, model.af)
    writeSurfaceDensityProfile ("model_stars_final.surfdens", modelStars)
    writeVerticalDensityProfile("model_stars_final.vertical", modelStars)
    writeVelocityDistributions ("model_stars_final.veldist",  modelStars)

    # export model to an N-body snapshot
    print("\033[1;33mCreating an N-body representation of the model\033[0m")
    format = 'text'  # could use 'text', 'nemo' or 'gadget' here

    # first create a representation of density profiles without velocities
    # (just for demonstration), by drawing samples from the density distribution
    print("Writing N-body sampled density profile for the dark matter halo")
    agama.writeSnapshot("dens_dm_final", model.components[2].getDensity().sample(800000), format)
    print("Writing N-body sampled density profile for the stellar bulge, disk and halo")
    # recall that component[0] contains stellar disks and stellar halo, and component[1] - bulge
    densStars = agama.Density(model.components[0].getDensity(), model.components[1].getDensity())
    agama.writeSnapshot("dens_stars_final", densStars.sample(200000), format)

    # now create genuinely self-consistent models of all components,
    # by drawing positions and velocities from the DF in the given (self-consistent) potential
    print("Writing a complete DF-based N-body model for the dark matter halo")
    agama.writeSnapshot("model_dm_final", \
        agama.GalaxyModel(potential=model.potential, df=dfHalo, af=model.af).sample(800000), format)
    print("Writing a complete DF-based N-body model for the stellar bulge, disk and halo")
    agama.writeSnapshot("model_stars_final", \
        agama.GalaxyModel(potential=model.potential, df=dfStellarAll, af=model.af).sample(200000), format)
    # we didn't use an action-based DF for the gas disk, leaving it as a static component;
    # to create an N-body representation, we sample the density profile and assign velocities
示例#2
0
    model.components[2] = agama.Component(df=dfHalo,  disklike=False, **iniSCMHalo)

    # do a few more iterations to obtain the self-consistent density profile for both disks
    for iteration in range(1,5):
        print("\033[1;37mStarting iteration #%d\033[0m" % iteration)
        model.iterate()
        printoutInfo(model, 'iter%d'%iteration)

    # export model to an N-body snapshot
    print("\033[1;33mCreating an N-body representation of the model\033[0m")
    format = 'text'  # one could also use 'nemo' or 'gadget' here

    # first create a representation of density profiles without velocities
    # (just for demonstration), by drawing samples from the density distribution
    print("Sampling disk density")
    agama.writeSnapshot("dens_disk_final",  model.components[0].getDensity().sample(160000), format)
    print("Sampling bulge density")
    agama.writeSnapshot("dens_bulge_final", model.components[1].getDensity().sample(40000), format)
    print("Sampling halo density")
    agama.writeSnapshot("dens_halo_final",  model.components[2].getDensity().sample(800000), format)

    # now create genuinely self-consistent models of both components,
    # by drawing positions and velocities from the DF in the given (self-consistent) potential
    print("Sampling disk DF")
    agama.writeSnapshot("model_disk_final", \
        agama.GalaxyModel(potential=model.potential, df=dfDisk,  af=model.af).sample(1600000), format)
    print("Sampling bulge DF")
    agama.writeSnapshot("model_bulge_final", \
        agama.GalaxyModel(potential=model.potential, df=dfBulge, af=model.af).sample(400000), format)
    print("Sampling halo DF")
    # note: use a 10x larger particle mass for halo than for bulge/disk
示例#3
0
if __name__ == '__main__':
    # read parameters from the INI file
    if len(sys.argv) <= 1:
        print("Provide the ini file name as the command-line argument")
        exit()
    if not os.path.isfile(sys.argv[1]):
        print("File " + sys.argv[1] + " does not exist!")
        exit()
    model = createModel(sys.argv[1])
    for name, comp in model.components.items():
        print("Running " + name)
        runComponent(comp, model.potential)
        print("Done with " + name)
        if hasattr(comp, 'nbody'):
            # export N-body model and save the trajectories into a numpy binary file
            agama.writeSnapshot("model_" + name + ".nbody", comp.nbodymodel)
            numpy.save("model_" + name + ".traj", comp.traj)
        # write out the complete model as a numpy binary archive
        args = {
            'ic': comp.ic,
            'inttime': comp.inttime,
            'weights': comp.weights
        }
        if hasattr(comp, 'densitydata'): args['densitydata'] = comp.densitydata
        if hasattr(comp, 'kinemdata'): args['kinemdata'] = comp.kinemdata
        try:
            numpy.savez_compressed("model_" + name + ".data", **args)
        except Exception as e:
            print(e)
        # write out the initial conditions and weights as a text file
        numpy.savetxt("model_"+name+".orb", \
示例#4
0
for i, d in enumerate(delta2):
    if abs(d) > 1e-8: print("KinemConstraint %i not satisfied: %.4g" % (i, d))

# export an N-body model
nbody = 100000
status, result = agama.sampleOrbitLibrary(nbody, trajs, weights)
if not status:
    # this may occur if there was not enough recorded trajectory points for some high-weight orbits:
    # in this case their indices and the required numbers of points are returned in the result tuple
    indices, trajsizes = result
    print("reintegrating %i orbits; max # of sampling points is %i" %
          (len(indices), max(trajsizes)))
    trajs[indices] = agama.orbit(potential=pot, ic=initcond[indices], time=inttimes[indices], \
        trajsize=trajsizes)
    status, result = agama.sampleOrbitLibrary(nbody, trajs[:, 1], weights)
    if not status: print("Failed to produce output N-body model")
agama.writeSnapshot("schwarzschild_model_nbody.txt", result,
                    't')  # one could also use numpy.savetxt

# also store the entire Schwarzschild model in a numpy binary archive
numpy.savez_compressed("schwarzschild_model_data", ic=initcond, inttime=inttimes, weight=weights, \
    data1=data1, data2=data2, cons1=rhs1)

# store trajectories in a numpy binary file
numpy.save("schwarzschild_model_traj", trajs)

# store the orbit initial conditions and weights in a text file
numpy.savetxt("schwarzschild_model_orbits", \
    numpy.column_stack((initcond, weights, weightprior, inttimes)), \
    header='x y z vx vy vz weight prior inttime')
#numpy.savetxt('orbits', numpy.column_stack((initcond, weights, inttimes))[numpy.argsort(inttimes)], '%g')

# export an N-body model
nbody = 100000
status, result = agama.sampleOrbitLibrary(nbody, trajs, weights)
if not status:
    # this may occur if there was not enough recorded trajectory points for some high-weight orbits:
    # in this case their indices and the required numbers of points are returned in the result tuple
    indices, trajsizes = result
    print("reintegrating %i orbits; max # of sampling points is %i" %
          (len(indices), max(trajsizes)))
    trajs[indices] = agama.orbit(potential=pot, ic=initcond[indices], time=inttimes[indices], \
        trajsize=trajsizes)
    status, result = agama.sampleOrbitLibrary(nbody, trajs[:, 1], weights)
    if not status: print("Failed to produce output N-body model")
agama.writeSnapshot("flattened_rotating_model.nemo", result, 'n')

# various diagnostic plots
import matplotlib.pyplot as plt

ax = plt.subplots(1, 2, figsize=(12, 6))[1]

# plot orbit weights as a function of mean radius and eccentricity (shown in color)
rperi, rapo = pot.Rperiapo(initcond).T
ravg = (rapo + rperi) / 2
ecc = (rapo - rperi) / (rapo + rperi)
meanw = numpy.median(weights)
plt.colorbar(ax[0].scatter(ravg,
                           weights,
                           c=ecc,
                           s=20 * numpy.log(1 + weights / meanw),
示例#6
0
import agama

mass_unit = (1.0/4.3)*(10.0**(6.0))

agama.setUnits(mass=mass_unit, length=1, velocity=1)

pot = agama.Potential(type='Spheroid', gamma=1.0, beta=3.1, scaleRadius=2.5, outerCutoffRadius=15.0)
df = agama.DistributionFunction(type='QuasiSpherical',potential=pot)
model = agama.GalaxyModel(pot,df)
M = model.sample(10000)

print(M[0][9999,0])
agama.writeSnapshot('test_snapshot.snp',M,'n')


scm = agama.SelfConsistentModel(**params)
scm.components=[comp]

# prepare visualization
r=numpy.logspace(-2.,2.)
xyz=numpy.vstack((r,r*0,r*0)).T
plt.plot(r, dens.density(xyz), label='Init density', color='k')

# perform several iterations of self-consistent modelling procedure
for i in range(6):
    scm.iterate()
    print('Iteration %i, Phi(0)=%g, Mass=%g' % \
        (i, scm.potential.potential(0,0,0), scm.potential.totalMass()))
    plt.plot(r, scm.potential.density(xyz), label='Iteration #'+str(i))

# save the final density/potential profile and create an N-body snapshot
comp.getDensity().export('flattened_sersic_density.ini')
scm.potential.export('flattened_sersic_potential.ini')
agama.writeSnapshot('flattened_sersic_nbody.nemo',
    agama.GalaxyModel(scm.potential, df).sample(1000000), 'nemo')

# show the results
plt.legend(loc='lower left')
plt.xlabel("r")
plt.ylabel(r'$\rho$')
plt.xscale('log')
plt.yscale('log')
plt.ylim(1e-5, 2e2)
plt.xlim(0.01, 10)
plt.show()