ramtools package

Submodules

ramtools.amr2cube module

ramtools.amr2cube.amr2cube(diri, center, width, lma, fo_fmt='amr2cube/{field}.dat', fields=['den', 'xHII'], is_redo=True)

Run amr2cube for a given output with given parameters

Parameters
  • diri – (str) input output directory

  • diro – (str) output data directory

  • center – (str or list_like) the domain center, in boxlen unit. ‘c’ means (.5, .5, .5)

  • width – (float) domain width in boxlen unit

  • lma – (int) max level

Returns:

ramtools.cacherun module

Run YT functions with cache support so that when a function is run a second time, a cache from the first run is used to return the results immediately.

Adapted from Sam Geen’s HamuLite.py which describes as ‘MODIFIED FROM Algorithm.py IN HAMU TO WORK INDEPENDENTLY OF THE HAMU FRAMEWORK’

Original script: https://github.com/samgeen/mcrtscripts/blob/master/scripts/HamuLite.py

class ramtools.cacherun.CacheFile(ds, algorithm)

Bases: object

Exists()

Does the cache file exist?

Load()
Save(data)
class ramtools.cacherun.CacheRun(function, force_replace_cache=False)

Bases: object

A wrapper class around a function that enables us to run functions and store their outputs for later use

Usage (new): >>> def get_max_pos(ds, field): >>> return ds.all_data().argmax(field) >>> CacheRun(get_max_pos)(ds, (‘gas’, ‘density’))

Usage (old): >>> ds = RamsesSnapshot(“tests/Job2”, 40) >>> def get_max_pos(ds, field): >>> return ds.all_data().argmax(field) >>> CacheRun(get_max_pos)(ds, (‘gas’, ‘density’))

CacheFilename(ext='data')

Return the name of this algorithm’s cache file Uses a hash function to hash the arguments of the function ext - File extension (used for writing multiple cache files; default is “.data”)

ForceReplaceCache(on=True)
FunctionName()

Return the function’s name

Run(ds, *args, **kwargs)

Run for a single snapshot

ramtools.cacherun.get_jobdir_and_out_from_ds(ds)

Given ds, which has ds.directory = ‘/path/Job1/output_00002’, return /path/Job1 and output_00002

ramtools.cacherun.turn_off_logging()
ramtools.cacherun.turn_on_global_force_replace_cache()

ramtools.cacherun_v1 module

Run YT functions with cache support so that when a function is run a second time, a cache from the first run is used to return the results immediately.

Adapted from Sam Geen’s HamuLite.py which describes as ‘MODIFIED FROM Algorithm.py IN HAMU TO WORK INDEPENDENTLY OF THE HAMU FRAMEWORK’

Original script: https://github.com/samgeen/mcrtscripts/blob/master/scripts/HamuLite.py

class ramtools.cacherun_v1.CacheFile(snapshot, algorithm)

Bases: object

Exists()

Does the cache file exist?

Load()
Save(data)
class ramtools.cacherun_v1.CacheRun(function)

Bases: object

A wrapper class around a function that enables us to run functions and store their outputs for later use

Usage: >>> ds = RamsesSnapshot(“tests/Job2”, 40) >>> def get_max_pos(ds, field): >>> return ds.all_data().argmax(field) >>> CacheRun(get_max_pos)(ds, (‘gas’, ‘density’))

CacheFilename(ext='data')

Return the name of this algorithm’s cache file Uses a hash function to hash the arguments of the function ext - File extension (used for writing multiple cache files; default is “.data”)

Cached(snap, *args, **kwargs)

Check that the cache for this data exists

ForceReplaceCache(on=True)
FunctionName()

Return the function’s name

Run(snap, *args, **kwargs)

Run for a single snapshot

class ramtools.cacherun_v1.RamsesSnapshot(folder, outnum, name=None)

Bases: object

CachePath()
ramtools.cacherun_v1.turn_on_global_force_replace_cache()

ramtools.cacherunbase module

A general protocal for storing function result in cache files

What is does: The first time you run CacheRun, the result is stored in a file using pickle and is named after a unique hash string based on (1) the path of the Python file you are running, (2) the function name, and (3) the parameters passed to the function. The second time you run CacheRun with the same hash, the previously stored data is loaded and returned.

Example: >>> def func(x, y=1): >>> return x + y >>> CacheRun(func, os.path.abspath(__file__))(10, y=2) >>> CacheRun(func, os.path.abspath(__file__))(10, y=2)

class ramtools.cacherunbase.CacheFile(folder, algorithm)

Bases: object

Exists()

Does the cache file exist?

Load()
Save(data)
class ramtools.cacherunbase.CacheRun(function, filename='global', force_replace_cache=False, flag='')

Bases: object

CacheFilename(ext='data')

Return the name of this algorithm’s cache file Uses a hash function to hash the arguments of the function ext - File extension (used for writing multiple cache files; default is “.data”)

ForceReplaceCache(on=True)
Run(*args, **kwargs)

Run for a single snapshot

ramtools.cacherunbase.turn_on_global_force_replace_cache()

ramtools.center module

center.py Define gloable variables for the RAMSES project.

Author: chongchonghe

ramtools.center.get_density(jobid)
ramtools.center.get_tff(jobid)

ramtools.center2 module

Use center.py. Jan 21, 2019 #Replacing center.py

@author: chongchonghe

ramtools.cloudparams module

Calculate some parameters of a cloud at given snapshot(s).

ramtools.cloudparams.check_pot_ene()
ramtools.cloudparams.describe_cloud(jobfolder, out, variables, filter)

Describe the parameters of a cloud at a given snapshot

Parameters
  • jobfolder

  • out

  • variables (list of strings) – a list of variables to calculate

  • filter – gas region filter

Returns

A dictionary of all parameters

ramtools.cloudparams.describe_cloud2(jobfolder, out, variables, slicepath, fo=None)

Describe the parameters of a cloud at a given snapshot

Parameters
  • jobfolder

  • out

  • variables (list of strings) – a list of variables to calculate

  • fo (str) – name of the output json file

  • dataset – YT dataset, e.g. ds.all_data()

  • filter – cut_region filter

  • pot_ref

  • pot_test_width

