File size: 22,814 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
function [PcOne,Diluted,PcMax,SfMax,Pc,Sf,conv,iter] = PcDilution(r1,v1,cov1,r2,v2,cov2,HBR,params)
% PcDilution - Evaluates collision probability (Pc) dilution and calculates
%              the associated maximum Pc value, resulting from scaling a
%              conjunction's secondary or primary 3x3 position, or both (default)
%              uncertainty covariance matrix by applying a "covariance
%              scaling factor" (Sf). 
%
% Syntax: [Diluted,PcMax,SfMax,PcOne,Pc,Sf,conv,iter] = PcDilution(r1,v1,cov1,r2,v2,cov2,HBR,params)
%
% Inputs:
%    r1      - Primary object's position vector in ECI coordinates
%              [1x3 or 3x1] (meters)
%    v1      - Primary object's velocity vector in ECI coordinates
%              [1x3 or 3x1] (meters/second)
%    cov1    - Primary object's covariance matrix in ECI coordinate frame
%              (3x3 or 6x6) (meters and meters/s)
%    r2      - Secondary object's position vector in ECI coordinates
%              [1x3 or 3x1] (meters)
%    v2      - Secondary object's velocity vector in ECI coordinates
%              [1x3 or 3x1] (meters/second)
%    cov2    - Secondary object's covariance matrix in ECI coordinate frame
%              (3x3 or 6x6) (meters and meters/s)
%    HBR     - Hard body region (meters)
%    params  - Run parameters [optional]
%            - params.RefineCA = Flag to refine CA point before analysis
%               (default = true; states propagated to true TCA)
%            - params.PriSecScaling = Scaled scovariance, can be 'primary'
%               'secondary' or 'both' (default = 'both')
%            - params.RedFact = Pc reduction factor required for
%               convergence. Recommendations:
%               1) Use RedFact = 10 to 100 when plotting the (Sf,Pc)
%                  output curve.
%               2) Use RedFact = 1.1 (the default) for automated processing
%                  with no post facto plotting.
%            - params.ConstTol - Tolerance to evaluate the occurence of
%                constant Pc values as a function of the scale factor Sf
%                (default = 1e-6).
%            - params.DilutTol - Tolerance to evaluate the occurence of
%                a diluted PcMax value (default = 1e-3).
%            - params.MissDist2HbrTol - Tolerance to assign Miss Distance 
%                to HBR when within tolerance proximity of the HBR 
%                (default = 1e-8).
%            - params.itermax - Maximum number of iterations allowed to
%               converge upon PcMax (default = 100)
%            - params.SfInit - Initial range of covariance scale factors
%               (default = [0.5 2.0]).
%            - params.dLfLevel - Log10 cov. scale factor spacing, initial
%               and refinement levels (default = 2*[1e-2 1e-3 1e-4]).
%            - params.verbose - Flag for verbose operation, used for
%               development and debugging (default = false).
%            - params.plotting - Plotting monitorint level, used for
%               development and debugging:
%               0 = No plotting (default)
%               1 = Plot final results only
%               2 = Plot iteration-by-iteration results
%            - params.StopCalcIfRobust - Detect if in the robust region
%               early and avoid performing the numerical calculation if so.
%               (default - true, cannot be true if params.plotting is not 0)
%
% Outputs:
%    PcOne   - Pc calculated for unscaled covariances (i.e., for a cov.
%              scale factor of one, or Sf = 1), commonly referred to
%              as "the conjunction's nominal 2D-Pc value."
%    Diluted - Flag to indicate probability is in dilution region.
%    PcMax   - Maximum Pc value found for any value of applied cov. scale
%              factor, if PcOne is found to be in dilution region.
%    SfMax   - Covariance scale factor for which maximum Pc occurs.
%    Pc      - The Pc buffer created in the iterative search for PcMax.
%    Sf      - Covariance scale factor buffer created in search for PcMax.
%              (Plotting y=Pc vs x=Sf creates a Pc dilution curve.)
%    conv    - Flag indicating satisfactory convergence to find PcMax.
%    iter    - Number of iterations performed in finding PcMax.
%
% Note:
%    The "covariance scale factors" factors returned by this function, 
%    SfMax and Sf, are multiplied by each of the 3 positional uncertainty 
%    elements to obtain the scaled covariance. 
%    These output factors are used for plotting dilution curves, 
%    or to pre- and post-multiply the original covariance matrix to obtain 
%    the scaled covariance.
%
% References:  M.Hejduk (2019) "Satellite Conjunction Assessment Risk 
%              Analysis for 'Dilution Region' Events: Issues and
%              Operational Approaches" Space Trafic Managment Conference,
%              28, https://commons.erau.edu/stm/2019/presentations/28
%
%              S.Alfano (2005) "Relating Position Uncertainty to Maximum
%              Conjunction Probability" The Journal of the Astronautical
%              Sciences, Vol.53, No.2, pp.193-205.
%
% Example/Validation Cases:
%
% Other m-files required:
%   FindNearbyCA.m
%   isconstant.m
%   PcCircle.m
%   plot_range.m
% Subfunctions: None
% MAT-files required: None
% See also: None
%
% November 2019; Last revision: 2025-OCT-31
%
% ----------------- BEGIN CODE -----------------
    
    persistent pathsAdded
    if isempty(pathsAdded)
        [p,~,~] = fileparts(mfilename('fullpath'));
        s = what(fullfile(p,'../ProbabilityOfCollision')); addpath(s.path);
        s = what(fullfile(p,'../ProbabilityOfCollision/Utils')); addpath(s.path);
        s = what(fullfile(p,'../Utils/Plotting')); addpath(s.path);
        pathsAdded = true;
    end

    % Set up default parameters
    
    Nargin = nargin;

    if Nargin < 8
        params = [];
    end
    
    % Refine CA point before analysis
    
    if ~isfield(params,'RefineCA') || isempty(params.RefineCA)
        params.RefineCA = true;
    end
    
    % Scaling secondary covariance (default), primary or both
    
    if ~isfield(params,'PriSecScaling') || isempty(params.PriSecScaling)
        params.PriSecScaling = 'both';
    end

    
    % Pc reduction factor required for convergence
    
    if ~isfield(params,'RedFact') || isempty(params.RedFact)
        params.RedFact = 1.1;
    end

    % PcMax constance tolerance
    
    if ~isfield(params,'ConstTol') || isempty(params.ConstTol)
        params.ConstTol = 1e-6;
    end
    
    % PcMax dilution tolerance
    
    if ~isfield(params,'DilutTol') || isempty(params.DilutTol)
        params.DilutTol = 1e-3;
    end

    % Set Miss Distance Equal to HBR Within Tolerance
    
    if ~isfield(params,'MissDist2HbrTol') || isempty(params.MissDist2HbrTol)
        params.MissDist2HbrTol = 1e-8;
    end
    
    % Maximum iteration numbers require for convergence
    
    if ~isfield(params,'itermax') || isempty(params.itermax)
        params.itermax = 100;
    end

    % Initial covariance scale factors and log10 values
    
    if ~isfield(params,'SfInit') || isempty(params.SfInit)
        params.SfInit = [0.5 2.0];
    end
    
    % Log10 cov. scale factor spacing, initial and refinement levels
    
    if ~isfield(params,'dLf') || isempty(params.dLf)
        params.dLfLevel = 2*[1e-2 1e-3 1e-4];
    end
    
    % Printing and plotting (mostly for debugging)
    
    if ~isfield(params,'verbose') || isempty(params.verbose)
        params.verbose = false;
    end
    
    if ~isfield(params,'plotting') || isempty(params.plotting)
        params.plotting = 0;
    end
    

    % Stop calculation if in the robust region and there is no need to find Pmax
    
    if ~isfield(params,'StopCalcIfRobust') || isempty(params.StopCalcIfRobust)
        params.StopCalcIfRobust = true;
    end

    % Check for valid parameters
    
    SfInit = unique(params.SfInit); % Sort into increasing order
    if (numel(SfInit) <= 1)
        error('Invalid SfInit parameter; [0.5 2.0] recommended');
    end
    
    RedFact = params.RedFact;
    if (RedFact <= 1)
        error('Invalid RedFact parameter; must be > 1');
    end
    
    PriSecScaling = params.PriSecScaling;
    if ischar(PriSecScaling)
        PriSecScaling = lower(PriSecScaling);
        switch PriSecScaling
            case {'primary','pri'}
                PriSecScaling = [true false];
            case {'secondary','sec'}
                PriSecScaling = [false true];
            case {'both'}
                PriSecScaling = [true true];
            otherwise
                error('Invalid PriSecScaling string parameter');
        end
    else
        if ~islogical(PriSecScaling)   || ...
           (numel(PriSecScaling) ~= 2) || ...
           ~any(PriSecScaling)
            error('Invalid PriSecScaling logical parameter');
        end
    end
    
    % Reshape the input vectors to be 1x3

    r1 = reshape(r1,1,3); v1 = reshape(v1,1,3);
    r2 = reshape(r2,1,3); v2 = reshape(v2,1,3);
    
    % Refine the CA point, if required
    
    if params.RefineCA
        [~,X1,X2] = FindNearbyCA([r1 v1]',[r2 v2]');
        r1 = X1(1:3)'; v1 = X1(4:6)';
        r2 = X2(1:3)'; v2 = X2(4:6)';
    end

    % Size down covariances to 3x3
    cov1 = cov1(1:3,1:3); cov2 = cov2(1:3,1:3);

    % Check if StopCalcIfRobust and plotting are turned on simultaneously
    if params.StopCalcIfRobust && params.plotting > 0
        warning('Cannot stop calculation if in the robust region when plotting is requested. "StopCalcIfRobust" set to false.')
        params.StopCalcIfRobust = false;
    end

    

    % Initialize output buffers to null, just in case no iterations are
    % required to converge upon dilution solution
    
    Pc = [];  Sf = []; conv = true; iter = 0;
    
    % If both covariances are zero then there can be no Pc dilution, and
    % the Pc estimate reduces to that of a hard-body collision
    
    iszerocov1 = all(cov1(:) == 0); iszerocov2 = all(cov2(:) == 0);

    DCA = norm(r1-r2); % Distance of closest approach
    % If DCA is near the HBR sphere surface within a small tolerance,
    % consider the DCA to be equal to HBR.
    if abs(DCA-HBR)<params.MissDist2HbrTol*HBR; DCA = HBR; end 

    if iszerocov1 && iszerocov2
        if params.verbose
            disp('Both covariances zero => no dilution possible');
        end
        Diluted = false;
        if (DCA < HBR)
            PcOne = 1; % Hard-body collision
        else
            PcOne = 0; % No hard-body collision
        end
        SfMax = 1; PcMax = PcOne;
        return;
    end
    

    % Find the Pc value for no cov. scaling (i.e., for Sf = 1)
    
    [PcOne,out] = PcCircle(r1,v1,cov1,r2,v2,cov2,HBR);
    xm = out.xm;
    ym = out.zm;
    sigx = out.sx;
    sigy = out.sz;
    
    % Return if 2D-Pc is NaN, but indicate no convergence
    
    if isnan(PcOne)
        conv = false; Diluted = NaN; SfMax = NaN; PcMax = NaN;
        return;
    end
    
    % Compare scaling factor to analytical approximations
    if (params.plotting > 0) && all(PriSecScaling)
        theta = atan(xm/ym);
        cth = cos(theta); sth = sin(theta);
        dist = norm(r1-r2);
        smallHBR = HBR < 0.2*min([dist,sigx,sigy]);
        if smallHBR
            SfMaxApp = (dist/(sqrt(2)*sigx*sigy))*sqrt((sigx*cth)^2+(sigy*sth)^2);
            PcOneApp = (HBR^2/2/sigx/sigy)*exp(-0.5*dist^2*((sth/sigx)^2+(cth/sigy)^2));
            PcMaxApp = (HBR^2/2/sigx/sigy/SfMaxApp^2)*exp(-0.5*dist^2*((sth/SfMaxApp/sigx)^2+(cth/SfMaxApp/sigy)^2));
            if params.verbose
                disp(['Approximation for HBR << min(MissDist,Sigx,Sigy) or ' ...
                    num2str(HBR) ' << ' num2str(min([dist,sigx,sigy]))]);
                disp(['SfMaxApp = ' num2str(SfMaxApp) ...
                     ' PcMaxApp = ' num2str(PcMaxApp) ...
                     ' Pc2DApp = ' num2str(PcOneApp)]);
            end
        end
    end
    
    % Check if the only scaled covariance is zero
    
    if iszerocov1 && PriSecScaling(1) && ~PriSecScaling(2)
        % No dilution because zero primary cov. can't be scaled down
        if params.verbose
            disp('Zero primary covariance => no primary-scaling dilution possible');
        end
        Diluted = false; SfMax = 1; PcMax = PcOne;
        return;
    elseif iszerocov2 && PriSecScaling(2) && ~PriSecScaling(1)
        % No dilution because zero secondary cov. can't be scaled down
        if params.verbose
            disp('Zero secondary covariance => no secondary-scaling dilution possible');
        end
        Diluted = false; SfMax = 1; PcMax = PcOne;
        return;
    end
    
    % Find the Pc value for complete cov. down-scaling (i.e., Sf = 0)

    if all(PriSecScaling)
        % Scaling both pri & sec covariance to zero again reduces to a
        % hard-body collision probability in the small scale factor limit,
        % because both covariances approach zero
        if (DCA < HBR)
            if params.StopCalcIfRobust
                PcMax = 1; SfMax = 0; Pc = 1; Sf = 0; conv = true; iter = 0; % Based on theory
                Diluted = ~isconstant([PcOne PcMax],params.DilutTol);
                return;
            else
                PcZero = 1;
            end
        elseif (DCA == HBR)
            if params.StopCalcIfRobust
                PcMax = 0.5; SfMax = 0; Pc = 0.5; Sf = 0; conv = true; iter = 0; % Based on theory
                Diluted = ~isconstant([PcOne PcMax],params.DilutTol);
                return;
            else
                PcZero = 0.5;
            end
        else
            PcZero = 0; % No hard-body collision
        end
    else
        % Pc value for Sf = 0
        % Scale pri or sec covariance using Sf = 0
        if PriSecScaling(1); f1 = 0; else; f1 = 1; end
        if PriSecScaling(2); f2 = 0; else; f2 = 1; end
        PcZero = PcCircle(r1,v1,f1*cov1,r2,v2,f2*cov2,HBR);
    end


    % Quickly find if in robust region or in dilution region
    if params.StopCalcIfRobust
        dSfMin = min(params.dLfLevel);
        dSf2Min = dSfMin^2;
        Sf2Delta = 1 - dSf2Min; % Slightly reduce scale factor from one
        Sf2_1 = 1; Sf2_2 = 1;
        if PriSecScaling(1); Sf2_1 = Sf2Delta; end
        if PriSecScaling(2); Sf2_2 = Sf2Delta; end
        PcDelta = PcCircle(r1,v1,cov1*Sf2_1,r2,v2,cov2*Sf2_2,HBR); % Calculate Pc at SF < 1
        if PcDelta < PcOne
            PcMax = PcOne; SfMax = 1; Pc = PcOne; Sf = 1; conv = true; iter = 0;
            Diluted = false;
            return;
        end
    end

    
    % Initial cov. scale factors and log10 values
    
    Sf1 = params.SfInit(1);
    Sf2 = params.SfInit(2);
    
    Lf1 = log10(Sf1);
    Lf2 = log10(Sf2);
    
    log10_two = log10(2);
    
    % Log10 cov. scale factor spacing

    NLfLevel = numel(params.dLfLevel);
    nLfLevel = 1;
    dLf = min(params.dLfLevel(nLfLevel),(Lf2-Lf1)/5);
    
    % Initialize buffers
    
    % Initialize plotting
    
    if params.plotting > 0
        figure;
    end
    
    % Iterate until converged or iteration limit exceeded
    
    iterating = true; conv = false;

    while iterating
        
        % Log10 cov. scale factor spacing
    
        Lf = (Lf1:dLf:Lf2)';

        N = numel(Lf);



        % Scaled covariances



        Sfb = 10.^linspace(Lf1,Lf2,N)'; f = Sfb.^2;
        if PriSecScaling(1); f1 = f; else; f1 = ones(size(f)); end
        if PriSecScaling(2); f2 = f; else; f2 = ones(size(f)); end

        c1 = NaN(3,3,N); c2 = c1;
        
        for n=1:N
            c1(:,:,n) = cov1(1:3,1:3)*f1(n); 
            c2(:,:,n) = cov2(1:3,1:3)*f2(n);
        end

        % Pc for scaled covariances

        Nx1 = [N 1];
        Pcb = PcCircle( ...
            repmat(r1,Nx1),repmat(v1,Nx1),c1, ...
            repmat(r2,Nx1),repmat(v2,Nx1),c2, ...
            repmat(HBR,Nx1));


        % Add to buffers
        
        Sf = cat(1,Sf,Sfb); Pc = cat(1,Pc,Pcb); Nf = numel(Sf);
        
        % Sort in increasing scale factor
        
        if iter > 0
            [Sf,srt] = sort(Sf); Pc = Pc(srt);
        end
        
        % Check if scale factor extremes are tolerable
        
        Pc0 = max(Pc);
        PcRed = Pc0/RedFact;
        
        if (Pc0 == 0)
            % Expand both bounds because all scale factors explored so far
            % have resulted in Pc = 0
            if params.verbose
                disp('Expanding both scale factor bounds');
            end
            Lf1 = Lf1-log10_two;
            Lf2 = Lf2+log10_two;
        elseif (Pc(1) > PcRed) && ~isconstant([Pc(1) PcZero],params.ConstTol)
            % Decrease lower bound
            if params.verbose
                disp('Decreasing lower scale factor');
            end
            Lf2 = log10(Sf(1))-dLf;
            Lf1 = Lf2-log10_two;
        elseif (Pc(end) > PcRed) && ~isconstant(Pc(Nf-N+1:Nf),params.ConstTol)
            % Increase upper bound
            if params.verbose
                disp('Increasing upper scale factor');
            end
            Lf1 = log10(Sf(end))+dLf;
            Lf2 = Lf1+log10_two;
        elseif nLfLevel < NLfLevel
            % Fine tuning maximum Pc
            nLfLevel = nLfLevel+1;
            if params.verbose
                disp(['Fine tuning level ' num2str(nLfLevel)]);
            end
            [~,imax] = max(Pc);
            i1 = max(imax-1,1);
            i2 = min(imax+1,numel(Pc));
            Lf1 = log10(Sf(i1));
            Lf2 = log10(Sf(i2));
            dLf = min(params.dLfLevel(nLfLevel),(Lf2-Lf1)/5);
        else
            % Converged
            if params.verbose
                disp('Converged');
            end
            iterating = false; conv = true;
        end
        
        % Increment iteration counter and terminate if too large
        
        iter = iter+1;
        
        if (iter > params.itermax)
            iterating = false;
        end
        
        if params.plotting > 1
            clf;
            loglog(Sf,Pc,'+--k');
            hold on;
            plot(1,PcOne,'or');
            hold off;
            drawnow;
        end
        
    end
    
    % Add unscaled Pc to output buffers, and make unique/sorted 
    
    Sf = cat(1,1,Sf);
    Pc = cat(1,PcOne,Pc);
    [Sf,srt] = unique(Sf); Pc = Pc(srt);

    % Unless due to numerical accuracies, the Pc should never exceed 0.5 if
    % the miss distance is outside the HBR sphere
    if DCA > HBR
        Pc(Pc>0.5) = 0.5;
    end

    % Define best-estimate Pc maximum

    [PcMax,imax] = max(Pc);
    if isnan(PcMax)
        SfMax = NaN;
        Diluted = NaN;
    else
        SfMax = Sf(imax);
        Diluted = SfMax < 1; % Dilution occurs only for cov. scaling < 1
        if Diluted
            % Dilution flagged only when PcMax/Pc-2D exceeds the 
            % specified dilution tolerance
            Diluted = ~isconstant([PcOne PcMax],params.DilutTol);
        end
        if params.verbose
            disp(['Primary scaling=' num2str(PriSecScaling(1)) ...
               ' Secondary scaling=' num2str(PriSecScaling(2)) ...
               ' Diluted=' num2str(Diluted) ...
               ' SfMax=' num2str(SfMax) ...
               ' PcMax=' num2str(PcMax) ...
               ' Pc2D=' num2str(PcOne)]);
        end
    end
    
    % Issue failure to convergence warning
    
    if params.verbose && ~conv
        warning(['PcDilution failed to converge: iter = ' num2str(iter)]);
    end
    
    if params.plotting > 0
        if all(PriSecScaling) && smallHBR
            smallHBRapp = true;
            lsty = '--';
        else
            smallHBRapp = false;
            lsty = '-';
        end
        clf;
        loglog(Sf,Pc,[lsty 'k']);
        hold on;
        plot(1,PcOne,'or');
        plot(SfMax,PcMax,'sm');
        hold off;
        if smallHBRapp
            ssx=Sf*sigx; ssy=Sf*sigy;
            PcApp = ((HBR^2)./2./ssx./ssy).*exp(-0.5*dist^2*((sth./ssx).^2+(cth./ssy).^2));
            hold on;
            plot(Sf,PcApp,':b');
            hold off;
            yrng = plot_range([min(Pc(Pc > 0)) max(Pc) PcMax],0);
            ylim(yrng);
        end
        xlabel('Covariance Scale Factor');
        ylabel('Pc');
        title(['Primary scaling = ' num2str(PriSecScaling(1)) ...
            ' Secondary scaling = ' num2str(PriSecScaling(2))]);
    end
    
    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         | 2019-SEP-04 | Initial Development
% D.Hall         | 2019-SEP-09 | Added DilutTol parameter
% D.Hall         | 2019-NOV-12 | Added code to handle cases where all Pc
%                                values are zero within the initial range
%                                of searched scale factors.
% D.Hall         | 2021-OCT-14 | Added comments to make it explicitly
%                                clear that the returned scale factors
%                                multiply the covariance matrix, so the
%                                square-root of these scale factors should
%                                be used for pre/post covariance
%                                multiplication.
% L. Baars       | 2023-FEB-22 | Added pathing information for the SDK
%                                reorganization.
% L. Baars       | 2023-FEB-27 | Fixed relative pathing issue in addpath
%                                calls.
% S.Es haghi     | 2025-AUG-22 | Code updated to use PcCircle
% S.Es haghi     | 2025-AUG-26 | Update code header. Change default
%                                settings to match Alfano's methodology. 
% S.Es haghi     | 2025-OCT-15 | Set default TCA correction option to true
% S.Es haghi     | 2025-OCT-22 | Ease Pc computation based on the miss
%                                distance location with respect to HBR
% S.Es haghi     | 2025-OCT-31 | Add option to avoid iterative process if
%                                detected to be in robust region early on