File size: 30,473 Bytes
5ab75a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
function [Pc,out] = PcCircle(r1,v1,cov1,r2,v2,cov2,HBR,params)
% PcCircle - Computes Pc for vectorized state/cov input by integrating over
%            a circle on the conjunction plane.
%
% Syntax: [Pc,out] =  PcCircle(r1,v1,cov1,r2,v2,cov2,HBR);
%         [Pc,out] =  PcCircle(r1,v1,cov1,r2,v2,cov2,HBR,params);
%
% =========================================================================
%
% Copyright (c) 2022-2025 United States Government as represented by the
% Administrator of the National Aeronautics and Space Administration.
% All Rights Reserved.
%
% =========================================================================
%
% Description:
%
%   Computes Pc for vectorized state/cov input by integrating over a circle 
%   on the conjunction plane. For this function, the conjunction plane is 
%   oriented so that the axes are aligned with the principal axes of the 
%   miss-distance PDF (i.e., aligned with the 2x2 covariance eigenvectors). 
%   It uses vectorized input and calculates the eigen-decompositions of the 
%   2x2 conjunction plane covariances using a vectorized algorithm. The 
%   most accurate mode (i.e., EstimationMode = 1), uses Matlab's  1D 
%   integration function "integral" to do the required integrations. The 
%   default mode (EstimationMode = 64) uses 64th-order Gauss-Chebyshev (GC) 
%   quadrature to approximate the 1D integrations, storing the GC points
%   and weights in persistent variables to avoid repetitive calculations. 
%   The non-default EstimationMode = 0 approximates the circular region Pc 
%   integral with the equal-area square Pc calculation, which requires no
%   numerical integration. EstimationMode = -1 calculates an upper-limit Pc 
%   value corresponding to the circumscribing square region, which requires 
%   no numerical integration. EstimationMode > 1 uses Gauss-Chebyshev 
%   quadrature, with order = EstimationMode.
%
% =========================================================================
%
% Input:
%
%    r1 - Primary object's position vector in ECI coordinates         [nx3]
%
%    v1 - Primary object's velocity vector in ECI coordinates  [nx3 or 1x3]
%         Note: If r1 is [nx3] but v1 is [1x3], the same v1
%               will be used for every r1
%
%    cov1 - Primary object's covariance matrix in    [nx9, 3x3xn, or 6x6xn]
%           ECI coordinate frame.
%           Note: representations are as follows:
%
%             nx9 row vectors for n primary covariances represented as
%             [(1,1) (2,1) (3,1) (1,2) (2,2) (3,2) (1,3) (2,3) (3,3)])
%                               
%             3x3xn matrices for n primary covariances
%
%             6x6xn matrices for n primary covariances
%
%             1x9 row vector which will be repeated for each primary
%             position
%
%             3x3 matrix which will be repeated for each primary position
%
%             6x6 matrix which will be repeated for each primary position
%
%    r2 - Secondary object's position vector in ECI coordinates       [nx3]
%
%    v2 - Secondary object's velocity vector in ECI            [nx3 or 1x3]
%         coordinates
%         Note: If r2 is [nx3] but v2 is [1x3], the same v2
%               will be used for every r2
%
%    cov2 - Secondary object's covariance matrix in  [nx9, 3x3xn, or 6x6xn]
%           ECI coordinate frame
%           Note: representations are as follows:
%
%             nx9 row vectors for n secondary covariances represented as
%             [(1,1) (2,1) (3,1) (1,2) (2,2) (3,2) (1,3) (2,3) (3,3)])
%                               
%             3x3xn matrices for n secondary covariances
%
%             6x6xn matrices for n secondary covariances
%
%             1x9 row vector which will be repeated for each secondary
%             position
%
%             3x3 matrix which will be repeated for each secondary position
%
%             6x6 matrix which will be repeated for each secondary position
%
%    HBR - Hard body radius                                    [1x1 or nx1]
%          Note: If the positions are given as [nx3] but HBR
%                only [1x1], the same HBR will be used for all
%                n cases
%
%    params - (Optional) Auxilliary input parameter structure with the
%             following fields:
%
%      EstimationMode - Specifies the method of estimating Pc and 
%                       peforming the required numerical integrations
%                       (optional, default = 64):
%                           -1 = Circumscribing square upper bound, which 
%                           is a very fast calculation mode requiring no 
%                           numerical integrations. This mode is 
%                           recommended for situations in which 
%                           computational speed is critical, but the use of 
%                           an upper-limit estimate of the encircled Pc 
%                           value is deemed to be acceptable.
%                           0 = Equal-area square approximation, which is 
%                           also a fast mode, but that can provide 
%                           inaccurate estimates of the encircled Pc value, 
%                           so it is not recommended for general-use 
%                           purposes.
%                           1 = Numerically integrate with Matlab's 
%                           "integral" function (which is the slowest but 
%                           most accurate mode, also not recommended for 
%                           general-use purposes).
%                           > 1 = Calculate using Gauss-Chebyshev (GC) 
%                           quadrature with order = EstimationMode, but 
%                           only for input cases that GC quadrature is 
%                           judged to be sufficiently accurate. Such 
%                           inaccuracies can occur in the large-HBR or 
%                           small-covariance limits; in these rare cases, 
%                           Matlab's "integral" function is used. For the 
%                           default GC order EstimationMode = 64, this mode 
%                           is both efficient and accurate, so it is 
%                           recommended for general-use purposes.
%
%      WarningLevel - Flag indicating if warning messages should be
%                     displayed (optional, default = 0).
%                       0 = Warning messages are suppressed
%                       positive integer = Warning messages are displayed
%
%      PriSecCovProcessing - Enables the calculation of individual
%                            covariance auxiliary outputs projected onto
%                            the conjunction plane. These outputs can be
%                            used to plot primary and secondary ellipses on
%                            CA distribution plots.
%                            (optional, default = false)
%
% =========================================================================
%
% Output:
%
%   Pc - Probability of collision
%
%   out - An auxilliary output structure which contains a number of extra
%         quantities from the Pc calculation. Includes the following
%         fields:
%
%     IsPosDef - Flag indicating if the combined and marginalized     [nx1]
%                covariance has a negative eigenvalue
%
%     IsRemediated - Flag indicating if the combined and marginalized [nx1]
%                    marginalized 2x2 covariance was remediated,
%                    either successfully or not
%
%     Amat - Combined covariance projected onto the nominal           [nx3]
%            conjunction plane
%
%     (xm,zm) - Position of the mean relative miss distance on the    [nx1]
%               conjunction plane
%
%     (sx,sz) - Sigma values of the relative miss distance PDF on the [nx1]
%               conjunction plane
%
%     r1,v1,cov1,r2,v2,cov2,HBR - Adjusted input parameters saved off for
%                                 use in other functions
%
%     xhat,yhat,zhat - Component vectors of the relative encounter    [nx3]
%                      frame.
%
%     EigV1,EigV2 - Eigenvectors of the combined covariance projected [nx2]
%                   onto the conjunction plane.
%
%     EigL1,EigL2 - Eigenvalues of the combined covariance projected  [nx1]
%                   onto the conjunction plane.
%
%     ClipBoundSet - Boolean indicating conjunctions where GC         [nx1]
%                    quadrature is not sufficiently accurate and
%                    Matlab's integral function was attempted instead.
%
%     The following set of out structure fields are only populated if the
%     params.PriSecCovProcessing parameter is set to true:
%
%       AmatPri/Sec - 2x2 pri/sec covariance matrix projected onto    [nx3]
%                     conjunction plane:
%                       Amat(:,1) is the 1,1 component of the cov matrix
%                       Amat(:,2) is the 1,2 or 2,1 component of the cov
%                         matrix
%                       Amat(:,3) is the 2,2 component of the cov matrix
%
%       EigV1Pri,EigV2Pri - Eigenvectors of the primary covariance    [nx2]
%                           projected onto the conjunction plane.
%
%       EigV1Sec,EigV2Sec - Eigenvectors of the secondary covariance  [nx2]
%                           projected onto the conjunction plane.
%
%       EigL1Pri,EigL2Pri - Eigenvalues of the primary covariance     [nx1]
%                           projected onto the conjunctoin plane.
%
%       EigL1Sec,EigL2Sec - Eigenvalues of the secondary covariance   [nx1]
%                           projected onto the conjunctoin plane.
%
% =========================================================================
%
% Dependencies:
%
%   erf_vec_dif.m
%   GenGCQuad.m
%
% =========================================================================
%
% Subfunctions:
%
%   Pc2DIntegrand   -   Integrand function for numerical integration
%
% =========================================================================
% 
% References:
%
%   Alfano, S. 2005a. "A Numerical Implementation of Spherical Object
%   Collision Probability." Journal of the Astronautical Sciences, Vol.53,
%   No.1, pp.103-109, Jan-Mar 2005.
%
% =========================================================================
%
% Disclaimer:
%
%    No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY
%    WARRANTY OF ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY,
%    INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE
%    WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF
%    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR FREEDOM FROM
%    INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE ERROR
%    FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO
%    THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER,
%    CONSTITUTE AN ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT
%    OF ANY RESULTS, RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY
%    OTHER APPLICATIONS RESULTING FROM USE OF THE SUBJECT SOFTWARE.
%    FURTHER, GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND LIABILITIES
%    REGARDING THIRD-PARTY SOFTWARE, IF PRESENT IN THE ORIGINAL SOFTWARE,
%    AND DISTRIBUTES IT "AS IS."
%
%    Waiver and Indemnity:  RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS
%    AGAINST THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND
%    SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT.  IF RECIPIENT'S USE OF
%    THE SUBJECT SOFTWARE RESULTS IN ANY LIABILITIES, DEMANDS, DAMAGES,
%    EXPENSES OR LOSSES ARISING FROM SUCH USE, INCLUDING ANY DAMAGES FROM
%    PRODUCTS BASED ON, OR RESULTING FROM, RECIPIENT'S USE OF THE SUBJECT
%    SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS THE UNITED
%    STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY
%    PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY LAW.  RECIPIENT'S SOLE
%    REMEDY FOR ANY SUCH MATTER SHALL BE THE IMMEDIATE, UNILATERAL
%    TERMINATION OF THIS AGREEMENT.
%
% =========================================================================
%
% Initial version: Jan 2022;  Latest update: Aug 2025
%
% ----------------- BEGIN CODE -----------------

    % Initializations and defaults
    
    % Use persistent variables to prevent repetitive recalculation
    % of Gauss-Chebyshev weights
    persistent NGC xGC yGC wGC pathsAdded
    
    if isempty(pathsAdded)
        [p,~,~] = fileparts(mfilename('fullpath'));
        s = what(fullfile(p, 'Utils')); addpath(s.path);
        s = what(fullfile(p, '../Utils/AugmentedMath')); addpath(s.path);
        pathsAdded = true;
    end

    % Number of input arguments
    Nargin = nargin;
    
    % Check for the parameters structure
    if Nargin == 7 || (Nargin == 8 && isempty(params))
        params = [];
    elseif Nargin ~= 8
        error('PcCircle:InvalidNumberOfArguments','Invalid number of arguments passed in');
    end
    % Default params.EstimationMode
    if ~isfield(params,'EstimationMode') || isempty(params.EstimationMode)
        params.EstimationMode = 64; % Default order for GC quadrature
    end
    EstimationMode = params.EstimationMode;
    % Default warning level
    if ~isfield(params,'WarningLevel') || isempty(params.WarningLevel)
        params.WarningLevel = 0;
    end
    WarningLevel = params.WarningLevel;
    % Default primary/secondary covariance processing (enables plotting of
    % primary and secondary ellipses on CA distribution plots)
    if ~isfield(params,'PriSecCovProcessing') || isempty(params.PriSecCovProcessing)
        params.PriSecCovProcessing = false;
    end
    
    % Check for a valid and sensible EstimationMode
    if EstimationMode <= 0
        if EstimationMode ~= 0 && EstimationMode ~= -1
            error('PcCircle:InvalidEstimationMode', 'Invalid EstimationMode');
        end
    else
        if EstimationMode ~= round(EstimationMode)
            error('PcCircle:InvalidEstimationMode', 'Invalid EstimationMode');
        elseif EstimationMode < 16 && WarningLevel > 0
            warning('PcCircle:InsufficientEstimationMode', 'EstimationMode specifies fewer than 16 quadrature points, which can cause inaccurate Pc estimates');
        end
    end
    
    % Reformat the inputs to expected dimensions
    %  (nx3 for positions & velocities; nx9 for covariances; nx1 for HBRs)
    [Nvec , v1] = CheckAndResizePosVel(r1, v1);
    [Nvec2, v2] = CheckAndResizePosVel(r2, v2);
    if Nvec ~= Nvec2
        error('PcCircle:UnequalPositionCount', 'Number of primary and secondary positions must be equal');
    end
    [cov1] = CheckAndResizeCov(Nvec , cov1);
    [cov2] = CheckAndResizeCov(Nvec2, cov2);

    % Replicate scalar HBR into an nx1 array
    if (numel(HBR) == 1) && (Nvec > 1)
        HBR = repmat(HBR,[Nvec 1]);
    end
    % Ensure HBR array has dimension nx1
    if ~isequal(size(HBR),[Nvec 1])
        error('PcCircle:InvalidHBRDimensions', 'Input HBR array dimension must be 1x1 or nx1');
    end
    % Ensure HBR values are nonnegative
    if any(HBR < 0)
        if WarningLevel > 0
            warning('PcCircle:NegativeHBR', 'Negative HBR values found and replaced with zeros');
        end
        HBR(HBR < 0) = 0;
    end
    
    % Save the adjusted input parameters into the output structure
    out.r1 = r1;
    out.v1 = v1;
    out.cov1 = cov1;
    out.r2 = r2;
    out.v2 = v2;
    out.cov2 = cov2;
    out.HBR = HBR;
    
    % Combine the covariances
    CombCov = cov1 + cov2;
    
    % Relative position and velocity, and normal
    r = r1 - r2;
    v = v1 - v2;
    
    % Check and adjust for zero miss distance (for processing Alfano (2009)
    % test cases)
    rmag = sqrt(r(:,1).^2 + r(:,2).^2 + r(:,3).^2);
    reps = max(10.*eps(rmag),1e-6*HBR);
    SmallRmag = rmag < reps;
    if sum(SmallRmag) > 0
        if WarningLevel > 0
            warning('PcCircle:ZeroMissDistance', 'Zero or near-zero miss distance cases found; perturbing miss distance for those cases');
        end
        rsum = r1(SmallRmag,:) + r2(SmallRmag,:);
        rsummag = sqrt(rsum(:,1).^2 + rsum(:,2).^2 + rsum(:,3).^2);
        vmag = sqrt(v(SmallRmag,1).^2 + v(SmallRmag,2).^2 + v(SmallRmag,3).^2);
        rdel = reps(SmallRmag).*cross(rsum,v(SmallRmag,:),2)./rsummag./vmag;
        r(SmallRmag,:) = r(SmallRmag,:) + rdel;
    end
    
    % Check for zero relative velocity (for processing Alfano (2009) test
    % cases)
    vmag = sqrt(v(:,1).^2 + v(:,2).^2 + v(:,3).^2);
    ZeroVmag = vmag == 0;
    if sum(ZeroVmag) > 0 && WarningLevel > 0
        warning('PcCircle:ZeroRelativeVelocity', 'Zero relative velocity cases found; setting Pc to NaN for those cases');
    end
    
    % Orbit normal
    h = cross(r,v,2);
    
    % Relative encounter frame
    y = v./sqrt(v(:,1).^2 + v(:,2).^2 + v(:,3).^2);
    z = h./sqrt(h(:,1).^2 + h(:,2).^2 + h(:,3).^2);
    x = cross(y,z,2);
    eci2xyz = [x y z];
    out.xhat = x; out.yhat = y; out.zhat = z;    
    
    % Pri and Sec cov processing
    if params.PriSecCovProcessing
        
        % Project combined covariances into conjunction planes
        RotatedCov = Product3x3(eci2xyz,Product3x3(cov1(:,1:1:9),eci2xyz(:,[1 4 7 2 5 8 3 6 9])));
        Amat = RotatedCov(:,[1 3 9]);
        out.AmatPri = Amat;
        if max(abs(Amat(:))) == 0
            warning('All zero primary covariance being processed');
        end
        % Calculate eigenvalues and eigenvectors for each covariance matrix,
        % 2nd eigenvector isn't needed for the rest of the calculation
        [V1, V2, L1, L2] = eig2x2(Amat);
        out.EigV1Pri = V1; out.EigL1Pri = L1;
        out.EigV2Pri = V2; out.EigL2Pri = L2;
    
        % Project combined covariances into conjunction planes
        RotatedCov = Product3x3(eci2xyz,Product3x3(cov2(:,1:1:9),eci2xyz(:,[1 4 7 2 5 8 3 6 9])));
        Amat = RotatedCov(:,[1 3 9]);
        if max(abs(Amat(:))) == 0
            warning('All zero secondary covariance being processed');
        end
        out.AmatSec = Amat;
        % Calculate eigenvalues and eigenvectors for each covariance matrix,
        % 2nd eigenvector isn't needed for the rest of the calculation
        [V1, V2, L1, L2] = eig2x2(Amat);
        out.EigV1Sec = V1; out.EigL1Sec = L1;
        out.EigV2Sec = V2; out.EigL2Sec = L2;
        
    end
    
    % Project combined covariances into conjunction planes
    RotatedCov = Product3x3(eci2xyz,Product3x3(CombCov(:,1:1:9),eci2xyz(:,[1 4 7 2 5 8 3 6 9])));
    Amat = RotatedCov(:,[1 3 9]);
    out.Amat = Amat;
    
    % Calculate eigenvalues and eigenvectors for each covariance matrix,
    % 2nd eigenvector isn't needed for the rest of the calculation
    [V1, V2, L1, L2] = eig2x2(Amat);
    out.EigV1 = V1; out.EigL1 = L1;
    out.EigV2 = V2; out.EigL2 = L2;
    
    % Issue error if any cases are found with two non-positive eigenvalues
    if any(L1 <= 0)
        error('PcCircle:TwoNonPositiveEigenvalues', 'Invalid case(s) found with two non-positive eigenvalues');
    end
    
    % Issue a warning for any NPD cases
    if WarningLevel > 0 && any(L2 <= 0)
        warning('PcCircle:NPDCovariance', 'NPD covariance(s) found; remediating using eigenvalue clipping method');
    end
    
    % Use eigenvalue clipping method to make the covariances positive
    % definite. Since this Pc algorithm does not require Cholesky
    % factorization, the covariance remediation is very simple: clip any
    % eigenvalues that are less than the clipping limit and then
    % recreate the remediated covariance using the original eigenvectors
    % and the clipped eigenvalues.
    FiniteHBR = ~isinf(HBR);
    Fclip = 1e-4;
    Lrem = (Fclip*HBR).^2; % Eigenvalue clipping level
    IsRem1 = L1 < Lrem & FiniteHBR;
    L1(IsRem1) = Lrem(IsRem1);
    IsRem2 = L2 < Lrem & FiniteHBR;
    L2(IsRem2) = Lrem(IsRem2);
    % L2 is guaranteed to be the smaller of the two eigenvalues, if the
    % remediated value is greater than 0, then the matrix is positive
    % definite
    out.IsPosDef = L2 > 0;
    out.IsRemediated = IsRem1 | IsRem2;
    
    % Sigma values
    sx = sqrt(L1);
    sz = sqrt(L2);
    out.sx = sx;
    out.sz = sz;
    
    % The miss distance coordinates in the conjunction plane (xm,zm),
    % calculated such that both are nonnegative
    rm = sqrt(r(:,1).^2+r(:,2).^2+r(:,3).^2);
    xm = rm.*abs(V1(:,1));
    zm = rm.*abs(V1(:,2));
    out.xm = xm;
    out.zm = zm;
    
    % Estimate the Pc
    
    if EstimationMode <= 0
        
        if EstimationMode == 0
            % Mode 0: Calculate the equal-area square Pc approximation,
            % representing the integral over the square with area equal to
            % the HBR circle
            HSQ = sqrt(pi/4)*HBR; % Half-width of square with equal area
        else
            % Mode -1: Calculate the circumscribing square Pc upper bound,
            % representing the integral over the square with area that is
            % always larger and complete encloses the HBR circle
            HSQ = HBR; % Half-width of square equal to radius
        end

        % Calculate analytical solution for the ensquared Pc, which has an
        % analytical solution involving error functions (Alfano 2005)
        sqrt2 = sqrt(2); dx = sqrt2*sx; dz = sqrt2*sz;
        Ex = erf_vec_dif( (xm+HSQ)./dx, (xm-HSQ)./dx );
        Ez = erf_vec_dif( (zm+HSQ)./dz, (zm-HSQ)./dz );
        Pc = Ex.*Ez/4;

    else
        
        % Use either Matlab's "integral" function (EstimationMode = 1) or 
        % Gauss-Chebyshev quadrature (EstimationMode = GC-Order > 1) 
        % to approximate the Pc estimate for the circular area on the 
        % conjunction plane
        
        % Initialize the limits for the integration along the x-axis
        % (the integral along the other axis is done analytically)
        xlo = xm-HBR;
        xhi = xm+HBR;
        
        % Use Nsigma bound testing to determine cases for which GC
        % quadrature will be sufficiently accurate
        Nsx = 4*sx;
        xloclip = xlo; xloclip(xlo < 0) = 0;
        out.ClipBoundSet = ~( (xlo > -Nsx) & (xhi < xloclip+Nsx) );
        
        % Find the cases for which Gauss-Chebyshev integration should be
        % sufficiently accurate
        if EstimationMode == 1
            % No GC cases for this estimation mode
            Iset = false(Nvec,1);
        else
            Iset = ~out.ClipBoundSet;
        end

        % Initialize output array of Pc estimates
        Pc = NaN(Nvec,1);
        
        % Constants for Pc integrations
        sqrt2 = sqrt(2); dx = sqrt2*sx; dz = sqrt2*sz;

        % Calculate set of integrals using GC quadrature
        if any(Iset)
            
            % Approximate Iset integrals with Gauss-Chebyshev quadrature
            Nset = sum(Iset);
            
            % Calculate GC quadrature points and weights, if required
            if isempty(NGC) || NGC ~= EstimationMode
                % Generate Gauss-Chebyshev quad points and weights
                NGC = EstimationMode;
                [xGC, yGC, wGC] = GenGCQuad(NGC);                
            end
            
            % Approximate integrals with GC quadrature
            DGC = [1 NGC]; Dset = [Nset 1];
            zmrep = repmat(zm(Iset) ,DGC);
            dzrep = repmat(dz(Iset) ,DGC);
            Hrep  = repmat(HBR(Iset),DGC);
            xrep  = repmat(xm(Iset) ,DGC) + Hrep .* repmat(xGC,Dset);
            Hxrep = Hrep .* repmat(yGC,Dset);            
            Fint = exp( -(xrep./repmat(dx(Iset),DGC)).^2 ) .* ...
                erf_vec_dif( (zmrep+Hxrep)./dzrep, (zmrep-Hxrep)./dzrep );
            
            Psum = sum(repmat(wGC,Dset).*Fint,2);
            
            Pc(Iset) = ( HBR(Iset) ./ sx(Iset) ) .* Psum;
            
        end
        
        % Calculate remaining set of integrals with Matlab's adaptive 1D
        % integration function "integral" as long as they don't have zero
        % relative velocity
        Iset = ~Iset & ~ZeroVmag;
        if any(Iset)
            
            % Adjust the limits based on the initial (xlo,xhi) values.
            NegSet = Iset & xlo < 0;
            if any(NegSet)
                % If xlo < 0 & xhi > 0, then clip to Nsigma standard deviations
                % for more accurate adaptive integrations
                Nsx = 5*sx; mNsx = -Nsx;
                ClipSet = NegSet & xlo < mNsx;
                xlo(ClipSet) = mNsx(ClipSet);
                ClipSet = NegSet & xhi > Nsx;
                xhi(ClipSet) = Nsx(ClipSet);
            end

            % Use "integral" function for each vector element, using an
            % algorithm built for accuracy not computational speed
            HBR2 = HBR(Iset).^2;
            Fset = find(Iset); Nset = numel(Fset);
            for kk=1:Nset
                % Current index
                k = Fset(kk);
                % Define the integrand function
                Integrand = @(xx)Pc2DIntegrand(xx,xm(k),zm(k),dx(k),dz(k),HBR2(kk));
                % Integrate alone x-axis using Matlab's integral function
                Pc(k) = integral(Integrand,xlo(k),xhi(k),'AbsTol',1e-300,'RelTol',1e-6);
            end

            % Apply the remaining factors for the final Pc estimate
            % (see Alfano, 2005)
            Pc(Iset) = (Pc(Iset)./sx(Iset))/sqrt(8*pi);
            
        end

    end
    
    % Make Pc = 1 exactly for any infinite HBR values
    Pc(~FiniteHBR) = 1;

    % Make Pc = 0 exactly for any zero HBR values
    Pc(HBR == 0) = 0;
    
    % Make Pc = Nan for any zero relative velocity cases
    Pc(ZeroVmag) = NaN;
    