Returns

None

ramtools.cloudparams.get_cloud_value(ds, var, dataset=None, filter=None, pot_ref='center', pot_test_width=0.000244140625)

Return the sum of a given quantity (e.g. the total mass.) over a region defined by filter of a given cloud (identified by ds).

Parameters
  • ds – yt.ds, instance of ds.load(…)

  • var – the variable name, one of totmass, totvolume, kin_ene, th_ene, mag_ene, pot_ene.

  • dataset – (optional) the dataset, e.g. ds.sphere(…)

  • filter – (string) filter to the dataset

  • pot_ref – the reference point of calculating potential energy. Refer to the code

  • pot_test_width – Refer to the code.

Returns

YT float.

ramtools.cloudvals module

ramtools.dynamics module

class ramtools.dynamics.Dyn(jobdir=None, jobid=None, ram_dir=None, fields=['Density', 'x-velocity', 'y-velocity', 'z-velocity', 'x-Bfield-left', 'y-Bfield-left', 'z-Bfield-left', 'x-Bfield-right', 'y-Bfield-right', 'z-Bfield-right', 'Pressure', 'xHII', 'xHeII', 'xHeIII'])

Bases: ramtools.ramses.Ramses

read_sink_as_msun_au(fname)

Read sink_x.csv as the following unit system (and move to com): [M] = 1 Msun [L] = 1 AU [T] = sqrt(AU**3*(1/(G*Msun))) = 5022642.892 s = 0.1591579490 yr [V] = [L]/[T] = 29.78469183 km / s

time, id, mass, x, y, z, vx, vy, vz

ramtools.imf module

imf.py

Author: Chong-Chong He (che1234@umd.edu) Written on Sat, 4 Apr 2020.

class ramtools.imf.Sink(jobdir=None, jobid=None, ram_dir=None, fields=['Density', 'x-velocity', 'y-velocity', 'z-velocity', 'x-Bfield-left', 'y-Bfield-left', 'z-Bfield-left', 'x-Bfield-right', 'y-Bfield-right', 'z-Bfield-right', 'Pressure', 'xHII', 'xHeII', 'xHeIII'])

Bases: ramtools.ramses.Ramses

Read sink info from outputs, make plots of SFE, sink number, and IMF

MassFunc(ax=None, bins='auto', outputID=None, tff=None, is_x_log_number=False, is_plot_kroupa=False, isFill=False, newsink=False, label=None, plotstyle={})

Plot the mass function kwargs could be: refPoint = [x_start, x_end], bin_max, bin_min, nbins, xlim, ylim, (ALL IN DEX), isDisplayMSM(bool)

is_x_log_number: If True, plot x as x = log10(masses).

display_summary(ax=None, **kwargs)

Summary of SFE

find_SF_length(sink_masses)
find_SNs(lastoutput=None, mSN=8.0)

Return the raw time (in Myr) of all SN explosions !!! Apply to the version of RAMSES where all stars never die.

Returns

  • time ({list}, the time of all SNe explosions, not necessary on)

  • output snapshots, before the lastoutput, when the first SN

  • explode

  • i (the outputID when the first SN explode)

  • Exeptions

  • -1, 0

find_first_SN(mSN=8.0)
Returns

  • i (the output of the first SN. If no SN found, return -1)

  • time (the time (in Myr) of the first SN (not - tRelax))

imf_fit(outputID=None)
imf_summary(ax, outputID=None, pos=None, **kwargs)

Write the mean sink mass at the top right corner

imf_summary_text(outputID=None)

Return the texts of the mean sink mass

metal_yield(outputID=None)
num_of_SN(outputID=None)
overplot_kroupa(ax, m_sum, m_min=0.08, m_max=100, textxy=None, ls='--', isxloged=False, scale=1.0, **kwargs)

over plot a Kroupa IMF curve. parameters are in log scale Normalized to total stellar mass

Notes

self is useless. I put INTERP here for INTERP to be copied in the Sink class

plot_IMF(ax, out=None, bins='auto', is_over_dlogm=False, **kwargs)

Plot MF of an output. Tag with time, out id, m_tot, and N

Parameters
  • ax (plot axis) – description

  • out (int) – output number. Default: self.get_last_output()

  • bins (str or list/array) – description

  • is_over_dlogm (bool) – False: y = dN. True: y = dN/dlogm

  • kwargs**kwargs for plot_imf()

plot_SFE(ax=None, label=None, color=None, yscale='log', ylim=None, is_disp_SN=True, **kwargs)

Plot a single SFE curve.

plot_SFE_and_MSM(ax=None, hold=False, isDisplayLegend=False, **kwargs)
plot_imf_one_grid_single_line(ax, outputid, color='k', ylim=None, mass_shift=0.4, is_plot_kroupa=False, is_title=True, is_text=False, is_met=False, is_text_cloud_param=True, **kwargs)

Plot one single line of the IMF.

Plot one single line of the IMF., optionally add a Kroupa line, set title, and add text.

Parameters
  • is_text (bool) – Control if or not to add texts at topleft (gas mass and den) and topright corner.

  • is_met (bool) – Only when is_text = True. Control if or not only add text at topright corner.

quick_plot_IMF(ax=None, out=None, masses=None, bin_width=None, bins=None, is_over_dlogm=False, shift=None, time0=0, is_kroupa=False, kroupa_kwargs={}, **kwargs)
sfe_time_length()
ramtools.imf.bayes_get_param(masses, thresh)

Given star masses and the percentile cummanative mass fraction to fit with, return the bayes parameters and the mass cut

ramtools.imf.bayesian_imf_fit(mass, m1, m2)

Do a Bayesian fitting to mass with a power-law slope at -alpha in range m1 to m2. Return alpha. mass is the shifted sink mass.

Parameters
  • mass ([array], all the masses to fit with) –

  • m1 (fitting range) –

  • m2 (fitting range) –

Returns

Return type

(A, a_peak, a_peak_minus, a_peak_plus)

ramtools.imf.bayesian_imf_fit_new(mass, m1, m2=None)

Based on and replacing bayesian_imf_fit. Now the mass fed in could be all the masses in a simulation. Masses outside of [m1, m2] will be cut out.

