OIFITS Handling
Reading
| Function | Description |
|---|---|
readoifits(file) | Read an OIFITS file into an OIdata struct; binning averages channels, insname / targetname read one instrument / target |
readoifits_multiepochs(file) | Read multi-epoch OIFITS data |
list_oifits_targets(file) | List all target names in an OIFITS file |
filter_data(data, idx; drop) | Remove the points set_data_filter selects; drop removes whole observables (:t3amp, :visphi, …) |
set_data_filter(data; kwargs...) | The indices of the points outside the given ranges (wavelength, MJD, baseline, …), for filter_data |
readfits(file) | Read a FITS image into a matrix |
writefits(data, file; pixsize, wavelengths, bandwidths, mjds, header) | Write an image or a cube to FITS, with its WCS, in the convention shared with ROTIR |
read_model_image(file) | Read a FITS image or cube for use as a model component: East-first, with its pixel scale, wavelengths and epochs |
model_image_plane(image, λ, mjd) | Which plane of a model image a data point uses |
model_image_vis(image, uv; wl, mjd) | Its complex visibilities at uv points, plane by plane |
fits_pixsize(file) | Pixel scale of a FITS image in mas, from its WCS keywords, or nothing |
oifits_prep(data; kwargs...) | Inflate error bars (additive/relative floors, multiplicative scaling) |
write_oifits(path, data; targetname, overwrite) | Write a dataset, filtered or binned, to an OIFITS v2 file |
merge_oidata(datas), readoifits(files::Vector) | Several files as one dataset: stations matched by name, every point kept |
updatefits_aspro(in, out, pixsize) | Add ASPRO-compatible WCS headers to a FITS image |
OITOOLS.load_oifits(file; notes) | The file as an OIDataSet, read table by table (below) |
OITOOLS.OIdata — Type
OIdata{T<:AbstractFloat}Central data container produced by readoifits. All observable arrays are flat vectors of length nobs; UV coordinates are stored in a 2×nuv matrix.
Observable arrays
v2,v2_err— squared visibilities and errorsv2_baseline,v2_lam,v2_dlam,v2_mjd,v2_flag— spatial frequency B/λ (cycles/rad), λ (m), Δλ (m), MJD, flagt3phi,t3phi_err,t3amp,t3amp_err— closure phases (deg) and triple amplitudest3_baseline— geometric mean of the three legs' B/λ (cycles/rad);t3_maxbaseline— longest leg, same unitst3_lam,t3_dlam,t3_mjd,t3_flagvisamp,visamp_err,visphi,visphi_err— complex visibility amplitude and phase (deg)vis_baseline(B/λ, cycles/rad),vis_lam,vis_dlam,vis_mjd,vis_flagflux,flux_err,flux_lam,flux_dlam,flux_mjd,flux_flagflux_sta_index— station index for each flux point;0means calibrated (OI_FLUX CALSTAT=C)flux_calibrated—trueif OI_FLUX has CALSTAT="C" (calibrated source spectrum / SED)
UV plane
uv—2×nuvmatrix of (u, v) spatial frequencies as baseline/λ. This is dimensionless — cycles per radian, not cycles/m. Plots divide by 1e6 and label Mλ; multiply by λ to recover the projected baseline in metres.uv_lam,uv_dlam,uv_mjd,uv_baseline.uv_mjdis the array$MJDresolves from; like the per-tablev2_mjd,t3_mjd,vis_mjdandflux_mjdit isFloat64whateverTis.indx_v2,indx_vis— index of each V²/vis point into the UV arrayindx_t3_1,indx_t3_2,indx_t3_3— UV indices for the three legs of each triangle
Station / telescope metadata
sta_name,tel_name,sta_index— station names, telescope names, station indicesv2_sta_index—2×nv2matrix;t3_sta_index—3×nt3matrix;vis_sta_index—2×nvis
Sizes
nv2,nt3amp,nt3phi,nvisamp,nvisphi,nflux,nuv
Correlation matrices (from OI_CORR; empty sparse matrices when absent)
v2_corr,v2_corr_idx— V² correlation matrix and per-point 1-based indext3amp_corr,t3amp_corr_idx,t3phi_corr,t3phi_corr_idxvisamp_corr,visamp_corr_idx,visphi_corr,visphi_corr_idxflux_corr,flux_corr_idx*_corr_idx[i] == 0means pointihas no associated correlation row.
Source tables
tables— one entry per observable table read, aNamedTuple(extname, insname, arrname, amptyp, phityp): the extension ("OI_VIS2"…), its instrument and array names, and for OI_VIS its AMPTYP / PHITYPvis_tab,v2_tab,t3_tab,flux_tab— for each point, the index of its table intables(0when none is known)
Other
mean_mjd::Float64— mean MJD of the bin (alwaysFloat64regardless ofT)filename— path to the originating OIFITS file
OITOOLS.writefits — Function
writefits(data, fitsfile; pixsize = -1, wavelengths = Float64[], bandwidths = Float64[],
mjds = Float64[], header = Pair{String,Any}[], refpix = nothing)Write an image or a cube to a FITS file, in the convention shared with ROTIR's write_sky_cube, readable by read_model_image and WCS-aware viewers.
data keeps its own dimensionality: a matrix is written 2-D, a reconstruction (nx, nx, nwav, nepoch) 4-D. Dimension 1 is East and dimension 2 North, as everywhere in this package.
pixsize is in milliarcseconds; without it no WCS is written. With it:
| key | value |
|---|---|
CTYPE1, CTYPE2 | 'RA---SIN', 'DEC--SIN' |
CUNIT1, CUNIT2 | 'deg' |
CDELT1, CDELT2 | +pixsize/3.6e6, positive: the index increases East and North |
CRPIX1, CRPIX2 | nx÷2+1, the NFFT's phase centre, or refpix = (x, y); CRVAL1/2 = 0, offsets from it |
PIXSIZE | the pixel size in mas, as a convenience |
wavelengths (metres, one per plane of axis 3) make axis 3 WAVE; bandwidths (metres) are optional. mjds (one per plane of axis 4) make axis 4 TIME, in days, UTC. An axis gets CRPIX/CRVAL/CDELT when its values are evenly spaced to 1%, otherwise WAVEIRR = T / TIMEIRR = T. The exact values are written to a CHANNELS (EFF_WAVE, EFF_BAND) or EPOCHS (MJD) table, which readers take first.
NORMALIZ = 'PLANE' is written when every plane sums to 1.
header holds further cards (name => value or name => (value, comment)), written ahead of the ones above.
See also fits_pixsize. Files in radians, with a negative CDELT1 and CRPIX = nx/2 are read; read_model_image warns about them.
OITOOLS.fits_pixsize — Function
fits_pixsize(fitsfile) -> Float64 or nothingThe pixel size of an image FITS in milliarcseconds, or nothing when the header does not give it.
Reads CDELT2 (then CDELT1, then CD2_2/CD1_1), converted with the axis's CUNIT. Without CUNIT: radians when the CDELT comment says radians, otherwise degrees (the FITS default) if the result is between 1e-4 and 1e4 mas, otherwise nothing.
OITOOLS.ModelImage — Type
ModelImageAn image or cube read for use as a model component, in OITOOLS' layout.
| field | meaning |
|---|---|
image | (nx, ny, nλ, nt), dimension 1 East, dimension 2 North, Float64 |
pixsize | mas per pixel |
wavelengths | length nλ, metres; NaN when the file does not say (a grey image) |
bandwidths | length nλ, metres; NaN when the file does not say |
mjds | length nt, MJD; NaN when the file does not say |
normalization | :plane (each plane sums to 1) or :relative (the cube's own SED and light curve kept) |
offset | (east, north) in mas of the file's reference pixel from the phase-centre pixel nx÷2+1; zero in the shared convention |
path | the file it came from |
OITOOLS.read_model_image — Function
read_model_image(path; pixsize = nothing, normalization = nothing) -> ModelImageRead a FITS image or cube for use as a model component, in the convention shared with ROTIR.
Dimensions. 2-D, 3-D and 4-D are accepted, a missing axis being length 1. A 3-D file is a wavelength cube or a time series according to CTYPE3 (WAVE or TIME); a 3-D file with more than one plane and no CTYPE3 is an error.
Orientation. The returned array has dimension 1 East and dimension 2 North:
- a file whose
CTYPE1names RA is read by its WCS:CDELT1 > 0is East-first;CDELT1 < 0(East to the left) is flipped.CDELT2 < 0is flipped likewise; - a file without
CTYPE1is read as stored, East-first, whatever the sign of itsCDELT1.
Pixel scale from fits_pixsize (CDELT or CD, with its CUNIT), or pixsize in mas, which takes precedence. Without either, an error is raised.
Reference pixel. The convention puts it at nx÷2+1, the NFFT's phase centre. Elsewhere, the difference is stored in offset and applied as a shift, so positions are relative to the file's reference pixel.
Wavelengths and epochs come from the CHANNELS (EFF_WAVE, optional EFF_BAND) and EPOCHS (MJD) tables when present. Otherwise from a linear WCS on axes 3 and 4 (CRVAL, CDELT, CRPIX, CUNIT, MJDREF); WAVEIRR/TIMEIRR = T without the table is an error.
Normalisation from NORMALIZ, or normalization (:plane or :relative), which takes precedence:
:plane(PLANE, and a file without the key): each plane divided by its sum (not bysum(abs)or the peak).:relative(RELATIVE): the whole cube divided by its brightest plane's sum, keeping its SED and light curve.
A plane summing to zero or less is an error.
OITOOLS.model_image_plane — Function
model_image_plane(mi, λ, mjd; wave_tol = nothing, mjd_tol = 0.5) -> (iλ, it)The plane of mi that a data point at wavelength λ (metres) and epoch mjd is evaluated with: the nearest in wavelength and the nearest in time, each within a tolerance, never an interpolation between planes.
- Wavelength. A single plane, or planes with no wavelength, serve every λ — a grey image. Otherwise the nearest plane, which must lie within half its
EFF_BANDwhen the file gives one, else within a quarter of the gap to its neighbouring plane: a channel's drift between nights is accepted (MIRC-X's channel 1: 1.515382 and 1.515206 µm five nights apart), a different channel is not (a cube of channels 1 and 4 serves neither 2 nor 3). Further away is an error listing the cube's channels.wave_tol(relative) overrides both. - Epoch. A single epoch, or epochs with no MJD, serve every time. Otherwise the nearest, within
mjd_toldays (default 0.5: one night's points share an epoch).
OITOOLS.model_image_vis — Function
model_image_vis(mi, uv; wl = nothing, mjd = nothing, cache = nothing, name = "image")
-> Vector{ComplexF64}The complex visibilities of the model image mi at the uv points uv (2×N, cycles/rad), each point evaluated with the plane model_image_plane picks for its wavelength wl (metres) and epoch mjd — per point, or one value for all. A plane is used as stored: one summing to 1 gives V(0) = 1, a :relative plane gives its own flux. mi.offset is applied as a shift.
A cube needs wl (and an epoch series mjd) to choose planes, and a point outside the cube's channels or epochs is an error from model_image_plane.
At a uv point beyond the image's Nyquist frequency, 1/(2 pixsize), the visibility is set to 0, with a warning (once per cache) naming the component (name) and the baseline.
With cache, a uv set seen before is returned without a transform.
OITOOLS.readoifits — Function
readoifits(files::AbstractVector{<:AbstractString}; kwargs...) -> Array{OIdata{T}, 2}Several files as one dataset: each is read with the same keywords, then bin [i, j] of every file is merged by merge_oidata. The files must give the same bin layout (the same spectralbin / temporalbin, or polychromatic on files with the same channels); otherwise an error is raised.
readoifits(oifitsfile; kwargs...) -> Array{OIdata{T}, 2}Read an OIFITS file and return a 2-D array of OIdata{T} indexed as [nwavbin, ntimebin]. The simplest call returns a 1×1 array containing all data in a single bin.
Keyword arguments
Target selection
targetname— select a single target by name. Default: all targets combined.insname— select one instrument (an OI_WAVELENGTH table'sINSNAME, e.g. GRAVITY's science or fringe-tracker channel): only its wavelength table and the observable tables that refer to it are read. Default: every instrument.
Averaging channels (binning)
binning— average spectral channels: an integer n (n adjacent channels become one), or a vector of[λ_min, λ_max]windows in metres (each window's channels become one).0, the default, keeps every channel. Applied to each table before anything else, so grouping,polychromaticand the filters see the averaged channels. OI_CORR, which describes the original channels, is then not used.binmode—:block(default): exact groups of channels, weights 1/σ², phases by the weighted circular mean, a channel's bandwidth the span it averages;:pmoired: PMOIRED'sbinning, for reproducing its results (a regular grid, a Gaussian kernel, errors not reduced).bincorr— c, channels per independent element (:block): the averaged error isσ_mean·√c, withσ_mean = (Σ 1/σ²)^(-1/2). 1 (default) for independent channels; n for no reduction; about 2-3 for an oversampled spectrograph.binstats— aDict{Symbol,Float64}to receive, per observable, the χ²/dof of the averaged channels about a straight line in λ within each new channel (:block). Near 1: the errors describe the channel-to-channel scatter. Well below 1: neighbouring channels agree better than their errors say — correlated channels (raisebincorr) or inflated errors. Well above 1: the errors are underestimated.
Grouping channels, and time windows
spectralbin— vector of[λ_min, λ_max]windows in metres: GROUPS the channels into polychromatic bins, every channel kept (oneOIdataper window). To average channels into one, usebinning. Default: single bin spanning all wavelengths.temporalbin— vector of[mjd_min, mjd_max]windows. Default: single bin spanning all epochs.polychromatic— iftrue, derive one spectral bin per instrument channel using midpoints between adjacent channel centres as boundaries. Overridesspectralbin.merge_oi_wavelength— iftrueandpolychromatic=true, check whether all OIWAVELENGTH tables share the same spectral channels (matching `effbandoverlap) and, if so, deduplicate them to avoid redundant bins. Errors if tables are incompatible. Ignored whenspectralbinis explicitly provided. Default:false`.splitting— force multi-bin mode even when bin vectors equal[[]].get_specbin_file— auto-derive spectral bins from the file. Default:true.get_timebin_file— auto-derive temporal bins from the file. Default:true.
Observable selection
use_vis,use_v2,use_t3,use_flux— load each observable type. Default: alltrue.
Quality filtering
filter_bad_data— apply quality cuts on load. Default:true.ignore_flags— reset the file's FLAG columns to false on load, so a flagged point is kept unless it fails another cut (oimodeler'soimResetFlagsFilter). The flags are cleared in the returned data too. Default:false.force_full_vis— require both visamp and visphi to be valid. Default:false.force_full_t3— require both t3amp and t3phi. Default:false.cutoff_minv2,cutoff_maxv2— V² range cut. Default:(-1, 2.0).cutoff_mint3amp,cutoff_maxt3amp— T3amp range cut. Default:(-1.0, 1.5).filter_v2_snr_threshold— minimum |V²/σ|. Default:0.01.special_filter_diffvis— differential visibility mode: keep only vis points common across all spectral bins.
UV deduplication
redundance_remove— merge UV points closer thanuvtol. Default:true.uvtol— merge radius in cycles/rad (i.e. B/λ). Default:200.0.
Numeric precision
T— element type of the numeric arrays. Default:Float32. MJDs areFloat64for anyT.
Output
warn— print warnings about non-standard files. Default:true.verbose— print summary of loaded tables. Default:true.
Example
data = readoifits("mystar.oifits") # all data, single bin
data = readoifits("mystar.oifits"; polychromatic=true) # one bin per channel
data = readoifits("multi.oifits"; polychromatic=true, merge_oi_wavelength=true) # merge compatible tables
data = readoifits("mystar.oifits"; T=Float64) # double precision
data = readoifits("multi.oifits"; targetname="Betelgeuse") # one targetOITOOLS.readoifits_multiepochs — Function
readoifits_multiepochs(oifitsfiles; polychromatic=false, kwargs...) -> Matrix{OIdata{T}}Read a list of OIFITS files, one per epoch, and return a Matrix{OIdata{T}} of size (nwav, nepochs).
- Without
polychromatic: each file yields a single spectral bin →1 × nepochs - With
polychromatic=true: each file is split into wavelength channels →nwav × nepochs
Mean MJD per epoch is available via data[1,i].mean_mjd.
Prints a summary line per file. Passes filter_bad_data, force_full_t3, and polychromatic through to readoifits.
OITOOLS.filter_data — Function
filter_data(data, indexes_to_discard; drop = Symbol[]) -> OIdataReturn a deep copy of data with the specified points removed. indexes_to_discard must be the five-element vector [uv_bad, vis_bad, v2_bad, t3_bad, flux_bad] returned by set_data_filter. UV points that become unreferenced after removing observables are pruned automatically and all index arrays are remapped.
drop removes whole observables, any of :v2, :t3amp, :t3phi, :visamp, :visphi, :flux. A T3 amplitude and its closure phase are one point, as are a VIS amplitude and its phase: dropping one half keeps the point for the other, the dropped half held as "not measured" (0 ± Inf, uncounted, ignored by χ², written back as NaN); a point whose other half is not measured either is removed. Dropping both halves, :v2 or :flux removes the points.
Example
idx = set_data_filter(data[1,1]; filter_bad_data=true, baseline_range=[5e6, 300e6])
clean = filter_data(data[1,1], idx)The default indexes_to_discard discards nothing.
OITOOLS.set_data_filter — Function
set_data_filter(data; kwargs...) -> [uv_bad, vis_bad, v2_bad, t3_bad, flux_bad]Compute lists of indices to discard from a loaded OIdata bin without modifying it. Pass the result to filter_data to obtain a filtered copy.
Keyword arguments
wav_range— wavelength window(s) in metres, e.g.[1.6e-6, 1.8e-6]or a vector of windows[[1.6e-6,1.8e-6],[2.0e-6,2.4e-6]]. Default: keep all.mjd_range— MJD window(s), same format. Default: keep all.baseline_range—[min, max]spatial frequency B/λ in cycles/rad (the same units asuv_baseline, so e.g.[5e6, 300e6]is 5–300 Mλ). Default: keep all.baseline_length_range—[min, max]projected baseline length in metres (B/λ × λ). Default: keep all.filter_bad_data— apply quality cuts (flags, NaN, SNR, amplitude range). Default:false.ignore_flags— the quality cuts disregard the FLAG columns. Default:false.filter_vis,filter_v2,filter_t3amp,filter_t3phi,filter_flux— enable cuts per observable type.cutoff_minv2,cutoff_maxv2— V² range cut. Default:(-1, 2.0).cutoff_mint3amp,cutoff_maxt3amp— T3 amplitude range cut. Default:(-1.0, 1.5).filter_v2_snr_threshold— minimum |V²/σ| to keep. Default:0.01.force_full_vis— require both amplitude and phase to be valid (default: either).force_full_t3— require both T3amp and T3phi to be valid (default: either).special_filter_diffvis— enable differential visibility filtering mode.uv_bad— pre-supplied list of UV indices to remove.remove_v2,remove_t3,remove_vis,remove_flux— indices of individual points to remove (intov2, the T3 arrays, the VIS arrays,flux): points picked by hand, as the GUI's selection tools do.filter_visphi,filter_visamp— enable visibility phase/amplitude filtering.exclude_stations— station names (sta_name, e.g.["E1", "W2"]): every V², VIS, T3 and flux point that uses one is removed.exclude_baselines— baselines as"S1-S2"in either order: the V² and VIS points on them, and every T3 point with one of them among its three baselines.exclude_triangles— triangles as"S1-S2-S3"in any order: those T3 points.max_v2_err,max_t3amp_err,max_t3phi_err(degrees),max_visamp_err,max_visphi_err(degrees),max_flux_err— remove points whose error bar is above this.max_v2_err_rel,max_t3amp_err_rel,max_visamp_err_rel,max_flux_err_rel— above this fraction of the value's magnitude. DefaultInf: no cap. A T3 or VIS point holds its amplitude and phase together, so a cap on either removes the point. To inflate error bars, seeoifits_prep.
Returns [uv_bad, vis_bad, v2_bad, t3_bad, flux_bad] — five Vector{Int64} of indices to discard.
OITOOLS.oifits_prep — Function
oifits_prep(data; quad = false, kwargs...) -> dataInflate error bars in place: per observable, a floor (absolute min_*_err_add, relative min_*_err_rel, a fraction of the value) and a multiplier (*_err_mult). Linear by default, each error bar becoming the larger of mult·σ and |value·rel| + add; with quad = true the terms add in quadrature, √((value·rel)² + (mult·σ)² + add²). Phases (T3φ, VISφ) take no relative floor; their absolute floor is in degrees.
| observable | floor | relative floor | multiplier |
|---|---|---|---|
| V² | min_v2_err_add | min_v2_err_rel | v2_err_mult |
| T3amp | min_t3amp_err_add | min_t3amp_err_rel | t3amp_err_mult |
| T3φ | min_t3phi_err_add | — | t3phi_err_mult |
| VISamp | min_visamp_err_add | min_visamp_err_rel | visamp_err_mult |
| VISφ | min_visphi_err_add | — | visphi_err_mult |
| flux | min_flux_err_add | min_flux_err_rel | flux_err_mult |
The defaults change nothing. To remove points with large error bars, see set_data_filter's max_*_err keywords.
OITOOLS.write_oifits — Function
write_oifits(path, data; template = :auto, targetname = "", overwrite = false) -> pathWrite an OIdata, or an array of them (the bins readoifits returns), to an OIFITS v2 file that readoifits reads back to the same points.
- One OI_WAVELENGTH table per instrument the points were read from (
data.tables), named by its INSNAME and holding the distinct wavelengths of that instrument's points, every bin included; points whose table is unknown go to an instrument named"OITOOLS". - Per instrument, one OIVIS2, OIT3 and OIFLUX table, and one OIVIS table per AMPTYP / PHITYP pair. One row per epoch, stations and baseline (or triangle), spanning the instrument's channels; a channel without a point is written NaN and flagged, so it is dropped again on reading. OI_FLUX likewise, per epoch and station.
- OITARGET is the original file's target named
targetname, or its first target whentargetnameis empty, and OIARRAY the data's own stations, their diameters and positions copied from the original file where the names match; both fromtemplate(by default the file the data was read from), or minimal when it cannot be read.
An existing file is refused unless overwrite = true.
OITOOLS.merge_oidata — Function
merge_oidata(datas) -> OIdataOne dataset holding every point of datas, typically the same bin of several files read separately. (OIFITS.jl refuses to merge files whose OI_TARGET entries share a name and differ in a coordinate, as files from different nights often do.)
- Stations are matched by NAME: each file's indices are renumbered into one table, so
A0in every file is one station; a blank name is never matched. Flux index 0 (a calibrated spectrum, no telescope) stays 0. - uv points are appended and each observable's uv indices shifted with them.
- OI_CORR matrices are combined block-diagonally: no correlation is assumed across files.
filenameis the first file's; the target is whatever the first file's is.
An ArgumentError is raised for files whose VIS points differ in AMPTYP or PHITYP, and for files whose fluxes differ in calibration.
OITOOLS.load_oifits — Function
load_oifits(path; notes = String[]) -> OIFITS.OIDataSetRead an OIFITS file as an OIDataSet, table by table, accepting what the standard's readers refuse when the data are still readable. Each table is read at the revision it declares; if that fails, at the other revisions OIFITS.jl defines (highest first); if none reads it, with a missing column tolerated – FLUX read as OIFLUX's FLUXDATA, one half of an amplitude/phase pair left NaN. Rows whose TARGETID is not in the file's OI_TARGET are dropped (a table left empty is skipped), as PMOIRED does. A ZIP archive holding one FITS file is read through that file.
Each such step is described in notes, one line per table. A table that cannot be read at all throws, naming the first reason.
Files that break the standard
All readers open a file through load_oifits, which reads it table by table. These deviations from the standard are read as follows:
| In the file | Read as |
|---|---|
a table without a column its declared revision requires (FOV in OI_ARRAY) | the revision whose columns it has |
| a revision OIFITS does not define (OI_ARRAY at 5) | the highest defined revision that reads |
OI_FLUX with its data in FLUX (GRAVITY) | FLUX as FLUXDATA |
| OI_VIS with amplitudes only, or phases only | the missing half "not measured" (see below) |
| rows whose TARGETID is not in OITARGET | left out; a table left without rows is skipped |
| a ZIP archive holding one FITS file | that FITS file |
readoifits lists these in one warning per file (warn = true); validate_oifits reports each.
Missing half. A T3 amplitude and its closure phase are one point, as are a VIS amplitude and its phase. When a point has only one half, the other is stored as 0 ± Inf: it is not counted (nt3amp, nvisphi, …), not in χ², not plotted, and written back as NaN. filter_data(…; drop = [:t3amp]) does the same to a half the file has.
Inspecting, checking and splitting files
| Function | Description |
|---|---|
oifits_headers(file) | Every HDU of a FITS file: extension, instrument, revision, rows, columns, image dimensions, and every header card in order |
oifits_table(file, hdu; per_channel) | A table HDU's contents as the file stores them; an OI data table per channel, with λ, stations, B and B/λ joined |
validate_oifits(file) | A list of (severity, table, message): what does not follow the standard, what was read around, and suspect values |
repair_oifits(file, out; targetname) | A copy of the file as clean OIFITS v2, one target at a time |
split_by_time(data; gap, binwidth, edges) | One OIdata per epoch, the epochs taken from every observable's times |
split_by_instrument(data) | One OIdata per instrument, from the table each point was read from |
split_by_target(file; kwargs...) | One dataset per target, each read with targetname |
join_targets(files, out) | Several OIFITS files written as one, a target per file listed in one OI_TARGET |
fits_set_keywords(file, out; pixsize, east_left, axis3, wavelengths, mjds, refpix) | A FITS image or cube written with the keywords read_model_image reads; the file's reference pixel and other cards kept |
fits_refpix(file) | Its reference pixel (CRPIX1, CRPIX2), or nothing |
fits_keyword_cube(file; east_left, axis3) | Its array as an (East, North, wavelength, epoch) cube |
OITOOLS.oifits_headers — Function
oifits_headers(path) -> Vector{NamedTuple}Every HDU of a FITS file, in order, as (index, extname, kind, revn, insname, arrname, nrows, dims, columns, cards):
kind—:primary,:imageor:table;extnameis""when the HDU has none;revn—OI_REVN(0 when absent);insname,arrname—INSNAME,ARRNAME("");nrows— rows of a table, 0 otherwise;dims— an image's axis lengths (NAXISn), empty for a table or a header-only HDU;columns— one(name, format, unit, dims)per table column, fromTTYPEn,TFORMn,TUNITn,TDIMn(""when absent);cards— every header card in order, COMMENT and HISTORY included, as(name, value, comment); a commentary card's text is itsvalue, and itscommentis"".
Works on any FITS file, images included. A ZIP archive holding one FITS file shows that file.
OITOOLS.oifits_table — Function
oifits_table(path, hdu; per_channel = true) -> NamedTupleThe contents of table HDU hdu (its index, as oifits_headers numbers them) of a FITS file, as (extname, names, units, comments, columns, nlines, flagged, per_channel, nwave, wl): columns[j] holds column names[j], one entry per line, with its unit (TUNIT) and its comment (the TTYPE card's), flagged a line's FLAG.
- An OI data table (OIVIS2, OIVIS, OIT3, OIFLUX) with
per_channel(the default): one line per row and channel, its array columns (VIS2DATA, VIS2ERR, FLAG, …) as one value each, and joined in frontλ(µm, from the OIWAVELENGTH with the row's INSNAME),stations(names from OIARRAY, through STA_INDEX),B(m, from UCOORD/VCOORD — the longest of a triangle's three) andB/λ(Mλ). - Otherwise the table as stored, one line per row; an array column's entries are vectors (
nwave, the channel count of an OI data table, for picking one channel of them;wlthe channels' wavelengths in µm).
A ZIP archive holding one FITS file shows that file.
OITOOLS.validate_oifits — Function
validate_oifits(path) -> Vector{NamedTuple}Check an OIFITS file and report what is wrong with it, as (severity, table, message) with severity one of :error (the file breaks the standard or cannot be read), :warning (it reads, but some data are suspect) and :info. An empty report means nothing was found.
The file is first read HDU by HDU (as oifits_headers does), then as readoifits opens it (load_oifits, table by table), and the data are checked:
- everything the opening had to work around, as warnings – a table that does not read at the revision it declares (a missing column, a revision that does not exist), GRAVITY's
FLUXread as OIFLUX'sFLUXDATA, one half of an amplitude/phase pair missing, rows whose TARGETID is not in OI_TARGET (dropped); a table that cannot be read at all, as an error. A ZIP archive is checked through the FITS file it holds, and said to be one; - INSNAME / ARRNAME with no OIWAVELENGTH / OIARRAY; two OIWAVELENGTH tables with one INSNAME; OIWAVELENGTH tables no data table uses; stations absent from their OIARRAY; TARGETIDs absent from OI_TARGET;
- AMPTYP / PHITYP disagreeing between OI_VIS tables (
readoifitskeeps one label per dataset); - per table: empty tables; unflagged points with NaN values or NaN / non-positive errors, or one half of a VIS / T3 pair carried with a non-finite error; the flagged fraction;
- what a repaired copy (
repair_oifits) would not keep: HDUs other than the OIFITS tables, several targets.
OITOOLS.repair_oifits — Function
repair_oifits(path, out; targetname = "", overwrite = false) -> outWrite a repaired copy of an OIFITS file: read by readoifits (every point kept, uv points not merged) and written by write_oifits as OIFITS v2: missing columns filled (e.g. FOV in OIARRAY), each instrument under its own name, OITARGET at revision 2. out cannot be path.
What the copy does not keep: HDUs other than the OIFITS tables, columns OITOOLS does not read, flagged points, OICORR, and whatever [`loadoifits](@ref) had to leave out (rows whose TARGET_ID is not in OI_TARGET). A ZIP archive's FITS file is written as a plain FITS file. A file with several targets is repaired one target at a time (targetname). [validate_oifits`](@ref) lists what would be lost.
OITOOLS.split_by_time — Function
split_by_time(data; gap = 0.5, binwidth = nothing, edges = nothing) -> (parts, mjd)Split an OIdata into epochs, from the times of all observables (V², T3, VIS, flux).
gap(days, default): a new epoch wherever consecutive times are more thangapapart;binwidth(days): fixed windows from the first time,[t₀ + kw, t₀ + (k+1)w);edges: given windows, a vector of(lo, hi)MJD pairs, inclusive (a point inside two windows goes to both).
parts holds one OIdata per non-empty epoch, made by filter_data; mjd is the mean time of each part's points. Points are assigned by their Float64 MJDs (v2_mjd, …).
OITOOLS.split_by_instrument — Function
split_by_instrument(data) -> Vector{Pair{String, OIdata}}Split an OIdata by instrument (the INSNAME of each point's table, data.tables), in the order the tables were read, without re-reading the file. Works on a filtered, merged or binned dataset. Points whose table is unknown are left out.
OITOOLS.split_by_target — Function
split_by_target(path; kwargs...) -> Vector{Pair{String, Matrix{OIdata}}}Read an OIFITS file once per target (readoifits(path; targetname, kwargs...)), in the order of its OI_TARGET table.
OITOOLS.join_targets — Function
join_targets(files, out; overwrite = false) -> outWrite the OIFITS files files into one file out: one OITARGET listing every target, each renumbered, and each data table kept with its rows pointing at its target. Tables of the same name (OIARRAY, OIWAVELENGTH, OICORR) are written once, and must be identical across the files. A target named in several files is one target. out may not be one of files.
OITOOLS.fits_set_keywords — Function
fits_set_keywords(path, out; pixsize, east_left = false, axis3 = :wave,
wavelengths = Float64[], mjds = Float64[], refpix = :file) -> StringWrite the image or cube of path to out with the keywords read_model_image reads: the array East-first (east_left when the file stores East on the left), the pixel size pixsize in mas, axis 3 the wavelengths (metres, one per plane) and axis 4 the epochs (MJD, one per plane), in the layout of writefits. axis3 = :time says the file's third axis is time (a 4-D file's axes 3 and 4 are then swapped). Every other card of the primary header (OBJECT, DATE-OBS, …) is copied; other HDUs are not. out may be path, which is then overwritten.
An axis with more than one plane needs its values, and their number must be the number of planes.
refpix is the reference pixel (x, y) — the image's origin — in the file's own pixel numbering (as CRPIX1, CRPIX2): :file takes the file's CRPIX1/2, or the phase centre nx÷2+1 when it has none; nothing the phase centre. A reference pixel off the phase centre is written as such, and read_model_image reads it back as the image's offset.
OITOOLS.fits_keyword_cube — Function
fits_keyword_cube(path; east_left = false, axis3 = :wave) -> Array{T,4}The primary array of a FITS file as an (East, North, wavelength, epoch) cube, in the file's own element type: axis 1 reversed when the file stores East on the left (east_left); a third axis read as wavelengths (axis3 = :wave) or epochs (:time, which for a 4-D file swaps the last two axes). A 2-D image is one plane.
OITOOLS.fits_refpix — Function
fits_refpix(path) -> Union{Nothing,NTuple{2,Float64}}The reference pixel (CRPIX1, CRPIX2) of a FITS file's primary header, or nothing when it does not give both.
File utilities
| Function | Description |
|---|---|
oifits_fix_tdim(file) | Remove the TDIM cards cfitsio writes on scalar columns, in place (astropy and PMOIRED read those columns as 2-D) |
oifits_check(; infile) | Run oifitslib's oifits-check on a file |
oifits_merge(; outfile, infiles) | Run oifitslib's oifits-merge; infiles a vector or a glob pattern |
oifits_filter(; outfile, infile, …) | Run oifitslib's oifits-filter with its selection options |
The last three call the command-line tools of John Young's oifitslib, which must be on the PATH.
OITOOLS.oifits_fix_tdim — Function
oifits_fix_tdim(file) -> IntRemove the one-dimensional TDIMn cards (TDIMn = (1)) that CFITSIO writes on scalar columns, in place, and return how many were removed. Files written through OIFITS.write (simulate, simulate_from_oifits, …) have them; astropy then reads those columns as (nrow, 1), and PMOIRED fails with TypeError: cannot use 'numpy.ndarray' as a set element. Multi-element columns (VIS2DATA, FLAG, STA_INDEX, …) keep their TDIM.
PMOIRED compatibility
| Function | Description |
|---|---|
pmoired_to_dict(s) | Convert a PMOIRED model string to a Julia Dict |
pmoired_to_julia(s) | Convert a PMOIRED model string to Julia source code (returns String) |
pmoired_to_julia_file(infile, outfile) | Convert a PMOIRED notebook snippet file |
dict_to_pmoired(d) | Render an OITOOLS model dict as PMOIRED source (returns String) |
dict_to_pmoired_file(d, outfile) | Write an OITOOLS model dict out as PMOIRED source |
OITOOLS.pmoired_to_dict — Function
pmoired_to_dict(s) -> Dict{String,Any}Convert a PMOIRED Python dict literal string directly to a Julia Dict. It evaluates the string produced by pmoired_to_julia.
model_dict = pmoired_to_dict("{'star,ud': 3.2, 'ring,f': '1 - \$star,f'}")OITOOLS.pmoired_to_julia — Function
pmoired_to_julia(s) -> StringConvert a PMOIRED Python dict literal string to an equivalent Julia Dict literal string. Handles nested dicts, expression strings with $ references, single-quoted strings, Python boolean/None literals, and list literals.
Transformation rules applied: { ... } -> Dict( ... ) 'key': value -> "key" => value (outside string literals) : -> => (outside string literals, single colon only) 'plain string' -> "plain string" 'expr with $ref' -> raw"expr with $ref" (raw string prevents interpolation) True / False -> true / false None -> nothing
Example
# Python / PMOIRED:
param = {
'star,ud': 3.2,
'star,f': 0.7,
'ring,udout': '$star,ud * 8',
'ring,f': '1 - $star,f',
'ring,incl': 30.0,
}
fitOnly = ['star,ud', 'star,f', 'ring,udout', 'ring,f']# Generated Julia:
param = Dict(
"star,ud" => 3.2,
"star,f" => 0.7,
"ring,udout" => raw"$star,ud * 8",
"ring,f" => raw"1 - $star,f",
"ring,incl" => 30.0,
)
fitOnly = ["star,ud", "star,f", "ring,udout", "ring,f"]OITOOLS.pmoired_to_julia_file — Function
pmoired_to_julia_file(infile, outfile)Read a Python/PMOIRED notebook snippet from infile, convert it, write to outfile. Lines that look like param = {...} or fitOnly = [...] are converted; other lines are passed through.
OITOOLS.dict_to_pmoired — Function
dict_to_pmoired(model_dict; check=true) -> StringRender an OITOOLS model dictionary as PMOIRED source — the inverse of pmoired_to_dict.
Keys are sorted. Julia true, false and nothing become True, False and None; string values are quoted with single quotes, and in expressions ^ becomes Python's **; $-references are the same in both packages.
With check=true (the default) a warning is emitted for keys that have no PMOIRED equivalent (the ldlin/ldquad/ldpow/resolved geometries); the model is still written.
See also pmoired_to_dict, dict_to_pmoired_file.
OITOOLS.dict_to_pmoired_file — Function
dict_to_pmoired_file(model_dict, outfile; check=true)Write model_dict to outfile as PMOIRED source. Returns outfile. Inverse of pmoired_to_julia_file.
Utilities
| Function | Description |
|---|---|
recenter(x; mask, max) | Recenter an image by circular shift to centroid or peak |
sexagesimal_to_degrees(s) | Parse "-46 28 00.5" or "12:34:56" to decimal degrees (sign applies to the whole value) |
OITOOLS.recenter — Function
recenter(x; mask=[], max=false)Recenter an image by circular shifting so the centroid (or peak if max=true) is at the image center. Works on 1D (vectorized square image) or 2D arrays. If mask is provided, the centroid is computed from the mask instead.
OITOOLS.sexagesimal_to_degrees — Function
sexagesimal_to_degrees(s) -> Float64Parse a sexagesimal coordinate string into a single decimal value. Fields may be separated by whitespace or colons, and one, two or three of them may be given.
The sign applies to the whole quantity: "-00 30 00" is -0.5, and "-46 28 00.57" is -46.4668.
julia> sexagesimal_to_degrees("-46 28 00.5731825")
-46.46682588402778SIMBAD
| Function | Description |
|---|---|
simbad_target(name) | SIMBAD record in one request: coordinates, proper motion, parallax, radial velocity, spectral type, object type, magnitudes |
ra_dec_from_simbad(name) | RA and Dec in decimal degrees |
magnitudes_from_simbad(name) | Magnitudes, B through N |
simbad_tap(adql) | Any ADQL query against SIMBAD's TAP service; returns column names and rows |
SIMBAD_BANDS | The ten bands simbad_target reports, in panel order |
SIMBAD_TAP_URL | The TAP endpoint queries go to |
t = simbad_target("Vega")
t.main_id # "* alf Lyr"
t.ra, t.dec # 279.2347, 38.7837 (degrees)
t.plx # 130.23 mas
t.sptype # "A0V"
t.mags["K"] # 0.129
t.mags["N"] # NaN: no N magnitude in SIMBADCoordinates are in decimal degrees. A value SIMBAD does not hold is NaN ("" for a string). mags has all ten SIMBAD_BANDS as keys. ra_dec_from_simbad and magnitudes_from_simbad each make the same single request as simbad_target. Requests go through Downloads (no Python). An unreachable service, a refused query and a query with no rows raise errors with different messages.
simbad_tap runs any query on the SIMBAD schema and returns the header and the rows as Strings:
cols, rows = simbad_tap("SELECT TOP 5 main_id, plx_value FROM basic WHERE plx_value > 500")OITOOLS.simbad_target — Function
simbad_target(name; timeout = 30) -> NamedTupleA target's SIMBAD record in one request: (; name, main_id, ra, dec, pmra, pmdec, plx, rv, sptype, otype, mags).
ra/dec in degrees, proper motions mas/yr, parallax mas, radial velocity km/s. Missing values are NaN, a missing string "". mags has all ten SIMBAD_BANDS as keys, NaN where there is no measurement.
name is any SIMBAD identifier: "Vega", "alf Lyr", "HD 172167".
t = simbad_target("Vega")
t.ra, t.dec # 279.2347, 38.7837 degrees
t.mags["K"] # 0.129ra_dec_from_simbad and magnitudes_from_simbad each call it.
OITOOLS.ra_dec_from_simbad — Function
ra_dec_from_simbad(name) -> (ra_deg, dec_deg)A target's J2000 right ascension and declination in decimal degrees, through simbad_target.
OITOOLS.magnitudes_from_simbad — Function
magnitudes_from_simbad(name) -> Dict{String,Float64}A target's magnitudes, keyed by SIMBAD_BANDS, through simbad_target. Bands without a measurement are NaN; a network or query failure raises an error.
OITOOLS.simbad_tap — Function
simbad_tap(adql; url = SIMBAD_TAP_URL, timeout = 30) -> (colnames, rows)Run one ADQL query against SIMBAD's TAP service and return its column names and rows, all as Strings.
cols, rows = simbad_tap("SELECT TOP 5 main_id, ra, dec FROM basic WHERE plx_value > 500")The schema is at https://simbad.cds.unistra.fr/simbad/tap/tapsearch.html. An unreachable service and a refused query raise errors with different messages.
OITOOLS.SIMBAD_BANDS — Constant
SIMBAD_BANDSThe ten photometric bands simbad_target reports, B through N.
OITOOLS.SIMBAD_TAP_URL — Constant
SIMBAD_TAP_URLThe TAP endpoint queries are sent to; simbad_tap's url keyword overrides it (for example for the mirror at simbad.u-strasbg.fr).