birli 0.20.0

A preprocessing pipeline for the Murchison Widefield Array
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
//! Calibrating visibilities.

use crate::{
    ndarray::{Array2, ArrayView1, ArrayView2, ArrayViewMut3, Axis},
    Complex,
};
use itertools::izip;
use marlu::Jones;
use thiserror::Error;

#[derive(Error, Debug)]
/// Errors that can occur when calibrating visibilities.
pub enum CalibrationError {
    #[error("The provided calibration solution has {calsol_chans} channels, but the data has {data_chans} channels")]
    /// When the number of channels in the calibration solution does not match the number of channels in the data.
    ChannelSizeMismatch {
        /// The argument name within the funciton
        calsol_chans: usize,
        /// The number of channels in the data
        data_chans: usize,
    },

    #[error("bad array shape supplied to argument {argument} of function {function}. expected {expected}, received {received}")]
    /// Error for bad array shape in provided argument
    BadArrayShape {
        /// The argument name within the funciton
        argument: String,
        /// The function name
        function: String,
        /// The expected shape
        expected: String,
        /// The shape that was received instead
        received: String,
    },
}

/// Returns whether every channel in a tile's calibration solution contains at least one NaN.
fn tile_calsol_is_nan_flagged(tile_row: ArrayView1<Jones<f64>>) -> bool {
    !tile_row.is_empty() && tile_row.iter().all(|j| j.any_nan())
}

/// Get a per-tile mask for tiles whose calibration solutions contain NaN in every channel.
pub fn get_calsol_nan_flagged_tiles(calsols: ArrayView2<Jones<f64>>) -> Vec<bool> {
    calsols
        .axis_iter(Axis(0))
        .map(tile_calsol_is_nan_flagged)
        .collect()
}

/// Flag antennas whose calibration solutions contain NaN in every channel.
pub fn flag_antennas_with_nan_calsols(antenna_flags: &mut [bool], calsols: ArrayView2<Jones<f64>>) {
    for (tile_idx, tile_row) in calsols.axis_iter(Axis(0)).enumerate() {
        if tile_idx >= antenna_flags.len() {
            break;
        }
        if tile_calsol_is_nan_flagged(tile_row) {
            antenna_flags[tile_idx] = true;
        }
    }
}

/// Unit-amplitude Jones: `z → z/|z|` for `|z|>0`; XX/YY with `|z|==0` → `1`;
/// XY/YX with `|z|==0` → `0`; NaN unchanged.
pub fn jones_phase_only(j: Jones<f64>) -> Jones<f64> {
    let mut out = [Complex::new(0., 0.); 4];
    for (i, z) in j.iter().enumerate() {
        if z.re.is_nan() || z.im.is_nan() {
            out[i] = *z;
            continue;
        }
        let amp = z.norm();
        if amp > 0. {
            out[i] = *z / amp;
        } else if i == 0 || i == 3 {
            // Diagonal zero amplitude has undefined phase → identity.
            out[i] = Complex::new(1., 0.);
        } else {
            // Off-diagonal zeros stay zero (do not invent a phase).
            out[i] = Complex::new(0., 0.);
        }
    }
    Jones::from(out)
}

/// Rewrite each Jones in a cal-sol array to unit amplitude, preserving phase.
pub fn calsols_phase_only(calsols: ArrayView2<Jones<f64>>) -> Array2<Jones<f64>> {
    calsols.mapv(jones_phase_only)
}