ramtools.imf.chabrier05(m)

The Chabrier 2015 single-star IMF. Reference: Eq. 3 of Krumholz:2014. The value of mc is missing. Refer to the original paper: Chabrier:2015

Return float

dndlogm

ramtools.imf.chabrier05_logm(logm)
Returns

float: dndlogm

ramtools.imf.chabrier2003(logm)

The chabrier 2003 system IMF

ramtools.imf.find_sigma(logl, alpha, deltalogl=- 0.5)

Return the most probable alpha and 1 sigam region of alpha, given the log likelihood logl.

Returns

alpha_max, alpha_minus, alpha_plus

ramtools.imf.get_bins(mass, maxBins=None, m_min=0.1)

Get the bins for IMF. Apply on shifted mass

ramtools.imf.get_bins_fixed()
ramtools.imf.imf(mass, ax=None, **kwargs)
ramtools.imf.imf_compare(m1, m2, ax, c1=None, c2=None, groups1=None, groups2=None)

Compare two MFs in a top-bottom view.

Parameters
  • m1 – (array )

  • m2 – (array )

  • ax – plt axis

  • c1 – color for m1 (default None)

  • c2 – color for m2 (default None)

  • groups1 – (list of lists) particle groups for m1 (default None)

  • groups2 – (list of lists) particle groups for m2 (default None)

Returns

f, ax

ramtools.imf.kroupa(m)
ramtools.imf.kroupa_int_two_side(a, b, alpha1, alpha2)

Sample Kroupa IMF. The coefficient is set by assuming alpha1 = 0.3, and alpha2 = 1.3

ramtools.imf.likeli(m1, m2, alpha, mu)

Return the log likelihood. mu = np.log10(mass) is all masses.

ramtools.imf.lognormal(logm)

A lognormal IMF. The default parameters correspond to the Chabrier IMF

ramtools.imf.mass_vertical_line(ax, masses, thresh, color='k')

add mass divider. Apply to masses directly (will not shift the mass)

ramtools.imf.overplot_kroupa_new(self, ax, m_sum, m_min=0.08, m_max=100, textxy=None, ls='--', isxloged=False, scale=1.0, **kwargs)

over plot a Kroupa IMF curve. parameters are in log scale Normalized to total stellar mass

Notes

self is useless. I put INTERP here for INTERP to be copied in the Sink class

ramtools.imf.overplot_kroupa_new2(self, ax, m_sum, m_min=0.08, m_max=None, textxy=None, ls='--', isxloged=False, scale=1.0, **kwargs)

over plot a Kroupa IMF curve. parameters are in log scale Normalized to total stellar mass

Notes

self is useless. I put INTERP here for INTERP to be copied in the Sink class

ramtools.imf.overplot_salpeter(ax, m_sum, m_min=0.08, m_max=100, textxy=None, **kwargs)

Overplot a Salpeter line. textxy=[textx, texty] in log scale

ramtools.imf.pick_kroupa(a, b, rand=None)

Pick a Kropam sampling rand is set for faster sampling based on numpy arrays.

ramtools.imf.pick_salpeter(a, b, alpha=2.35, rand=None)

For salpeter, rand is set for faster sampling based on numpy arrays.

ramtools.imf.plot_bayes_fit(ax, masses, thresh, color='g')
ramtools.imf.plot_bayes_fit_any_width(ax, masses, thresh, yscaleup=1, color='g', is_xlog=False)

plot a bayes fit on top of a IMF

ramtools.imf.plot_chab03(ax, msum, m_min=0.1, m_max=100, **kwargs)
ramtools.imf.plot_chab05(ax, msum, m_min=0.1, m_max=100, isxloged=0, **kwargs)
ramtools.imf.plot_imf(ax, mass, bins=None, xlim=[- 2, 2], ylim=[0.7, 330.0], is_over_dlogm=True, is_text=True, **kwargs)

Plot the mass spectrum of mass on ax. x: mass bins; y: d N / d log10(m)

ramtools.imf.plot_imf_N_vs_m(ax, m, color='k', istext=True, bin_width=None, bins=None)

Given m, plot the mass function where the y axis is the number of stars and x axis is log(m), with bin size 0.1 deg.

ramtools.imf.plot_imf_from_nbins(ax, n, bins, isLog=True, **kwargs)

Plot a mass spectrum on ax, given n and bins. y: d N / d log(m)

ramtools.imf.plot_imf_from_output(ax, r, out, isbay=False)
Parameters
  • ax (plt axis) – the axis to plot on

  • r (Sink class object) – Instance of ramses.Ramses

  • out (int) – output ID

  • isbay (bool) – If True, plot Bayesian fit to the power-law slopw

ramtools.imf.plot_single_imf(ax, jobid, is_set_title=True, is_plot_kroupa=True)

Outdated. Do not use. Plot the MFs of one job. The indxes must be in reversed order (from big to small)

