コード例 #1
0
def export_to_fits(cli):
	
	#
	# Read in the model:
	#
	file = filename(cli, "plot")
	file += ".rtout"
	model = ModelOutput(file)
	
	
	#
	# Write fits file:
	#
	if(cli.mode == "images"):
		
		los = [0 for i in range(3)]
		los[0] = 'x'
		los[1] = 'y'
		los[2] = 'z'

		for k in range(0, 3):
			image = model.get_image(distance=1*pc, units='MJy/sr', inclination=0, component='total', group=k)
			Nwavelength=image.val.shape[2]
			for i in range(0, Nwavelength):
				file = filename(cli, "fits")
				file += "_wavelength=" + str(image.wav[i]) + "micron_los=" + los[k] + ".fits"
				fits.writeto(file, image.val[:, :, i], clobber=True)
				if(cli.verbose):
					print("  The fits file was written to", file)

	else:
		print("ERROR: The specified mode", mode, "is not available. Use 'images' only.")
コード例 #2
0
def plot_results(cli):
	
	file = filename(cli, "plot")
	file += ".rtout"
	
	#
	# Read in the model:
	#
	model = ModelOutput(file)
	
	if(cli.mode == "images"):
	
		#
		# Extract the quantities
		#
		g = model.get_quantities()
	
		#
		# Get the wall positions:
		#
		ww = g.w_wall / pc
		zw = g.z_wall / pc
		pw = g.p_wall
	
		grid_Nw = len(ww) - 1
		grid_Nz = len(zw) - 1
		grid_Np = len(pw) - 1
		
		#
		# Graphics:
		#
		fig = plt.figure()
	
		los = [0 for i in range(3)]
		los[0] = 'x'
		los[1] = 'y'
		los[2] = 'z'
	
		#Imaxp = [0 for i in range(4)]
		##Imaxp[0] = 1e-4
		#Imaxp[1] = 1e-5
		#Imaxp[2] = 1e-7
		#Imaxp[3] = 1e-8
	
		for k in range(0, 3):
			if(cli.verbose):
				print("Group: ", k)
		
			image = model.get_image(distance=1*pc, units='MJy/sr', inclination=0, component='total', group=k)
			source_emit = model.get_image(distance=1*pc, units='MJy/sr', inclination=0, component='source_emit', group=k)
			dust_emit   = model.get_image(distance=1*pc, units='MJy/sr', inclination=0, component='dust_emit'  , group=k)
			source_scat = model.get_image(distance=1*pc, units='MJy/sr', inclination=0, component='source_scat', group=k)
			dust_scat   = model.get_image(distance=1*pc, units='MJy/sr', inclination=0, component='dust_scat'  , group=k)
			
			if(cli.verbose):
				print(" Data cube: ", image.val.shape)
				print(" Wavelengths =", image.wav)
				print(" Uncertainties =", image.unc)
		
			image_Nx=image.val.shape[0]
			image_Ny=image.val.shape[1]
			Nwavelength=image.val.shape[2]

			if(cli.verbose):
				print(" Image Nx =", image_Nx)
				print(" Image Ny =", image_Ny)
				print(" Nwavelength =", Nwavelength)
			
			for i in range(0, Nwavelength):
				
				if(cli.verbose):
					print(" Image #", i,":")
					print("  Wavelength =", image.wav[i])
	
				Imin = np.min(image.val[:, :, i])
				Imax = np.max(image.val[:, :, i])
				# TODO: compute the mean value as well and use this for specifying the maximum value/color?!
		
				if(cli.verbose):
					print("  Intensity min =", Imin)
					print("  Intensity max =", Imax)
			
				#Imax=Imaxp[i]
	
				#ax = fig.add_subplot(2, 1, 2)
				ax = fig.add_subplot(1, 1, 1)
				if(image.wav[i] < 10.0):
					ax.imshow(source_scat.val[:, :, i] + dust_scat.val[:, :, i], vmin=Imin, vmax=Imax/10, cmap=plt.cm.gist_heat, origin='lower')
				else:
					ax.imshow(image.val[:, :, i], vmin=Imin, vmax=Imax/10, cmap=plt.cm.gist_heat, origin='lower')
				ax.set_xticks([0,100,200,300], minor=False)
				ax.set_yticks([0,100,200,300], minor=False)
				ax.set_xlabel('x (pixel)')
				ax.set_ylabel('y (pixel)')
				ax.set_title(str(image.wav[i]) + ' microns' + '\n' + los[k] + '-direction', y=0.88, x=0.5, color='white')
				
				#ax = fig.add_subplot(2, 1, 1)
				#ax.imshow([np.logspace(np.log10(Imin+1e-10),np.log10(Imax/10),100),np.logspace(np.log10(Imin+1e-10),np.log10(Imax/10),100)], vmin=Imin, vmax=Imax/10, cmap=plt.cm.gist_heat)
				#ax.set_xticks(np.logspace(np.log10(Imin+1e-10),np.log10(Imax/10),1), minor=False)
				##ax.set_xticks(np.linspace(np.log10(Imin+1e-10),np.log10(Imax/10),10), minor=False)
				#ax.set_yticks([], minor=False)
				#ax.set_xlabel('flux (MJy/sr)')
	
				file = filename(cli, "plot")
				file += "_wavelength=" + str(image.wav[i]) + "micron_los=" + los[k] + ".png"
	
				fig.savefig(file, bbox_inches='tight')
				if(cli.verbose):
					print("  The image graphics was written to", file)
				plt.clf()
	
	elif(cli.mode == "sed"):
	
		#
		# Graphics:
		#
		fig = plt.figure()

		z_center = [0 for i in range(3)]
		z_center[0] = '2.5'
		z_center[1] = '5.0'
		z_center[2] = '7.5'
		
		for k in range(0, 3):
			if(cli.verbose):
				print("Group: ", k)
				
			sed = model.get_sed(distance=1*pc, inclination=0, aperture=-1, group=k)
			
			ax = fig.add_subplot(1, 1, 1)
			ax.loglog(sed.wav, sed.val)
			ax.set_xlabel(r'$\lambda$ [$\mu$m]')
			ax.set_ylabel(r'$\lambda F_\lambda$ [ergs/s/cm$^2$]')
			ax.set_xlim(0.01, 2000.0)
			#ax.set_ylim(2.e-16, 2.e-9)
			
			file = filename(cli, "plot")
			file += "_z=" + z_center[k] + ".png"
			fig.savefig(file)
			if(cli.verbose):
				print(" The sed graphics was written to", file)
			plt.clf()
	
	else:
		print("ERROR: The specified mode", mode, "is not available. Use 'images' or 'sed' only.")
