Beispiel #1
0
def test_slice_density():
    # RamsesOutput
    ro = RamsesOutput("/data/Aquarius/output/", 193)

    # AMR data source
    amr = ro.amr_source(["rho"])

    # Defining a Camera object
    cam = Camera(center=[0.5, 0.5, 0.5],
                 line_of_sight_axis='z',
                 region_size=[1., 1.],
                 up_vector='y',
                 map_max_size=100,
                 log_sensitive=True)

    # Density field access operator
    rho_op = ScalarOperator(lambda dset: dset["rho"])

    # Slice map computation
    map = SliceMap(amr, cam, rho_op, z=0.4)
    # create a density slice map at z=0.4 depth position

    map = apply_log_scale(map)

    #h5f = tables.openFile("./long_tests/slice_density.h5", mode='w')
    #h5f.createArray("/", "map", map)
    #h5f.close()

    h5f = tables.openFile("./long_tests/slice_density.h5", mode='r')
    mapB = h5f.getNode("/map").read()
    h5f.close()

    #print map
    assert (map - mapB).all() < 10e-6
Beispiel #2
0
def test_fft_amr():
    # Ramses data
    ioutput = 193
    ro = RamsesOutput("/data/Aquarius/output/", ioutput)
    amr = ro.amr_source(["rho"])

    # Map operator : mass-weighted density map
    up_func = lambda dset: (dset["rho"]**2 * dset.get_sizes()**3)
    down_func = lambda dset: (dset["rho"] * dset.get_sizes()**3)
    scal_func = FractionOperator(up_func, down_func)

    # Map region
    center = [0.567811, 0.586055, 0.559156]

    # Map processing
    mp = fft_projection.MapFFTProcessor(amr, ro.info)

    axname = "los"
    axis = [-0.172935, 0.977948, -0.117099]

    cam  = Camera(center=center, line_of_sight_axis=axis, up_vector="z", region_size=[5.0E-1, 4.5E-1], \
      distance=2.0E-1, far_cut_depth=2.0E-1, map_max_size=100)
    map = mp.process(scal_func, cam, surf_qty=True)

    #h5f = tables.openFile("./long_tests/fft_amr.h5", mode='w')
    #h5f.createArray("/", "map", map)
    #h5f.close()

    h5f = tables.openFile("./long_tests/fft_amr.h5", mode='r')
    mapB = h5f.getNode("/map").read()
    h5f.close()

    #print map
    assert (map - mapB).all() < 10e-6
Beispiel #3
0
def test_cyl_profile():
    # Galactic cylinder parameters
    gal_center = [0.567811, 0.586055, 0.559156]  # in box units
    gal_radius = 0.00024132905460547268  # in box units
    gal_thickn = 0.00010238202316595811  # in box units
    gal_normal = [-0.172935, 0.977948, -0.117099]  # Norm = 1

    # RamsesOutput
    ro = RamsesOutput("/data/Aquarius/output", 193)

    # Prepare to read the density field only
    source = ro.amr_source(["rho"])

    # Cylinder region
    cyl = Cylinder(gal_center, gal_normal, gal_radius, gal_thickn)

    # AMR density field point sampling
    numpy.random.seed(1652336)
    points = cyl.random_points(1.0e6)  # 1M sampling points
    point_dset = sample_points(source, points)
    rho_weight_func = lambda dset: dset["rho"]
    r_bins = numpy.linspace(0.0, gal_radius, 200)

    # Profile computation
    rho_profile = bin_cylindrical(point_dset,
                                  gal_center,
                                  gal_normal,
                                  rho_weight_func,
                                  r_bins,
                                  divide_by_counts=True)

    # Plot
    # Geometrical midpoint of the bins
    length = ro.info["unit_length"].express(C.kpc)
    bins_centers = (r_bins[1:] + r_bins[:-1]) / 2. * length
    dens = ro.info["unit_density"].express(C.H_cc)

    #h5f = tables.openFile("./long_tests/cyl_profile.h5", mode='w')
    #h5f.createArray("/", "cyl_profile", rho_profile)
    #h5f.close()

    h5f = tables.openFile("./long_tests/cyl_profile.h5", mode='r')
    rho_profileB = h5f.getNode("/cyl_profile").read()
    h5f.close()

    print(rho_profile)
    assert sum(rho_profile - rho_profileB) < 10e-6