end

% =========================================================================

function Integrand = Pc2DIntegrand(x,xm,zm,dx,dz,R2)
% Vectorized integrand for the 1D integral along x-axis of the conjunction
% plane -- the axis aligned with the eigenvector of corresponding to the
% largest eigenvalue of the 2D miss-distance covariance matrix
Rx = real(sqrt(R2-(x-xm).^2));
Integrand = exp(-(x/dx).^2) .* erf_vec_dif( (zm+Rx)/dz, (zm-Rx)/dz );
return
end

% ----------------- END OF CODE ------------------
%
% Please record any changes to the software in the change history 
% shown below:
%
% ----------------- CHANGE HISTORY ------------------
% Developer      |    Date    |     Description
% ---------------------------------------------------
% D. Hall        | 01-02-2022 |  Adapted from PcElrod.m and
%                                Pc2D_SquareErrFunc.m for initial
%                                development, with the goal of having the
%                                function work for all HBR values spanning
%                                zero to Inf.
% D. Hall        | 02-02-2022 |  Added test cases and header comments.
% L. Baars       | 05-23-2022 |  Moved some inline function calls into
%                                external functions which can be reused by
%                                multiple Pc estimation routines. Replaced
%                                internal eigenvalue/eigenvector
%                                calculation with a call to eig2x2().
%                                Removed extra output data which is not
%                                used as a part of the calculation. Added
%                                tolerances to the call of the integral()
%                                function.
% D. Hall        | 08-17-2022 |  Added (xm,zm,sx,sz) to output parameters.
% L. Baars       | 09-28-2022 |  Fixed paths for SDK directory restructure.
% D. Hall        | 11-17-2022 |  Renamed from Pc1D_ConjPlaneCircle to
%                                PcConjPlaneCircle, and added a new mode, 
%                                EstimationMode = -1, which calculates the
%                                Pc value for the square that circumscribes
%                                the HBR circle.
% L. Baars       | 02-27-2023 |  Fixed relative pathing issue in addpath
%                                calls.
% L. Baars       | 03-08-2023 |  Added projected covariance eigenvalue and
%                                eigenvector outputs.
% D. Hall        | 09-07-2023 |  Added zero miss distance and zero relative
%                                velocity processing for input single
%                                conjunctions that do not require
%                                vectorized processing
% E. White       | 08-09-2023 |  Added compliant documenation, added error
%                                and warning names
% L. Baars       | 12-27-2023 |  Renamed from PcConjPlaneCircle.m to
%                                PcCircle.m. Modified inputs/outputs to
%                                match standardized structures for Pc
%                                calls. Vectorized the zero miss distance
%                                and zero relative velocity calculations.
% D. Hall        | 02-07-2024 |  Added "PriSecCovProcessing" flag, to
%                                calculate eigendecompositions of primary
%                                and secondary conjunction plane
%                                covariances (optional, default = false)
% D. Hall        | 03-05-2025 |  Added Nsigma bound testing to determine
%                                cases where GC quadrature will be
%                                sufficiently accurate.
% L. Baars       | 08-21-2025 |  Added disclaimer notice and updated
%                                documentation.

% =========================================================================
%
% Copyright (c) 2022-2025 United States Government as represented by the
% Administrator of the National Aeronautics and Space Administration.
% All Rights Reserved.
%
% =========================================================================