コード例 #3
0
ファイル: run_all.py プロジェクト: hyperion-rt/hyperion-trust
# Resolution in pc:
cli.resolution          = 100.0

# Photons per grid cell:
cli.photons_temperature = 1
cli.photons_raytracing  = 1
cli.photons_imaging     = 1

for cli.case in [1, 2]:
    for cli.opticaldepth in [0.256434, 1.28217, 6.41084]:
        for cli.mode in ["temperature", "images", "seds"]:
            
            # Setup step:
            setup_model(cli);
            
            # Compute step:
            file = filename(cli, cli.mode)
            model = Model.read(file+".rtin")
            model.write("temp.rtin")
            model.run(filename=file+".rtout", logfile=file+".hyout", overwrite=True)
            
            # Plotting step:
            #TODO: if(cli.mode == "temperature"): visualize_setup + visualize_results => plot_setup
            if(cli.mode != "temperature"):
                plot_results(cli);
            
            # Export to fits format:
            if(cli.mode == "images"):
                export_to_fits(cli);
コード例 #4
0
def setup_model(cli):
	
    lsun_TRUST = 3.839e33
        
    #
    # Hyperion setup:
    #
    model = Model()


    if(cli.mode == "temperature"):
        #
        # Dust properties:
        #
        dust_properties = SphericalDust('dust_integrated_full_scattering.hdf5')
            
            
        #
        # Write dust properties:
        #
        dust_properties.write('dust_properties.hdf5')
        dust_properties.plot('dust_properties.png')
        
        
        #
        # Specify galaxy setup:
        #
        hR                     =  4000.0*pc             # [cm]
        Rmax                   =     5.0*hR             # [cm]
        hz_oldstars            =   350.0*pc             # [cm]
        hz_youngstars          =   200.0*pc             # [cm]
        hz_dust                =   200.0*pc             # [cm]
        zmax_oldstars          =     5.0*hz_oldstars    # [cm]
        zmax_youngstars        =     5.0*hz_youngstars  # [cm]
        zmax_dust              =     5.0*hz_dust        # [cm]
        zmax                   =  zmax_oldstars         # [cm]
        reff                   =  1600.0*pc             # [cm]
        n                      =     3.0
        q                      =     0.6
        bn                     = 2.0*n - 1.0/3.0 + 4.0/405.0/n + 46.0/25515.0/n/n + 131.0/1148175.0/n/n/n
        temperature_oldstars   =  3500.0                # [K]
        temperature_youngstars = 10000.0                # [K]
        temperature_bulge      =  3500.0                # [K]
        luminosity_oldstars    =     4.0e+10*lsun_TRUST # [ergs/s]
        luminosity_youngstars  =     1.0e+10*lsun_TRUST # [ergs/s]
        luminosity_bulge       =     3.0e+10*lsun_TRUST # [ergs/s]
        
        w_oldstars             =     0.25
        w_youngstars           =     0.75
        w_dust                 =     0.75
        phi0_oldstars          =     0.0
        phi0_youngstars        =    20.0 * pi/180.0
        phi0_dust              =    20.0 * pi/180.0
        modes                  =     2
        pitchangle             =    20.0 * pi/180.0
        
        
        
        #
        # Grid setup:
        #
        grid_wmin =  0.0
        grid_wmax =  Rmax
        grid_zmin = -zmax
        grid_zmax = +zmax
        grid_pmin =  0.0
        grid_pmax =  2.0*pi
        
        grid_dx = cli.resolution*pc
        grid_dw = grid_dx # uniform resolution
        grid_dz = grid_dx # uniform resolution
        grid_dp = grid_dx # resolution at characteristic radial disk spatial scale hR = 4000.0 pc
        
        grid_Nw   = int((grid_wmax - grid_wmin) / grid_dw) + 1
        grid_Nz   = int((grid_zmax - grid_zmin) / grid_dz) + 1
        if(cli.case == 1):
            grid_Np = 1
        if(cli.case == 2):
            grid_Np = int((grid_pmax - grid_pmin) * hR / grid_dp)
        
        if(cli.verbose):
            print("Grid setup:")
            print(" Grid resolution =",cli.resolution, "pc.")
            print(" grid_Nw =",grid_Nw)
            print(" grid_Nz =",grid_Nz)
            print(" grid_Np =",grid_Np)
        
        #grid_w      = np.logspace(np.log10(grid_wmin), np.log10(grid_wmax), grid_Nw)
        #grid_w      = np.hstack([0., grid_w]) # add innermost cell interface at w=0
        grid_w    = np.linspace(grid_wmin, grid_wmax, grid_Nw+1)
        grid_z    = np.linspace(grid_zmin, grid_zmax, grid_Nz+1)
        grid_p    = np.linspace(grid_pmin, grid_pmax, grid_Np+1)
        
        model.set_cylindrical_polar_grid(grid_w, grid_z, grid_p)
        
        #
        # Dust density and sources setup:
        #
        rho_oldstars   = np.zeros(model.grid.shape)
        rho_youngstars = np.zeros(model.grid.shape)
        rho_bulge      = np.zeros(model.grid.shape)
        rho_dust       = np.zeros(model.grid.shape)
        
        for k in range(0, grid_Np):
            for j in range(0, grid_Nz):
                for i in range(0, grid_Nw):
                    
                    R = model.grid.gw[k,j,i]
                    z = model.grid.gz[k,j,i]
                    m = math.sqrt(R*R + z*z/q/q)
                    
                    rho_dust[k,j,i]       = math.exp(- R/hR -abs(z)/hz_dust      )
                    rho_oldstars[k,j,i]   = math.exp(- R/hR -abs(z)/hz_oldstars  )
                    rho_youngstars[k,j,i] = math.exp(- R/hR -abs(z)/hz_youngstars)
                    rho_bulge[k,j,i]      = math.pow(m/reff, 0.5/n - 1.0) * math.exp(- bn * math.pow(m/reff, 1.0/n))
                    
                    if(cli.case == 2):
                        phi = model.grid.gp[k,j,i]
                        perturb = math.sin(modes * (math.log(R/hR) / math.tan(pitchangle) - (phi - phi0_dust)))
                        rho_dust[k,j,i]       *= (1.0 + w_dust       * perturb)
                        perturb = math.sin(modes * (math.log(R/hR) / math.tan(pitchangle) - (phi - phi0_oldstars)))
                        rho_oldstars[k,j,i]   *= (1.0 + w_oldstars   * perturb)
                        perturb = math.sin(modes * (math.log(R/hR) / math.tan(pitchangle) - (phi - phi0_youngstars)))
                        rho_youngstars[k,j,i] *= (1.0 + w_youngstars * perturb)
        
        rho_dust[model.grid.gw > grid_wmax] = 0
        rho_dust[model.grid.gz < grid_zmin] = 0
        rho_dust[model.grid.gz > grid_zmax] = 0
        
        kappa_ref     = dust_properties.optical_properties.interp_chi_wav(0.55693)
        rho0          = cli.opticaldepth / (2.0 * hz_dust * kappa_ref)
        rho_dust[:]  *= rho0
        model.add_density_grid(rho_dust, 'dust_properties.hdf5')
        
        source_oldstars                = model.add_map_source()
        source_oldstars.luminosity     = luminosity_oldstars
        source_oldstars.temperature    = temperature_oldstars
        source_oldstars.map            = rho_oldstars
        
        source_youngstars              = model.add_map_source()
        source_youngstars.luminosity   = luminosity_youngstars
        source_youngstars.temperature  = temperature_youngstars
        source_youngstars.map          = rho_youngstars
        
        source_bulge                   = model.add_map_source()
        source_bulge.luminosity        = luminosity_bulge
        source_bulge.temperature       = temperature_bulge
        source_bulge.map               = rho_bulge
        
        
        #
        # Check face-on optical depth at 1.0 micron (per gram dust) through the dust disk:
        #
        tau   = 0
        
        k = 0
        i = 0
        for j in range(0, grid_Nz):
            #print(model.grid.gz[k,j,i]/pc, rho_dust[k,j,i])
            dz   = model.grid.widths[1,k,j,i]
            dtau = dz * rho_dust[k,j,i] * kappa_ref
            tau += dtau
        
        deviation = 100.0 * abs(cli.opticaldepth - tau) / cli.opticaldepth
        
        if(cli.verbose):
            print("Check optical depth of dust density setup:")
            print(" kappa(0.55693 micron) = ", kappa_ref, "cm^2 g^-1")
            print(" Numerical integration of the face-on optical depth at 0.55693 micron through the central dust disk yields tau = ", tau)
            print(" This corresponds to a deviation to the chosen setup value of", deviation, "percent")
    
        #
        # Check central dust density:
        #
        rho_max = np.max(rho_dust)
        if(cli.opticaldepth < 1.0):
            rho_setup = 1.04366e-4 * msun/pc/pc/pc
        if(cli.opticaldepth < 3.0):
            rho_setup = 5.21829e-4 * msun/pc/pc/pc
        else:
            rho_setup = 2.60915e-3 * msun/pc/pc/pc

        deviation = 100.0 * abs(rho_setup - rho_max) / rho_setup

        if(cli.verbose):
            print("Check value of central dust density:")
            print(" rho_max = ", rho_max, "g cm^-3")
            print(" This corresponds to a deviation to the chosen setup value of", deviation, "percent")

        #
        # To compute total photon numbers:
        #
        grid_N = grid_Nw * grid_Nz * grid_Np
        if(cli.verbose):
            print("Radiation setup:")
            print(" photons_temperature / cell =", cli.photons_temperature)
            print(" photons_temperature total  =", grid_N * cli.photons_temperature)

        file = filename(cli, "temperature")
        file += ".rtin"
    
    
    else:
        file = filename(cli, "temperature")
        file += ".rtout"
        
        try:
            with open(file):
                if(cli.verbose):
                    print("Using the specific energy distribution from file", file)
                model.use_geometry(file)
                model.use_quantities(file, only_initial=False, copy=False)
                model.use_sources(file)
            
        except IOError:
            print("ERROR: File '", file, "' cannot be found. \nERROR: This file, containing the specific energy density, has to be computed first via calling hyperion.")
            exit(2)
        
		#
		# To compute total photon numbers:
		#
        grid_Nw = len(model.grid.gw[0,0,:])
        grid_Nz = len(model.grid.gw[0,:,0])
        grid_Np = len(model.grid.gw[:,0,0])
        grid_N = grid_Nw * grid_Nz * grid_Np
        if(cli.verbose):
            print("Grid setup:")
            print(" grid_Nw =",grid_Nw)
            print(" grid_Nz =",grid_Nz)
            print(" grid_Np =",grid_Np)
            print("Radiation setup:")
            print(" photons_temperature / cell =", cli.photons_temperature)
            print(" photons_temperature total  =", grid_N * cli.photons_temperature)
            print(" photons_raytracing / cell  =", cli.photons_raytracing)
            print(" photons_raytracing total   =", grid_N * cli.photons_raytracing)
            print(" photons_imaging / cell     =", cli.photons_imaging)
            print(" photons_imaging total      =", grid_N * cli.photons_imaging)
        
        file = filename(cli, "")
        file += ".rtin"


    ##
    ## Temperature, Images, and SEDs:
    ##
    if(cli.mode == "temperature"):
    
        model.set_raytracing(True)
        model.set_n_photons(
            initial            = grid_N * cli.photons_temperature,
            raytracing_sources = grid_N * cli.photons_raytracing,
            raytracing_dust    = grid_N * cli.photons_raytracing,
            imaging            = grid_N * cli.photons_imaging
        )
        
    elif(cli.mode == "images"):
        
        model.set_n_initial_iterations(0)
        model.set_raytracing(True)
        # old setup: model.set_monochromatic(True, wavelengths=[0.4, 1.0, 10.0, 100.0, 500.0])
        model.set_monochromatic(True, wavelengths=[0.45483, 1.2520, 26.114, 242.29])
        model.set_n_photons(
            raytracing_sources = grid_N * cli.photons_raytracing,
            raytracing_dust    = grid_N * cli.photons_raytracing,
            imaging_sources    = grid_N * cli.photons_imaging,
            imaging_dust       = grid_N * cli.photons_imaging
        )
    
        # group = 0
        image1 = model.add_peeled_images(sed=False, image=True)
        image1.set_image_size(501, 501)
        image1.set_image_limits(-12500.0*pc, +12500.0*pc, -12500.0*pc, +12500.0*pc)
        image1.set_viewing_angles([30],[0])
        image1.set_uncertainties(True)
        image1.set_output_bytes(8)
        image1.set_track_origin('basic')
    
        # group = 1
        image2 = model.add_peeled_images(sed=False, image=True)
        image2.set_image_size(501, 501)
        image2.set_image_limits(-12500.0*pc, +12500.0*pc, -12500.0*pc, +12500.0*pc)
        image2.set_viewing_angles([80],[90])
        image2.set_uncertainties(True)
        image2.set_output_bytes(8)
        image2.set_track_origin('basic')
    
        # group = 2
        image3 = model.add_peeled_images(sed=False, image=True)
        image3.set_image_size(501, 501)
        image3.set_image_limits(-12500.0*pc, +12500.0*pc, -12500.0*pc, +12500.0*pc)
        image3.set_viewing_angles([88],[0]) # mostly edge-on
        image3.set_uncertainties(True)
        image3.set_output_bytes(8)
        image3.set_track_origin('basic')

    elif(cli.mode == "seds"):
        
        model.set_n_initial_iterations(0)
        model.set_raytracing(True)
        model.set_n_photons(
            raytracing_sources = grid_N * cli.photons_raytracing,
            raytracing_dust    = grid_N * cli.photons_raytracing,
            imaging            = grid_N * cli.photons_imaging
        )
    
        # group = 0
        sed1 = model.add_peeled_images(sed=True, image=False)
        sed1.set_wavelength_range(47, 0.081333, 1106.56)
        sed1.set_viewing_angles([30],[0])
        sed1.set_peeloff_origin((0, 0, 0))
        sed1.set_aperture_range(1, 25000.0*pc, 25000.0*pc)
        sed1.set_uncertainties(True)
        sed1.set_output_bytes(8)
        sed1.set_track_origin('basic')
        
        # group = 1
        sed2 = model.add_peeled_images(sed=True, image=False)
        sed2.set_wavelength_range(47, 0.081333, 1106.56)
        sed2.set_viewing_angles([80],[0])
        sed2.set_peeloff_origin((0, 0, 0))
        sed2.set_aperture_range(1, 25000.0*pc, 25000.0*pc)
        sed2.set_uncertainties(True)
        sed2.set_output_bytes(8)
        sed2.set_track_origin('basic')
    
        # group = 2
        sed3 = model.add_peeled_images(sed=True, image=False)
        sed3.set_wavelength_range(47, 0.081333, 1106.56)
        sed3.set_viewing_angles([88],[0])
        sed3.set_peeloff_origin((0, 0, 0))
        sed3.set_aperture_range(1, 25000.0*pc, 25000.0*pc)
        sed3.set_uncertainties(True)
        sed3.set_output_bytes(8)
        sed3.set_track_origin('basic')

    ##
    ## Write model for hyperion runs:
    ##
    model.conf.output.output_density         = 'last'
    model.conf.output.output_specific_energy = 'last'
    model.conf.output.output_n_photons       = 'last'
    model.write(file)
    if(cli.verbose):
        print("The input file for hyperion was written to", file)