Beispiel #4
0
from pymses import RamsesOutput
from pymses.filters import CellsToPoints
import matplotlib.pyplot as plt
import numpy as np
import sys


# Parse Arguments
if len(sys.argv) == 1:
	iout = 1
elif len(sys.argv) == 2:
	iout = int(sys.argv[1])

# Prepare Output
output = RamsesOutput(".", iout)
source = output.amr_source(["rho"])

# Convert Leaf-Cells to Points
cell_source = CellsToPoints(source)
cells = cell_source.flatten()

# Get Density & Cell Size
rho = cells["rho"]
dx = output.info["boxlen"] * cells.get_sizes()
dV = dx**output.info["ndim"]

# Print Stuff
# print cells["rho"] # contains densities
# print rho          # contains densities
# print cells.points # contains coordinates
# print dx
axe = [N.sin(angle), 0, N.cos(angle)]
center = center_init + (zoom_focus - center_init) * (i * 1. / nbImgRot)
region_size = region_size_init * ((1. / zoom_factor - 1) / nbImgRot * i + 1)
distance = distance_init * ((1. / zoom_factor - 1) / nbImgRot * i + 1)
far_cut_depth = far_cut_depth_init * (
    (1. / zoom_factor - 1) / nbImgRot * i + 1)
cam = Camera(center=center,
             line_of_sight_axis=axe,
             up_vector="y",
             region_size=region_size,
             distance=distance,
             far_cut_depth=far_cut_depth,
             map_max_size=mms)

# Octree source creation :
source = ro.amr_source(["rho"])
# We need to add an extension to the octree box loaded in memory,
# or not (if min(distance,far_cut_depth) > max(region_size))
# as the rotation is around the "y" axis,
# to allow rotation without empty starting point ray bugs
esize = 0.5**(ro.info["levelmin"] + 1) + max(region_size)
camOctSource = cam.copy()
fullOctreeDataSource = CameraOctreeDatasource(camOctSource,
                                              esize,
                                              source,
                                              ngrid_max=ngrid_max,
                                              include_split_cells=True).dset
OctreeRT = OctreeRayTracer(fullOctreeDataSource)

t0 = time()
map, levelmax_map = OctreeRT.process(op, cam, rgb=False, use_openCL=use_openCL)
Beispiel #6
0
def main():

	# Defaults
	iout = 1
	npsample = ['128', '128', '64']
	npbin = ['32', '32']

	# Parse Arguments
	if len(sys.argv) == 4:
		npbin = re.split(',', sys.argv[3])
	if len(sys.argv) >= 3:
		npsample = re.split(',', sys.argv[2])
	if len(sys.argv) >= 2:
		iout = int(sys.argv[1])

	# Compute Requested Outputs
	if iout < 0:
		iouts = range(1, abs(iout) + 1)
	else:
		iouts = range(iout, iout + 1)

	# Define Region of Interest (Box Units)
	center    = 0.5
	radius    = 0.4
	thickness = 0.2

	# Sample Points
	nr   = int(npsample[0])
	nphi = int(npsample[1])
	nz   = int(npsample[2])

	# Binning Points
	nrbins = int(npbin[0])
	nzbins = int(npbin[1])

	# Give Feedback
	print "Computing RZ Profile(s) for Output(s) %s." % iouts
	print "Sampling Grid with %ix%ix%i = %i Points." % ( nr, nphi, nz, nr * nphi * nz )
	print ""

	# Generate Sampling Points
	x, y, z = mkpoints_rpz(center, radius, thickness, nr, nphi, nz)

	# Make Sampling Vectors, Reshape Them
	xx, yy, zz = mkvec(x, y, z)
	points = np.zeros((xx.shape[0], 3))
	for ii in range(xx.shape[0]):
		points[ii,:] = np.array([xx[ii], yy[ii], zz[ii]])

	# Loop Desired Outputs
	for iiout in iouts:

		# Link AMR Data
		output = RamsesOutput(".", iiout)
		source = output.amr_source(["rho"])

		# Sample AMR Data
		point_dset = sample_points(source, points)

		# Shift Origin, Convert to RZ Coordinates
		points_xyz  = points
		points_xyz0 = points_xyz - 0.5
		points_r0   = np.sqrt(points_xyz0[:,0]**2. + points_xyz0[:,1]**2.)
		points_z0   = points_xyz0[:,2]

		print ""
		print "Binning onto (RxZ) = (%ix%i) Grid." % ( nrbins, nzbins )

		# Prepare Bins
		rbins = np.linspace(0.0, radius, nrbins + 1)
		zbins = np.linspace(-thickness/2., thickness/2., nzbins + 1)

		# Binning Routine
		rhoRZ, rbins, zbins = prof2d(points_r0, points_z0, point_dset["rho"], rbins, zbins)

		# Compute Extent
		ext = np.array([rbins.min(), rbins.max(), -thickness/2., thickness/2.])

		# Save Binned Data
		fname = 'rhoRZ_%i.npz' % iiout

		print ""
		print "Saving Data to File %s..." % fname

		# Save Binned Data
		np.savez(fname,\
			rhoRZ=rhoRZ, rbins=rbins, zbins=zbins,\
			iout=iiout,\
			boxlen=output.info["boxlen"],\
			tout=output.info["time"],\
			ext=ext,
			center=center, radius=radius, thickness=thickness,\
			nr=nr, nphi=nphi, nz=nz,\
			nrbins=nrbins, nzbins=nzbins)

		print "Done."
