Ejemplo n.º 1
0
 def test_sigma_clip(self):
     ds = fake_random_ds(32)
     sc = yt.create_scene(ds)
     im = sc.render()
     sc.save("raw.png")
     sc.save("clip_2.png", sigma_clip=2)
     sc.save("clip_4.png", sigma_clip=4.0)
     return im, sc
Ejemplo n.º 2
0
def set_the_scene():
    """ creates the yt scene, except for transfer function and rendering """
    sc = yt.create_scene(ds,datafld)

    # Draw the domain boundary and useful grids
    lat_rnge=[np.min(model.data.variables['latitude']),np.max(model.data.variables['latitude'])]
    lon_rnge=[np.min(model.data.variables['longitude']),np.max(model.data.variables['longitude'])]
    min_dep=0.
    max_dep=1200.
    R=6371.
    r_rnge=[(R-max_dep)*1000.,(R-min_dep)*1000.]
    Chunk=sp.sphericalChunk(lat_rnge,lon_rnge,r_rnge)
    sc=Chunk.domainExtent(sc,RGBa=[1.,1.,1.,0.002],n_latlon=100,n_rad=50)
    sc=Chunk.latlonGrid(sc,RGBa=[1.,1.,1.,0.005])
    sc=Chunk.latlonGrid(sc,RGBa=[1.,1.,1.,0.002],radius=(R-410.)*1000.)
    sc=Chunk.latlonGrid(sc,RGBa=[1.,1.,1.,0.002],radius=(R-max_dep)*1000.)
    sc=Chunk.wholeSphereReference(sc,RGBa=[1.,1.,1.,0.002])

    # Add shapefile data
    print('adding shapefile data to scene')
    shp_bbox=[lon_rnge[0],lat_rnge[0],lon_rnge[1],lat_rnge[1]]

    for shpfi in ['us_states']:
        thisshp=sp.shapedata(shpfi,bbox=shp_bbox,radius=R*1000.)
        sc=thisshp.addToScene(sc)

    clrs={
        'transform':[0.8,0.,0.8,0.05],
        'ridge':[0.,0.,0.8,0.05],
        'trench':[0.8,0.,0.,0.05],
        'global_volcanos':[0.,0.8,0.,0.05]
    }
    for bound in ['transform','ridge','trench','global_volcanos']:
        tect=sp.shapedata(bound,radius=R*1000.,buildTraces=False)
        sc=tect.buildTraces(RGBa=clrs[bound],sc=sc,bbox=shp_bbox)


    # some camera settings
    pos=sc.camera.position
    Rmax=6371*1000.
    center_vec=np.array([np.mean(bbox[0])/Rmax,np.mean(bbox[1])/Rmax,np.mean(bbox[2])/Rmax])
    sc.camera.set_position(pos,north_vector=center_vec)
    source = sc.sources['source_00']
    source.tfh.set_log(False)

    res=sc.camera.get_resolution()
    res_factor=settings.get('res_factor', 1)
    new_res=(int(res[0]*res_factor),int(res[1]*res_factor))
    sc.camera.set_resolution(new_res)

    zoom_factor=0.7 # < 1 zooms in
    init_width=sc.camera.width
    sc.camera.width = (init_width * zoom_factor)
    sc.camera.rotate(0*np.pi/180)

    return (sc,source)
Ejemplo n.º 3
0
    def test_save_render(self):
        ds = fake_random_ds(ndims=32)
        sc = yt.create_scene(ds)

        # make sure it renders if nothing exists, even if render = False
        sc.save(os.path.join(self.tmpdir, "raw.png"), render=False)
        # make sure it re-renders
        sc.save(os.path.join(self.tmpdir, "raw_2.png"), render=True)
        # make sure sigma clip does not re-render
        sc.save(os.path.join(self.tmpdir, "clip_2.png"),
                sigma_clip=2.0,
                render=False)
        sc.save(os.path.join(self.tmpdir, "clip_4.png"),
                sigma_clip=4.0,
                render=False)

        return sc
Ejemplo n.º 4
0
def loop_one():
    global lower_bound
    global upper_bound
    global homdir
    
    os.chdir("/groups/yshirley/skong/s7_t0p1_g512_4pc_isoth_grav_noTurb_rho0p5_rhoamb0p05_b3_resist0p001_vcol2_vshear0p5_T15")
    file_list = os.listdir()
    file_list_2 = []
    for i in file_list:
        if '.athdf' in i:
            if '.xdmf' not in i:
                file_list_2.append(i)
    # #print(file_list_2)

    # # loop through first dir
    i = 0
    theta = 0
    while i <= 20:
        os.chdir("/groups/yshirley/skong/s7_t0p1_g512_4pc_isoth_grav_noTurb_rho0p5_rhoamb0p05_b3_resist0p001_vcol2_vshear0p5_T15")
        data = yt.load(file_list_2[i])
        sc = yt.create_scene(data)
        # really think about it. it needs to go from 0, 4 to 4, 0.

        x = 2
        z = 2
        coord_array = [x, 0, z]

        tfh = TransferFunctionHelper(data)
        tfh.set_field('density')
        tfh.set_log(True)
        tfh.set_bounds()
        sc[0].tfh.bounds = [lower_bound, upper_bound]

        cam = sc.add_camera()
        cam.position = data.arr(coord_array, 'code_length')
        cam.zoom(2.5)

        sc.render()
        #sc.show()
        os.chdir(homdir)
        sc.save(str(file_list_2[i]+'1')) # weirdest error ever? and i don't know why it's happening? not a big deal, though
        # did end up wasting some time but it's the weekend so
        print('Done with', str(file_list_2[i]))
        i += 1
Ejemplo n.º 5
0
def img_onestep(filename):
    ds = yt.load( filename )
    ad = ds.all_data()
    iteration=int(filename[-5:])
    sc = yt.create_scene(ds, field='Ez')
    if use_moving_window:
        z_shift = jitter_shift( ds, ad, cfl, iteration )
    array_shift = z_shift * np.array([0., 0., 1.])
    if plot_mr_patch:
        box_patch = yt.visualization.volume_rendering.render_source.BoxSource(
            left_edge =ds.index.grids[1].LeftEdge +array_shift,
            right_edge=ds.index.grids[1].RightEdge+array_shift,
            color=[1.,0.1,0.1,.01] )
        sc.add_source(box_patch)
    ########################
    ### volume rendering ###
    ########################
    source = sc[0]
    source.use_ghost_zones = True
    source.grey_opacity = True
    source.set_log(False)
    tf = yt.ColorTransferFunction(bounds)
    if rendering_type == 'smooth':
        tf.add_gaussian(-my_max/4, width=15**2*w,  height=[0.0, 0.0, 1.0, 1])
        tf.add_gaussian( my_max/4, width=15**2*w,  height=[1.0, 0.0, 0.0, 1])
    if rendering_type == 'layers':
        # NEGATIVE
        tf.add_gaussian(-.04 *my_max, width=8*w,  height=[0.1, 0.1, 1.0, 0.2])
        tf.add_gaussian(-.2 *my_max, width=5*w,  height=[0.1, 0.1, 1.0, 0.5])
        tf.add_gaussian(-.6 *my_max, width=w,  height=[0.0, 0.0, 1.0, 1.])
        # POSITIVE
        tf.add_gaussian(.04 *my_max, width=8*w,  height=[1.0, 1.0, 0.2, 0.2])
        tf.add_gaussian(.2 *my_max, width=5*w,  height=[1.0, 1.0, 0.2, 0.5])
        tf.add_gaussian(.6 *my_max, width=w,  height=[1.0, 1.0, 0.0, 1.])

    ######################
    ### plot particles ###
    ######################
    species_points = {}
    for species in species_to_plot:
        species_points[ species ] = get_species_ytpoints(ad,
                                        species, species_colors[species])
        sc.add_source( species_points[ species ] )
    source.tfh.tf = tf
    source.tfh.bounds = bounds
    #########################
    ### camera properties ###
    #########################
    cam = sc.camera
    cam.resolution = (2048, 2048)
    cam.width = .00018*yt.units.meter
    cam.focus = ds.domain_center + \
                np.array([0., 0., 10.e-6 ])*yt.units.meter + \
                array_shift
    cam.position = ds.domain_center + \
                np.array([15., 15., -5.  ])*yt.units.micrometer + \
                array_shift
    cam.normal_vector = [-0.3, -0.3, -.2]
    cam.switch_orientation()
    # save image
    if rendering_type == 'smooth':
        sc.save('img_' + str(my_number_list[count]).zfill(5), sigma_clip=5.)
    if rendering_type == 'layers':
        sc.save('img_' + str(my_number_list[count]).zfill(5), sigma_clip=2.)