ramtools.imf.plot_sp_imf_one_job(ax, jobid, gammas, m_min=0.1, m_lower=0.08, sample_label_ext='')
Parameters
  • ax (plt axis) – the axis to plot in

  • jobid (str) – jobid, e.g. ‘4.3.1’

  • is_sal (#) –

  • If True (#) –

  • Salpeter sampling along with Kroupa sampling. (add) –

ramtools.imf.plot_step_func(ax, n, bins, **kwargs)

Accurate and precise. The bins are representing the value between the pivots.

ramtools.imf.pow_formula(x, a, b, beta)
ramtools.imf.pow_int(a, b, beta)

Return the integral of x^-alpha from a to b. beta = 1 - alpha.

ramtools.imf.random() → x in the interval [0, 1).
ramtools.imf.sample_filename(jobid, outputID, version, kind=0)

When version=’’ and kind=0, returns the original sink filename :param jobid: e.g. “3.3.2”, or “XL-VC” :type jobid: str :param version: description :type version: str :param kind: 0: sink, 1: Kroupa, 2: Salpeter :type kind: int

ramtools.imf.sample_imf(pdf, m_tot, m_mean=0.2)

Sample a cluster of stars with total mass m_tot with a given PDF

Parameters
  • pdf (function) – The MF

  • m_tot (double) – total mass to sample to (e.g. the mass of a sink particle to fragment)

  • m_mean (double (not used)) – The estimated mean mass from pdf

ramtools.imf.sample_masses(masses, kind='sal', m_min=0.1, m_lower=0.08, m_max=- 1, **kwargs)
Parameters
  • masses (array) – The masses to sample from

  • kind (str) – ‘sal’ for salpeter and ‘kro’ for Kroupa sampling recipe

  • m_min (double) – The lower bound of IMF. 0.0 < m_min < 0.5

  • m_lower (double) – Only useful when m_min is a string. m_min = max(m_lower, x * m_sink)

  • m_max (double) – If m_max < 0: use m_sink as m_max

  • **kwargs (passed to pick_salpeter (not to pick_kroupa) to set alpha.) –

Returns

  • mass_samp (array) – The sampled masses

  • # n (list of integers)

  • # Counts of the histogram of the sampled masses

  • # bins (list of double)

  • # Bins of the histogram of the sample masses

ramtools.imf.sample_two_powerlaw(rand, a1, a2, m1, m2, m3)

Given a random number from 0 to 1, return a sampled mass based the following distribution: a broken power law from m1 to m2, m2 to m3, with negative slopes a1 and a2

ramtools.imf.set_imf_xticks(axes)
ramtools.imf.set_imf_xticks_single(ax, is_remove_rightmost=False)
ramtools.imf.test_mean()

A driver to test the mean mass of sampling. For Salpeter, INTERP’s ~0.6.

ramtools.luminosity module

Calculate luminosity histograms of sink particles in a simulation, for each outputs.

Example

from ramtools.luminosity import lumhist lumhist(jobdir=”../../2017-RAMSES/Job2.2.2/”, recipe=”frig_he”, plotdir=”./trash”, xlim=[38, 52])

ramtools.luminosity.lumhist(jobdir, recipe, plotdir, xlim=[38, None], ylim=None, bins='auto')
Parameters
  • jobidr (list of str) – paths to job directories

  • recipe (str) – one of “frig_he”, “sp”

  • plotdir (str) – directory to save plots

  • xlim – xlim of the histogram

  • ylim – ylim

ramtools.plotutils module

Plot utilities for RAMSES outputs

Example

ramtools.plotutils.T_setup(p, zlim=None, time_offset=None, is_time=False)
ramtools.plotutils.add_scalebar(ax, length, label, h=0.014, left=0.03, right=None, color='w', gap=0.01, **kwargs)

Add a scalebar to a figure Author: ChongChong He

Parameters
  • ax (matplotlib axes) – The axes passed to add_scalebar

  • length (double) – The length of the scalebar in code units

  • label (string) – The scalebar label

  • h (double) – The height of the scalebar relative to figure height

  • color (string) – color

  • **kwargs (dict) – kwargs passed to ax.text

Examples

>>> im = plt.imread("/Users/chongchonghe/Pictures/bj.jpg")[:800, :800, :]
>>> plt.imshow(im)
>>> ax = plt.gca()
>>> add_scalebar(ax, 200, '3 pc')
>>> plt.show()
ramtools.plotutils.annotate_axis_label(ax, axis, **kwargs)
ramtools.plotutils.annotate_box(p, center, width, axis, plot_args={'color': 'w', 'linewidth': 1})
ramtools.plotutils.base_find_peak_density_location(ds, box_l, box_r)
ramtools.plotutils.den_setup(p, zlim=None, time_offset=None, mu=1.4, unit='number_density', weight_field='density', is_time=False)
Parameters
  • p (YT plot) –

  • zlim (tuple) – limits of the field

  • mu (float) – the mean particle weight. The mass density rho = mu * n

  • quant (str) – ‘volume’ or ‘column’ for volumetric and column density

ramtools.plotutils.find_peak_density_location(ds, box_l, box_r)
ramtools.plotutils.overplot_time_tag(time, ax, loc='upper left', unit='Myr', **kwargs)

Overplot time tag on top-left corner

Parameters
  • time (float) –

  • ax

  • loc (str) – one of ‘upper left’, ‘upper right’, ‘upper center’

  • timeshift

Returns:

ramtools.plotutils.plot_prj(ds, center, width, sinks, field='density', axis='x', axis_unit='pc', kind='prj', **kwargs)
Parameters
  • ds – YT ds instance, e.g. ds = yt.load(…)

  • center – center in boxlen units (0, 1)

  • width – width in boxlen units

  • sinks (n-by-3 array) – position of the sink particles in code units

ramtools.plotutils.quick_plot_prj(ds, sinks, field='density', axis='z', use_h5=True, **kwargs)
Parameters
  • ds – YT ds instance, e.g. ds = yt.load(…)

  • sinks (n-by-3 array) – position of the sink particles in code units

ramtools.radiation_module module

class ramtools.radiation_module.DustExtinction(Z=1.0, cloud='SMC')

Bases: object

get_sigma(lam)
Parameters

lam (double or array) – wavelength in um

get_tau(lam, N_H)

Formula: N_dust = Z / Z_0 * N_H

class ramtools.radiation_module.InterpolateTau

Bases: object

Perform realistic tau-to-get_ef conversion :param tau: array, ndim=1. log10 of tau :return: get_ef: array, ndim=1. log10 of get_ef

c = 299792458.0
deno(x, T)

x = nu/nuH

do_interpolation()
e = 1.602176634e-19
h = 6.62607015e-34
interpolate(logtauLim=[- 1, 2.5], Tlim=[5000, 50000], isNewStyle=True, field='HI')
k = 1.380649e-23
logef(tau, T, field)

the calculated escape fraction Return: ——- log(ef)

nume(x, tau, T, field)

x = nu/nuH

planck(nu, T)

Return the planck function

tau_to_ef(tau, temps, field)

Convert tau to log(ef). np.ndim(tau) must be 2 :param tau: tau :param T: T in Kelvin :return: log10 of ef

tau_to_ef_H(tau, T)

tau and T are doubles

vH = 3288465369235488.0
ramtools.radiation_module.QHeI(mass)

Return Schaerer QHeI * center.unit_lum.

ramtools.radiation_module.QHeII(mass)
ramtools.radiation_module.QHeII_raw(mass)
ramtools.radiation_module.QHeI_raw(mass)
ramtools.radiation_module.QVacca(Mass)

Return VaccaQHI in 1e44 s^-1. Mass range: 1 - 10000.

ramtools.radiation_module.QVaccaRaw(m)
ramtools.radiation_module.QVacca_sp(m)

Modified Vacca, single power law

ramtools.radiation_module.colden_to_tau_ev(eVs, colden_HI=0.0, colden_HeI=0.0, colden_HeII=0.0)

Only apply to gas (not dust)! eVs can be scaler or array Remember to multiply tau by self.n_colden_H to get actual tau

ramtools.radiation_module.dust_model(model)
ramtools.radiation_module.find_bin(nu)
ramtools.radiation_module.luminosity(masses, recipe, info_path, masstot=None)
Args

masses (list): list of sink mass in Msun recipe (str): one of [“frig_he”, “sp”] info_path (str): of the of info_000##.txt file, which is used to

get unit_d and unit_l

masstot (float): total mass. When masstot = None (default), this

is np.sum(masses)

ramtools.radiation_module.poly(logm, a)
ramtools.radiation_module.rescale_ratio_do_not_use(mass)

Calculate the rescaling ratio – scluster / wcluster, where wcluster = Sigma ssink – of a given sink mass function. This rescaling is used in all the simulations shown in He2019 and He2019a.

ramtools.radiation_module.scluster_fit(mtot)
ramtools.radiation_module.sigmaHI(nu)

[nu] = eV Return sigma (cm^2)

ramtools.radiation_module.sigmaHeI(nu)

[nu] = eV

ramtools.radiation_module.sigmaHeII(nu)

[nu] = eV

ramtools.ramplot module

Some utilities to make figures.

...
class ramtools.ramplot.RamPlot(jobdir=None, jobid=None, ram_dir=None, fields=['Density', 'x-velocity', 'y-velocity', 'z-velocity', 'x-Bfield-left', 'y-Bfield-left', 'z-Bfield-left', 'x-Bfield-right', 'y-Bfield-right', 'z-Bfield-right', 'Pressure', 'xHII', 'xHeII', 'xHeIII'])

Bases: ramtools.ramses.Ramses

plot_2d_profile(out, center, radius, field_x, field_y, field, ds=None, weight_field=None, lims={}, units={}, vlims=None, with_cb=True, force_redo=False, define_field=None)

Plot 2D profile. Will store intermediate to disk for fast recreate of the figure.

Parameters
  • jobpath (str) – path to job

  • out (int) –

  • center (tuple or str) – tuple (boxlen unit) or ‘c’ (center)

  • radius (float or tuple) – radius (half-width) of the region

  • ds (YT ds) – optional, feed ds (default None)

  • lims (dict) – limits of the axes, e.g. {‘density’: [1e3, 1e5], ‘temperature’: [1e0, 1e4]}

  • vlims (tuple) – vlims of the colorbar (default None)

  • with_cb (bool) – toggle colorbar (default True)

  • define_field (function) – a function that defines a new field. It should take ds as an argument.

Returns

yt profile plot

plot_phaseplot_for_all(figdir, center, radius, prefix='', phaseplot_kwargs={})

Usage:

>>> plot_phaseplot_for_all(center='c', radius=0.4, x_field=('gas', 'density'),
        y_field=('gas', 'temperature'), z_fields=('gas', 'cell_mass'))
plot_prj(out, ds=None, center=0.5, 0.5, 0.5, width=0.5, axis='x', field='density', weight_field='density', kind='projection', normal=None, north=None, tag=0, use_h5=True, force_redo=False)

Plot projection or slice plot. When plotting projection plot, an intermediate data is stored for fast recreate of the figure.

Parameters
  • out (int) – the frame number

  • ds (YT ds) – optional. If not specified, will load a ds using self.load_ds

  • center (tuple) – the center as a tuple in boxlen unit. Default: (0.5, 0.5, 0.5)

  • width (tuple or float) – the width of the area to plot. e.g. (0.1 ‘pc’); 0.02. Default: 0.5

  • axis (int or str) – the axis of the line of sight. Default: ‘x’

  • field (tuple or str) – the field to plot. Default: ‘density’

  • weight_field (tuple or str) – the field to weight with. Default: ‘density’

  • kind (str) – the figure type, either ‘projection’ (default) or ‘slice’.

  • normal (tuple or list) – normal vector

  • north (tuple or lsit) – north vector

  • tag (any) – a tag

  • use_h5 (bool) – whether or not to use h5 data

  • force_redo (bool) – whether or not to force remake the h5 data and figure

Returns

you can save it to file by p.save(‘filename.png’)

Return type

p (YT plot instance)

projection_for_all_outputs(outdir, prefix='output', center='c', width=1.0, force_redo=False)

Plot (density-weighted) projection of density for all frames of a simulation job.

Parameters
  • ourdir (int) –

  • prefix (str) – prefix of the filenames (default “output”). The name of the figures would be prefix-x-output_00001.png

  • center (str or list) – (default ‘c’)

  • width (float or tuple) – (default 1.0) float as in boxlen unit or a tuple containing a number and unit, e.g. (0.1, ‘pc’)

Returns

None

to_boxlen(quant)
ramtools.ramplot.dict_hash(dictionary: Dict[str, Any]) → str

MD5 hash of a dictionary.

ramtools.ramplot.plot_a_region(ram, out, ds, center, fields='den', kind='slc', axis='z', width=None, center_vel=None, L=None, direcs='face', zlims={}, l_max=None, is_id=False, bar_length=2000.0, sketch=False, time_offset='tRelax', is_set_size=True, is_time=True, scalebar_length=None, streamplot_kwargs={}, more_kwargs={})

Do projection or slice plots in a region.

Parameters
  • ram – a ramtools.Ramses instance

  • out (int) – output frame

  • ds (yt.ds) – yt.load instance

  • center (list_like) – the center of the region like in yt.SlicePlot

  • fields (str or tuple) –

    the field to plot. The avaialble options are: ‘den’ or ‘density’ - density. ‘logden’ - log of density. ‘T’ or ‘temperature’ - temperature. ‘T_vel_rela’ - temperature overplot with velocity field. ‘pressure’ - thermal pressure. ‘magstream’ - stream lines of magnetic fields on top of density slice.

    The magnetic strength is be indicated by the color of the stream lines.

    ’beta’ - plasma beta parameter. ‘AlfMach’ - Alfvenic Mach number. ‘xHII’ - hydrogen ionization fraction. ‘mach’ - thermal Mach number. ‘mag’ - magnetic field strength. ‘vel’ - velocity field on top of density slice. ‘vel_rela’ - relative velocity field, i.e. the velocity field in the frame

    with a velocity defined by center_vel.

    ’mach2d’ - thermal Mach number in the plane. ‘p_mag’ - magnetic pressure.

  • kind (str) – ‘slc’ or ‘prj’. Default: ‘slc’

  • axis (str or int) – One of (0, 1, 2, ‘x’, ‘y’, ‘z’).

  • width (float or tuple) – width of the field of view. e.g. 0.01, (1000, ‘AU’).

  • center_vel (list_like or None) – the velocity of the center. (Default None)

  • L (list_like) – the line-of-sight vector. Will overwrite axis. Default: None

  • direcs (str) – ‘face’ or ‘edge’. Will only be used if L is not None.

  • zlims (dict) – The limits of the fields. e.g. {‘density’: [1e4, 1e8]}, {‘B’: [1e-5, 1e-2]} (the default of B field).

  • l_max (int) –

  • is_id (bool) – toggle marking sink ID (the order of creation)

  • bar_length (float) – not using

  • sketch (bool) – If True, will do a faster plot of a simple imshow for test purpose. Default: False.

  • is_time (bool) – toggle overplotting time tag

  • time_offset (str or int or float) – One of the following cases: str: ‘rRelax’ int: the frame of which the time is used float: time in Myr

  • is_set_size (bool) – toggle setting figure size to 6 to make texts bigger. Default: True.

  • scalebar_length (bool) – the length of a scalebar to plot at the bottom-right corner. e.g. (2, ‘pc’), (1000, ‘AU’)

  • streamplot_kwargs (dict) – More kwargs for plt.streamplot that is used when fields=’magstream’. Default: {}

  • more_kwargs (dict) –

    more field-specific kwargs. Default: {} plot_cb (bool): toggle plotting the first colorbar for the main field plot_cb2 (bool): toogle plotting the second colorbar for the

    secondary field (e.g. magnetic or velocity field lines)

    cb2_orientation (str): either ‘vertical’ or ‘horizontal’ cb2_dark_background (bool): toggle plot cb2 with white axes cb_axis (plt axis): the plt axis to plot the first colorbar on cb2_axis (plt axis): the plt axis to plot the second colorbar on

Returns

yt figure or plt.figure

ramtools.ramplot.to_boxlen(quant, ds)

ramtools.ramses module

Defines the Ramses class, the core of ramtools.

ramtools.ramses.RAM_DIR

Global variable defining the path to RAMSES jobs

Type

str

class ramtools.ramses.Ramses(jobdir=None, jobid=None, ram_dir=None, fields=['Density', 'x-velocity', 'y-velocity', 'z-velocity', 'x-Bfield-left', 'y-Bfield-left', 'z-Bfield-left', 'x-Bfield-right', 'y-Bfield-right', 'z-Bfield-right', 'Pressure', 'xHII', 'xHeII', 'xHeIII'])

Bases: ramtools.ramsesbase.RamsesBase

Inherit from RamsesBase for the use of the author’s personal use. The methods defined in this class may not work for another person’s RAMSES simulations.

find_formation_pos_from_movie(sinkid, msg='off')

Find the formation location of the sink particles with given sinkid. This is done by finding the sink_*.txt file where the sink first form and stops accreting.

Parameters
  • sinkid (int) – (starting from 1)

  • msg (bool or string) – print message if msg is True or ‘on’

Returns

n by 3 array. Position of sink particle at formation

Return type

array

get_gas_mass()
get_gas_peak_density()
get_out_after(t)

Get the out number right after a give time t (Myr)

get_sink_acc_rate(out)

Get the sink accretion rate.

Warning

DO NOT USE THIS. The results are not trustable. This column of data from RAMSES outputs seems to be problematic

get_sink_info_from_movie1(sinkid)

Return a list of time and a list of sink masses

Parameters

sinkid (int) – sink id, starting from 0

Returns

a dictionary containing the following keys: ‘out’, ‘t’, ‘m’, ‘x’,

’y’, ‘z’, ‘vx’, ‘vy’, ‘vz’. All in code units.

Return type

int

get_times_from_movie1()
get_trelax()
movie_sink_path(num)
overplot_time_tag(ax, out, timeshift=0, loc='upper left', unit='Myr', **kwargs)

Overplot time tag on top-left corner

Parameters
  • ax

  • out

  • timeshift

Returns:

read_movie_sink_as_particle(num)

Read sink_xxxxx.csv in job/movie1 as particle array containing the following columns: m, x, y, z, vx, vy, vz, all in code units

read_zoom_center()
read_zoom_radius(idx=- 1)

ramtools.ramses module

Defines the Ramses class, the core of ramtools.

ramtools.ramses.RAM_DIR

Global variable defining the path to RAMSES jobs

Type

str

class ramtools.ramses.Ramses(jobdir=None, jobid=None, ram_dir=None, fields=['Density', 'x-velocity', 'y-velocity', 'z-velocity', 'x-Bfield-left', 'y-Bfield-left', 'z-Bfield-left', 'x-Bfield-right', 'y-Bfield-right', 'z-Bfield-right', 'Pressure', 'xHII', 'xHeII', 'xHeIII'])

Bases: ramtools.ramsesbase.RamsesBase

Inherit from RamsesBase for the use of the author’s personal use. The methods defined in this class may not work for another person’s RAMSES simulations.

find_formation_pos_from_movie(sinkid, msg='off')

Find the formation location of the sink particles with given sinkid. This is done by finding the sink_*.txt file where the sink first form and stops accreting.

Parameters
  • sinkid (int) – (starting from 1)

  • msg (bool or string) – print message if msg is True or ‘on’

Returns

n by 3 array. Position of sink particle at formation

Return type

array

get_gas_mass()
get_gas_peak_density()
get_out_after(t)

Get the out number right after a give time t (Myr)

get_sink_acc_rate(out)

Get the sink accretion rate.

Warning

DO NOT USE THIS. The results are not trustable. This column of data from RAMSES outputs seems to be problematic

get_sink_info_from_movie1(sinkid)

Return a list of time and a list of sink masses

Parameters

sinkid (int) – sink id, starting from 0

Returns

a dictionary containing the following keys: ‘out’, ‘t’, ‘m’, ‘x’,

’y’, ‘z’, ‘vx’, ‘vy’, ‘vz’. All in code units.

Return type

int

get_times_from_movie1()
get_trelax()
movie_sink_path(num)
overplot_time_tag(ax, out, timeshift=0, loc='upper left', unit='Myr', **kwargs)

Overplot time tag on top-left corner

Parameters
  • ax

  • out

  • timeshift

Returns:

read_movie_sink_as_particle(num)

Read sink_xxxxx.csv in job/movie1 as particle array containing the following columns: m, x, y, z, vx, vy, vz, all in code units

read_zoom_center()
read_zoom_radius(idx=- 1)

ramtools.ramsesbase module

exception ramtools.ramsesbase.NoSinkParticle

Bases: Exception

exception: no sink particle found in an output or a .csv file.

class ramtools.ramsesbase.RamsesBase(jobdir, fields=None)

Bases: object

This is the core of ramtools. Most of the times, you want to start ramtools by declaring this class.

Examples

>>> import ramtools as rt
>>> ram = rt.Ramses("../tests/Job_test")
>>> par = ram.get_sink_particles(1)
>>> mass = par[:, 0]
>>> print("Total mass =", mass.sum())
>>> ram = rt.Ramses("Job1", fields=FIELDS)
delete_ds(out)

Remove a ds from self.ds_container

exist(out)
get_all_outputs()
get_ds()

Load the first output out there. This is necessary to get the units and other things

get_first_output()
get_info_path(out)

Return the path to info_out.txt

get_last_output_backward()
get_sink_masses(out)

Get sink masses in M_sun of one output (not shifted) Replacing get_sink_mass

Parameters

out (int) – the output frame

Returns

an array of shape (n, ) containing the particle masses in

solar mass.

Return type

array

Raises
get_sink_particles(out)
Parameters

out (int) – the output frame

Returns

(n, 7) array containing the sink

parameters, where n is the number of particles and the 7 columns are: [m, x, y, z, vx, vy, vx], all in code units

Return type

particles (array)

Raises
get_sink_path(out)

Return the path to sink_*.csv

get_sink_positions(out)
Parameters

out (int) – the output frame

Returns

an array with shape (n, 3) containing the particle positions

in code unit

Return type

array

Raises
get_time(out, readinfo=False)

Get the time in Myr (not substracting t_relax) of data_id.

get_units()

Define the following units for this job:

  1. unit_l: this is the boxlen (in cm), which equals to unit_l_code * boxlen

  2. unit_l_code: this is the actually length unit (in cm)

  3. unit_d: dnesity unit in cgs

  4. unit_t: time unit in cgs

  5. unit_v: velocity unit in cgs

  6. unit_m: mass unit in cgs

  7. unit_m_in_Msun: mass unit in Msun

  8. kin_ene_in_cgs: kinectic energy in cgs

load_ds(out)

Return a yt.load instance of the frame out

overplot_sink(p, out, plot_args={})

Over plot sink particles (as green crosses) on top of a YT slice/project plot

Parameters
  • p (yt.sliceplot or yt.projectplot) – the plot to overplot on

  • out (int) – the output frame

  • plot_args (dict) –

overplot_sink_with_id(plot, out, center, radius, is_id=True, colors=<matplotlib.colors.LinearSegmentedColormap object>, withedge=False, zorder='time', lims=[0.01, 100.0])
Parameters
  • plot (yt plot) – the plot to overplot on

  • out (int) – the output frame

  • center (tuple or list) – the center of the plot in boxlen units

  • radius (float) – the radius (half width) of the box around the center defining the domain of interest, in boxlen units

  • weight (str) – give weights to the annotates of the sink particles by the ‘time’ of creation, or by their ‘mass’

ramtools.ramsesbase.set_RAM_DIR(ram_dir)

Set the global variable RAM_DIR. Check Ramses.__init__ for its usage.

ramtools.ramsesbase.to_boxlen(quant, ds)

ramtools.to_skirt module

ramtools.to_skirt.to_skirt(jobid, output, fn_out, family='BC', center=None, width=inf, width_boxlen=None, letdie=False, skip_exist=True, jobdir=None)

Make particle data for SKIRT run

Parameters
  • jobid (str) – will be overwritten by jobdir if jobdir is not None

  • output (int) –

  • fn_out (str) – output filename

  • center (float or array) – center of the box in boxlen units. Default: (.5, .5, .5)

  • width – width of the box in code unit (unit_l_code, not boxlen)

  • width_boxlen – width of the box in boxlen unit. Will overwrite width.

ramtools.units module

Define the following constants in cgs units:
  • all constants in con_list

  • all constants in units_list

  • m_H

@author: chongchonghe

ramtools.utilities module

ramtools.utilities.add_B_squared(ds)
ramtools.utilities.add_B_squared_gauss(ds)
ramtools.utilities.add_v_squared(ds)
ramtools.utilities.get_sink_info_from_movie1(movie_dir, sinkid)

Return a list of time and a list of sink masses

Args

sinkid: interger, starting from 0

Returns

  • Return a dictionary containing the following keys ‘out’, ‘t’, ‘m’, ‘x’,

  • ’y’, ‘z’, ‘vx’, ‘vy’, ‘vz’. All in code units.

ramtools.utilities.get_sink_mass_from_movie1_for_all_sinks(movie_dir)

Get the times and sink masses of all sink particles from movie files

Parameters

movie_dir (str) – path to movie1

Returns

(outs, times, masses)

outs (list of int): length n list storing the movie frame indices.

n is the number of movie frames that has sink information.

times (list of float): length n list storing the times (in code unit)

of the movie frames

masses (array of float): (m, n) array storing the masses of all sink

particles over time. m is the number of total sink particles in the last movie file. For instance, masses[3] is a list of the masses of sink particle #3 (starting from 0) over times.

Return type

A tuple of 3

Usage:

>>> outs, times, masses = get_sink_mass_from_movie1_for_all_sinks("tests/Job1/movie1")
>>> plt.plot(times, masses[0])    # plot the mass of sink #0 over time
ramtools.utilities.get_times_from_movie1(movie_dir)

Return a dictionary: {100: 0.012, 101: 0.013, …}

ramtools.utilities.get_unit_B_new(ds)

NEW: the original version was wrong Get the unit of B field strength.

[B] = sqrt(4pi) * [v] * [sqrt(rho)]

Returns

the unit of B in cgs units

Return type

YT.unit

ramtools.utilities.get_unit_B_wrong(ds)

Get the unit of B field strength

\(1 \ \mathrm{Gauss} = \sqrt{{g} / {cm}} / s, u_B = B^2 / 8 \pi\)

Returns

the unit of B in cgs units

Return type

YT.unit

ramtools.utilities.mass_to_radius(mass)

Input: mass (Msun); output: stellar radius (Rsun)

ramtools.utilities.mass_to_temp(mass)

input: mass (M_sun); output: T (K)

ramtools.utilities.my_yt_load(job_path, out)

Quickly yt.load a job with the correct FIELDS

Parameters
  • job_path (str) – path to a job directory

  • out (int) – the output frame you want to load

Usage: >>> ds = my_yt_load(“tests/Job1”, 1)

ramtools.utilities.read_from_nml(fn, cat, field)
ramtools.utilities.read_quant_from_ramses_info(info, quant)
ramtools.utilities.read_zoom_center(nml)

Given the namelist file nml, return the center of the zoom

ramtools.utilities.read_zoom_radius(nml, idx=- 1)

Given the namelist file nml, return the radius of the zoom region (with maximum l_max

ramtools.yt_field_descrs module

ramtools.yt_field_descrs.FIELDS

a list of RAMSES fields. This is different from the default fields in the public version of RAMSES

Type

list

ramtools.ytfast module

A general wrapper to make some fo the common yt functions more efficient by reusing intermediate data

General-purpose yt wrappers. Apply to any data that yt supports.

ramtools.ytfast.PhasePlot(data_source, x_field, y_field, z_fields, weight_field=None, x_bins=128, y_bins=128, accumulation=False, fractional=False, fontsize=18, figure_size=8.0, shading='nearest', extrema=None, units=None, zlims=None, force_redo=False, define_field=None, is_cb=True, cmap='viridis', cb_label='', f=None, ax=None, ret='imshow', is_pcc=False)

A wrapper to yt.PhasePlot to use cache file to speed up re-production of a figure with different aesthetic settings like new colormap, different zlim, etc. For the use of yt.PhasePlot, check the official documentation

The following Args are in addition to the parameters of yt.PhasePlot.

Parameters
  • zlims (list_like) – lims of z_fields

  • force_redo (bool) – toggle always remake the figure

  • define_field (func) – function to define a new field

  • is_cb (bool) – toggle show colorbar (default: True)

  • cb_label (str) – colorbar label (default: ‘’)

  • f (plt.figure) – figure to plot on (default: None)

  • ax (plt.axis) – axis to plot on (default: None)

  • ret (str) – what to return (default: ‘imshow’). One of [‘imshow’, ‘data’]

ramtools.ytfast.ProfilePlot(data_source, x_field, y_fields, weight_field='gas', 'mass', n_bins=64, accumulation=False, fractional=False, label=None, plot_spec=None, x_log=True, y_log=True, xlims=[None, None], force_redo=False, define_field=None, f=None, ax=None, ret='plot', mpl_kwargs={})

A wrapper to yt.ProfilePlot to use cache file to speed up re-production of a figure with different aesthetic settings. For the use of yt.ProfilePlot, check the official documentation

The following Args are in addition to the parameters of yt.ProfilePlot.

Parameters
  • xlims (list_like) – x limits

  • force_redo (bool) – toggle always remake the figure

  • define_field (func) – a function to define a new field.

  • f (plt.figure) – figure to plot on (default: None)

  • ax (plt.axis) – axis to plot on (default: None)

  • ret (str) – what to return (default: ‘plot’). One of [‘plot’, ‘data’]

  • mpl_kwargs – kwargs to plt.plot

Returns

If ret == ‘plot’, return a tuple (f, ax) If ret == ‘data’, return a tuple (x, y)

ramtools.ytfast.ProjectionPlot(ds, axis, fields, center='c', width=None, axes_unit=None, weight_field=None, max_level=None, tag=None, force_redo=False, return_data=False, **kwargs)

A wrapper to yt.ProjectionPlot to use cache file to speed up re-production of a figure with different aesthetic settings like new colormap, different zlim, overplotting sink particles, etc. For the use of yt.ProjectionPlot, check the official documentation

The following Args are in addition to the parameters of yt.ProjectionPlot.

Parameters
  • force_redo (bool) – toggle always remake the figure and write a new .h5 file no matter the .h5 exits or not.

  • **kwargs – more kwargs passed to yt.ProjectionPlot

Returns

A PWViewerMPL object containing the plot. See the official documentation of YT for details.

ramtools.ytfast.SlicePlot(ds, normal=None, fields=None, center='c', width=None, zlim=None, tag=None, force_redo=False, *args, **kwargs)

A wrapper to yt.SlicePlot to use cache file to speed up re-production of a figure with different aesthetic settings like new colormap, different zlim, overplotting sink particles, etc. For the use of yt.SlicePlot, check the official documentation

Parameters
  • force_redo (bool) – toggle always remake the figure and write a new .h5 file no matter the .h5 exits or not.

  • **kwargs – more kwargs passed to yt.SlicePlot

Returns

A PWViewerMPL object containing the plot. See the official documentation of YT for details.

Module contents