Beispiel #7
0
def test_amr2cube_cartesian_rt():
    # backuped referenced data :
    cubeB = numpy.array(
        [[[0.08186216, 0.03206611, 0.05075889, 0.21691999, 0.08395087],
          [0.11306132, 0.05707518, 0.03212786, 0.33522855, 0.13602483],
          [0.05632005, 0.04249893, 0.09034388, 0.1588526, 0.2080538],
          [0.06852026, 0.03090859, 0.04515618, 0.17721034, 0.23618275],
          [0.07367933, 0.11752801, 0.03341876, 0.2254721, 0.39768221]],
         [[0.05193184, 0.03975904, 0.05116311, 0.14412791, 0.21599674],
          [0.08652996, 0.07561322, 0.06104241, 0.09306177, 0.06347754],
          [0.03311921, 0.03681144, 0.04637034, 0.10137452, 0.02770789],
          [0.06000543, 0.0630374, 0.07050136, 0.08983026, 0.06849894],
          [0.11372988, 0.17594275, 0.09902632, 0.07525623, 0.10831208]],
         [[0.10366187, 0.12453692, 0.18768945, 0.16773106, 0.11033484],
          [0.1043405, 0.13150752, 0.06345165, 0.02748383, 0.05059519],
          [0.06553906, 0.07011834, 0.06567988, 0.04461206, 0.0677126],
          [0.19513314, 0.10922475, 0.04116418, 0.09346056, 0.07560843],
          [0.1156556, 0.11896267, 0.42504693, 0.14856789, 0.08862464]],
         [[0.0683512, 0.10387651, 0.08278252, 0.05064939, 0.11547664],
          [0.08297042, 0.08370349, 0.03658147, 0.02292432, 0.05400176],
          [0.14583478, 0.10265131, 0.10521284, 0.03336809, 0.05561544],
          [0.10904973, 0.05832567, 0.04876777, 0.10397124, 0.14783567],
          [0.21239959, 0.06806608, 0.28383805, 0.26950828, 0.46882107]],
         [[0.39340254, 0.21568631, 0.11401807, 0.09364021, 0.11969451],
          [0.17342993, 0.0847922, 0.02964273, 0.07289768, 0.2268799],
          [0.06048485, 0.09604769, 0.06068367, 0.06307055, 0.37759786],
          [0.09158091, 0.05048944, 0.03639829, 0.25110933, 0.32988721],
          [0.3167426, 0.17177987, 0.23479188, 0.42511884, 0.10431827]]])

    mapB = numpy.array([
        0.46555802, 0.67351774, 0.55606925, 0.55797812, 0.84778041, 0.50297864,
        0.37972491, 0.24538341, 0.35187338, 0.57226726, 0.69395413, 0.37737869,
        0.31366193, 0.51459106, 0.89685772, 0.42113625, 0.28018146, 0.44268245,
        0.46795008, 1.30263307, 0.93644163, 0.58764244, 0.65788461, 0.75946518,
        1.25275146
    ])

    # Ramses data
    ioutput = 193
    ro = RamsesOutput("/data/Aquarius/output/", ioutput)
    cam = Camera(center=[0.5, 0.5, 0.5],
                 line_of_sight_axis=[0.1, 0.1, 0.9],
                 up_vector="y",
                 region_size=[5.0E-1, 5.0E-1],
                 distance=2.5E-1,
                 far_cut_depth=2.5E-1,
                 map_max_size=3)
    bb = cam.get_bounding_box()
    source = ro.amr_source(["rho"])
    from pymses.utils import misc
    misc.NUMBER_OF_PROCESSES_LIMIT = 1  # amr2cube no multiprocessing test
    cube = amr2cube(source, "rho", bb.min_coords, bb.max_coords,
                    cam.get_required_resolution())
    print("cube", cube)
    print("cubeB", cubeB)
    assert ((cube - cubeB) < 10e-8).all()

    misc.NUMBER_OF_PROCESSES_LIMIT = 8  # amr2cube with multiprocessing test
    cube = amr2cube(source, "rho", bb.min_coords, bb.max_coords,
                    cam.get_required_resolution())
    print("cube", cube)
    assert ((cube - cubeB) < 10e-8).all()
    # ray_trace_cartesian test
    cube_size = numpy.min(cube.shape)
    cam = Camera(center=[0.5, 0.5, 0.5],
                 line_of_sight_axis=[0.1, 0.1, 0.9],
                 up_vector="y",
                 region_size=[5.0E-1, 5.0E-1],
                 distance=2.5E-1,
                 far_cut_depth=2.5E-1,
                 map_max_size=cube_size)
    (ray_vectors, ray_origins, ray_lengths) = cam.get_rays()
    map = raytracing.ray_trace.ray_trace_cartesian(cube, ray_origins,
                                                   ray_vectors, ray_lengths,
                                                   bb, cube_size)
    print("map", map)
    print("mapB", mapB)
    assert ((map - mapB) < 10e-8).all()
