use std::{f64::consts::FRAC_PI_2, fmt::Display, str::FromStr};
use thiserror::Error;
use crate::{Complex, Jones};
#[derive(Error, Debug, Clone, PartialEq, Eq)]
#[error("'{got}' is not a known {kind}; expected one of {expected}")]
pub struct UnknownConvention {
kind: &'static str,
got: String,
expected: &'static str,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum XOrientation {
#[default]
East,
North,
}
impl XOrientation {
pub const NAMES: &'static str = "east, north";
pub fn feed_angles_rad(self) -> [f64; 2] {
match self {
XOrientation::East => [FRAC_PI_2, 0.0],
XOrientation::North => [0.0, FRAC_PI_2],
}
}
pub fn from_feed_angle_rad(x_angle_rad: f64) -> XOrientation {
let a = x_angle_rad.rem_euclid(std::f64::consts::PI);
if (a - FRAC_PI_2).abs() < std::f64::consts::FRAC_PI_4 {
XOrientation::East
} else {
XOrientation::North
}
}
}
impl FromStr for XOrientation {
type Err = UnknownConvention;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim().to_lowercase().as_str() {
"east" | "e" => Ok(XOrientation::East),
"north" | "n" => Ok(XOrientation::North),
_ => Err(UnknownConvention {
kind: "x orientation",
got: s.to_string(),
expected: Self::NAMES,
}),
}
}
}
impl Display for XOrientation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
XOrientation::East => "east",
XOrientation::North => "north",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum StokesConvention {
#[default]
Avg,
Sum,
}
impl StokesConvention {
pub const NAMES: &'static str = "avg, sum";
}
impl FromStr for StokesConvention {
type Err = UnknownConvention;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim().to_lowercase().as_str() {
"avg" | "average" | "mean" => Ok(StokesConvention::Avg),
"sum" => Ok(StokesConvention::Sum),
_ => Err(UnknownConvention {
kind: "Stokes convention",
got: s.to_string(),
expected: Self::NAMES,
}),
}
}
}
impl Display for StokesConvention {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
StokesConvention::Avg => "avg",
StokesConvention::Sum => "sum",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum VisUnits {
#[default]
#[cfg_attr(feature = "serde", serde(rename = "uncalib"))]
Uncalib,
#[cfg_attr(feature = "serde", serde(rename = "Jy"))]
Jy,
#[cfg_attr(feature = "serde", serde(rename = "K str"))]
KStr,
}
impl VisUnits {
pub const NAMES: &'static str = "uncalib, Jy, K str";
pub fn is_calibrated(self) -> bool {
!matches!(self, VisUnits::Uncalib)
}
}
impl FromStr for VisUnits {
type Err = UnknownConvention;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim().to_lowercase().as_str() {
"uncalib" | "uncalibrated" => Ok(VisUnits::Uncalib),
"jy" => Ok(VisUnits::Jy),
"k str" | "k sr" => Ok(VisUnits::KStr),
_ => Err(UnknownConvention {
kind: "visibility units",
got: s.to_string(),
expected: Self::NAMES,
}),
}
}
}
impl Display for VisUnits {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
VisUnits::Uncalib => "uncalib",
VisUnits::Jy => "Jy",
VisUnits::KStr => "K str",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PolConvention {
pub x_orientation: XOrientation,
pub stokes: StokesConvention,
}
impl PolConvention {
pub const MWA: PolConvention = PolConvention {
x_orientation: XOrientation::East,
stokes: StokesConvention::Avg,
};
pub const IAU: PolConvention = PolConvention {
x_orientation: XOrientation::North,
stokes: StokesConvention::Avg,
};
pub const ASKAP: PolConvention = PolConvention {
x_orientation: XOrientation::North,
stokes: StokesConvention::Sum,
};
pub const NAMES: &'static str = "mwa (alias: oskar), iau (aliases: lofar, casacore, wsclean), askap (alias: askapsoft), or east|north[/avg|sum]";
pub fn stokes_to_instrumental(self, i: f64, q: f64, u: f64, v: f64) -> Jones<f64> {
let scale = match self.stokes {
StokesConvention::Avg => 1.0,
StokesConvention::Sum => 0.5,
};
match self.x_orientation {
XOrientation::East => Jones::from([
Complex::new(scale * (i - q), 0.0),
Complex::new(scale * u, -scale * v),
Complex::new(scale * u, scale * v),
Complex::new(scale * (i + q), 0.0),
]),
XOrientation::North => Jones::from([
Complex::new(scale * (i + q), 0.0),
Complex::new(scale * u, scale * v),
Complex::new(scale * u, -scale * v),
Complex::new(scale * (i - q), 0.0),
]),
}
}
pub fn instrumental_to_stokes(self, j: Jones<f64>) -> [f64; 4] {
let (xx, xy, yx, yy) = (j[0], j[1], j[2], j[3]);
let scale = match self.stokes {
StokesConvention::Avg => 0.5,
StokesConvention::Sum => 1.0,
};
let (i, q, u, v) = match self.x_orientation {
XOrientation::East => ((xx + yy).re, (yy - xx).re, (xy + yx).re, (yx - xy).im),
XOrientation::North => ((xx + yy).re, (xx - yy).re, (xy + yx).re, (xy - yx).im),
};
[scale * i, scale * q, scale * u, scale * v]
}
pub fn feed_angles_rad(self) -> [f64; 2] {
self.x_orientation.feed_angles_rad()
}
pub fn describe(self) -> String {
let (preset, mapping) = match self.x_orientation {
XOrientation::East => ("X east-west", "XX = I-Q, XY = U-iV, YX = U+iV, YY = I+Q"),
XOrientation::North => ("X north-south", "XX = I+Q, XY = U+iV, YX = U-iV, YY = I-Q"),
};
match self.stokes {
StokesConvention::Avg => format!("{preset}, {mapping}"),
StokesConvention::Sum => format!("{preset}, half of {mapping} (I = XX+YY)"),
}
}
}
impl FromStr for PolConvention {
type Err = UnknownConvention;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let lower = s.trim().to_lowercase();
match lower.as_str() {
"mwa" | "oskar" => return Ok(PolConvention::MWA),
"iau" | "lofar" | "casacore" | "wsclean" => return Ok(PolConvention::IAU),
"askap" | "askapsoft" => return Ok(PolConvention::ASKAP),
_ => (),
}
let unknown = || UnknownConvention {
kind: "polarisation convention",
got: s.to_string(),
expected: Self::NAMES,
};
let (x, stokes) = match lower.split_once('/') {
Some((x, stokes)) => (x, stokes),
None => (lower.as_str(), "avg"),
};
Ok(PolConvention {
x_orientation: x.parse().map_err(|_| unknown())?,
stokes: stokes.parse().map_err(|_| unknown())?,
})
}
}
impl Display for PolConvention {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
PolConvention::MWA => f.write_str("mwa"),
PolConvention::IAU => f.write_str("iau"),
PolConvention::ASKAP => f.write_str("askap"),
PolConvention {
x_orientation,
stokes,
} => write!(f, "{x_orientation}/{stokes}"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum UvwFrame {
#[default]
#[cfg_attr(feature = "serde", serde(alias = "casa"))]
Hyperdrive,
#[cfg_attr(
feature = "serde",
serde(
alias = "lofar",
alias = "wsclean",
alias = "askap",
alias = "uvh5",
alias = "pyuvdata"
)
)]
Casacore,
Oskar,
Cotter,
}
impl UvwFrame {
pub const NAMES: &'static str = "hyperdrive (aliases: marlu, mwa, aips, casa), casacore (aliases: lofar, wsclean, askap, uvh5, pyuvdata), oskar, cotter";
pub fn baseline_sign(self) -> f64 {
match self {
UvwFrame::Hyperdrive | UvwFrame::Oskar | UvwFrame::Cotter => 1.0,
UvwFrame::Casacore => -1.0,
}
}
pub fn precesses(self) -> bool {
!matches!(self, UvwFrame::Oskar)
}
pub fn describe(self) -> &'static str {
match self {
UvwFrame::Hyperdrive => "hyperdrive (J2000, apparent sidereal time, phase-centre aberration rotation, antenna1 - antenna2)",
UvwFrame::Casacore => {
"casacore (J2000, apparent sidereal time, phase-centre aberration rotation, antenna2 - antenna1)"
}
UvwFrame::Oskar => {
"oskar (no precession: coordinates of date, apparent sidereal time, antenna1 - antenna2)"
}
UvwFrame::Cotter => {
"cotter (J2000, mean sidereal time, projected onto the aberrated phase centre, antenna1 - antenna2)"
}
}
}
}
impl FromStr for UvwFrame {
type Err = UnknownConvention;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim().to_lowercase().as_str() {
"hyperdrive" | "marlu" | "mwa" | "aips" | "casa" => Ok(UvwFrame::Hyperdrive),
"casacore" | "lofar" | "wsclean" | "askap" | "uvh5" | "pyuvdata" => {
Ok(UvwFrame::Casacore)
}
"oskar" => Ok(UvwFrame::Oskar),
"cotter" => Ok(UvwFrame::Cotter),
_ => Err(UnknownConvention {
kind: "UVW frame",
got: s.to_string(),
expected: Self::NAMES,
}),
}
}
}
impl Display for UvwFrame {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
UvwFrame::Hyperdrive => "hyperdrive",
UvwFrame::Casacore => "casacore",
UvwFrame::Oskar => "oskar",
UvwFrame::Cotter => "cotter",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum Convention {
#[default]
Mwa,
#[cfg_attr(feature = "serde", serde(alias = "casa"))]
Iau,
Lofar,
#[cfg_attr(
feature = "serde",
serde(alias = "wsclean", alias = "uvh5", alias = "pyuvdata")
)]
Casacore,
#[cfg_attr(feature = "serde", serde(alias = "askapsoft"))]
Askap,
Oskar,
}
impl Convention {
pub const NAMES: &'static str = "mwa, iau (alias: casa), lofar, casacore (aliases: wsclean, uvh5, pyuvdata), askap (alias: askapsoft), oskar";
pub fn pol_convention(self) -> PolConvention {
match self {
Convention::Mwa | Convention::Oskar => PolConvention::MWA,
Convention::Iau | Convention::Lofar | Convention::Casacore => PolConvention::IAU,
Convention::Askap => PolConvention::ASKAP,
}
}
pub fn uvw_frame(self) -> UvwFrame {
match self {
Convention::Mwa | Convention::Iau => UvwFrame::Hyperdrive,
Convention::Lofar | Convention::Casacore | Convention::Askap => UvwFrame::Casacore,
Convention::Oskar => UvwFrame::Oskar,
}
}
}
impl FromStr for Convention {
type Err = UnknownConvention;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim().to_lowercase().as_str() {
"mwa" => Ok(Convention::Mwa),
"iau" | "casa" => Ok(Convention::Iau),
"lofar" => Ok(Convention::Lofar),
"casacore" | "wsclean" | "uvh5" | "pyuvdata" => Ok(Convention::Casacore),
"askap" | "askapsoft" => Ok(Convention::Askap),
"oskar" => Ok(Convention::Oskar),
_ => Err(UnknownConvention {
kind: "convention",
got: s.to_string(),
expected: Self::NAMES,
}),
}
}
}
impl Display for Convention {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Convention::Mwa => "mwa",
Convention::Iau => "iau",
Convention::Lofar => "lofar",
Convention::Casacore => "casacore",
Convention::Askap => "askap",
Convention::Oskar => "oskar",
})
}
}
#[cfg(test)]
mod tests {
use approx::assert_abs_diff_eq;
use super::*;
const I: f64 = 10.0;
const Q: f64 = 1.0;
const U: f64 = 2.0;
const V: f64 = 3.0;
#[test]
fn mwa_mapping() {
let j = PolConvention::MWA.stokes_to_instrumental(I, Q, U, V);
assert_abs_diff_eq!(j[0], Complex::new(9.0, 0.0));
assert_abs_diff_eq!(j[1], Complex::new(2.0, -3.0));
assert_abs_diff_eq!(j[2], Complex::new(2.0, 3.0));
assert_abs_diff_eq!(j[3], Complex::new(11.0, 0.0));
}
#[test]
fn iau_is_mwa_with_pols_swapped() {
let m = PolConvention::MWA.stokes_to_instrumental(I, Q, U, V);
let i = PolConvention::IAU.stokes_to_instrumental(I, Q, U, V);
assert_abs_diff_eq!(i[0], Complex::new(11.0, 0.0));
assert_abs_diff_eq!(i[1], Complex::new(2.0, 3.0));
assert_abs_diff_eq!(i[0], m[3]);
assert_abs_diff_eq!(i[1], m[2]);
assert_abs_diff_eq!(i[2], m[1]);
assert_abs_diff_eq!(i[3], m[0]);
}
#[test]
fn askap_is_half_iau() {
let a = PolConvention::ASKAP.stokes_to_instrumental(I, Q, U, V);
let i = PolConvention::IAU.stokes_to_instrumental(I, Q, U, V);
for p in 0..4 {
assert_abs_diff_eq!(a[p], i[p] * 0.5);
}
}
#[test]
fn round_trips() {
for x in [XOrientation::East, XOrientation::North] {
for stokes in [StokesConvention::Avg, StokesConvention::Sum] {
let conv = PolConvention {
x_orientation: x,
stokes,
};
let back = conv.instrumental_to_stokes(conv.stokes_to_instrumental(I, Q, U, V));
assert_abs_diff_eq!(back[0], I, epsilon = 1e-12);
assert_abs_diff_eq!(back[1], Q, epsilon = 1e-12);
assert_abs_diff_eq!(back[2], U, epsilon = 1e-12);
assert_abs_diff_eq!(back[3], V, epsilon = 1e-12);
assert_eq!(conv.to_string().parse::<PolConvention>().unwrap(), conv);
}
}
}
#[test]
fn feed_angles() {
let [a, b] = PolConvention::MWA.feed_angles_rad();
assert_abs_diff_eq!(a, FRAC_PI_2);
assert_abs_diff_eq!(b, 0.0);
let [a, b] = PolConvention::IAU.feed_angles_rad();
assert_abs_diff_eq!(a, 0.0);
assert_abs_diff_eq!(b, FRAC_PI_2);
assert_eq!(
XOrientation::from_feed_angle_rad(FRAC_PI_2),
XOrientation::East
);
assert_eq!(
XOrientation::from_feed_angle_rad(-FRAC_PI_2),
XOrientation::East
);
assert_eq!(XOrientation::from_feed_angle_rad(0.0), XOrientation::North);
assert_eq!(
XOrientation::from_feed_angle_rad(-std::f64::consts::FRAC_PI_4),
XOrientation::North
);
}
#[test]
fn vis_units_parse_and_display() {
for (name, expected) in [
("uncalib", VisUnits::Uncalib),
("UNCALIB", VisUnits::Uncalib),
("uncalibrated", VisUnits::Uncalib),
("Jy", VisUnits::Jy),
("JY", VisUnits::Jy),
("K str", VisUnits::KStr),
("k sr", VisUnits::KStr),
] {
assert_eq!(name.parse::<VisUnits>().unwrap(), expected, "{name}");
}
assert!("mJy".parse::<VisUnits>().is_err());
for units in [VisUnits::Uncalib, VisUnits::Jy, VisUnits::KStr] {
assert_eq!(units.to_string().parse::<VisUnits>().unwrap(), units);
assert_eq!(units.is_calibrated(), units != VisUnits::Uncalib);
}
assert_eq!(VisUnits::default(), VisUnits::Uncalib);
assert_eq!(VisUnits::Jy.to_string(), "Jy");
assert_eq!(VisUnits::KStr.to_string(), "K str");
}
#[test]
fn names_and_aliases() {
for (name, expected) in [
("mwa", PolConvention::MWA),
("MWA", PolConvention::MWA),
("iau", PolConvention::IAU),
("lofar", PolConvention::IAU),
("casacore", PolConvention::IAU),
("wsclean", PolConvention::IAU),
("OSKAR", PolConvention::MWA),
("askap", PolConvention::ASKAP),
("askapsoft", PolConvention::ASKAP),
("east", PolConvention::MWA),
("north/avg", PolConvention::IAU),
("north/sum", PolConvention::ASKAP),
] {
assert_eq!(name.parse::<PolConvention>().unwrap(), expected, "{name}");
}
assert!("circular".parse::<PolConvention>().is_err());
assert!("east/circular".parse::<PolConvention>().is_err());
assert_eq!(PolConvention::MWA.to_string(), "mwa");
assert_eq!(
PolConvention {
x_orientation: XOrientation::East,
stokes: StokesConvention::Sum
}
.to_string(),
"east/sum"
);
assert_eq!("lofar".parse::<UvwFrame>().unwrap(), UvwFrame::Casacore);
assert_eq!("uvh5".parse::<UvwFrame>().unwrap(), UvwFrame::Casacore);
assert_eq!("marlu".parse::<UvwFrame>().unwrap(), UvwFrame::Hyperdrive);
assert_eq!("casa".parse::<UvwFrame>().unwrap(), UvwFrame::Hyperdrive);
assert_eq!("casa".parse::<Convention>().unwrap(), Convention::Iau);
assert_eq!(
"wsclean".parse::<Convention>().unwrap(),
Convention::Casacore
);
for c in [
Convention::Mwa,
Convention::Iau,
Convention::Lofar,
Convention::Casacore,
Convention::Askap,
Convention::Oskar,
] {
assert_eq!(c.to_string().parse::<Convention>().unwrap(), c);
}
for f in [
UvwFrame::Hyperdrive,
UvwFrame::Casacore,
UvwFrame::Oskar,
UvwFrame::Cotter,
] {
assert_eq!(f.to_string().parse::<UvwFrame>().unwrap(), f);
}
}
#[test]
fn presets() {
assert_eq!(Convention::Lofar.pol_convention(), PolConvention::IAU);
assert_eq!(Convention::Lofar.uvw_frame(), UvwFrame::Casacore);
assert_eq!(Convention::Askap.pol_convention(), PolConvention::ASKAP);
assert_eq!(Convention::Askap.uvw_frame(), UvwFrame::Casacore);
assert_eq!(Convention::Oskar.pol_convention(), PolConvention::MWA);
assert_eq!(Convention::Oskar.uvw_frame(), UvwFrame::Oskar);
assert_eq!("oskar".parse::<UvwFrame>().unwrap(), UvwFrame::Oskar);
assert!(!UvwFrame::Oskar.precesses() && UvwFrame::Casacore.precesses());
assert_eq!(Convention::Mwa.uvw_frame(), UvwFrame::Hyperdrive);
assert_abs_diff_eq!(UvwFrame::Casacore.baseline_sign(), -1.0);
assert_abs_diff_eq!(UvwFrame::Hyperdrive.baseline_sign(), 1.0);
assert_abs_diff_eq!(UvwFrame::Oskar.baseline_sign(), 1.0);
}
#[cfg(feature = "serde")]
#[test]
fn serde_names_and_aliases() {
let x: XOrientation = serde_json::from_str("\"north\"").unwrap();
assert_eq!(x, XOrientation::North);
let s: StokesConvention = serde_json::from_str("\"sum\"").unwrap();
assert_eq!(s, StokesConvention::Sum);
let p: PolConvention =
serde_json::from_str("{\"x_orientation\": \"east\", \"stokes\": \"avg\"}").unwrap();
assert_eq!(p, PolConvention::MWA);
let f: UvwFrame = serde_json::from_str("\"askap\"").unwrap();
assert_eq!(f, UvwFrame::Casacore);
let c: Convention = serde_json::from_str("\"casa\"").unwrap();
assert_eq!(c, Convention::Iau);
let f: UvwFrame = serde_json::from_str("\"casa\"").unwrap();
assert_eq!(f, UvwFrame::Hyperdrive);
assert_eq!(
serde_json::to_string(&UvwFrame::Casacore).unwrap(),
"\"casacore\""
);
}
}