/// apply a direction independent calibration solution for a single timeblock to the given
/// visibility data
///
/// Baselines involving a tile marked in `flagged_tiles`, or a calibration solution containing
/// NaN, are flagged and calibration is not applied.
///
/// # Errors
///
/// calsols should have the same number of channels as `vis_array`, `flag_array`, `weight_array` etc.
///
#[allow(clippy::too_many_arguments)]
pub fn apply_di_calsol(
    // a two dimensional array of jones matrix calibration solutions with
    // dimensions `[tile][channel]`
    calsols: ArrayView2<Jones<f64>>,
    // dimensions `[timestep][channel][baselines]`
    mut vis_array: ArrayViewMut3<Jones<f32>>,
    // dimensions `[timestep][channel][baselines]`
    mut weight_array: ArrayViewMut3<f32>,
    // dimensions `[timestep][channel][baselines]`
    // todo: setting both flags and weights is redundant, but it's not clear how to rip this out
    mut flag_array: ArrayViewMut3<bool>,
    // The tile index pairs for each selected baseline
    sel_baselines: &[(usize, usize)],
    // Per-tile flag mask indexed by antenna/tile number (e.g. from [`FlagContext::antenna_flags`])
    flagged_tiles: &[bool],
    // If we are emulating cotter we don't flag NaNs
    emulate_cotter: bool,
) -> Result<(), CalibrationError> {
    let di_dims = calsols.dim();
    let vis_dims = vis_array.dim();
    let weight_dims = weight_array.dim();
    let flag_dims = flag_array.dim();
    if weight_dims != vis_dims {
        return Err(CalibrationError::BadArrayShape {
            argument: "weight_array".into(),
            function: "apply_di_calsol".into(),
            expected: format!("{vis_dims:?}"),
            received: format!("{weight_dims:?}"),
        });
    }
    if flag_dims != vis_dims {
        return Err(CalibrationError::BadArrayShape {
            argument: "flag_array".into(),
            function: "apply_di_calsol".into(),
            expected: format!("{vis_dims:?}"),
            received: format!("{flag_dims:?}"),
        });
    }

    if (vis_dims.1 as f64 / di_dims.1 as f64).fract().abs() > 0.01 {
        return Err(CalibrationError::ChannelSizeMismatch {
            calsol_chans: di_dims.1,
            data_chans: vis_dims.1,
        });
    }
    let channel_ratio = (vis_dims.1 as f64 / di_dims.1 as f64).round() as usize;

    // time axis
    for (mut vis_array, mut weight_array, mut flag_array) in izip!(
        vis_array.axis_iter_mut(Axis(0)),
        weight_array.axis_iter_mut(Axis(0)),
        flag_array.axis_iter_mut(Axis(0)),
    ) {
        // baseline axis
        for (&(ant1_idx, ant2_idx), mut vis_array, mut weight_array, mut flag_array) in izip!(
            sel_baselines.iter(),
            vis_array.axis_iter_mut(Axis(1)),
            weight_array.axis_iter_mut(Axis(1)),
            flag_array.axis_iter_mut(Axis(1)),
        ) {
            let baseline_tile_flagged = flagged_tiles.get(ant1_idx).copied().unwrap_or(false)
                || flagged_tiles.get(ant2_idx).copied().unwrap_or(false);

            // channel axis (chunked by channel_ratio)
            for (&sol1, &sol2, mut vis_chunk, mut weight_chunk, mut flag_chunk) in izip!(
                calsols.index_axis(Axis(0), ant1_idx),
                calsols.index_axis(Axis(0), ant2_idx),
                vis_array.axis_chunks_iter_mut(Axis(0), channel_ratio),
                weight_array.axis_chunks_iter_mut(Axis(0), channel_ratio),
                flag_array.axis_chunks_iter_mut(Axis(0), channel_ratio),
            ) {
                // apply the calibration solution to all visibilities in the chunk
                for (vis, weight, flag) in izip!(
                    vis_chunk.iter_mut(),
                    weight_chunk.iter_mut(),
                    flag_chunk.iter_mut()
                ) {
                    // ignore nans if we are emulating cotter
                    if baseline_tile_flagged
                        || (!emulate_cotter && (sol1.any_nan() || sol2.any_nan()))
                    {
                        *flag = true;
                        if *weight > 0. {
                            *weight = -*weight;
                        }
                        continue;
                    }

                    // promote
                    let vis_f64 = Jones::<f64>::from(*vis);

                    // demote J1 * D * J2^H
                    *vis = Jones::<f32>::from(sol1 * vis_f64 * sol2.h());

                    // if the data now contains a NaN, flag it
                    // Cotter doesn't do this, so skip when emulating it.
                    if !emulate_cotter && vis.any_nan() {
                        *flag = true;
                        if *weight > 0. {
                            *weight = -*weight;
                        }
                    }
                }
            }
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use approx::assert_abs_diff_eq;

    use crate::{compare_jones, Complex};

    use ndarray::{array, Array2, Array3};

    use super::*;

    /// Test the calsols are correctly applied in the antenna axis.
    #[test]
    fn test_apply_calsols_antenna() {
        let sel_baselines = vec![(0, 0), (0, 1), (1, 1)];
        let num_times = 1;

        let calsols = Array2::from_shape_fn((2, 1), |(i, _)| Jones::identity() * (i + 1) as f64);
        let shape = (num_times, calsols.dim().1, sel_baselines.len());
        let mut vis_array = Array3::from_shape_fn(shape, |(_, _, bl)| {
            Jones::<f32>::identity() * (bl + 1) as f32
        });
        let mut flag_array = Array3::from_shape_fn(shape, |_| false);
        let mut weight_array = Array3::from_shape_fn(shape, |_| 1_f32);
        let emulate_cotter = false;
        apply_di_calsol(
            calsols.view(),
            vis_array.view_mut(),
            weight_array.view_mut(),
            flag_array.view_mut(),
            &sel_baselines,
            &[],
            emulate_cotter,
        )
        .unwrap();

        compare_jones!(
            vis_array[(0, 0, 0)],
            calsols[(0, 0)] * (Jones::<f64>::identity() * 1.) * calsols[(0, 0)].h()
        );
        compare_jones!(
            vis_array[(0, 0, 1)],
            calsols[(0, 0)] * (Jones::<f64>::identity() * 2.) * calsols[(1, 0)].h()
        );
        compare_jones!(
            vis_array[(0, 0, 2)],
            calsols[(1, 0)] * (Jones::<f64>::identity() * 3.) * calsols[(1, 0)].h()
        );
    }

    /// Test the calsols are correctly applied in the channel axis.
    #[test]
    fn test_apply_calsols_chan() {
        let sel_baselines = vec![(0, 0)];
        let num_times = 1;

        let calsols =
            Array2::from_shape_fn((1, 2), |(_, c)| Jones::identity() * (c * 2 + 1) as f64);
        let shape = (num_times, calsols.dim().1, sel_baselines.len());
        let mut vis_array = Array3::from_shape_fn(shape, |(_, c, _)| {
            Jones::<f32>::identity() * (c * 2 + 2) as f32
        });
        let mut flag_array = Array3::from_shape_fn(shape, |_| false);
        let mut weight_array = Array3::from_shape_fn(shape, |_| 1_f32);
        let emulate_cotter = false;
        apply_di_calsol(
            calsols.view(),
            vis_array.view_mut(),
            weight_array.view_mut(),
            flag_array.view_mut(),
            &sel_baselines,
            &[],
            emulate_cotter,
        )
        .unwrap();

        compare_jones!(
            vis_array[(0, 0, 0)],
            calsols[(0, 0)] * (Jones::<f64>::identity() * 2.) * calsols[(0, 0)].h()
        );
        compare_jones!(
            vis_array[(0, 1, 0)],
            calsols[(0, 1)] * (Jones::<f64>::identity() * 4.) * calsols[(0, 1)].h()
        );
    }

    /// Test the calsols are correctly applied in the channel axis, when vis chans = 2 * cal chans.
    #[test]
    fn test_apply_calsols_chan_uneven() {
        let sel_baselines = vec![(0, 0)];
        let num_times = 1;

        let calsols =
            Array2::from_shape_fn((1, 2), |(_, c)| Jones::identity() * (c * 2 + 1) as f64);
        let shape = (num_times, calsols.dim().1 * 2, sel_baselines.len());
        let mut vis_array = Array3::from_shape_fn(shape, |(_, c, _)| {
            Jones::<f32>::identity() * (c * 2 + 2) as f32
        });
        let mut flag_array = Array3::from_shape_fn(shape, |_| false);
        let mut weight_array = Array3::from_shape_fn(shape, |_| 1_f32);
        let emulate_cotter = false;
        apply_di_calsol(
            calsols.view(),
            vis_array.view_mut(),
            weight_array.view_mut(),
            flag_array.view_mut(),
            &sel_baselines,
            &[],
            emulate_cotter,
        )
        .unwrap();

        compare_jones!(
            vis_array[(0, 0, 0)],
            calsols[(0, 0)] * (Jones::<f64>::identity() * 2.) * calsols[(0, 0)].h()
        );
        compare_jones!(
            vis_array[(0, 1, 0)],
            calsols[(0, 0)] * (Jones::<f64>::identity() * 4.) * calsols[(0, 0)].h()
        );
        compare_jones!(
            vis_array[(0, 2, 0)],
            calsols[(0, 1)] * (Jones::<f64>::identity() * 6.) * calsols[(0, 1)].h()
        );
        compare_jones!(
            vis_array[(0, 3, 0)],
            calsols[(0, 1)] * (Jones::<f64>::identity() * 8.) * calsols[(0, 1)].h()
        );
    }

    /// Test the calsols are correctly applied in to all timesteps.
    #[test]
    fn test_apply_calsols_time() {
        let sel_baselines = vec![(0, 0)];
        let num_times = 2;

        let calsols = Array2::from_shape_fn((1, 1), |_| Jones::identity() * 2.);
        let shape = (num_times, calsols.dim().1, sel_baselines.len());
        let mut vis_array = Array3::from_shape_fn(shape, |(t, _, _)| {
            Jones::<f32>::identity() * (t * 2 + 2) as f32
        });
        let mut flag_array = Array3::from_shape_fn(shape, |_| false);
        let mut weight_array = Array3::from_shape_fn(shape, |_| 1_f32);
        let emulate_cotter = false;
        apply_di_calsol(
            calsols.view(),
            vis_array.view_mut(),
            weight_array.view_mut(),
            flag_array.view_mut(),
            &sel_baselines,
            &[],
            emulate_cotter,
        )
        .unwrap();

        compare_jones!(
            vis_array[(0, 0, 0)],
            calsols[(0, 0)] * (Jones::<f64>::identity() * 2.) * calsols[(0, 0)].h()
        );
        compare_jones!(
            vis_array[(1, 0, 0)],
            calsols[(0, 0)] * (Jones::<f64>::identity() * 4.) * calsols[(0, 0)].h()
        );
    }

    /// Test the calsols are correctly applied based on real values from cotter debugger.
    #[test]
    fn test_apply_calsols_real() {
        let sel_baselines = vec![(0, 1)];

        let calsols: Array2<Jones<f64>> = array![
            // -exec p solA[solChannel]
            [
                Jones::from([
                    Complex::new(-0.05711880819681107, 0.8909723224701427),
                    Complex::new(0., 0.),
                    Complex::new(0., 0.),
                    Complex::new(-0.3190681285208096, 0.8975262420831493)
                ]),
                Jones::from([
                    Complex::new(-0.05790403500446751, 0.8906022388084277),
                    Complex::new(0., 0.),
                    Complex::new(0., 0.),
                    Complex::new(-0.31938558050469074, 0.8973555420886708)
                ]),
            ],
            // -exec p solB[solChannel]
            [
                Jones::from([
                    Complex::new(0.7738792841865286, 0.4448506027871696),
                    Complex::new(0., 0.),
                    Complex::new(0., 0.),
                    Complex::new(0.218178442910526, 0.8469966867353856)
                ]),
                Jones::from([
                    Complex::new(0.7727769657690016, 0.4451541611407178),
                    Complex::new(0., 0.),
                    Complex::new(0., 0.),
                    Complex::new(0.21786624664314946, 0.8466270165385981)
                ]),
            ],
        ];
        let shape = (1, calsols.dim().1, sel_baselines.len());

        let mut vis_array = array![[
            // -exec p dataAsDouble
            [Jones::<f32>::from([
                Complex::new(24.25, 1.),
                Complex::new(85.5, 81.75),
                Complex::new(35.25, -2.),
                Complex::new(154.5, 9.625)
            ])],
            [Jones::<f32>::from([
                Complex::new(58.25, -67.),
                Complex::new(3.875, -12.375),
                Complex::new(-36., 75.75),
                Complex::new(17.375, 75.625)
            ])],
        ]];
        let exp_vis_array = array![[
            // -exec p dataAsDouble
            [Jones::<f32>::from([
                Complex::new(7.8246384, 17.68882),
                Complex::new(43.610638, 81.43078),
                Complex::new(7.043186, 29.182451),
                Complex::new(102.209915, 78.65481)
            ])],
            [Jones::<f32>::from([
                Complex::new(68.32589, 18.026802),
                Complex::new(5.8807054, -8.232894),
                Complex::new(-68.7944, -18.519669),
                Complex::new(-23.242767, 60.28708)
            ])],
        ]];
        let mut flag_array = Array3::from_shape_fn(shape, |_| false);
        let mut weight_array = Array3::from_shape_fn(shape, |_| 1_f32);
        let emulate_cotter = false;
        apply_di_calsol(
            calsols.view(),
            vis_array.view_mut(),
            weight_array.view_mut(),
            flag_array.view_mut(),
            &sel_baselines,
            &[],
            emulate_cotter,
        )
        .unwrap();

        compare_jones!(vis_array[(0, 0, 0)], exp_vis_array[(0, 0, 0)]);
        compare_jones!(vis_array[(0, 1, 0)], exp_vis_array[(0, 1, 0)]);
    }

    /// Tiles with all-NaN calibration solutions flag all baselines involving that tile.
    #[test]
    fn test_apply_calsols_nan_flagged_tile() {
        let sel_baselines = vec![(0, 0), (0, 1), (1, 1)];
        let num_times = 1;
        let num_chans = 2;

        let mut calsols = Array2::from_shape_fn((2, num_chans), |(_, _)| Jones::identity());
        for chan in 0..num_chans {
            calsols[(1, chan)] = Jones::nan();
        }

        let shape = (num_times, num_chans, sel_baselines.len());
        let mut vis_array = Array3::from_shape_fn(shape, |(_, _, bl)| {
            Jones::<f32>::identity() * (bl + 1) as f32
        });
        let orig_vis_array = vis_array.clone();
        let mut flag_array = Array3::from_shape_fn(shape, |_| false);
        let mut weight_array = Array3::from_shape_fn(shape, |_| 1_f32);
        let emulate_cotter = false;

        apply_di_calsol(
            calsols.view(),
            vis_array.view_mut(),
            weight_array.view_mut(),
            flag_array.view_mut(),
            &sel_baselines,
            &[false, true],
            emulate_cotter,
        )
        .unwrap();

        // auto on unflagged tile 0 is calibrated
        compare_jones!(
            vis_array[(0, 0, 0)],
            calsols[(0, 0)] * (Jones::<f64>::identity() * 1.) * calsols[(0, 0)].h()
        );
        assert!(!flag_array[(0, 0, 0)]);

        // baselines involving all-NaN tile 1 are flagged without modifying visibilities
        for chan in 0..num_chans {
            assert!(flag_array[(0, chan, 1)]);
            assert!(flag_array[(0, chan, 2)]);
            assert_abs_diff_eq!(weight_array[(0, chan, 1)], -1.);
            assert_abs_diff_eq!(weight_array[(0, chan, 2)], -1.);
            compare_jones!(vis_array[(0, chan, 1)], orig_vis_array[(0, chan, 1)]);
            compare_jones!(vis_array[(0, chan, 2)], orig_vis_array[(0, chan, 2)]);
        }
    }

    /// Partially NaN calibration solutions flag only affected channels.
    #[test]
    fn test_apply_calsols_partial_nan_channel() {
        let sel_baselines = vec![(0, 1)];
        let num_times = 1;
        let num_chans = 2;

        let mut calsols = Array2::from_shape_fn((2, num_chans), |(_, _)| Jones::identity() * 2.);
        calsols[(1, 1)] = Jones::nan();

        let shape = (num_times, num_chans, sel_baselines.len());
        let mut vis_array = Array3::from_shape_fn(shape, |_| Jones::<f32>::identity());
        let orig_vis_array = vis_array.clone();
        let mut flag_array = Array3::from_shape_fn(shape, |_| false);
        let mut weight_array = Array3::from_shape_fn(shape, |_| 1_f32);
        let emulate_cotter = false;

        apply_di_calsol(
            calsols.view(),
            vis_array.view_mut(),
            weight_array.view_mut(),
            flag_array.view_mut(),
            &sel_baselines,
            &[],
            emulate_cotter,
        )
        .unwrap();

        assert!(!flag_array[(0, 0, 0)]);
        assert!(flag_array[(0, 1, 0)]);
        compare_jones!(vis_array[(0, 0, 0)], orig_vis_array[(0, 0, 0)] * 4.);
        compare_jones!(vis_array[(0, 1, 0)], orig_vis_array[(0, 1, 0)]);
    }

    /// User-flagged tiles skip calibration even when solutions are valid.
    #[test]
    fn test_apply_calsols_user_flagged_tile() {
        let sel_baselines = vec![(0, 0), (0, 1)];
        let num_times = 1;

        let calsols = Array2::from_shape_fn((2, 1), |(_, _)| Jones::identity() * 2.);
        let shape = (num_times, calsols.dim().1, sel_baselines.len());
        let mut vis_array = Array3::from_shape_fn(shape, |(_, _, bl)| {
            Jones::<f32>::identity() * (bl + 1) as f32
        });
        let orig_vis_array = vis_array.clone();
        let mut flag_array = Array3::from_shape_fn(shape, |_| false);
        let mut weight_array = Array3::from_shape_fn(shape, |_| 1_f32);
        let emulate_cotter = false;

        apply_di_calsol(
            calsols.view(),
            vis_array.view_mut(),
            weight_array.view_mut(),
            flag_array.view_mut(),
            &sel_baselines,
            &[false, true],
            emulate_cotter,
        )
        .unwrap();

        compare_jones!(
            vis_array[(0, 0, 0)],
            calsols[(0, 0)] * (Jones::<f64>::identity() * 1.) * calsols[(0, 0)].h()
        );
        assert!(!flag_array[(0, 0, 0)]);

        assert!(flag_array[(0, 0, 1)]);
        assert_abs_diff_eq!(weight_array[(0, 0, 1)], -1.);
        compare_jones!(vis_array[(0, 0, 1)], orig_vis_array[(0, 0, 1)]);
    }

    #[test]
    fn test_get_calsol_nan_flagged_tiles() {
        let mut calsols = Array2::from_shape_fn((3, 2), |(_, _)| Jones::identity());
        calsols[(1, 0)] = Jones::nan();
        calsols[(1, 1)] = Jones::nan();
        calsols[(2, 0)] = Jones::from([
            Complex::new(f64::NAN, 0.),
            Complex::new(0., 0.),
            Complex::new(0., 0.),
            Complex::new(0., 0.),
        ]);

        let flagged = get_calsol_nan_flagged_tiles(calsols.view());
        assert_eq!(flagged, vec![false, true, false]);
    }

    #[test]
    fn test_jones_phase_only_diagonal_preserves_phase() {
        let phase = std::f64::consts::FRAC_PI_4;
        let amp = 3.5;
        let xx = Complex::from_polar(amp, phase);
        let yy = Complex::from_polar(amp * 2., -phase);
        let j = Jones::from([xx, Complex::new(0., 0.), Complex::new(0., 0.), yy]);
        let po = jones_phase_only(j);

        assert_abs_diff_eq!(po[0].norm(), 1.0, epsilon = 1e-12);
        assert_abs_diff_eq!(po[3].norm(), 1.0, epsilon = 1e-12);
        assert_abs_diff_eq!(po[0].arg(), phase, epsilon = 1e-12);
        assert_abs_diff_eq!(po[3].arg(), -phase, epsilon = 1e-12);
        assert_eq!(po[1], Complex::new(0., 0.));
        assert_eq!(po[2], Complex::new(0., 0.));

        // Apply to identity vis: amplitude matches uncalibrated; only phase rotates.
        let vis = Jones::<f64>::identity();
        let mut vis_full = Array3::from_elem((1, 1, 1), Jones::<f32>::from(vis));
        let mut vis_po = vis_full.clone();
        let mut weight = Array3::from_elem((1, 1, 1), 1_f32);
        let mut flag = Array3::from_elem((1, 1, 1), false);
        let calsols = Array2::from_elem((1, 1), j);
        let calsols_po = calsols_phase_only(calsols.view());
        apply_di_calsol(
            calsols.view(),
            vis_full.view_mut(),
            weight.view_mut(),
            flag.view_mut(),
            &[(0, 0)],
            &[],
            false,
        )
        .unwrap();
        apply_di_calsol(
            calsols_po.view(),
            vis_po.view_mut(),
            weight.view_mut(),
            flag.view_mut(),
            &[(0, 0)],
            &[],
            false,
        )
        .unwrap();

        assert_abs_diff_eq!(vis_po[(0, 0, 0)][0].norm() as f64, 1.0, epsilon = 1e-5);
        assert_abs_diff_eq!(vis_po[(0, 0, 0)][3].norm() as f64, 1.0, epsilon = 1e-5);
        // Full apply scales XX by |Jxx|^2 for auto.
        assert_abs_diff_eq!(
            vis_full[(0, 0, 0)][0].norm() as f64,
            amp * amp,
            epsilon = 1e-5
        );
    }

    #[test]
    fn test_phase_only_vs_full_apply_amplitudes_differ() {
        let j = Jones::from([
            Complex::from_polar(2.0, 0.3),
            Complex::new(0., 0.),
            Complex::new(0., 0.),
            Complex::from_polar(1.5, -0.2),
        ]);
        let vis0 = Jones::from([
            Complex::new(4., 1.),
            Complex::new(0.5, 0.25),
            Complex::new(0.25, -0.5),
            Complex::new(3., -1.),
        ]);
        let calsols = Array2::from_elem((1, 1), j);
        let calsols_po = calsols_phase_only(calsols.view());

        let mut vis_full = Array3::from_elem((1, 1, 1), Jones::<f32>::from(vis0));
        let mut vis_po = vis_full.clone();
        let mut weight = Array3::from_elem((1, 1, 1), 1_f32);
        let mut flag = Array3::from_elem((1, 1, 1), false);

        apply_di_calsol(
            calsols.view(),
            vis_full.view_mut(),
            weight.view_mut(),
            flag.view_mut(),
            &[(0, 0)],
            &[],
            false,
        )
        .unwrap();
        apply_di_calsol(
            calsols_po.view(),
            vis_po.view_mut(),
            weight.view_mut(),
            flag.view_mut(),
            &[(0, 0)],
            &[],
            false,
        )
        .unwrap();

        // Amplitudes differ when |J| ≠ 1.
        assert!(
            (vis_full[(0, 0, 0)][0].norm() - vis_po[(0, 0, 0)][0].norm()).abs() > 0.1,
            "full vs phase-only XX amplitudes should differ"
        );
        // Phase-only keeps visibility amplitude (auto: |J|=1 ⇒ |vis'| = |vis|).
        assert_abs_diff_eq!(
            vis_po[(0, 0, 0)][0].norm() as f64,
            vis0[0].norm(),
            epsilon = 1e-5
        );
        assert_abs_diff_eq!(
            vis_po[(0, 0, 0)][3].norm() as f64,
            vis0[3].norm(),
            epsilon = 1e-5
        );
    }

    #[test]
    fn test_jones_phase_only_zeros_and_nans() {
        let j = Jones::from([
            Complex::new(0., 0.),
            Complex::new(0., 0.),
            Complex::new(0., 0.),
            Complex::new(0., 0.),
        ]);
        let po = jones_phase_only(j);
        assert_eq!(po[0], Complex::new(1., 0.));
        assert_eq!(po[1], Complex::new(0., 0.));
        assert_eq!(po[2], Complex::new(0., 0.));
        assert_eq!(po[3], Complex::new(1., 0.));
        assert!(!po.any_nan());

        let nan_j = Jones::from([
            Complex::new(f64::NAN, 1.),
            Complex::new(0., 0.),
            Complex::new(0., 0.),
            Complex::new(2., 0.),
        ]);
        let nan_po = jones_phase_only(nan_j);
        assert!(nan_po[0].re.is_nan());
        assert_eq!(nan_po[1], Complex::new(0., 0.));
        assert_eq!(nan_po[2], Complex::new(0., 0.));
        assert_abs_diff_eq!(nan_po[3].norm(), 1.0, epsilon = 1e-12);
        assert_abs_diff_eq!(nan_po[3].arg(), 0.0, epsilon = 1e-12);
    }
}