コード例 #5
0
def setup_model(cli):

	#
	# Hyperion setup:
	#
	model = Model()


	if(cli.mode == "temperature"):
		#
		# Dust properties:
		#
		dust_properties = SphericalDust('dust_integrated_full_scattering.hdf5')


		#
		# Write dust properties:
		#
		dust_properties.write('dust_properties.hdf5')
		dust_properties.plot('dust_properties.png')

	
		#
		# Grid setup:
		#
		grid_wmin =  0
		grid_wmax =  5.0*pc # 4.0*pc
		grid_zmin =  0.0*pc
		grid_zmax = 10.0*pc
		grid_pmin =  0
		grid_pmax =  2*pi

		grid_dx = cli.resolution*pc
		grid_dw = grid_dx # uniform resolution
		grid_dz = grid_dx # uniform resolution
		grid_dp = grid_dx # resolution at filament location at r = 1 pc

		grid_Nw   = int((grid_wmax - grid_wmin) / grid_dw)
		grid_Nz   = int((grid_zmax - grid_zmin) / grid_dz)
		grid_Np   = int(2*pi * 1.0*pc / grid_dp)

		if(cli.verbose):
			print("Grid setup:")
			print(" Grid resolution =",cli.resolution, "pc.")
			print(" grid_Nw =",grid_Nw)
			print(" grid_Nz =",grid_Nz)
			print(" grid_Np =",grid_Np)

		#grid_w      = np.logspace(np.log10(grid_wmin), np.log10(grid_wmax), grid_Nw)
		#grid_w      = np.hstack([0., grid_w]) # add innermost cell interface at w=0
		grid_w    = np.linspace(grid_wmin, grid_wmax, grid_Nw+1)
		grid_z    = np.linspace(grid_zmin, grid_zmax, grid_Nz+1)
		grid_p    = np.linspace(grid_pmin, grid_pmax, grid_Np+1)

		model.set_cylindrical_polar_grid(grid_w, grid_z, grid_p)

		#
		# Dust density setup:
		#
		RC  = 0.1*pc
		nC  = 6.6580e+03       # in cm^-3
		nC *= cli.opticaldepth # the optical depth at 1 micron
		nC *= m_h              # in g cm^-3
		nC /= 100.0            # converts from gas to dust density
	
		rho = np.zeros(model.grid.shape)
	
		#
		# n(r) = nC / [ 1.0 + (r/RC)**2.0 ]
		# x = -sin(2.0×pi×t) pc, y = +cos(2.0×pi×t) pc, z = 10.0×t pc, t = [0.0, 1.0]
		#  => t = m.grid.gz / (10*pc)
		#  => phi(t) = mod(360*t+270, 360)
		#
		for k in range(0, grid_Np):
			for j in range(0, grid_Nz):
				for i in range(0, grid_Nw):
				
					t = model.grid.gz[k,j,i] / (10*pc)
				
					if(cli.filament == "linear"):
						filament_center_x  = 0
						filament_center_y  = 0
					elif(cli.filament == "spiraling"):
						filament_center_x  = - math.sin(2*pi*t)*pc
						filament_center_y  = + math.cos(2*pi*t)*pc
				
					spherical_grid_r   = model.grid.gw[k,j,i]
					spherical_grid_phi = model.grid.gp[k,j,i]
				
					cartesian_grid_x   = spherical_grid_r * math.cos(spherical_grid_phi)
					cartesian_grid_y   = spherical_grid_r * math.sin(spherical_grid_phi)
				
					rsquared = (
								(cartesian_grid_x - filament_center_x)**2
								+
								(cartesian_grid_y - filament_center_y)**2
								)
				
					rho[k,j,i] = nC / (1.0 + (rsquared / (RC*RC)))
				
					if rsquared**0.5 > 3*pc:
						rho[k,j,i] = 0

		rho[model.grid.gw > grid_wmax] = 0
		rho[model.grid.gz < grid_zmin] = 0
		rho[model.grid.gz > grid_zmax] = 0

		model.add_density_grid(rho, 'dust_properties.hdf5')


		#
		# Check optical depth through the filament:
		#
		#  (y,z = 0, 2.5 pc goes through the filament center in all setups)
		
		#
		# Determine index of closest grid cell to z = 2.5 pc:
		#
		dz_last = 2*abs(grid_zmax-grid_zmin)
		for j in range(0, grid_Nz):
			dz = abs(model.grid.gz[0,j,0] - 2.5*pc)
			if(dz > dz_last):
				j=j-1
				break
			else:
				dz_last = dz

		#
		# Opacity at 1.0 micron (per gram dust):
		#
		chi = dust_properties.optical_properties.interp_chi_wav(1.0)

		tau_max = 0
		for k in range(0, grid_Np):
			tau = 0
			for i in range(0, grid_Nw):
				dr = model.grid.widths[0,k,j,i]
				dtau = dr * rho[k,j,i] * chi
				tau += dtau
			tau_max = max(tau_max, tau)

		if(cli.filament == "linear"):
			tau_max *= 2

		dev = 100 * abs(cli.opticaldepth - tau_max) / cli.opticaldepth

		if(cli.verbose):
			print("Check:")
			print(" Numerical integration of the optical depth through the filament center yields tau = ", tau_max)
			print(" This corresponds to a deviation to the chosen setup value of", dev, "percent")


		#
		# Source:
		#
		if(cli.sources == "external"):
		
			nu, jnu            = np.loadtxt('bg_intensity_modified.txt', unpack=True)
			source_R           = 5*pc
			source             = model.add_external_spherical_source()
			source.peeloff     = False
			source.position    = (0, 0, 5.0*pc) # in a Cartesian frame
			source.radius      = source_R
			source.spectrum    = (nu, jnu)
			#source_MeanIntensity_J = <integrate bg_intensity.txt>
			#source_Area        = 4.0 * pi * source_R*source_R
			source.luminosity  = 8237.0*lsun #source_Area * pi * source_MeanIntensity_J
		
		elif(cli.sources == "stellar"):

			source             = model.add_point_source()
			source.luminosity  = 3.839e35 # in ergs s^-1
			source.temperature = 10000.0 # in K
			if(cli.filament == "linear"):
				source.position    = (3.0*pc, 0, 5.0*pc)
			elif(cli.filament == "spiraling"):
				source.position    = (0     , 0, 3.0*pc)

		#
		# To compute total photon numbers:
		#
		grid_N = grid_Nw * grid_Nz * grid_Np
		if(cli.verbose):
			print("Radiation setup:")
			print(" photons_temperature / cell =", cli.photons_temperature)
			print(" photons_temperature total  =", grid_N * cli.photons_temperature)

		file = filename(cli, "temperature")
		file += ".rtin"

	else:
		file = filename(cli, "temperature")
		file += ".rtout"
	
		try:
			with open(file):
				if(cli.verbose):
					print("Using the specific energy distribution from file", file)
				model.use_geometry(file)
				model.use_quantities(file, only_initial=False, copy=False)
				model.use_sources(file)

		except IOError:
			print("ERROR: File '", file, "' cannot be found. \nERROR: This file, containing the specific energy density, has to be computed first via calling hyperion.")
			exit(2)

		#
		# To compute total photon numbers:
		#
		grid_Nw = len(model.grid.gw[0,0,:])
		grid_Nz = len(model.grid.gw[0,:,0])
		grid_Np = len(model.grid.gw[:,0,0])
		grid_N = grid_Nw * grid_Nz * grid_Np
		if(cli.verbose):
			print("Grid setup:")
			print(" grid_Nw =",grid_Nw)
			print(" grid_Nz =",grid_Nz)
			print(" grid_Np =",grid_Np)
			print("Radiation setup:")
			print(" photons_temperature / cell =", cli.photons_temperature)
			print(" photons_temperature total  =", grid_N * cli.photons_temperature)
			print(" photons_raytracing / cell  =", cli.photons_raytracing)
			print(" photons_raytracing total   =", grid_N * cli.photons_raytracing)
			print(" photons_imaging / cell     =", cli.photons_imaging)
			print(" photons_imaging total      =", grid_N * cli.photons_imaging)

		file = filename(cli, "")
		file += ".rtin"


	##
	## Temperature, Images, and SEDs:
	##
	if(cli.mode == "temperature"):

		model.set_raytracing(True)
		model.set_n_photons(
						initial            = grid_N * cli.photons_temperature,
						raytracing_sources = grid_N * cli.photons_raytracing,
						raytracing_dust    = grid_N * cli.photons_raytracing,
						imaging            = grid_N * cli.photons_imaging
						)
	
	elif(cli.mode == "images"):
	
		model.set_n_initial_iterations(0)
		model.set_raytracing(True)
		model.set_monochromatic(True, wavelengths=[100.0, 500.0, 0.55, 2.2])
		model.set_n_photons(
						raytracing_sources = grid_N * cli.photons_raytracing,
						raytracing_dust    = grid_N * cli.photons_raytracing,
						imaging_sources    = grid_N * cli.photons_imaging,
						imaging_dust       = grid_N * cli.photons_imaging
						)
	
		# group = 0
		image1x = model.add_peeled_images(sed=False, image=True)
		image1x.set_image_size(300, 300)
		image1x.set_image_limits(-5*pc, +5*pc, 0, 10*pc)
		image1x.set_viewing_angles([90],[0]) # along the x-direction
		image1x.set_uncertainties(True)
		image1x.set_output_bytes(8)
		image1x.set_track_origin('basic')
	
		# group = 1
		image1y = model.add_peeled_images(sed=False, image=True)
		image1y.set_image_size(300, 300)
		image1y.set_image_limits(-5*pc, +5*pc, 0, 10*pc)
		image1y.set_viewing_angles([90],[90]) # along the y-direction
		image1y.set_uncertainties(True)
		image1y.set_output_bytes(8)
		image1y.set_track_origin('basic')
	
		# group = 2
		image1z = model.add_peeled_images(sed=False, image=True)
		image1z.set_image_size(300, 300)
		image1z.set_image_limits(-5*pc, +5*pc, -5*pc, +5*pc)
		image1z.set_viewing_angles([0],[0]) # along the z-direction
		image1z.set_uncertainties(True)
		image1z.set_output_bytes(8)
		image1z.set_track_origin('basic')

	elif(cli.mode == "sed"):
	
		model.set_n_initial_iterations(0)
		model.set_raytracing(True)
		model.set_n_photons(
							raytracing_sources = grid_N * cli.photons_raytracing,
							raytracing_dust    = grid_N * cli.photons_raytracing,
							imaging            = grid_N * cli.photons_imaging
							)
	
		# group = 0
		sed1 = model.add_peeled_images(sed=True, image=False)
		sed1.set_wavelength_range(250, 0.01, 2000.0)
		sed1.set_viewing_angles([90],[0]) # along the x-direction
		sed1.set_peeloff_origin((0, 0, 2.5*pc))
		sed1.set_aperture_range(1, 0.3*pc, 0.3*pc)
		sed1.set_uncertainties(True)
		sed1.set_output_bytes(8)
		sed1.set_track_origin('basic')

		# group = 1
		sed2 = model.add_peeled_images(sed=True, image=False)
		sed2.set_wavelength_range(250, 0.01, 2000.0)
		sed2.set_viewing_angles([90],[0]) # along the x-direction
		sed2.set_peeloff_origin((0, 0, 5.0*pc))
		sed2.set_aperture_range(1, 0.3*pc, 0.3*pc)
		sed2.set_uncertainties(True)
		sed2.set_output_bytes(8)
		sed2.set_track_origin('basic')

		# group = 2
		sed3 = model.add_peeled_images(sed=True, image=False)
		sed3.set_wavelength_range(250, 0.01, 2000.0)
		sed3.set_viewing_angles([90],[0]) # along the x-direction
		sed3.set_peeloff_origin((0, 0, 7.5*pc))
		sed3.set_aperture_range(1, 0.3*pc, 0.3*pc)
		sed3.set_uncertainties(True)
		sed3.set_output_bytes(8)
		sed3.set_track_origin('basic')

	##
	## Write model for hyperion runs:
	##
	model.conf.output.output_density         = 'last'
	model.conf.output.output_specific_energy = 'last'
	model.conf.output.output_n_photons       = 'last'
	model.write(file)
	if(cli.verbose):
		print("The input file for hyperion was written to", file)