Ejemplo n.º 6
0
 def test_simple_scene_creation(self):
     yt.create_scene(self.ds)
import yt

data_dir = "SecondOrderTets"
# data_set = "few-element-mesh_out.e"
data_set = "tet10_unstructured_out.e"
ds = yt.load(data_dir + "/" + data_set, step=-1)

# create a default scene
# sc = yt.create_scene(ds)
sc = yt.create_scene(ds, field='uz')

# override the default colormap
ms = sc.get_source(0)
ms.cmap = 'Eos A'
# ms.color_bounds = (.07, .15)
# ms.color_bounds = (-.02, .02)
ms.color_bounds = (-.01, .2)

# adjust the camera position and orientation
cam = sc.camera
# increase the default resolution
cam.resolution = (800, 800)

cam.focus = ds.arr([0.5, 0.5, 0.5], 'code_length')

cam_pos = ds.arr([0.5, 0.5, -1.0], 'code_length')
north_vector = [1,0,0]
cam.set_position(cam_pos, north_vector)
sc.save(data_set + "_from-minus-z-axis-second-order-embree.png")

cam_pos = ds.arr([0.5, 0.5, 4.0], 'code_length')
Ejemplo n.º 8
0
import numpy as np

import yt

ds = yt.load("MOOSE_sample_data/out.e-s010")
sc = yt.create_scene(ds)
cam = sc.camera

# save an image at the starting position
frame = 0
sc.save("camera_movement_%04i.png" % frame)
frame += 1

# Zoom out by a factor of 2 over 5 frames
for _ in cam.iter_zoom(0.5, 5):
    sc.save("camera_movement_%04i.png" % frame)
    frame += 1

# Move to the position [-10.0, 10.0, -10.0] over 5 frames
pos = ds.arr([-10.0, 10.0, -10.0], "code_length")
for _ in cam.iter_move(pos, 5):
    sc.save("camera_movement_%04i.png" % frame)
    frame += 1

# Rotate by 180 degrees over 5 frames
for _ in cam.iter_rotate(np.pi, 5):
    sc.save("camera_movement_%04i.png" % frame)
    frame += 1
Ejemplo n.º 9
0
def makemovie(name):
    data_name = 'cut_co/xycut_co/' + name

    ds = yt.load(data_name, nan_mask=0.0)

    sc = yt.create_scene(ds, "intensity")
    source = sc[0]
    sc.annotate_domain(ds, color=[128 / 255, 128 / 255, 128 / 255, 0.01])
    sc.annotate_axes(alpha=0.1)
    source.set_log(False)
    source.tfh.build_transfer_function()
    sc.camera.switch_orientation(normal_vector=[-0.1, -0.1, -9])
    sc.camera.set_resolution((1024, 1024))
    sc.camera.roll(radians(-180))

    header = fits.getheader(data_name)
    data = fits.getdata(data_name)
    obj1 = header['object']
    obj = obj1.strip()

    max1 = ds.r['intensity'].max()

    max = max1 / K

    sig = mad_std(
        data, ignore_nan=True
    )  # Older astropy version does not support ignore_nan argument. Delete it and the code will run.

    tf2 = yt.ColorTransferFunction((sig, max))

    tf2.add_gaussian(3 * sig, sig / 100, [106 / 255, 90 / 255, 205 / 255, 0.6])

    tf2.add_gaussian(5 * sig, sig / 100, [30 / 255, 144 / 255, 1, 1.0])

    if max > 18 * sig:
        tf2.add_gaussian(0.4 * max, sig / 100, [0, 1, 127 / 255, 1.4])

        tf2.add_gaussian(0.54 * max, sig / 100, [1, 215 / 255, 0, 1.8])

        tf2.add_gaussian(0.68 * max, sig / 100, [1, 0, 0, 2.8])

        tf2.add_gaussian(0.85 * max, sig / 100, [240 / 255, 1, 1, 3.8])

    else:

        tf2.add_gaussian(7 * sig, sig / 100, [0, 1, 127 / 255, 1.4])

        tf2.add_gaussian(9 * sig, sig / 100, [1, 215 / 255, 0, 1.8])

        tf2.add_gaussian(11.5 * sig, sig / 100, [1, 0, 0, 2.8])

        tf2.add_gaussian(13.5 * sig, sig / 100, [240 / 255, 1, 1, 3.8])

    command3 = 'mkdir cut_co/' + obj
    command4 = 'mkdir cut_co/' + obj + '/movie'
    call(command3, shell=True)
    call(command4, shell=True)

    save_place = 'cut_co/' + obj + '/movie'

    source.set_transfer_function(tf2)
    source.tfh.tf = tf2

    #-----------------------------makeing the colormap------------------------------------------------
    if max > 18 * sig:
        white_patch = mpatches.Patch(color='#F0FFFF', label='0.85 max')
        red_patch = mpatches.Patch(color='#FF0000', label='0.68 max')
        yellow_patch = mpatches.Patch(color='#FFD700', label='0.54 max')
        green_patch = mpatches.Patch(color='#00FF7F', label='0.4 max')
        blue_patch = mpatches.Patch(color='#1E90FF', label='5 $\sigma$')
        purple_patch = mpatches.Patch(color='#6A5ACD', label='3 $\sigma$')
    else:
        white_patch = mpatches.Patch(color='#F0FFFF', label='13.5 $\sigma$')
        red_patch = mpatches.Patch(color='#FF0000', label='11.5 $\sigma$')
        yellow_patch = mpatches.Patch(color='#FFD700', label='9 $\sigma$')
        green_patch = mpatches.Patch(color='#00FF7F', label='7 $\sigma$')
        blue_patch = mpatches.Patch(color='#1E90FF', label='5 $\sigma$')
        purple_patch = mpatches.Patch(color='#6A5ACD', label='3 $\sigma$')

    source.tfh.plot(save_place + '/transfer_function.png')

    img = mpimg.imread(save_place + '/transfer_function.png')
    fig, ax = plt.subplots(figsize=(8, 4))

    imgnew = np.delete(img, np.arange(0, 77), 1)

    imgplot = plt.imshow(imgnew)

    ax.axis('off')

    plt.legend(handles=[
        white_patch, red_patch, yellow_patch, green_patch, blue_patch,
        purple_patch
    ],
               loc=(0.91, 0.4),
               prop={'size': 9})

    plt.savefig('cut_co/colormaps/colormap_' + obj + '.png',
                bbox_inches='tight')

    #----------------------------------------------------------------------------------------------------

    i = 0
    j = 1
    while i < 180:
        sc.camera.yaw(
            radians(rotate_angle_per_time))  #rotate about the north vector
        sc.save(save_place + '/pic' + str(j) + '.png', sigma_clip=4.5)
        i += rotate_angle_per_time
        j += 1


#I zoomed in 1.07 times for 9 times/frames
    k = 0
    l = j
    while k <= 8:
        sc.camera.zoom(1.07)
        sc.camera.yaw(radians(rotate_angle_per_time))
        sc.save(save_place + '/pic' + str(l) + '.png', sigma_clip=4.5)
        k += 1
        l += 1

    a = l
    b = 0
    while b < 360:
        sc.camera.yaw(radians(rotate_angle_per_time))
        sc.save(save_place + '/pic' + str(a) + '.png', sigma_clip=4.5)
        b += rotate_angle_per_time
        a += 1

    num_of_frames = str(a)

    command = "ffmpeg -r " + frames_per_sec + " -f image2 -s 1920x1080 -start_number 1 -i " + save_place + "/pic%d.png -vframes " + num_of_frames + " -vcodec libx264 -crf 15  -b 5000K -vb 20M -pix_fmt yuv420p " + save_place + "/movie.mp4"

    command2 = "ffmpeg -i " + save_place + "/movie.mp4 -vf drawtext=\"fontfile=/Library/Fonts/SignPainter.ttc: \\" + obj + ": fontcolor=white: fontsize=33: x=(w-text_w)/8: y=(h-text_h)/8\" -codec:a copy cut_co/movies/" + obj + ".mp4"

    call(command, shell=True)

    call(command2, shell=True)
