--- name: mera description: Analyse astrophysical simulation output with the Julia package Mera.jl (RAMSES hydro, particles, gravity, clumps, sinks, radiative transfer). Use when loading or analysing RAMSES data in Julia, or when writing code that calls Mera functions such as getinfo, gethydro, getparticles, getvar, subregion, filterdata, projection, profile, phase, msum or savedata. Gives the data model, units, regions, selections and the common traps. --- ## Keeping this skill current This copy was made for Mera 1.11.3. A user's copy does not update itself. When the project uses a newer Mera (check with `pkgversion(Mera)`), read the current rules from https://manuelbehrendt.github.io/Mera.jl/stable/llms.txt or from Context7 (`/manuelbehrendt/mera.jl`) before relying on this file, and tell the user that installing the skill again updates it: https://manuelbehrendt.github.io/Mera.jl/stable/assistant/#Install-the-Mera-skill # Mera.jl > Analysis of astrophysical simulation output in Julia. Reads RAMSES adaptive-mesh-refinement > data natively (hydro and MHD, particles, gravity, clumps, sinks, radiative transfer), holds a > snapshot as one table with one row per cell, and computes derived physics, regions, projections, > profiles, phase diagrams and structure catalogues from it. Documentation: > https://manuelbehrendt.github.io/Mera.jl/stable/ This file is a compact grounding for an AI assistant. It is not a tutorial. It states the data model, the vocabulary, the mistakes that are easy to make, and how to check that an answer is right. The current release is Mera 1.11.3 (`pkg> add Mera`); version numbers in docstring examples are illustrations. Everything below holds for Mera 1.11. Versions before 1.8 have none of the region values, `filterdata` or the off-axis features named here. Items marked (1.9) need Mera 1.9 or later: `exportdata`, the sidecar files and the functions around them. Items marked (1.10) need 1.10. ## Data model A snapshot is a table: one row per AMR cell, one column per quantity, and every row carries its refinement `:level`. Nothing is resampled onto a uniform grid unless you ask with `covering_grid`. Particles, clumps and sinks are separate objects with the same shape of interface. RAMSES star and dark-matter particles carry no temperature: for the gas around stars, read the hydro data of the same region. The registered release reads RAMSES only. Readers for GADGET/AREPO, PLUTO, Athena++, FLASH, Chombo and AMReX/Quokka are in development on the `multicode` branch (`pkg> add https://github.com/ManuelBehrendt/Mera.jl#multicode`). There AREPO and GADGET gas comes as particles, and `getvar(gas, :T)` works on it. Selections return **objects of the same type**, so calls chain: `subregion` into `filterdata`, and the result goes to `getvar`, `msum`, `profile` or `projection`. ## Loading info = getinfo(400, "/path/to/sim") # a RAMSES output folder gas = gethydro(info; lmax=10) # also getparticles/getgravity/getrt/getclumps/getsinks (; hydro, particles, info) = loadall(path, 400; components=[:hydro, :particles]) `loadall` dispatches on what it finds: a folder of RAMSES files goes through the RAMSES readers, a folder holding `output_NNNNN.jld2` through `loaddata`. Prefer it when the code should work on both. `getinfo` is RAMSES-only and **fails on a MERA-file folder**; `infodata` is its counterpart there. Limit the read rather than trimming afterwards. Every getter, and `loadall`, takes `xrange`/`yrange`/`zrange` with `center` and `range_unit`, and applies them while reading. The defaults are the box corner and code units, so pass `center=[:bc], range_unit=:kpc`. `checkoutputs(path)` lists the output numbers that exist in a run folder. ## Saving and reloading: Mera files To keep loaded data for later work in Mera, save the object itself, not an export: mkpath("mera_files") # Mera 1.11.0 and older need the folder savedata(gas, :write; path="mera_files/") # output_00400.jld2, LZ4-compressed savedata(part, :append; path="mera_files/") # a further data type into the same file gas = loaddata(400, "mera_files/", :hydro; xrange=[-10,10], center=[:bc], range_unit=:kpc) viewdata(400, "mera_files/") # what the file holds, without loading it convertdata(400; datatypes=[:hydro, :particles], path="/path/to/sim", fpath="mera_files/") **`savedata` writes nothing without `:write` or `:append`**, so a file is never overwritten by accident. A Mera file reloads much faster than the RAMSES output and keeps the simulation information, unit scales and load options, so every Mera function works on the reloaded object. `infodata(400; path="mera_files/")` is the `getinfo` of a Mera file, and `loadall` reads either kind of folder. `exportdata` (below) is the other route: it writes a result as plain arrays for other tools, not data for Mera. ## Units: always say the unit Every quantity takes a unit symbol, and the unit is part of the question: getvar(gas, :T, :K) msum(gas, :Msol) projection(gas, :sd, :Msol_pc2) filterdata(gas, Above(:T, 1e4, unit=:K)) `getvar(obj, :q)` without a unit returns **code units**, which mean something different in the next simulation. `getvar()` with no arguments prints every derived quantity; `list_units()` prints the units; `viewfields(obj)` shows what an object holds. A plain number in code units converts with the run's scale table: `x * info.scale.kpc` (also `gas.info.scale`, or `getunit(info, :kpc)`). The time of a snapshot is `gettime(info, :Myr)`; without the unit it is in code units too. In a cosmological run it is the age of the universe. Own derived quantities: `add_field(:name, (obj, deps) -> ...; depends_on=[:rho, :T], unit=...)` registers one that then works in `getvar`, `projection`, `profile` and `phase` like a built-in. The kernel returns code units. `list_fields(:hydro; builtin=true)` lists everything known. ## Regions are values sphere(r; center=[:bc], range_unit=:kpc) # centre is ABSOLUTE, in range_unit cuboid(xrange=[a,b], yrange=[c,d], zrange=[e,f], center=[:bc], range_unit=:kpc) cylinder(radius, half_height; axis=[0,0,1], center=[:bc], range_unit=:kpc) Combine them with `∩` `∪` `\` `!`, meaning intersection, union, difference and complement, then `subregion(obj, region)`. Every one has an ASCII spelling, so Unicode is never required: `A & B`, `A | B`, `intersect(A, B)`, `union(A, B)`, `setdiff(A, B)`, `!A`. A ring is one cylinder minus another. `subregion` splits boundary cells by default (`split=true`): a half-inside cell keeps half of itself as `:fraction`, and that weighting carries through `getvar`, `msum` and `projection`. Pass `split=false` for the classic whole-cell test. Only the value form splits: the older `subregion(gas, :sphere, radius=...)` form keeps every intersecting cell whole and gives no `:fraction`. Two separate things, and they are easy to confuse: - **`:fraction` makes the numbers exact.** It is on by default and needs no thought. A region and its complement add up to the parent. - **`refine` / `refine_to` make the picture sharp.** `subregion(obj, region, refine_to=[0.05, :kpc])` subdivides each straddling cell until its children are no larger than the given length; match it to a projection's `pxsize` and the rendered boundary becomes pixel-sharp. It changes no total. Points (particles, clumps, sinks) have no volume. Their in/out test is already exact, so leave `split` out: `split=true` raises an error on particles, and clumps and sinks do not take it. ## Selecting by value hot = filterdata(gas, Above(:T, 1e4, unit=:K)) mask = getmask(gas, Above(:T, 1e4, unit=:K)) # BitVector, pass as mask= band = filterdata(gas, Above(:T, 1e4, unit=:K) & Below(:rho, 1e3, unit=:nH)) Predicates: `Above`, `Below`, `InRange`, `Equals`, `IsFinite`, `AbovePercentile`, `BelowPercentile`, `Satisfies`, composed with `&` `|` `!`. They work on anything `getvar` computes, including derived physics. `getmask(gas, region)` tests cell centres only, so `msum(gas, mask=getmask(gas, reg))` is not the exact `msum(subregion(gas, reg))`. ## Computing projection(gas, :sd, :Msol_pc2; pxsize=[50.0, :pc], center=[:bc]) projection(gas, :vlos, :km_s; center=[:bc], inclination=60.0, azimuth=30.0, fov=14.0, fov_unit=:kpc, aperture=:circle, split=true) profile(gas, :r_cylinder, :T; xunit=:kpc, unit=:K) # also profile3d, profiletimeseries phase(gas, :rho, :T; xunit=:nH, yunit=:K) velocitydispersion(gas; center=[:bc]) # a radial sigma profile clumpfind(gas, :rho; threshold=1e2, threshold_unit=:nH, linking_length=0.2) # 7 finders timeseries(...) # one snapshot in memory at a time Use `pxsize=[value, :unit]` rather than `res=`. `:sd`, `:vlos` and `:σlos` are not in `getvar`: they need a camera, so they exist in `projection` (and `:vlos` in `volumerender`). Single numbers: `msum`, `center_of_mass`, `bulk_velocity`, `getextent`, `wstat` (mean, median, std, skewness, kurtosis, extrema, optionally weighted and masked). ## Traps These are mistakes an assistant makes confidently. Each was reproduced. 1. **`@filter` compares in code units.** `@filter gas :T > 1e4` is not ten thousand Kelvin. On one test run `1e4` code units is `6.8e9` K, so it selected 0 cells while `Above(:T, 1e4, unit=:K)` selected all 849332. The macro is fine for `:level` or for a threshold you already have in code units; for physics, name the unit with `Above`/`Below`. The macro also takes one comparison only; `&` `|` `!` need the predicate form. 2. **The region constructors are lowercase.** `sphere`, `cylinder`, `cuboid`, `sphericalshell`, `cylindricalshell`. Capitalized `Sphere`/`Cylinder` are not exported, because Makie exports those names too and a name exported by two loaded packages binds to neither. The types are still reachable as `Mera.Sphere` for dispatch. 3. **`projection` does honour cell fractions.** It reaches mass through `getvar`, so a map of a split subregion totals exactly what `msum` reports (with `fov`, only when `split=true`). 4. **`extent` is absolute, `cextent` is measured from `center`.** `cextent` is symmetric only when the centre sits in the middle of the window. Plot with `cextent` when the axis is centred. 5. **`fov` fixes the frame; `aperture=:square` then crops it.** The frame is ±`fov` about `center` at every angle, also for sparse data such as a star disc. The square keeps only what lies inside it, so never read a total off a `:square` map. For a total, use `aperture=:circle` together with `split=true`, or leave out `fov`. Projection's default is `split=false`, which keeps every cell the sphere touches whole (7 % too much mass in a 5 kpc aperture on Mera's test galaxy), while `subregion` defaults to `split=true`. `depth` cuts a slab along the view and also needs `split=true` to be exact; it is refused on axis-aligned calls, where `zrange` does the job. With the same `fov` and `aperture=:circle`, a gas map is a few pixels larger than a star map (its frame keeps room for the edge cells). Do not crop by hand: `matchframe(stars, gas)` puts the star map on the gas grid, pixel for pixel. With `aperture=:square` both are the same size. Both maps need ONE camera: `direction=:faceon` on each takes each object's own angular momentum, so gas and stars look along different axes and `matchframe` refuses them. Compute `L = angmom([gas, stars]; ...)` once and pass `axis=L` to both. 6. **`@where` and `@apply` act on the raw table** (`gas.data`), not on the Mera object. 7. **On particles, `:mass` is a mean and the face-on axis includes the dark matter.** A particle has no volume, so `projection(part, :mass)` is the mass-weighted mean particle mass per pixel; use `mode=:sum`, or `:sd` times the pixel area, for a total. `direction=:faceon` and `axis=:angmom` sum over every particle drawn, so the halo usually sets the axis: pass `parttypes=[:stars]` or a mask, or compute `L = angmom(...)` and pass `axis=L`. 8. **`refine` does not improve accuracy.** It is tempting to reach for it to make a mass "more exact". The integrals were already exact through `:fraction`, and a straddling cell's children inherit its piecewise-constant values, so their fraction-weighted volumes telescope back to the parent's. Refining changes what a boundary looks like, not what it weighs. 9. **Radii and velocities need a frame.** `getvar`, `filterdata`, the getters and `projection` measure from the box corner unless you pass `center` (`center=[:bc]` for the box centre). Region constructors and `profile` default to `[:bc]`, so a region and a getter given the same numbers can mean different places. Velocity quantities such as `:mach` or `:vϕ_cylinder` are in the box frame unless you pass `vcenter`. 10. **Distances are not periodic unless you ask.** Use `:r_sphere_periodic` or `:r_cylinder_periodic`, and `center_of_mass(...; periodic=true)`. `getinfo` reports what the namelist implies as `info.boundaries`, and Mera never acts on it by itself. 11. **`getvar(grav, :epot)` is corrected, the raw column is not.** RAMSES stores the potential short by a factor `boxlen`; `getvar` multiplies it back. The raw column `grav.data.epot`, and so `@where`/`@apply` on it, holds RAMSES's uncorrected value. 12. **(1.9) Every save writes a second file.** `savedata`, `savemap`, `savemovie`, `save_clumps`, `exportdata` and `batch_convert_mera` put a sidecar `.meta.json` next to the file. Code that reads every file in a folder must filter by extension: `filter(endswith(".jld2"), readdir(dir))`, not `readdir(dir)`. 13. **(1.9) h5py shows exported maps transposed.** Julia arrays are column-major, so a Julia `nx × ny` map has shape `(ny, nx)` in h5py: use `f["sd"][:].T`. NumPy files from `exportdata` are written in Fortran order and need no transpose. From Python, Mera runs through JuliaCall: add it once with `juliapkg.add("Mera", "02f895e8-fdb1-4346-8fe6-c721699f5126")` (not `Pkg.add` inside a running session), then `from juliacall import Main as jl; jl.seval("using Mera")`. Its functions take Julia symbols, written `jl.Symbol("rho")`, not strings, and `.to_numpy()` turns a result into NumPy (needs numpy installed). 14. **(1.9) A `getvar` array does not know its snapshot, and a figure is not seen by Mera.** `exportdata(values, file; source=gas)` records the provenance of plain arrays. A figure saved with Makie or PyPlot gets its record from `writesidecar("fig.png", m)` right after the save. 15. **(1.10) The temperature of an RT run depends on the ion columns.** `:T` takes the mean molecular weight of each cell from its ionisation fractions, so load the hydro data with them (the default loads everything). Without them Mera warns and falls back to a constant μ, and `:T` changes. 16. **Before 1.11, a gas projection with `fov` ignores `myargs`.** The camera angles, `center` and `pxsize` set in an `ArgumentsType` are lost, and `:vlos` then fails for want of a camera. On those versions pass them to `projection` (or `@project`) as keywords. ## Write it so a person can read it Analysis code is read far more often than it is written, usually by someone deciding whether to trust the number. Code produced for a Mera user should look like the examples above: - **Short and flat.** Prefer a few named steps to one dense expression. `subregion` then `filterdata` then `projection` reads as a sentence; the same thing nested does not. - **Name the physical constants.** `R_DISC = 14.0 # kpc, disc radius` rather than a bare `14.0` four lines down. A reader should be able to change the science without hunting. - **Comment the decisions, not the syntax.** Nobody needs `# project the gas`. They do need to know why the colour range is fixed, why the aperture is circular, why that temperature cut. - **Say the unit in the code**, not only in a comment, by using the unit arguments. - **Leave the check in.** The partition check below is three lines and belongs in the script, not in a throwaway REPL session. ## Checking the answer An assistant should not hand back a number without one of these. They are cheap. **Code.** A condition and its negation must reproduce the parent, for regions and for values alike: a = msum(subregion(gas, reg), :Msol) b = msum(subregion(gas, !reg), :Msol) abs(a + b - msum(gas, :Msol)) / msum(gas, :Msol) # measured 0.0 Same for `filterdata(gas, cond)` against `filterdata(gas, !cond)`. This catches an inverted comparison, a wrong unit and a mis-specified region in one line. A projected map should also total its `msum` when it has no `fov`, or when `fov` is used with `split=true`. **Physics.** Prefer a case with a known answer. `download_testdata()` fetches fifteen public test simulations, about 300 MB together (or one by name, `download_testdata("sedov3d_amr")`), chosen for exactly this: a Sedov blast whose radius grows as `t^(2/5)`, an MHD shock tube where a divergence-free field keeps `Bx` constant, four density blobs that a clump finder must return as four, a Strömgren sphere whose ionisation front follows the analytic law, and three of RAMSES's own tests checked against published reference values. Beyond that: check limiting cases, check a total against an independent route, and check that a result does not move when the pixel size, the viewing angle or the thread count changes. **Reproducibility.** Record what produced a number: provenance_string(gas) # version, git branch and commit, dirty flag, snapshot, time mera_build() # distinguishes a registry install from a checkout of a branch `pkgversion` reports the same string for a release and for a development checkout, so a result from a branch looks like a result from the release unless `mera_build` is used. `mera_install()` gives the full record: registry, branch, checkout or path install, and whether the code is exactly the registered release. Saved maps and reports carry provenance with them. For a shared analysis, pin the environment in a `Project.toml` next to the script and commit the `Manifest.toml` that `instantiate` produces; `meraproject("my_analysis")` (1.9) starts such a folder. **(1.9) The record on disk: FAIR results.** These functions make results findable, accessible, interoperable and reusable (the FAIR principles) without extra work. The same record exists at three levels: `provenance(obj)` in memory, a sidecar next to every saved file, and `bundle` for a whole folder, ready for a DOI repository. exportdata(m, "fig3.h5"; note="Figure 3") # .h5 .jld2 .csv .npy .npz .json, .fits after using FITSIO save("fig3.png", fig); writesidecar("fig3.png", m) readsidecar("fig3.h5") # prints it; .status says if the file changed sidecaroverview(".") # one line per file in a folder citation(gas; file="software.bib") # Mera at its version, plus the RAMSES papers bundle("."; simulation=info) # ro-crate-metadata.json, software.bib, simulation.json simulationrecord(info); datacite(rec; creators=..., title=..., license=...) simulationrecord("/path/to/sim") # the whole run: every output with time and size writesimulationrecord(rec, "simulation.json") # that record as readable JSON The crate is RO-Crate 1.3 with the Process Run Crate profile: each "Mera wrote this file" is a `CreateAction` (instrument Mera and the script, object the snapshot, agent the `creators`). Publish the folder zipped on a DOI repository such as Zenodo; `rocrate-validator validate ` (Python, `pip install roc-validator`) checks the record. Mera itself has no crate reader beyond JSON3; to check files against the record, compare each entity's `sha256`. A sidecar holds the snapshot's provenance, the units, the file's SHA-256, the SHA-256 of the run's namelist and makefile, the analysis environment (Project.toml and Manifest.toml SHA-256, the script by name and SHA-256) and the Julia, Mera and thread count that ran; never the host name, and with `anonymize=true` only the last two parts of the simulation path. Sidecars are on by default; `sidecar(false)` or the environment variable `MERA_SIDECAR=0` turns them off. A failed sidecar is a warning, never a failed save. `simulationrecord` describes the simulation rather than a result: code, box, resolution, units, cosmology, the physics the run used (`rec["physics"]["summary"]`, the same keys for every code) and the SHA-256 of its input files. Given the run folder it also lists every output and the outputs at which the input files changed, i.e. a restart with new settings (`rec["run"]["namelist_changed_at"]`). Threads: a result repeats bit for bit at the same thread count. Across thread counts reading and axis-aligned projections stay identical, while off-axis, particle and volume maps differ only at round-off. ## Also in Mera - `volumerender(gas, :rho, ...)` with `volumelook`, `volumeorbit` and `volumepath` renders hydro data as a translucent volume. Orthographic only, no perspective fly-through. - `repartition(output, path, ncpu)` rewrites a RAMSES output for another number of CPUs, `writeramses(ncpu; hydro, gravity, particles, ...)` writes one from Mera data or a mera file, `compareramses` checks two outputs, and `restart_completeness(gas; ...)` says what a restart still lacks. - `face_on`, `edge_on` and `angmom` give a frame to pass to `projection`; `periodic_recenter(map; center)` moves a finished map across a periodic box so a structure on a face appears whole. - `quicklook(output; path)` draws a first look at an unknown snapshot in physical units picked for the run; `report(output; path)` composes cards (maps, phase diagrams, profiles, star formation, and the ionised-fraction or `|B|` map of an RT or MHD run) and renders them as text or to a file. - (1.10) `projection(part, :sd; weighting=:sph)` smooths any particles, also those without a stored smoothing length (RAMSES stars and dark matter), from their nearest neighbours. - `center_of(gas; method=:densest, unit=:kpc)` finds a centre (`:com` by default). It returns code units unless `unit` is given, so pass the result on with the same `range_unit`: `center=c, range_unit=:kpc`. - `slice(gas, :rho, :nH; slice_axis=:z, slice_pos=0.5)` cuts a plane without integrating; any off-axis view keyword makes it an off-axis cut. It samples the nearest cell, so it conserves nothing: use `projection` for totals. - `covering_grid` resamples to a uniform 3-D grid; `export_vtk(gas, "out")` writes ParaView files. - Star formation: `sfr(part; tbinsize=10.0)` gives the history `(t_Myr, sfr)` from the star particles; `depletion_time(gas_region, sfr_Msol_yr)` the depletion time and efficiency per free-fall time; `localdispersion(gas; patchsize=[500, :pc])` the local velocity dispersion. - Cosmological runs: `iscosmological(info)`, `redshift(info)`, `lookback_time(info, a)`, `comoving_to_proper_length(info, l)` and the matching density functions. - Clumps found with `clumpfind` go into a table with `clumptable(cat)` (ready for `DataFrame`). - `synthetic_clumps()` builds real Mera objects with a known answer and no simulation files, for testing code before it meets data. - Long runs: when a script takes more than a few minutes (`convertdata` over many outputs, a loop over a time series, a movie, a large load on a server), end it with `notifyme("…")`, or `bell()` at a desk. `notifyme` sends an email and/or a Zulip message, configured once in `~/.mera.toml` (`mera_config_example()` prints a template). Without a configuration it sends nothing. Never write addresses or API keys into the script. `safe_execute("task") do … end` also reports a failure, and `timed_notify("task", () -> …)` adds the run time. Suggest it for long runs only, not in every snippet. **Not part of Mera:** emission or extinction transfer functions, `column_integral`, line-of-sight cubes, kinematic mock observations and their FITS export, a fly-through renderer, and a `rotationcurve` function. Do not write code that calls them. ## Where to read more - Getting started and first look: https://manuelbehrendt.github.io/Mera.jl/stable/first_look/ - How the numbers are computed: https://manuelbehrendt.github.io/Mera.jl/stable/computation_reference/ - Masking and filtering: https://manuelbehrendt.github.io/Mera.jl/stable/05_multi_Masking_Filtering/ - Off-axis projection: https://manuelbehrendt.github.io/Mera.jl/stable/06_offaxis_Projection/ - Off-axis cheatsheet: https://manuelbehrendt.github.io/Mera.jl/stable/offaxis_cheatsheet/ - Periodic boxes: https://manuelbehrendt.github.io/Mera.jl/stable/periodic_boxes/ - Profiles and phase diagrams: https://manuelbehrendt.github.io/Mera.jl/stable/15_multi_Profiles_Phase/ - Find the right function by task: https://manuelbehrendt.github.io/Mera.jl/stable/where_to_start/ - Reproducibility: https://manuelbehrendt.github.io/Mera.jl/stable/reproducibility/ - Mera files, saving and reloading: https://manuelbehrendt.github.io/Mera.jl/stable/07_multi_Mera_Files/ - Exporting data for other tools (1.9): https://manuelbehrendt.github.io/Mera.jl/stable/exporting_data/ - Sidecars, citing and publishing (1.9): https://manuelbehrendt.github.io/Mera.jl/stable/export_sidecars/ - Complete worked recipes: https://manuelbehrendt.github.io/Mera.jl/stable/gallery/ - Full API: https://manuelbehrendt.github.io/Mera.jl/stable/api/