Welcome to ramtools’s Documentation!¶
This is a Python module based on YT to post-process RAMSES simulation data. The code is accessible from this github repository: https://github.com/chongchonghe/ramtools
Author: Chong-Chong He (che1234 @ umd.edu)
Overview on How to Use this Module¶
Install required packages (yt)
Clone this repository and install it via
pip install -e .
inside the code directory.
Setup procedure¶
Features of ramtools¶
Simplify the process of analysing RAMSES data with plenty of powerful tools
Make sliceplot/projectplot extremely fast by storing intermediate data at first run and reuse them in subsequent runs
Documentation for the Code¶
Executables in bin/¶
plot_projection¶
plot_projection
is an executable to efficiently plot
slices/projections of a given RAMSES simulation. This function is extremely
useful for a quick first analysis of a new simulation. Run
plot_projection in a folder named, say ‘postprocess’, inside a job
directory and it will create density projections and slices along the x, y, and
z axis for all outputs. The output figures will be stored in ./projections.
You can regenerate the figures with different aesthetic settings and the code
will make use of the cache stored in the job directory from the first run to
accelerate the image production process. For a complete documentation, do
plot_projection -h
.
usage: plot_projection [-h] [-c CENTER] [-l LOS LOS LOS] [--no-edgeon]
[-w WIDTH] [-f FIELDS] [-t TO] [-k KINDS] [-s]
[--sink-color SINK_COLOR]
[--mass-lim MASS_LIM MASS_LIM] [-o] [--overwrite-cache]
[--hide-axes] [-a] [--scale SCALE]
[--scaleloc SCALELOC] [--no-ytfast]
[--den-zlim DEN_ZLIM DEN_ZLIM] [--T-zlim T_ZLIM T_ZLIM]
[--xHII-zlim XHII_ZLIM XHII_ZLIM] [--dry-run]
[--inzoombox] [--rise RISE] [--t0 T0]
[--time-unit TIME_UNIT] [--darkbg]
[--draw-box DRAW_BOX] [--box-center BOX_CENTER]
[--skip SKIP]
[jobdir] [outs] [axes]
A program to efficiently make slices/projections plots of a RAMSES simualtion.
Quick examples:
>>> plot_projection ..
>>> plot_projection . 10-20 z -t figures
>>> plot_projection . 10-20 x,y -t figures -c 0.6,0.6,0.6 -w 10,pc -f den,temp -k slc --sink --den-zlim 1e4 1e10 --T-zlim 10 1e4
positional arguments:
jobdir (Default '..') Path to the simulation directory
outs (Default 'all') Output frames. If 'all', do all output frames. Examples: '10', '10,11,13', '10-20', '10-20-2'
axes (Default 'x,y,z') The line of sight. Examples: 'x', 'x,y,z'
optional arguments:
-h, --help show this help message and exit
-c CENTER, --center CENTER
(Default 'c') The center.
Cases:
'c': = [0.5, 0.5, 0.5]
'peak': the peak density location x,y,z: position in boxlen unit, e.g. 0.5,0.5,0.5
a single integer: use the location of a sink particle with the given index as the center
-l LOS LOS LOS, --los LOS LOS LOS
The line of sight vector, usually the face-on vector of the disk. When this is set, will plot a face-on and edge view that are perpendicular to each other.
--no-edgeon Turn off plotting edge-on view when los is set
-w WIDTH, --width WIDTH
The width of the view. Examples: '1', '1000,AU'. Default: '1'
-f FIELDS, --fields FIELDS
The fields to plot. Examples: 'den', 'den,temp'. Default: 'den'
-t TO, --to TO The destination directory. Default: './projections'
-k KINDS, --kinds KINDS
Plot types, either 'slc', 'prj', or 'slc,prj' (default)
-s, --sink Turn on overplotting sink particles
--sink-color SINK_COLOR
Set sink particle color. Default: Greens. Examples: Greens_r, Reds, Reds_r
--mass-lim MASS_LIM MASS_LIM
Colormap limits (in Msun) of the sink particles
-o, --overwrite Turn on overwritting existing figures. If left off (default), will skip existing files.
--overwrite-cache Turn on overwritting cache files used by ytfast
--hide-axes Toggle hide axes
-a, --annotate-scale Toggle annotate scale
--scale SCALE Coeff and unit of annotate_scale
--scaleloc SCALELOC Location of the scale bar: lower_right (default) orlower_left
--no-ytfast Turn off using ytfast to speedup projection/slice plot
--den-zlim DEN_ZLIM DEN_ZLIM
zlim of density (in cm-3)
--T-zlim T_ZLIM T_ZLIM
zlim of temperature (in K)
--xHII-zlim XHII_ZLIM XHII_ZLIM
zlim of xHII
--dry-run Toggle dry run: making one figure only and store it in local dierctory
--inzoombox with center=integer or center='peak', use sink particles/gas in zoombox only.
--rise RISE raise the slice plot by percent of the box width
--t0 T0 set the t0 and annotate time. t0 could be one of the following options: 1. an integer indicating the time of the corresponding output frame; 2. a float indicating the t0 in Myr
--time-unit TIME_UNIT
time unit, either Myr (default) or kyr
--darkbg Use dark background
--draw-box DRAW_BOX If not None, draw a box with this width
--box-center BOX_CENTER
define the center of the box to draw, used along with --draw-box. The syntax is similar to center
--skip SKIP skip certain outputs
plot_imf¶
plot_imf -h
usage: plot_imf [-h] [-c CENTER] [-w WIDTH] [-t TO]
[--mass-lim MASS_LIM [MASS_LIM ...]] [--kroupa]
[--kroupa-max KROUPA_MAX] [--kroupa-min KROUPA_MIN] [-o]
[--short] [--ylim YLIM YLIM] [--xlim XLIM XLIM] [--inzoombox]
[--t0 T0]
[jobdir] [outs]
A program to plot stellar mass functions of a RAMSES simulation.
Examples:
>>> plot_imf ..
>>> plot_imf .. 10-20
>>> plot_imf .. 10-20 -c 0.6,0.6,0.6 -w 10,pc
positional arguments:
jobdir Path to the simulation directory
outs Output frames. If 'all', do all output frames. Examples: '10', '10,11,13', '10-20'.
optional arguments:
-h, --help show this help message and exit
-c CENTER, --center CENTER
The center. Examples: 'c', '0.5,0.5,0.5'. Default: 'c'
-w WIDTH, --width WIDTH
The width of the view. Examples: '1', '1000,AU'. Default: '1'
-t TO, --to TO The destination directory. Default: '.'
--mass-lim MASS_LIM [MASS_LIM ...]
Turn on overplotting sink particles
--kroupa Enable overplotting mass-normalized Kroupa IMF
--kroupa-max KROUPA_MAX
Default: totmass, = sum(sink_masses)
--kroupa-min KROUPA_MIN
Default: sinkmin, = max(min(sink_masses), 10**-1.25)
-o, --overwrite Toggle overwrite existing figures.
--short Make short figures instead of a square one.
--ylim YLIM YLIM Set ylim.
--xlim XLIM XLIM Set xlim.
--inzoombox with center=integer, use sink particles in zoombox only.
--t0 T0 Define t0. If not 'off', will annotate timestamp,and will set t=0 to the t0th frame
Modules¶
ytfast¶
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.
ramsesbase¶
-
class
ramtools.ramsesbase.
RamsesBase
(jobdir, fields=None)¶ 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
-
get_ds
()¶ Load the first output out there. This is necessary to get the units and other things
-
get_info_path
(out)¶ Return the path to info_out.txt
-
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
FileNotFoundError –
-
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
FileNotFoundError –
-
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
FileNotFoundError –
-
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:
unit_l: this is the boxlen (in cm), which equals to unit_l_code * boxlen
unit_l_code: this is the actually length unit (in cm)
unit_d: dnesity unit in cgs
unit_t: time unit in cgs
unit_v: velocity unit in cgs
unit_m: mass unit in cgs
unit_m_in_Msun: mass unit in Msun
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’
-
ramses¶
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'])¶ 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_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
-
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
-
ramplot¶
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'])¶ -
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
-
-
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
utilities¶
-
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_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
plotutils¶
Plot utilities for RAMSES outputs
Example
-
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.
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.
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
units¶
- Define the following constants in cgs units:
all constants in con_list
all constants in units_list
m_H
@author: chongchonghe
imf¶
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'])¶ 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_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_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
-
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_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.
-
-
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.
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_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_any_width
(ax, masses, thresh, yscaleup=1, color='g', is_xlog=False)¶ plot a bayes fit on top of a IMF
-
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_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.
test_mean
()¶ A driver to test the mean mass of sampling. For Salpeter, INTERP’s ~0.6.