Ejemplo n.º 10
0
bounds = (2e7, 3e9)

# Since this rendering is done in log space, the transfer function needs
# to be specified in log space.
tf = yt.ColorTransferFunction(np.log10(bounds))

tf.sample_colormap(np.log10(2E9), 0.005, alpha=0.1, colormap="arbre")
#tf.sample_colormap(np.log10(1E9), 0.005, alpha=0.5, colormap="arbre")
#tf.sample_colormap(np.log10(6E8), 0.005, alpha=0.1,  colormap="arbre")
tf.sample_colormap(np.log10(7.5E8), 0.005, alpha=0.1, colormap="arbre")
tf.sample_colormap(np.log10(2.5E8), 0.005, alpha=0.1, colormap="arbre")
tf.sample_colormap(np.log10(1E8), 0.005, alpha=0.1, colormap="arbre")
tf.sample_colormap(np.log10(3.5E7), 0.005, alpha=0.01, colormap="arbre")

for ds in ts.piter():
    sc = yt.create_scene(ds, field='temperature', lens_type='plane-parallel')

    render_source = sc.get_source(0)
    render_source.transfer_function = tf
    render_source.tfh.tf = tf
    render_source.tfh.bounds = bounds

    render_source.tfh.plot(tfdir +
                           '/%s_render_transfer_function.png' % ds.basename,
                           profile_field='density')

    cam = sc.add_camera(ds, lens_type='plane-parallel')
    cam.resolution = (1920, 1080)
    cam.width = ds.arr([100, 56.25, 56.25], 'kpc')
    cam.position = ds.arr([50, 0, 0], 'kpc')
    cam.switch_orientation(normal_vector=[-1, 0, 0], north_vector=[0, 1, 0])
Ejemplo n.º 11
0
  H2[H2<=0] = np.min(H2[H2>0])
  shape_data = H2.shape

  bounds = (1.e-3, 1.e+3)

data = dict(density=H2)
# data = dict(density=density*H2)
#data = dict(density=density, H2=H2)
ds = yt.load_uniform_grid(data, shape_data)
#dd = ds.all_data()

# from refined_snapshot28_ytclump_fields import _h2density
# from yt.units import dimensions
# ds.add_field(("stream", "h2density"), function=_h2density, units='code_mass/code_length**3')   # units="1/cm**3")

sc = yt.create_scene(ds, lens_type='perspective')

# Get reference to the VolumeSource associated with this scene
# It is the first source associated with the scene, so we can refer to it
# using index 0.
source = sc[0]

source.set_log = True

# Set bounds of transfer function
# # plt.hist((density * H2).flatten(), bins=70)
# plt.hist((H2).flatten(), bins=70)
# plt.xscale('log')
# plt.yscale('log')
# plt.show()
Ejemplo n.º 12
0
#ds = yt.load(fname)

bounds = (1e-28, 1e-25)

# Since this rendering is done in log space, the transfer function needs
# to be specified in log space.
tf = yt.ColorTransferFunction(np.log10(bounds))

tf.sample_colormap(np.log10(1E-25), 0.005, alpha=0.03, colormap="arbre")
#tf.sample_colormap(np.log10(2E-26), 0.005, alpha=0.05, colormap="arbre")
tf.sample_colormap(np.log10(1E-26), 0.005, alpha=0.2, colormap="arbre")
tf.sample_colormap(np.log10(3E-27), 0.005, alpha=0.5, colormap="arbre")
tf.sample_colormap(np.log10(1E-27), 0.005, alpha=0.9, colormap="arbre")

for ds in ts.piter():
    sc = yt.create_scene(ds, field='density', lens_type='plane-parallel')

    render_source = sc.get_source(0)
    render_source.transfer_function = tf
    render_source.tfh.tf = tf
    render_source.tfh.bounds = bounds

    render_source.tfh.plot(tfdir +
                           '/%s_render_transfer_function.png' % ds.basename,
                           profile_field='density')

    cam = sc.add_camera(ds, lens_type='plane-parallel')
    cam.resolution = (1600, 1600)
    cam.width = ds.quan(80, 'kpc')
    cam.position = ds.arr([50, 0, 0], 'kpc')
    cam.switch_orientation(normal_vector=[-1, 0, 0], north_vector=[0, 0, 1])
Ejemplo n.º 13
0
def VolumeRender(colorbound, RenderingOperation, outputfile, X1,X2,X3, data, Particles):

  bbox = np.array([[X1[0], X1[-1]], [X2[0], X2[-1]], [X3[0], X3[-1]]])
  
  arr=data
  data = dict(density = (arr, "g/cm**3"))

  ds = yt.load_uniform_grid(data, arr.shape, length_unit="pc", bbox=bbox, nprocs=1) 

  #************************************** 
  # Extracting user's specified 
  #                parameters in main.py
  #**************************************
  zooming         = RenderingOperation[0]
  Operationalfile = RenderingOperation[1]
  Initial_L0      = RenderingOperation[2]
  Lmin            = RenderingOperation[3]
  Lmax            = RenderingOperation[4]
  dl              = RenderingOperation[5]
  Rotation        = RenderingOperation[6]
  RotaAngle       = RenderingOperation[7]
  RotaSteps       = int(RenderingOperation[8]) 
  length = Initial_L0
  
  frame=1
  print(">> Performing volume rendering ...")
  
  fout= "%s.%04d.png" % (outputfile,frame)

  print(">>",frame,length,fout)

  #**************************************
  # main part starts
  #**************************************
  sc = yt.create_scene(ds)
  source = sc[0]
  sc.camera.resolution = [1024, 1024]  #horizontal, verticle
  sc.camera.width = (length, 'pc')
  sc.camera.switch_orientation(normal_vector=np.array([0,0,-1]),north_vector=np.array([0,1,0]))
  #sc.camera.set_position(ds.domain_left_edge)
  
  if len(Particles) > 1:
    print(">>Adding particles")
    colors = 2 + np.zeros((len(Particles), 4)) #np.random.random([len(Particles), 4])    
    colors[:, 3] = 0.7  # Opacity of Star particles
    points = PointSource(Particles, colors=colors)
    sc.add_source(points)
  
  source.set_log(True)
  source.tfh.set_bounds((colorbound[0], colorbound[1]))
  source.tfh.set_log(True)
  source.tfh.grey_opacity = True
  source.tfh.plot('%s-transferfunction'% outputfile, profile_field='density')

  #sc.annotate_axes(alpha=.02)
  #sc.annotate_domain(ds, color=[1, 1, 1, .01]
  sc.annotate_axes()
  sc.save(fout)
  #text_string = '10' #"%s" % (length)
  #sc.save_annotated(fout,text_annotate=[[(.8, 0.2), text_string]])

  frame = frame + 1
  cam = sc.camera
  #**************************************
  # Zooming-in
  #**************************************
  if ('%s' % zooming) == 'yes':
    print("Zooming in requested!")
    # Zoom in 
    while(length>Lmin):
       print(length)
       sc.camera.width = (length, 'pc')
       sc.render()
       sc.save('%s.%04d.png' % (outputfile,frame)) 
       length = length - dl
       frame += 1

  #**************************************
  # Rotation: 180 degree
  #**************************************
  if ('%s' % Rotation) == 'yes':
    print("Rotation is requested! Forward.")
    #Rotate by 180 degrees over 5 frames
    for _ in cam.iter_rotate(RotaAngle, RotaSteps):
      sc.render()
      sc.save('%s.%04d.png' % (outputfile,frame))
      frame += 1
  
  #**************************************
  # Zooming out
  #**************************************
  if ('%s' % zooming) == 'yes':
    print("Zooming out requested!")
    length = length + dl 
    while(length<=Lmax):
       print(length)
       sc.camera.width = (length, 'pc')
       sc.render()
       sc.save('%s.%04d.png' % (outputfile,frame)) 
       length = length + dl
       frame += 1

  #**************************************
  # 180 degree rotation to return to 
  # original position
  #**************************************
  if ('%s' % Rotation) == 'yes':
    print("Rotation is requested! Backward.")
    #Rotate by 180 degrees over 5 frames
    for _ in cam.iter_rotate(RotaAngle, RotaSteps):
      sc.render()
      sc.save('%s.%04d.png' % (outputfile,frame))
      frame += 1
