OIFITS Handling

Reading

FunctionDescription
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 errors
  • v2_baseline, v2_lam, v2_dlam, v2_mjd, v2_flag — spatial frequency B/λ (cycles/rad), λ (m), Δλ (m), MJD, flag
  • t3phi, t3phi_err, t3amp, t3amp_err — closure phases (deg) and triple amplitudes
  • t3_baseline — geometric mean of the three legs' B/λ (cycles/rad); t3_maxbaseline — longest leg, same units
  • t3_lam, t3_dlam, t3_mjd, t3_flag
  • visamp, visamp_err, visphi, visphi_err — complex visibility amplitude and phase (deg)
  • vis_baseline (B/λ, cycles/rad), vis_lam, vis_dlam, vis_mjd, vis_flag
  • flux, flux_err, flux_lam, flux_dlam, flux_mjd, flux_flag
  • flux_sta_index — station index for each flux point; 0 means calibrated (OI_FLUX CALSTAT=C)
  • flux_calibrated — true if OI_FLUX has CALSTAT="C" (calibrated source spectrum / SED)

UV plane

  • uv — 2×nuv matrix 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_mjd is the array $MJD resolves from; like the per-table v2_mjd, t3_mjd, vis_mjd and flux_mjd it is Float64 whatever T is.
  • indx_v2, indx_vis — index of each V²/vis point into the UV array
  • indx_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 indices
  • v2_sta_index — 2×nv2 matrix; t3_sta_index — 3×nt3 matrix; 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 index
  • t3amp_corr, t3amp_corr_idx, t3phi_corr, t3phi_corr_idx
  • visamp_corr, visamp_corr_idx, visphi_corr, visphi_corr_idx
  • flux_corr, flux_corr_idx
  • *_corr_idx[i] == 0 means point i has no associated correlation row.

Source tables

  • tables — one entry per observable table read, a NamedTuple (extname, insname, arrname, amptyp, phityp): the extension ("OI_VIS2"…), its instrument and array names, and for OI_VIS its AMPTYP / PHITYP
  • vis_tab, v2_tab, t3_tab, flux_tab — for each point, the index of its table in tables (0 when none is known)

Other

  • mean_mjd::Float64 — mean MJD of the bin (always Float64 regardless of T)
  • filename — path to the originating OIFITS file
source
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:

keyvalue
CTYPE1, CTYPE2'RA---SIN', 'DEC--SIN'
CUNIT1, CUNIT2'deg'
CDELT1, CDELT2+pixsize/3.6e6, positive: the index increases East and North
CRPIX1, CRPIX2nx÷2+1, the NFFT's phase centre, or refpix = (x, y); CRVAL1/2 = 0, offsets from it
PIXSIZEthe 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.

source
OITOOLS.fits_pixsize — Function
fits_pixsize(fitsfile) -> Float64 or nothing

The 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.

source
OITOOLS.ModelImage — Type
ModelImage

An image or cube read for use as a model component, in OITOOLS' layout.

fieldmeaning
image(nx, ny, nλ, nt), dimension 1 East, dimension 2 North, Float64
pixsizemas per pixel
wavelengthslength nλ, metres; NaN when the file does not say (a grey image)
bandwidthslength nλ, metres; NaN when the file does not say
mjdslength 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
paththe file it came from
source
OITOOLS.read_model_image — Function
read_model_image(path; pixsize = nothing, normalization = nothing) -> ModelImage