Beispiel #8
0
if not (svar in svars):
    print "Invalid Variable. Terminating."
    sys.exit()

sscales = ("lin", "log")
if not (sscale in sscales):
    print "Invalid Scaling (log, lin). Terminating."
    sys.exit()

# Give Feedback
print "Creating Cuts for Output %i." % iout
print ""

# Link AMR Data
output = RamsesOutput(".", iout)
source = output.amr_source([svar])

# Define Cameras
camZ = Camera(
    center=[0.5, 0.5, 0.5],
    line_of_sight_axis="z",
    region_size=[1.0, 1.0],
    up_vector="y",
    map_max_size=512,
    log_sensitive=True,
)
camY = Camera(
    center=[0.5, 0.5, 0.5],
    line_of_sight_axis="y",
    region_size=[1.0, 1.0],
    up_vector="z",
Beispiel #9
0
def main():

    # Set Defaults
    iout = 1
    npsample = ['128', '128', '64']

    # Parse Arguments
    if len(sys.argv) == 3:
        npsample = re.split(',', sys.argv[2])
    if len(sys.argv) >= 2:
        iout = int(sys.argv[1])

    # Compute Requested Outputs
    if iout < 0:
        iouts = range(1, abs(iout) + 1)
    else:
        iouts = range(iout, iout + 1)

    # Define Region of Interest (Box Units)
    center    = 0.5
    radius    = 0.4
    thickness = 0.2

    # Sample Points
    nx = int(npsample[0])
    ny = int(npsample[1])
    nz = int(npsample[2])

    # Generate Sampling Points
    x, y, z = mkpoints_xyz(center, radius, thickness, nx, ny, nz)

    # Some Reshaping
    zz, yy, xx = mkvec(z, y, x)
    points = np.zeros((xx.shape[0], 3))
    for ii in range(xx.shape[0]):
        points[ii,:] = np.array([xx[ii], yy[ii], zz[ii]])

    # Loop Over Outputs
    for iiout in iouts:

        # Open Ramses Output
        output = RamsesOutput(".", iiout)
        source = output.amr_source(["P"])

        # Fetch Ramses Data
        points_dset = sample_points(source, points)

        # Allocate Memory for Output Array
        PXY = np.zeros((nx, ny))

        # Integrate Along Z (Simpson's Rule)
        print "(%s UTC) Integrating..." % strftime("%H:%M:%S", gmtime())
        idx_lo = 0
        for ix in range(nx):
            for iy in range(ny):
                idx_hi = idx_lo + nz
                PXY[ix,iy] = simps(points_dset["P"][idx_lo:idx_hi], z)
                idx_lo = idx_hi
        print "(%s UTC) Done Integrating." % strftime("%H:%M:%S", gmtime())

        # Compute Limits, Centre, Rescale
        ext = np.array([x.min(), x.max(), y.min(), y.max()])
        ext = ( ext - 0.5 ) * output.info["boxlen"]

        # Save 2D Pressure Map
        np.savez('PXY_%i.npz' % iiout, \
            PXY=PXY,\
            x=x, y=y, z=z,\
            boxlen=output.info["boxlen"],\
            ext=ext,\
            tout=output.info["time"])
from numpy import array
import pylab
from pymses.analysis.visualization import *
from pymses import RamsesOutput
from pymses.utils import constants as C
# Ramses data
ioutput = 4
ro = RamsesOutput("Data/Sedov3d/output", ioutput)
amr = ro.amr_source(["rho", "P"])
# Map region
## center = [ 0.567811, 0.586055, 0.559156 ]
center = [ 0.5, 0.5, 0.5 ]
# Map processin#g
#cam = Camera()
cam = Camera(center=center, line_of_sight_axis='z', up_vector="y", region_size=(1.0, 1.0), far_cut_depth=0.2, map_max_size=64, distance=0., log_sensitive=True)
from pymses.analysis.visualization import SliceMap, ScalarOperator
op = ScalarOperator(lambda dset: dset["rho"])
map = SliceMap(amr, cam, op, z=0.3) # create a density slice map at z=0.4 depth position
  
#factor = ro.info["unit_density"].express(C.H_cc)
#scale = ro.info["unit_length"].express(C.kpc)
# imshow(map)
pylab.imshow(map)
# Save map into HDF5 file
#mapname = "sedov3d%5.5i"%ioutput
#h5fname = save_map_HDF5(map, cam, map_name=mapname)
# Plot map into Matplotlib figure/PIL Image
#fig = save_HDF5_to_plot(h5fname, map_unit=("H/cc",factor), axis_unit=("kpc", scale), cmap="jet")
# pil_img = save_HDF5_to_img(h5fname, cmap="jet")
# Save into PNG image file
# save_HDF5_to_plot(h5fname, map_unit=("H/cc",factor), axis_unit=("Mpc", scale), img_path="./", # save_HDF5_to_img(h5fname, img_path="./", cmap="jet")
Beispiel #11
0
def main():

    # Set Defaults
    iout = 1
    npsample = ['128', '128', '64']

    # Parse Arguments
    if len(sys.argv) == 3:
        npsample = re.split(',', sys.argv[2])
    if len(sys.argv) >= 2:
        iout = int(sys.argv[1])

    # Compute Requested Outputs
    if iout < 0:
        iouts = range(1, abs(iout) + 1)
    else:
        iouts = range(iout, iout + 1)

    # Define Region of Interest (Box Units)
    center    = 0.5
    radius    = 0.4
    thickness = 0.2

    # Sample Points
    nx = int(npsample[0])
    ny = int(npsample[1])
    nz = int(npsample[2])

    # Generate Sampling Points
    x, y, z = mkpoints_xyz(center, radius, thickness, nx, ny, nz)

    # Some Reshaping
    zz, yy, xx = mkvec(z, y, x)
    points = np.zeros((xx.shape[0], 3))
    for ii in range(xx.shape[0]):
        points[ii,:] = np.array([xx[ii], yy[ii], zz[ii]])

    # Loop Over Outputs
    for iiout in iouts:

        # Open Ramses Output
        output = RamsesOutput(".", iiout)
        source = output.amr_source(["rho", "vel"])

        # Fetch Ramses Data
        points_dset = sample_points(source, points)

        # Allocate Memory for Output Array
        OmegaXY = np.zeros((nx, ny))

        # Average Along Z
        print "(%s UTC) Z-Averaging XY Velocity Field..." % strftime("%H:%M:%S", gmtime())
        idx_lo = 0
        for ix in range(nx):
            for iy in range(ny):
                idx_hi = idx_lo + nz
                v_x = points_dset["vel"][idx_lo:idx_hi,0]
                v_y = points_dset["vel"][idx_lo:idx_hi,1]
                v_xy = np.sqrt(v_x**2. + v_y**2.)
                rho_tot = np.sum(points_dset["rho"][idx_lo:idx_hi])
                weight = points_dset["rho"][idx_lo:idx_hi] / rho_tot
                v_xy_avg = np.sum(v_xy * weight) / nz
                r = np.sqrt((x[ix] - 0.5)**2. + (y[iy]-0.5)**2.) * output.info["boxlen"]
                OmegaXY[ix,iy] = v_xy_avg / r
                idx_lo = idx_hi
        print "(%s UTC) Done Averaging." % strftime("%H:%M:%S", gmtime())

        # Compute Limits, Centre, Rescale
        ext = np.array([x.min(), x.max(), y.min(), y.max()])
        ext = ( ext - 0.5 ) * output.info["boxlen"]

        # Save Z-Averaged Planar Angular Velocity Map
        np.savez('OmegaXY_%i.npz' % iiout, \
            OmegaXY=OmegaXY,\
            x=x, y=y, z=z,\
            boxlen=output.info["boxlen"],\
            ext=ext,\
            tout=output.info["time"])
try:
	fileDir = args[0]
	outNumber = int(args[1])
except:
	# "None" leads to an automatic look for 
	# a RAMSES output in the current directory
	fileDir = None 
	outNumber = None
ro = RamsesOutput(fileDir, outNumber)
outNumber = ro.iout
ncpu = ro.info["ncpu"]
if myrank == 0: print("levelmin =", ro.info["levelmin"],"levelmax =", ro.info["levelmax"])
cpu_full_list = list(range(1,ncpu+1))
cpu_node_list = chunks(cpu_full_list, MPI_process_number)
ro.verbose = False
rho = ro.amr_source([])
nbCells = 0
leaf_cells_level = {}
t1 = time()
if myrank < len(cpu_node_list):
	for icpu in cpu_node_list[myrank]:
		dset = rho.get_domain_dset(icpu)
		grid_mask = dset.get_active_mask()
		cell_lvl = repeat(dset.get_grid_levels(grid_mask)[:, newaxis], \
			8, axis=1).reshape((-1,))
		lvlmax = dset.amr_struct["readlmax"]
		sons = dset.amr_struct["son_indices"][grid_mask, :].reshape((-1,))
		leaf_mask = (sons < 0)+(cell_lvl == lvlmax)
		nbCells += leaf_mask.sum()
		if CELL_LEVEL_HISTOGRAM:
			for ilvl in range(lvlmax):
Beispiel #13
0
import sys


# Parse Arguments
if len(sys.argv) == 1:
	iout = 1
elif len(sys.argv) == 2:
	iout = int(sys.argv[1])

# Give Feedback
print "Creating Cuts for Output %i." % iout
print ""

# Link AMR Data
output = RamsesOutput(".", iout)
source = output.amr_source(["rho", "vel", "P"])

# Define Cameras
camZ = Camera(center=[0.5, 0.5, 0.5], line_of_sight_axis='z',
	region_size=[1., 1.], up_vector='y', map_max_size=512, log_sensitive=True)
camX = Camera(center=[0.5, 0.5, 0.5], line_of_sight_axis='x',
	region_size=[1., 1.], up_vector='y', map_max_size=512, log_sensitive=True)

# Functions to Get Data
func_rho = lambda dset: dset["rho"]
func_vel = lambda dset: (np.sqrt(np.sum(dset["vel"]**2, axis=1)))
func_pre = lambda dset: dset["P"]

# Operator to Get Data
op_rho = ScalarOperator(func_rho)
op_vel = ScalarOperator(func_vel)