import yt

# Load the dataset.
ds = yt.load("Enzo_64/DD0043/data0043")
sc = yt.create_scene(ds, ('gas', 'density'))

# You may need to adjust the alpha values to get a rendering with good contrast
# For annotate_domain, the fourth color value is alpha.

# Draw the domain boundary
sc.annotate_domain(ds, color=[1, 1, 1, 0.01])
sc.save("%s_vr_domain.png" % ds, sigma_clip=4)

# Draw the grid boundaries
sc.annotate_grids(ds, alpha=0.01)
sc.save("%s_vr_grids.png" % ds, sigma_clip=4)

# Draw a coordinate axes triad
sc.annotate_axes(alpha=0.01)
sc.save("%s_vr_coords.png" % ds, sigma_clip=4)
Ejemplo n.º 15
0
def img_onestep(filename):

    # Load the data
    ds = yt.load(filename)
    ad = ds.all_data()

    # Calculate the z position of the box.
    # You can use ds.domain_right_edge[2] instead. However, if a moving window
    # was used in the simulation, the rendering shows some jitter.
    # This is because a cell is added in z at some iterations but not all.
    # These lines calculate this jitter z_shift and remove it from the camera position and focus
    iteration = int(filename[-5:])
    dt = 1. / clight * 1. / np.sqrt(
        (1. / ad['dx'][-1]**2 + 1. / ad['dy'][-1]**2 + 1. / ad['dz'][-1]**2))
    z_front = dt * float(iteration) * clight
    z_shift = z_front - ds.domain_right_edge[2]

    # Create a yt source object for the level1 patch
    box_patch = yt.visualization.volume_rendering.render_source.BoxSource(
        left_edge=ds.index.grids[1].LeftEdge +
        np.array([0., 0., z_shift]) * yt.units.meter,
        right_edge=ds.index.grids[1].RightEdge +
        np.array([0., 0., z_shift]) * yt.units.meter,
        color=[1., 0.1, 0.1, .01])

    # Handle 2 populations of particles: beam and plasma electrons
    # Color for each of these particles
    colors0_vect = [1., 1., 1., .05]  # the last value is overwritten later
    colors1_vect = [1., 1., 1., .05]  # the last value is overwritten later
    # particle0: read data and create a yt source object
    x0 = ad['particle0', 'particle_position_x'].v
    y0 = ad['particle0', 'particle_position_y'].v
    z0 = ad['particle0', 'particle_position_z'].v
    vertices0 = np.column_stack((x0, y0, z0))
    colors0 = np.tile(colors0_vect, (vertices0.shape[0], 1))
    colors0[:, 3] = .01
    point0 = yt.visualization.volume_rendering.render_source.PointSource(
        vertices0, colors=colors0, radii=2)
    # particle1: read data and create a yt source object
    x1 = ad['particle1', 'particle_position_x'].v
    y1 = ad['particle1', 'particle_position_y'].v
    z1 = ad['particle1', 'particle_position_z'].v
    # select only some particles
    selector = np.abs(x1) < .1e-6
    x1 = x1[selector]
    y1 = y1[selector]
    z1 = z1[selector]
    vertices1 = np.column_stack((x1, y1, z1))
    colors1 = np.tile(colors1_vect, (vertices1.shape[0], 1))
    colors1[:, 3] = .002
    point1 = yt.visualization.volume_rendering.render_source.PointSource(
        vertices1, colors=colors1, radii=1)

    # Set the field rendering and camera attributes
    # Max field in the simulation. This is easy to get from a single image, but
    # it must be set by hand for a video
    my_max = 500000000000
    sc = yt.create_scene(ds, field='Ez')
    # Set camera properties
    cam = sc.camera
    cam.set_width(ds.quan(35, yt.units.micrometer))
    cam.position = ds.domain_center + np.array([
        15., 20., -5.
    ]) * yt.units.micrometer + np.array([0., 0., z_shift]) * yt.units.meter
    cam.focus = ds.domain_center + np.array([0., 0., z_shift]) * yt.units.meter
    cam.resolution = (2048, 2048)
    # Field rendering properties
    source = sc[0]
    source.set_field('Ez')
    source.set_log(False)
    source.use_ghost_zones = True
    bounds = (-my_max, my_max)
    tf = yt.ColorTransferFunction(bounds)
    w = (.01 * my_max)**2
    # Define the transfer function for 3d rendering
    # 3 isocontours for negative field values
    # The sharpness of the contour is controlled by argument width
    tf.add_gaussian(-.04 * my_max, width=8 * w, height=[0.1, 0.1, 1.0, 0.02])
    tf.add_gaussian(-.2 * my_max, width=5 * w, height=[0.1, 0.1, 1.0, 0.05])
    tf.add_gaussian(-.6 * my_max, width=w, height=[0.0, 0.0, 1.0, 0.3])
    # 3 isocontours for positive field values
    tf.add_gaussian(.04 * my_max, width=8 * w, height=[1.0, 1.0, 0.2, 0.02])
    tf.add_gaussian(.2 * my_max, width=5 * w, height=[1.0, 1.0, 0.2, 0.05])
    tf.add_gaussian(.6 * my_max, width=w, height=[1.0, 1.0, 0.0, 0.3])
    source.tfh.tf = tf
    source.tfh.bounds = bounds
    source.tfh.set_log(False)
    source.tfh.tf.grey_opacity = True
    # Plot user-defined sources (here, 2 species for particles and 1 box)
    sc.add_source(point0)
    sc.add_source(point1)
    sc.add_source(box_patch)
    # Save file
    sc.save(filename + '_quarter.png', sigma_clip=1.)
    return 0
Ejemplo n.º 16
0
import yt

# Load the dataset.
ds = yt.load("Enzo_64/DD0043/data0043")
sc = yt.create_scene(ds, ("gas", "density"))

# You may need to adjust the alpha values to get a rendering with good contrast
# For annotate_domain, the fourth color value is alpha.

# Draw the domain boundary
sc.annotate_domain(ds, color=[1, 1, 1, 0.01])
sc.save("%s_vr_domain.png" % ds, sigma_clip=4)

# Draw the grid boundaries
sc.annotate_grids(ds, alpha=0.01)
sc.save("%s_vr_grids.png" % ds, sigma_clip=4)

# Draw a coordinate axes triad
sc.annotate_axes(alpha=0.01)
sc.save("%s_vr_coords.png" % ds, sigma_clip=4)
Ejemplo n.º 17
0
idx_start = args.idx_start
idx_end = args.idx_end
didx = args.didx
prefix_in = args.prefix_in
prefix_out = args.prefix_out

yt.enable_parallelism()
ts = yt.load([
    prefix_in + '/Data_%06d' % idx
    for idx in range(idx_start, idx_end + 1, didx)
])

for ds in ts.piter():

    #  create a scene
    sc = yt.create_scene(ds, field=field, lens_type='perspective')
    cam = sc.camera

    #  get a reference to the VolumeSource associated with this scene
    src = sc[0]

    #  set the target field
    src.set_field(field)

    #  set that the transfer function should be evaluated in log space
    src.tfh.set_log(True)

    #  make underdense regions appear opaque
    #  src.tfh.grey_opacity = True

    #  set the image resolution
Ejemplo n.º 18
0
# Since this rendering is done in log space, the transfer function needs
# to be specified in log space.
tf = yt.ColorTransferFunction(np.log10(bounds))

tf.sample_colormap(-0.35, 0.001, alpha=0.9, colormap="arbre")
tf.sample_colormap(-0.2, 0.001, alpha=0.3, colormap="arbre")
tf.sample_colormap(-0.1, 0.001, alpha=0.2, colormap="arbre")
tf.sample_colormap(0.2, 0.001, alpha=0.4, colormap="arbre")
tf.sample_colormap(0.3, 0.0005, alpha=0.7, colormap="arbre")