Read 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 CTYPE1 names RA is read by its WCS: CDELT1 > 0 is East-first; CDELT1 < 0 (East to the left) is flipped. CDELT2 < 0 is flipped likewise;
  • a file without CTYPE1 is read as stored, East-first, whatever the sign of its CDELT1.

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 by sum(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.

source
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_BAND when 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_tol days (default 0.5: one night's points share an epoch).
source
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.

source
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.

source
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's INSNAME, 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, polychromatic and 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's binning, 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 — a Dict{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 (raise bincorr) 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 (one OIdata per window). To average channels into one, use binning. Default: single bin spanning all wavelengths.
  • temporalbin — vector of [mjd_min, mjd_max] windows. Default: single bin spanning all epochs.
  • polychromatic — if true, derive one spectral bin per instrument channel using midpoints between adjacent channel centres as boundaries. Overrides spectralbin.
  • merge_oi_wavelength — if true and polychromatic=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: all true.

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's oimResetFlagsFilter). 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 than uvtol. 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 are Float64 for any T.

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 target
source
OITOOLS.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.

source
OITOOLS.filter_data — Function
filter_data(data, indexes_to_discard; drop = Symbol[]) -> OIdata

Return 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.

source
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 as uv_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 (into v2, 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. Default Inf: 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, see oifits_prep.

Returns [uv_bad, vis_bad, v2_bad, t3_bad, flux_bad] — five Vector{Int64} of indices to discard.

source
OITOOLS.oifits_prep — Function
oifits_prep(data; quad = false, kwargs...) -> data

Inflate 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.

observablefloorrelative floormultiplier
V²min_v2_err_addmin_v2_err_relv2_err_mult
T3ampmin_t3amp_err_addmin_t3amp_err_relt3amp_err_mult
T3φmin_t3phi_err_add—t3phi_err_mult
VISampmin_visamp_err_addmin_visamp_err_relvisamp_err_mult
VISφmin_visphi_err_add—visphi_err_mult
fluxmin_flux_err_addmin_flux_err_relflux_err_mult

The defaults change nothing. To remove points with large error bars, see set_data_filter's max_*_err keywords.

source
OITOOLS.write_oifits — Function
write_oifits(path, data; template = :auto, targetname = "", overwrite = false) -> path

Write 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 when targetname is empty, and OIARRAY the data's own stations, their diameters and positions copied from the original file where the names match; both from template (by default the file the data was read from), or minimal when it cannot be read.

An existing file is refused unless overwrite = true.

source
OITOOLS.merge_oidata — Function
merge_oidata(datas) -> OIdata

One 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 A0 in 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.
  • filename is 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.

source
OITOOLS.load_oifits — Function
load_oifits(path; notes = String[]) -> OIFITS.OIDataSet

Read 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.

source

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 fileRead 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 onlythe missing half "not measured" (see below)
rows whose TARGETID is not in OITARGETleft out; a table left without rows is skipped
a ZIP archive holding one FITS filethat 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

FunctionDescription
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, :image or :table; extname is "" 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, from TTYPEn, 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 its value, and its comment is "".

Works on any FITS file, images included. A ZIP archive holding one FITS file shows that file.

source
OITOOLS.oifits_table — Function
oifits_table(path, hdu; per_channel = true) -> NamedTuple

The 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) and B/λ (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; wl the channels' wavelengths in µm).

A ZIP archive holding one FITS file shows that file.

source
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 FLUX read as OIFLUX's FLUXDATA, 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 (readoifits keeps 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.
source
OITOOLS.repair_oifits — Function
repair_oifits(path, out; targetname = "", overwrite = false) -> out

Write 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.

source
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 than gap apart;
  • 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, …).

source
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.

source
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.

source
OITOOLS.join_targets — Function
join_targets(files, out; overwrite = false) -> out

Write 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.

source
OITOOLS.fits_set_keywords — Function
fits_set_keywords(path, out; pixsize, east_left = false, axis3 = :wave,
                  wavelengths = Float64[], mjds = Float64[], refpix = :file) -> String

Write 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.

source
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.

source
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.

source

File utilities

FunctionDescription
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) -> Int

Remove 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.

source

PMOIRED compatibility

FunctionDescription
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'}")
source
OITOOLS.pmoired_to_julia — Function
pmoired_to_julia(s) -> String

Convert 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"]
source
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.

source
OITOOLS.dict_to_pmoired — Function
dict_to_pmoired(model_dict; check=true) -> String

Render 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.

source

Utilities

FunctionDescription
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.

source
OITOOLS.sexagesimal_to_degrees — Function
sexagesimal_to_degrees(s) -> Float64

Parse 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.46682588402778
source

SIMBAD

FunctionDescription
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_BANDSThe ten bands simbad_target reports, in panel order
SIMBAD_TAP_URLThe 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 SIMBAD

Coordinates 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) -> NamedTuple

A 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.129

ra_dec_from_simbad and magnitudes_from_simbad each call it.

source
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.

source
OITOOLS.SIMBAD_TAP_URL — Constant
SIMBAD_TAP_URL

The TAP endpoint queries are sent to; simbad_tap's url keyword overrides it (for example for the mirror at simbad.u-strasbg.fr).

source