コード例 #6
0
def plot_results(cli):
    
    file = filename(cli, "plot")
    file += ".rtout"
    
    #
    # Read in the model:
    #
    model = ModelOutput(file)
    
    los = [0 for k in range(3)]
    los[0] = '30degree'
    los[1] = '80degree'
    los[2] = '88degree'
    
    
    if(cli.mode == "images"):
        
        #
        # Extract the quantities
        #
        g = model.get_quantities()
        
        #
        # Get the wall positions:
        #
        ww = g.w_wall / pc
        zw = g.z_wall / pc
        pw = g.p_wall
        
        grid_Nw = len(ww) - 1
        grid_Nz = len(zw) - 1
        grid_Np = len(pw) - 1
        
        #
        # Graphics:
        #
        fig = plt.figure()
        
        Imaxp = [0 for i in range(5)]
        Imaxp[0] = 1e-15 # in W/cm^2
        Imaxp[1] = 1e-14 # in W/cm^2
        Imaxp[2] = 1e-15 # in W/cm^2
        Imaxp[3] = 1e-15 # in W/cm^2
        Imaxp[4] = 1e-18 # in W/cm^2
        
        for k in range(0, 3):
            if(cli.verbose):
                print("Group: ", k)
            
            image = model.get_image(distance=1e+7*pc, units='ergs/cm^2/s', inclination=0, component='total', group=k)
            #source_emit = model.get_image(distance=1e+7*pc, units='MJy/sr', inclination=0, component='source_emit', group=k)
            #dust_emit   = model.get_image(distance=1e+7*pc, units='MJy/sr', inclination=0, component='dust_emit'  , group=k)
            #source_scat = model.get_image(distance=1e+7*pc, units='MJy/sr', inclination=0, component='source_scat', group=k)
            #dust_scat   = model.get_image(distance=1e+7*pc, units='MJy/sr', inclination=0, component='dust_scat'  , group=k)
            
            if(cli.verbose):
                print(" Data cube: ", image.val.shape)
                print(" Wavelengths =", image.wav)
                print(" Uncertainties =", image.unc)
            
            image_Nx=image.val.shape[0]
            image_Ny=image.val.shape[1]
            Nwavelength=image.val.shape[2]
            
            if(cli.verbose):
                print(" Image Nx =", image_Nx)
                print(" Image Ny =", image_Ny)
                print(" Nwavelength =", Nwavelength)
            
            for i in range(0, Nwavelength):
                
                if(cli.verbose):
                    print(" Image #", i,":")
                    print("  Wavelength =", image.wav[i])
                
                image.val[:, :, i] *= 1e-4 # in W/m^2
                
                #Imin = np.min(image.val[:, :, i])
                #Imax = np.max(image.val[:, :, i])
                #Imax = Imaxp[i]
                #Imin = Imax/1e+20
                Imax = np.max(image.val[:, :, i])/5
                Imin = 0.0
                
                if(cli.verbose):
                    print("  Intensity min data values =", np.min(image.val[:, :, i]))
                    print("  Intensity max data values =", np.max(image.val[:, :, i]))
                    print("  Intensity min color-table =", Imin)
                    print("  Intensity max color-table =", Imax)
                
                #ax = fig.add_subplot(2, 1, 2)
                ax = fig.add_subplot(1, 1, 1)
                # 'hot', see http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps
                ax.imshow(image.val[:, :, i], vmin=Imin, vmax=Imax, cmap=plt.cm.hot, origin='lower')
                ax.set_xticks([0,100,200,300,400,500], minor=False)
                ax.set_yticks([0,100,200,300,400,500], minor=False)
                ax.set_xlabel('x (pixel)')
                ax.set_ylabel('y (pixel)')
                ax.set_title(str(image.wav[i]) + ' microns' + '\n' + los[k], y=0.88, x=0.5, color='white')
                
                #ax = fig.add_subplot(2, 1, 1)
                #ax.imshow([np.logspace(np.log10(Imin+1e-10),np.log10(Imax/10),100),np.logspace(np.log10(Imin+1e-10),np.log10(Imax/10),100)], vmin=Imin, vmax=Imax/10, cmap=plt.cm.gist_heat)
                #ax.set_xticks(np.logspace(np.log10(Imin+1e-10),np.log10(Imax/10),1), minor=False)
                ##ax.set_xticks(np.linspace(np.log10(Imin+1e-10),np.log10(Imax/10),10), minor=False)
                #ax.set_yticks([], minor=False)
                #ax.set_xlabel('flux (MJy/sr)')
                
                #x = plt.colorbar()
                #print(x)
                
                file = filename(cli, "plot")
                file += "_wavelength=" + str(image.wav[i]) + "micron_los=" + los[k] + ".png"
                
                fig.savefig(file, bbox_inches='tight')
                if(cli.verbose):
                    print("  The image graphics was written to", file)
                plt.clf()
    
    elif(cli.mode == "seds"):
        
        #
        # Graphics:
        #
        fig = plt.figure()
        
        for k in range(0, 3):
            if(cli.verbose):
                print("Group: ", k)
            
            sed = model.get_sed(distance=1e+7*pc, inclination=0, aperture=-1, group=k)
            #units='ergs/cm^2/s' # = default, if distance is specified
            ax = fig.add_subplot(1, 1, 1)
            ax.loglog(sed.wav, sed.val)
            ax.set_xlabel(r'$\lambda$ [$\mu$m]')
            ax.set_ylabel(r'$\lambda F_\lambda$ [ergs/s/cm$^2$]')
            ax.set_xlim(0.09, 1000.0)
            ax.set_ylim(1.e-13, 1.e-7)
            
            file = filename(cli, "plot")
            file += "_los=" + los[k] + ".png"
            fig.savefig(file)
            if(cli.verbose):
                print(" The sed graphics was written to", file)
            plt.clf()
        
        #
        # Data files:
        #
        for k in range(0, 3):
            sed = model.get_sed(distance=1e+7*pc, inclination=0, aperture=-1, group=k)
            file = filename(cli, "plot")
            file += "_los=" + los[k] + ".dat"
            sedtable = open(file, 'w')
            sedtable.write("# wavelength [micron] - flux [erg cm^-2 s^-1]\n")
            for lp in range(0, len(sed.wav)):
                l = len(sed.wav)-lp-1
                line = str("%.4e" % sed.wav[l]) + " " + str("%.4e" % sed.val[l]) + "\n"
                sedtable.write(line)
            sedtable.close()

    else:
        print("ERROR: The specified mode", mode, "is not available. Use 'images' or 'seds' only.")