for ds in ts[::-1].piter():
    figfname = figuredir + '/' + ds.basename + '.png'
    #if os.path.exists(figfname): continue
    sp = ds.sphere([0, 0, 0], (150, 'kpc'))
    sc = yt.create_scene(sp, field='entropy_ratio', lens_type='perspective')

    render_source = sc.get_source(0)
    render_source.transfer_function = tf
    render_source.tfh.tf = tf
    render_source.tfh.bounds = bounds
    #render_source.set_use_ghost_zones(True)

    render_source.tfh.plot(tfdir +
                           '/%s_render_transfer_function.png' % ds.basename,
                           profile_field='density')

    cam = sc.camera
    cam.resolution = (1920, 1080)
    cam.width = ds.arr([512, 288, 512], 'kpc')
    cam.position = ds.arr([256, 0, 0], 'kpc')
Ejemplo n.º 19
0
                   tf.funcs[3].y]).T
fig = plt.figure(figsize=[6, 3])
ax = fig.add_axes([0.2, 0.2, 0.75, 0.75])
d_hist=ax.hist(data['dvs'][~np.isnan(dvs)].ravel(),bins=100,density=True,log=False)
ax.bar(x, tf.funcs[3].y, w, edgecolor=[0.0, 0.0, 0.0, 0.0],
       log=False, color=colors, bottom=[0])
plt.savefig(os.path.join(out_dir,'shapeplotter_TF_exploration_tf.png'))

# load the data as a uniform grid, create the 3d scene
sc_mult=1.0 # scale multiplier
bbox = model.cart['bbox'] # list-like [[xmin,xmax],[ymin,ymax],[zmin,zmax]]
print(bbox)
ds = yt.load_uniform_grid(data,data['dvs'].shape,sc_mult,bbox=bbox,nprocs=1,
                        periodicity=(True,True,True),unit_system="mks")

sc = yt.create_scene(ds,'dvs')

# Draw the domain boundary

# draw true boundary extents
lat_rnge=[np.min(model.data.variables['latitude']),np.max(model.data.variables['latitude'])]
lon_rnge=[np.min(model.data.variables['longitude']),np.max(model.data.variables['longitude'])]
min_dep=0.
max_dep=1200.
R=6371.
r_rnge=[(R-max_dep)*1000.,(R-min_dep)*1000.]
Chunk=sp.sphericalChunk(lat_rnge,lon_rnge,r_rnge)
sc=Chunk.domainExtent(sc,RGBa=[1.,1.,1.,0.005],n_latlon=100,n_rad=50)
sc=Chunk.latlonGrid(sc,RGBa=[1.,1.,1.,0.005])
sc=Chunk.latlonGrid(sc,RGBa=[1.,1.,1.,0.001],radius=(R-410.)*1000.)
sc=Chunk.latlonGrid(sc,RGBa=[1.,1.,1.,0.001],radius=(R-max_dep)*1000.)
Ejemplo n.º 20
0
 def test_sigma_clip(self):
     ds = fake_random_ds(32)
     sc = yt.create_scene(ds)
     sc.save("clip_2.png", sigma_clip=2)
Ejemplo n.º 21
0
os.chdir(
    "/groups/yshirley/skong/s7_t0p01_g512_4pc_isoth_grav_noTurb_rho0p5_rhoamb0p05_b3_resist0p001_vcol2_vshear0p5_T15"
)
file_list = os.listdir()
file_list_2 = []
for i in file_list:
    if '.athdf' in i:
        if '.xdmf' not in i:
            file_list_2.append(i)
i = 0
while i <= 10:
    os.chdir(
        "/groups/yshirley/skong/s7_t0p01_g512_4pc_isoth_grav_noTurb_rho0p5_rhoamb0p05_b3_resist0p001_vcol2_vshear0p5_T15"
    )
    data = yt.load(file_list_2[i])
    sc = yt.create_scene(data)

    tfh = TransferFunctionHelper(data)
    tfh.set_field('density')
    tfh.set_log(True)
    tfh.set_bounds()
    sc[0].tfh.bounds = [lower_bound, upper_bound]

    cam = sc.add_camera()
    cam.position = data.arr([4, 0, 0], 'code_length')
    cam.zoom(2.5)

    sc.render()
    #sc.show()
    os.chdir("/home/u20/avichalk/exports/29_3_export")
    sc.save(
Ejemplo n.º 22
0
def make_scene(grid_ds):
    sc = yt.create_scene(grid_ds, field=('gas', 'PartType1_density'))
    cam = sc.add_camera(grid_ds, lens_type='perspective')
    focus = cam.focus
    print('-------- Scene created. --------')
    return sc, cam, focus
Ejemplo n.º 23
0
import yt

ds = yt.load("Enzo_64/DD0043/data0043")

sc = yt.create_scene(ds, lens_type="perspective")

source = sc[0]

source.set_field(("gas", "density"))
source.set_log(True)

# Set up the camera parameters: focus, width, resolution, and image orientation
sc.camera.focus = ds.domain_center
sc.camera.resolution = 1024
sc.camera.north_vector = [0, 0, 1]
sc.camera.position = [1.7, 1.7, 1.7]

# You may need to adjust the alpha values to get an image with good contrast.
# For the annotate_domain call, the fourth value in the color tuple is the
# alpha value.
sc.annotate_axes(alpha=0.02)
sc.annotate_domain(ds, color=[1, 1, 1, 0.01])

text_string = f"T = {float(ds.current_time.to('Gyr'))} Gyr"

# save an annotated version of the volume rendering including a representation
# of the transfer function and a nice label showing the simulation time.
sc.save_annotated(
    "vol_annotated.png", sigma_clip=6, text_annotate=[[(0.1, 0.95), text_string]]
)
Ejemplo n.º 24
0
import numpy as np
from scipy import stats
import numexpr as ne
import yt
import math
root = "/Volumes/External/JanData/"
array = np.load(root+"AxDensity4_036.npy")
maxdens = array.max()
for i in range(36,365):
	print i
	array = np.load(root+"AxDensity4_%03d.npy"%i)
	data = dict(density=array)
	bbox = np.array([[0., 1.0], [0, 1.0], [0., 1.0]])
	ds = yt.load_uniform_grid(data, array.shape,length_unit="cm",bbox=bbox)
	ad = ds.all_data()
	sc = yt.create_scene(ds, field="density")
	sc.camera.width = (0.3,'cm')
	alpha = i/(365.0-36.0)*2*math.pi
	sc.camera.position = np.array([0.5,0.5,0.5])+np.array([np.cos(alpha),0,np.sin(alpha)])
	sc.camera.focus = np.array([0.5,0.5,0.5])
	sc.camera.north_vector = np.array([0,1.0,0])
# sc.camera.focus = np.array(np.unravel_index(array.argmax(),array.shape))/406.0

	source =sc[0]
	bounds = (maxdens/1e3, maxdens)

	tf = yt.ColorTransferFunction(np.log10(bounds))
	tf.sample_colormap(np.log10(maxdens*0.75), w=.005,colormap='RAINBOW')
	tf.sample_colormap(np.log10(maxdens/2.0e1), w=.005, alpha =
	0.2,colormap='RAINBOW')
	tf.sample_colormap(np.log10(maxdens/1.0e2), w=.005, alpha =
Ejemplo n.º 25
0
def img_onestep(filename):
    # Load the data
    ds = yt.load(filename)
    ad = ds.all_data()

    # Calculate the z position of the box.
    # You can use ds.domain_right_edge[2] instead. However, if a moving window
    # was used in the simulation, the rendering shows some jitter.
    # This is because a cell is added in z at some iterations but not all.
    # These lines calculate this jitter z_shift and remove it from the camera position and focus
    iteration = int(filename[-5:])
    dt = 1. / clight * 1. / np.sqrt(
        (1. / ad['dx'][-1]**2 + 1. / ad['dy'][-1]**2 + 1. / ad['dz'][-1]**2))
    z_front = dt * float(iteration) * clight
    z_shift = z_front - ds.domain_right_edge[2]

    # Create a yt source object for the level1 patch
    if do_patch:
        box_patch = yt.visualization.volume_rendering.render_source.BoxSource(
            left_edge=ds.index.grids[1].LeftEdge +
            np.array([0., 0., z_shift]) * yt.units.meter,
            right_edge=ds.index.grids[1].RightEdge +
            np.array([0., 0., z_shift]) * yt.units.meter,
            color=[1., 0.1, 0.1, .01])

    # Handle 2 populations of particles: beam and plasma electrons
    if do_particles:
        point0 = plot_species(species0, ad, 2, .01, 1.)
        point1 = plot_species(species1, ad, 1, .002, 20.e-6)
    sc = yt.create_scene(ds, field=field)

    # Set camera properties
    cam = sc.camera
    dom_length = ds.domain_width[2].v
    cam.set_width(ds.quan(dom_length, yt.units.meter))
    cam.position = ds.domain_center + camera_position + np.array(
        [0., 0., z_shift]) * yt.units.meter
    cam.focus = ds.domain_center + np.array([0., 0., z_shift]) * yt.units.meter
    cam.resolution = resolution
    # Field rendering properties
    source = sc[0]
    source.set_field(field)
    source.set_log(False)
    source.use_ghost_zones = True
    bounds = (-my_max, my_max)
    tf = yt.ColorTransferFunction(bounds)
    w = (.01 * my_max)**2
    # Define the transfer function for 3d rendering
    # 3 isocontours for negative field values
    # The sharpness of the contour is controlled by argument width
    tf.add_gaussian(-.04 * my_max, width=8 * w, height=[0.1, 0.1, 1.0, 0.02])
    tf.add_gaussian(-.2 * my_max, width=5 * w, height=[0.1, 0.1, 1.0, 0.05])
    tf.add_gaussian(-.6 * my_max, width=w, height=[0.0, 0.0, 1.0, 0.3])
    # 3 isocontours for positive field values
    tf.add_gaussian(.04 * my_max, width=8 * w, height=[1.0, 1.0, 0.2, 0.02])
    tf.add_gaussian(.2 * my_max, width=5 * w, height=[1.0, 1.0, 0.2, 0.05])
    tf.add_gaussian(.6 * my_max, width=w, height=[1.0, 1.0, 0.0, 0.3])
    source.tfh.tf = tf
    source.tfh.bounds = bounds
    source.tfh.set_log(False)
    source.tfh.tf.grey_opacity = True
    if do_particles:
        sc.add_source(point0)
        sc.add_source(point1)
    if do_patch:
        sc.add_source(box_patch)
    sc.save('./img_' + filename[-8:] + '.png', sigma_clip=1.)
Ejemplo n.º 26
0
    ax.set_title(r'Isocontour of max($\rho$)/4 = ' + str(float(ISO) / 4.) +
                 r' $\frac{M_{pl}^2}{m}$')

    plt.savefig("%s_Surface.png" % i, dpi=300)
    os.system("mv *.png SurfRend2")

    #surface.export_obj("%s_VR" % i )
    #os.system("mv *.obj *.mtl OBJRend2")

    print("===============================================")
    print("Time to compute SurfaceRender 2 ")
    print("time = ", time.time() - Debug, "s ")
    print("===============================================")

    #==============================================
    #	Volume rendering
    #==============================================

    Debug = time.time()

    sc = yt.create_scene(i, "rho")
    sc.camera.resolution = 1024
    sc.annotate_domain(i, color=[1, 1, 1, 1])
    sc.save()
    os.system("mv *.png VolRend")

    print("===============================================")
    print("Time to compute VolumeRender")
    print("time = ", time.time() - Debug, "s ")
    print("===============================================")
Ejemplo n.º 27
0
    os.mkdir(out_dir)

plt.savefig(os.path.join(out_dir, 'transfer_function.png'))

# load the data as a uniform grid, create the 3d scene
sc_mult = 1.0  # scale multiplier
bbox = model.cart['bbox']  # list-like [[xmin,xmax],[ymin,ymax],[zmin,zmax]]
ds = yt.load_uniform_grid(data,
                          data[datafld].shape,
                          sc_mult,
                          bbox=bbox,
                          nprocs=1,
                          periodicity=(True, True, True),
                          unit_system="mks")

sc = yt.create_scene(ds, datafld)

# Draw the domain boundary and useful grids
lat_rnge = [
    np.min(model.data.variables['latitude']),
    np.max(model.data.variables['latitude'])
]
lon_rnge = [
    np.min(model.data.variables['longitude']),
    np.max(model.data.variables['longitude'])
]
min_dep = 0.
max_dep = 1200.
R = 6371.
r_rnge = [(R - max_dep) * 1000., (R - min_dep) * 1000.]
Chunk = sp.sphericalChunk(lat_rnge, lon_rnge, r_rnge)
Ejemplo n.º 28
0
# Volume renders. These are very finiky, so you need to alter the values case by case.
# Documentation can be found here: http://yt-project.org/doc/visualizing/volume_rendering.html
#Find the min and max of the field
mi, ma = ds.all_data().quantities.extrema('wavefunction')
#Reduce the dynamic range
mi = mi.value + 0.004
#ma = ma.value - 0.002
# Choose a vector representing the viewing direction.
L = [0.4, 0.5, 0.15]
# Define the center of the camera to be the domain center
c = ds.domain_center[0]
# Define the width of the image
W = 1.5*max(ds.domain_width)

sc = yt.create_scene(ds, 'wavefunction')
dd = ds.all_data()
source = sc[0]
source.log_field = False
tf = yt.ColorTransferFunction((mi, ma), grey_opacity=False)
tf.map_to_colormap(mi, ma, scale=0.5, colormap='YlGnBu')
source.set_transfer_function(tf)
sc.add_source(source)
cam = sc.add_camera()
sc.annotate_domain(ds, color=[1, 1, 1, 0.1])
sc.annotate_axes(alpha=0.5)
cam.width = W
cam.resolution = 1024
cam.center = c
cam.normal_vector = L
cam.north_vector = [0, 0, 1]
Ejemplo n.º 29
0
import yt
import numpy as np

# Load the dataset
ds = yt.load("Enzo_64/DD0043/data0043")

# Create a volume rendering
sc = yt.create_scene(ds, field=('gas', 'density'))

# Modify the transfer function

# First get the render source, in this case the entire domain, with field ('gas','density')
render_source = sc.get_source()

# Clear the transfer function
render_source.transfer_function.clear()

# Map a range of density values (in log space) to the Reds_r colormap
render_source.transfer_function.map_to_colormap(
    np.log10(ds.quan(5.0e-31, 'g/cm**3')),
    np.log10(ds.quan(1.0e-29, 'g/cm**3')),
    scale=30.0,
    colormap='RdBu_r')

sc.save('new_tf.png')
Ejemplo n.º 30
0
ax.scatter(x, y, z, c=cvar, marker='.')
ax.set_xlim([min(x), 0])
ax.set_ylim([min(y), 0])
ax.set_zlim([max(z), 0])
plt.show()

# https://yt-project.org/doc/examining/loading_data.html#unstructured-grid-data
# model.unstructured['data']['connect1', 'dvs']=np.float64(model.unstructured['data']['connect1', 'dvs'])
# model.unstructured['cnnct']=np.float64(model.unstructured['cnnct'])

ds = yt.load_unstructured_mesh(model.unstructured['cnnct'],
                               model.unstructured['vertices'],
                               node_data=model.unstructured['data'])

sc = yt.create_scene(ds, ('connect1', 'depth'))
# # override the default colormap
# ms = sc.get_source()
# ms.cmap = 'Eos A'
#
# # adjust the camera position and orientation
# cam = sc.camera
# cam.focus = ds.arr([0.0, 0.0, 0.0], 'code_length')
# cam_pos = ds.arr([-3.0, 3.0, -3.0], 'code_length')
# north_vector = ds.arr([0.0, -1.0, -1.0], 'dimensionless')
# cam.set_position(cam_pos, north_vector)
#
# # increase the default resolution
# cam.resolution = (800, 800)

# render and save
Ejemplo n.º 31
0
def visualize_tables(table_path,
                     geom_file,
                     slices=True,
                     projections=True,
                     plot_3d=True):
    tables_dir = dirname(table_path)
    table_fname = basename(table_path)
    tables_basename = table_fname
    for name in [
            'survival_prob', 'avg_photon_x', 'avg_photon_y', 'avg_photon_z'
    ]:
        tables_basename = tables_basename.replace('_' + name + '.fits', '')
    if tables_basename[-1] == '_':
        tables_basename = tables_basename[:-1]

    det_string_depth_xyz = np.load(geom_file)

    num_doms_in_detector = np.prod(det_string_depth_xyz.shape[:2])

    data = {}
    fname = '%s_survival_prob.fits' % tables_basename
    fpath = join(tables_dir, fname)
    with pyfits.open(fpath) as fits_file:
        survival_prob = fits_file[0].data
        ma = survival_prob.max()
        print('Max survival probability         :', ma)
        mi = survival_prob.min()
        print('Min survival probability         :', mi)
        mi_nonzero = survival_prob[survival_prob != 0].min()
        print('Min non-zero survival probability:', mi_nonzero)
        data['density'] = (survival_prob, 'kg/m**3')
        xyz_shape = fits_file[1].data
        lims = fits_file[2].data
        doms_used = fits_file[3].data

        # If 3D, dims represent: (string numbers, depth indices, (x, y, z))
        if len(doms_used.shape) == 3:
            doms_used = np.stack(
                (doms_used[:, :, 0].flatten(), doms_used[:, :, 1].flatten(),
                 doms_used[:, :, 2].flatten())).T

        nx, ny, nz = xyz_shape
        xlims = lims[0, :]
        ylims = lims[1, :]
        zlims = lims[2, :]
        print('x lims:', xlims)
        print('y lims:', ylims)
        print('z lims:', zlims)
        print('(nx, ny, nz):', xyz_shape)
        num_doms_used = doms_used.shape[0]
        print('num doms used:', num_doms_used)
        print('doms used:', doms_used.shape)

    if slices:
        mask = survival_prob > 0  #(ma / 10000000)
        avg_photon_info = {}
        for dim in ['x', 'y', 'z']:
            fname = '%s_avg_photon_%s.fits' % (tables_basename, dim)
            fpath = join(tables_dir, fname)
            with pyfits.open(fpath) as fits_file:
                d = np.zeros_like(survival_prob)
                d[mask] = fits_file[0].data[mask]
                #d = -fits_file[0].data
                avg_photon_info[dim] = d
                data['velocity_' + dim] = (d, 'm/s')
        avg_photon_info = Cart3DCoord(**avg_photon_info)
        del mask

    bbox = lims
    ds = yt.load_uniform_grid(data,
                              domain_dimensions=(nx, ny, nz),
                              bbox=bbox,
                              nprocs=4)

    savefig_kw = dict(name=join(tables_dir, tables_basename),
                      suffix='png',
                      mpl_kwargs=dict(dpi=300))
    plots = []

    sphere_kwargs = dict(radius=(5 * DOM_RADIUS_M, 'cm'),
                         coord_system='data',
                         circle_args=dict(color=(0, 0.8, 0),
                                          linewidth=1,
                                          alpha=0.3))

    if projections:
        for normal in ['x', 'y', 'z']:
            prj = yt.ProjectionPlot(ds, normal, 'density')
            prj.set_log('density', False)
            prj.set_cmap('density', 'inferno')

            # Display all doms in the detector
            for depth_xyz in det_string_depth_xyz:
                for xyz in depth_xyz:
                    prj.annotate_sphere(xyz, **sphere_kwargs)

            # Display only doms used (if subset of the detector)
            if num_doms_used != num_doms_in_detector:
                kw = deepcopy(sphere_kwargs)
                kw['radius'] = (15 * DOM_RADIUS_M, 'cm')
                kw['circle_args']['alpha'] = 1
                for depth_xyz in doms_used:
                    prj.annotate_sphere(depth_xyz, **kw)

            prj.save(**savefig_kw)
            plots.append(prj)

    if plot_3d:
        # Choose a vector representing the viewing direction.
        L = [-0.5, -0.5, -0.5]

        # Define the center of the camera to be the domain center
        c = ds.domain_center[0]
        #c = (1400*100, 1300*100, 1300*100)

        # Define the width of the image
        W = 1.0 * ds.domain_width[0]

        # Define the number of pixels to render
        Npixels = 2048

        sc = yt.create_scene(ds, 'density')
        source = sc[0]
        source.log_field = False

        tf = yt.ColorTransferFunction((0, ma), grey_opacity=True)
        tf.map_to_colormap(0, ma, scale=1.0, colormap='inferno')

        source.set_transfer_function(tf)

        sc.add_source(source)

        cam = sc.add_camera()
        cam.width = W
        cam.center = c
        cam.normal_vector = L
        cam.north_vector = [0, 0, 1]
        cam.position = (1400, 1300, 1300)

        #sc.show(sigma_clip=4)

        sc.save(savefig_kw['name'])

        plots.append(sc)

    if slices:
        skw = deepcopy(sphere_kwargs)
        skw['circle_args']['color'] = (0.8, 0, 0)
        if num_doms_used != num_doms_in_detector:
            center = np.mean(doms_used, axis=0)
        else:
            center = (0, 0, 0)
            #center = det_string_depth_xyz[35, 47]
            #cut_plane_strings = [1 - s for s in [6, 12, 27, 36, 45, 54, 62, 69, 75]]
            #normal =
            #north_vector = (0, 0, 1)

        for normal in ['x', 'y', 'z']:
            #if normal == 'x':
            #    plt.
            slc = yt.SlicePlot(ds,
                               normal=normal,
                               fields='density',
                               center=center)
            slc.set_cmap('density', 'octarine')
            #slc.set_log('density', False)

            for depth_xyz in det_string_depth_xyz:
                for xyz in depth_xyz:
                    slc.annotate_sphere(xyz, **skw)

            if num_doms_used != num_doms_in_detector:
                kw = deepcopy(skw)
                kw['radius'] = (15 * DOM_RADIUS_M, 'cm')
                kw['circle_args']['alpha'] = 1
                for depth_xyz in doms_used:
                    slc.annotate_sphere(depth_xyz, **kw)

            nskip = 10
            kw = dict(factor=nskip, scale=1e3)
            if normal == 'x':
                slc.annotate_quiver('velocity_y', 'velocity_z', **kw)
            elif normal == 'y':
                slc.annotate_quiver('velocity_z', 'velocity_x', **kw)
            elif normal == 'z':
                slc.annotate_quiver('velocity_x', 'velocity_y', **kw)

            #slc.annotate_grids(cmap=None)
            slc.save(**savefig_kw)
            plots.append(slc)

    return ds, plots
Ejemplo n.º 32
0
import yt

# We load the last time frame
ds = yt.load("/home/lindsayad/yt_data/MOOSE_sample_data/mps_out.e", step=-1,
             displacements={'connect2': (10.0, [0.01, 0.0, 0.0])})

# create a default scene
sc = yt.create_scene(ds, ("connect2", "temp"))

# override the default colormap. This time we also override
# the default color bounds
ms = sc.get_source(0)
ms.cmap = 'hot'
ms.color_bounds = (500.0, 1700.0)

# adjust the camera position and orientation
cam = sc.camera
camera_position = ds.arr([-1.0, 1.0, -0.5], 'code_length')
north_vector = ds.arr([0.0, -1.0, -1.0], 'dimensionless')
cam.width = ds.arr([0.05, 0.05, 0.05], 'code_length')
cam.set_position(camera_position, north_vector)

# increase the default resolution
cam.resolution = (800, 800)

# render, draw the element boundaries, and save
sc.render()
sc.annotate_mesh_lines()
sc.save()
Ejemplo n.º 33
0
import yt
from yt.testing import fake_hexahedral_ds

ds = fake_hexahedral_ds()

sc = yt.create_scene(ds)
cam = sc.camera
cam.focus = ds.arr([0.0, 0.0, 0.0], 'code_length')
cam_pos = ds.arr([-3.0, 3.0, -3.0], 'code_length')
north_vector = ds.arr([0.0, -1.0, -1.0], 'dimensionless')
cam.set_position(cam_pos, north_vector)

# increase the default resolution
cam.resolution = (800, 800)

sc.show()
Ejemplo n.º 34
0
def plot_a_vr(path,
              header,
              cycle,
              use_ghost_zones=True,
              annotate=True,
              rotate=False,
              zoom=False):
    """
    volume rendering plot

    path [string]  : the path of data files
    header [string]: the header of the data file
    cycle [int]    : the data cycle

    ex. for file: /data/ccsn3d_hdf5_plt_cnt_0100

        path   = "/data"
        header = "ccsn3d"
        cycle  = 100
    """

    fn = get_fn(path, header, cycle)
    ds = yt.load(fn)

    # register new units for entropy
    ds.unit_registry.add('kB',
                         1.3806488e-16,
                         dimensions=energy / temperature,
                         tex_repr='k_{B}')
    ds.unit_registry.add('by', 1.674e-24, dimensions=mass, tex_repr='baryon')

    # create a new derived field: Entropy
    def _entr(field, data):
        """
	fixed the entropy units in flash
        """
        entr = data["entr"]
        kb_by = yt.YTQuantity(1, 'erg') / yt.YTQuantity(
            1, 'K') / yt.YTQuantity(1, 'g') * (1.3806488e-16 / 1.674e-24)
        return entr * kb_by

    ds.add_field("Entr",
                 function=_entr,
                 units="kB/by",
                 display_name="Entropy",
                 dimensions=energy / temperature / mass)

    # create a new derived field: Entropy
    def _entrdens(field, data):
        """
        create a new derived field to show both entropy and density

        if density > PNS_DENSITY:
            entropy = PNS_ENTR
        else:
            entropy = entropy

        """
        dens = data["dens"]
        entr = data["entr"]
        entrdens = entr * (
            np.exp(-(dens.in_cgs() / PNS_DENSITY)**5)) + PNS_ENTR
        kb_by = yt.YTQuantity(1, 'erg') / yt.YTQuantity(
            1, 'K') / yt.YTQuantity(1, 'g') * (1.3806488e-16 / 1.674e-24)
        return entrdens * kb_by

    ds.add_field("Entropy",
                 function=_entrdens,
                 units="kB/by",
                 display_name="Entropy",
                 dimensions=energy / temperature / mass)

    #debug: also plot a entropy slice
    if yt.is_root():
        pc = yt.SlicePlot(ds, 'z', 'Entr')
        pc.zoom(40)
        pc.set_log('Entr', False)
        pc.save('fig_slice_z_' + header + '_' + string.zfill(cycle, 4) +
                '.png')

    # get the entropy range from time
    time = ds.current_time.in_cgs().v - TSHIFT

    if CUSTOM_EMAX:
        emin, emax = get_emin_emax(time)
    else:
        entropy_max, pe = ds.find_max('Entropy')
        emax = entropy_max.v - 1.0
        emin = emax - 3.0

    if yt.is_root():
        print "emin/emax:", emin, emax
        # check if emax > emin
        if emax <= emin:
            print "Error: emax <= emin"
            quit()

    # only render the region with r < 1.e8 cm
    # this is necessary if we want to include ghost zones
    sphere = ds.sphere([0, 0, 0], (1.e8, 'cm'))
    sc = yt.create_scene(sphere, field='Entropy')

    # set the camera resolution and width
    sc.camera.north_vector = [0, 0, 1]
    sc.camera.resolution = (VR_RESOLUTION, VR_RESOLUTION)
    sc.camera.set_width(ds.quan(VR_WIDTH, 'cm'))

    #sc.camera.set_width(ds.quan(2.5e7,'cm'))

    # define the tranfer function for high entropy region
    def linearFunc(values, minv, maxv):
        try:
            return ((values) - values.min()) / (values.max() - values.min())
            #return (na.sqrt(values) - values.min())/(values.max()-values.min())
        except:
            return 1.0

    source = sc.get_source(0)
    source.set_use_ghost_zones(use_ghost_zones)  # *** SLOW ***
    source.set_log(False)
    source.grey_opacity = True

    # create a transfer function helper
    tfh = TransferFunctionHelper(ds)
    tfh.set_field('Entropy')
    tfh.set_bounds()
    tfh.set_log(False)
    tfh.build_transfer_function()

    # add a thin layer to show the shock front
    esh, ew = get_shock_entropy(time, emin, emax)
    tfh.tf.add_layers(1,
                      w=(ew),
                      mi=(esh),
                      ma=(esh + 0.5),
                      col_bounds=[4.0, (esh + 1.0)],
                      alpha=10.0 * esh * np.ones(1),
                      colormap='cool_r')

    # plot the PNS at entr = PNS_ENTR
    tfh.tf.add_layers(1,
                      w=0.5,
                      mi=0.49,
                      ma=0.55,
                      col_bounds=[0.05, 0.55],
                      alpha=100.0 * np.ones(1),
                      colormap='Purples')

    # map the high entropy region: version 3
    tfh.tf.map_to_colormap(emin,
                           emax,
                           scale=100.0,
                           scale_func=linearFunc,
                           colormap='autumn')

    # version 1: use many layers
    #tfh.tf.add_layers(12,w=0.05,mi=emin,ma=emax,col_bounds=[emin,emax],
    #        alpha=70*np.linspace(0.0,1.5,10),colormap='hot')

    tfh.tf.grey_opacity = True
    source.set_transfer_function(tfh.tf)
    source.grey_opacity = True

    # plot the transfer function
    #source.tfh.plot('fig_transfer_function_entr.png', profile_field='cell_mass')

    # plot volume rendering plot without annotation
    if not annotate:
        sc.save('fig_vr_' + header + '_' + string.zfill(cycle, 4) + '.png',
                sigma_clip=4)

    else:
        # with annotation
        sc.annotate_axes(alpha=0.8)
        #sc.annotate_scale()  #

        # line annotation
        #annotate_width = 1.0e7  # [cm]
        #annotate_axis  = 1.5e7  # [cm]
        #annotate_at    = (annotate_axis/2.0 - annotate_width/(2.0*np.sqrt(2.0)))

        #colors   = np.array([[0.45,0.5,0.5,0.7]]) # white
        #vertices = np.array([[[annotate_at,0.,0.],[0.,annotate_at,0.]]])*annotate_width*cm
        #lines    = LineSource(vertices,colors)
        #sc.add_source(lines)

        #sc.annotate_domain(ds,color=[1,1,1,0.01])
        #text_string= "Time = %.1f (ms)" % (float(ds.current_time.to('s')*1.e3))
        text_string = "Time = %.1f (ms)" % (float(time * 1.e3))
        sc.save_annotated("fig_vr_" + header + "_annotated_" +
                          string.zfill(cycle, 4) + '.png',
                          sigma_clip=4.0,
                          label_fmt="%.1f",
                          text_annotate=[[(0.05, 0.95), text_string,
                                          dict(color="w",
                                               fontsize="20",
                                               horizontalalignment="left")]])

    # rotate the camera
    if DO_ROT:
        rotate = True

    if rotate:
        fstart = 1  # modify here for restart
        frames = ROT_FRAMES  # total number of frames for rotation
        cam = sc.camera
        i = 0
        for _ in cam.iter_rotate(2.0 * np.pi, frames):
            i += 1
            if i >= fstart:
                sc.render()
                if not annotate:
                    sc.save("fig_vr_" + header + "_" + string.zfill(cycle, 4) +
                            '_rot_' + string.zfill(i, 4) + '.png',
                            sigma_clip=2)
                else:
                    sc.save_annotated("fig_vr_" + header + "_annotated_" +
                                      string.zfill(cycle, 4) + '_rot_' +
                                      string.zfill(i, 4) + '.png',
                                      sigma_clip=4.0,
                                      text_annotate=[[
                                          (0.05, 0.95), text_string,
                                          dict(color="w",
                                               fontsize="20",
                                               horizontalalignment="left")
                                      ]])

    # TODO: zoom in or zoom out
    if DO_ZOOM:
        zoom = True

    if zoom:
        fstart = 0  # modify here for restart
        frames = ZOOM_FRAMES
        cam = sc.camera
        i = 0
        for _ in cam.iter_zoom(ZOOM_FACT, ZOOM_FRAMES):
            i += 1
            if i >= fstart:
                sc.render()
                if not annotate:
                    sc.save("fig_vr_" + header + "_" + string.zfill(cycle, 4) +
                            '_zoom_' + string.zfill(i, 4) + '.png',
                            sigma_clip=2)
                else:
                    sc.save_annotated("fig_vr_" + header + "_annotated_" +
                                      string.zfill(cycle, 4) + '_zoom_' +
                                      string.zfill(i, 4) + '.png',
                                      sigma_clip=4.0,
                                      text_annotate=[[
                                          (0.05, 0.95), text_string,
                                          dict(color="w",
                                               fontsize="20",
                                               horizontalalignment="left")
                                      ]])
        quit()

    return