forked from hybridreachability/HybridRoA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHJIPDE_solve_with_reset_map.m
1665 lines (1405 loc) · 59.1 KB
/
HJIPDE_solve_with_reset_map.m
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function [data, tau, extraOuts] = ...
HJIPDE_solve(data0, tau, schemeData, compMethod, extraArgs)
% [data, tau, extraOuts] = ...
% HJIPDE_solve(data0, tau, schemeData, minWith, extraargs)
% Solves HJIPDE with initial conditions data0, at times tau, and with
% parameters schemeData and extraArgs
%
% ----- How to use this function -----
%
% Inputs:
% data0 - initial value function
% tau - list of computation times
% schemeData - problem parameters passed into the Hamiltonian func
% .grid: grid (required!)
% .accuracy: accuracy of derivatives
% compMethod - Informs which optimization we're doing
% - 'set' or 'none' to compute reachable set
% (not tube)
% - 'zero' or 'minWithZero' to min Hamiltonian with
% zero (tube)
% - 'minVOverTime' to do min with previous data
% (tube)
% - 'maxVOverTime' to do max with previous data
% - 'minVWithL' or 'minVWithTarget' to do min with
% targets
% - 'maxVWithL' or 'maxVWithTarget' to do max with
% targets
% - 'minVWithV0' to do min with original data
% (default)
% - 'maxVWithV0' to do max with original data
% extraArgs - this structure can be used to leverage other
% additional functionalities within this function.
% Its subfields are:
% .obstacleFunction: (matrix) a function describing a single
% obstacle or a list of obstacles with time
% stamps tau (obstacles must have same time stamp
% as the solution)
% .targetFunction: (matrix) the function l(x) that describes a
% stationary goal/unsafe set or a list of targets
% with time stamps tau (targets must have same
% time stamp as the solution). This functionality
% is mainly useful when the targets are
% time-varying, in case of variational inequality
% for example; data0 can be used to specify the
% target otherwise. This is also useful when
% warm-starting with a value function (data0)
% that is not equal to the target/cost function
% (l(x))
% .keepLast: (bool) Only keep data from latest time stamp
% and delete previous datas
% .quiet: (bool) Don't spit out stuff in command window
% .lowMemory: (bool) use methods to save on memory
% .fipOutput: (bool) flip time stamps of output
% .stopInit: (vector) stop the computation once the
% reachable set includes the initial state
% .stopSetInclude: (matrix) stops computation when reachable set
% includes this set
% .stopSetIntersect: (matrix) stops computation when reachable set
% intersects this set
% .stopLevel: (double) level of the stopSet to check the
% inclusion for. Default level is zero.
% .stopConverge: (bool) set to true to stop the computation when
% it converges
% .convergeThreshold: Max change in each iteration allowed when
% checking convergence
% .ignoreBoundary: Ignores the boundary of the grid when
% calculating convergence
% .discountFactor: (double) amount by which you'd like to discount
% the value function. Used for ensuring
% convergence. Remember to move your targets
% function (l(x)) and initial value function
% (data0) down so they are below 0 everywhere.
% you can raise above 0 by the same amount at the
% end.
% .discountMode: Options are 'Kene' or 'Jaime'. Defaults to
% 'Jaime'. Math is in Kene's minimum discounted
% rewards paper and Jaime's "bridging
% hamilton-jacobi safety analysis and
% reinforcement learning" paper
% .discountAnneal: (string) if you want to anneal your discount
% factor over time so it converges to the right
% solution, use this.
% - 'soft' moves it slowly towards 1 each
% time convergence happens
% - 'hard' sets it to 1 once convergence
% happens
% - 1 sets it to 'hard'
% .SDModFunc, .SDModParams:
% Function for modifying scheme data every time step given by tau.
% Currently this is only used to switch between using optimal control at
% every grid point and using maximal control for the SPP project when
% computing FRS using centralized controller
%
% .saveFilename, .saveFrequency:
% file name under which temporary data is saved at some frequency in
% terms of the number of time steps
%
% .compRegion: unused for now (meant to limit computation
% region)
% .addGaussianNoiseStandardDeviation:
% adds random noise
%
% .makeVideo: (bool) whether or not to create a video
% .videoFilename: (string) filename of video
% .frameRate: (int) framerate of video
% .visualize: either fill in struct or set to 1 for generic
% visualization
% .plotData: (struct) information
% required to plot the data:
% .plotDims: dims to plot
% .projpt: projection points.
% Can be vector or
% cell. e.g.
% {pi,'min'} means
% project at pi for
% first dimension,
% take minimum
% (union) for second
% dimension
% .sliceLevel: (double) level set of
% reachable set to visualize
% (default is 0)
% .holdOn: (bool) leave whatever was
% already on the figure?
% .lineWidth: (int) width of lines
% .viewAngle: (vector) [az,el] angles for
% viewing plot
% .camlightPosition: (vector) location of light
% source
% .viewGrid: (bool) view grid
% .viewAxis: (vector) size of axis
% .xTitle: (string) x axis title
% .yTitle: (string) y axis title
% .zTitle: (string) z axis title
% .dtTime How often you want to
% update time stamp on title
% of plot
% .fontSize: (int) font size of figure
% .deleteLastPlot: (bool) set to true to
% delete previous plot
% before displaying next one
% .figNum: (int) for plotting a
% specific figure number
% .figFilename: (string) provide this to
% save the figures (requires
% export_fig package)
% .initialValueSet: (bool) view initial value
% set
% .initialValueFunction: (bool) view initial
% value function
% .valueSet: (bool) view value set
% .valueFunction: (bool) view value function
% .obstacleSet: (bool) view obstacle set
% .obstacleFunction: (bool) view obstacle
% function
% .targetSet: (bool) view target set
% .targetFunction: (bool) view target function
% .plotColorVS0: color of initial value set
% .plotColorVF0: color of initial value
% function
% .plotAlphaVF0: transparency of initial
% value function
% .plotColorVS: color of value set
% .plotColorVF: color of value function
% .plotAlphaVF: transparency of initial
% value function
% .plotColorOS: color of obstacle set
% .plotColorOF: color of obstacle function
% .plotAlphaOF: transparency of obstacle
% function
% .plotColorTS: color of target set
% .plotColorTF: color of target function
% .plotAlphaTF: transparency of target
% function
% Outputs:
% data - solution corresponding to grid g and time vector tau
% tau - list of computation times (redundant)
% extraOuts - This structure can be used to pass on extra outputs, for
% example:
% .stoptau: time at which the reachable set contains the initial
% state; tau and data vectors only contain the data till
% stoptau time.
%
% .hVS0: These are all figure handles for the appropriate
% .hVF0 set/function
% .hTS
% .hTF
% .hOS
% .hOF
% .hVS
% .hVF
%
%
% -------Updated 11/14/18 by Sylvia Herbert (sylvia.lee.herbert@gmail.com)
%
%% Default parameters
if numel(tau) < 2
error('Time vector must have at least two elements!')
end
if nargin < 4
compMethod = 'minVOverTime';
end
if nargin < 5
extraArgs = [];
end
extraOuts = [];
quiet = false;
lowMemory = false;
keepLast = false;
flipOutput = false;
small = 1e-4;
g = schemeData.grid;
gDim = g.dim;
clns = repmat({':'}, 1, gDim);
%% Backwards compatible
if isfield(extraArgs, 'low_memory')
extraArgs.lowMemory = extraArgs.low_memory;
extraArgs = rmfield(extraArgs, 'low_memory');
warning('we now use lowMemory instead of low_memory');
end
if isfield(extraArgs, 'flip_output')
extraArgs.flipOutput = extraArgs.low_memory;
extraArgs = rmfield(extraArgs, 'flip_output');
warning('we now use flipOutput instead of flip_output');
end
if isfield(extraArgs, 'stopSet')
extraArgs.stopSetInclude = extraArgs.stopSet;
extraArgs = rmfield(extraArgs, 'stopSet');
warning('we now use stopSetInclude instead of stopSet');
end
if isfield(extraArgs, 'visualize') && ...
~isstruct(extraArgs.visualize) && ...
extraArgs.visualize
% remove visualize boolean
extraArgs = rmfield(extraArgs, 'visualize');
% reset defaults
extraArgs.visualize.initialValueSet = 1;
extraArgs.visualize.valueSet = 1;
end
if isfield(extraArgs, 'visualize')
if isfield(extraArgs, 'RS_level')
extraArgs.visualize.sliceLevel = extraArgs.RS_level;
extraArgs = rmfield(extraArgs, 'RS_level');
warning(['we now use extraArgs.visualize.sliceLevel instead of'...
'extraArgs.RS_level']);
end
if isfield(extraArgs, 'plotData')
extraArgs.visualize.plotData = extraArgs.plotData;
extraArgs = rmfield(extraArgs, 'plotData');
warning(['we now use extraArgs.visualize.plotData instead of'...
'extraArgs.plotData']);
end
if isfield(extraArgs, 'deleteLastPlot')
extraArgs.visualize.deleteLastPlot = extraArgs.deleteLastPlot;
extraArgs = rmfield(extraArgs, 'deleteLastPlot');
warning(['we now use extraArgs.visualize.deleteLastPlot instead'...
'of extraArgs.deleteLastPlot']);
end
if isfield(extraArgs, 'fig_num')
extraArgs.visualize.figNum = extraArgs.fig_num;
extraArgs = rmfield(extraArgs, 'fig_num');
warning(['we now use extraArgs.visualize.figNum instead'...
'of extraArgs.fig_num']);
end
if isfield(extraArgs, 'fig_filename')
extraArgs.visualize.figFilename = extraArgs.fig_filename;
extraArgs = rmfield(extraArgs, 'fig_filename');
warning(['we now use extraArgs.visualize.figFilename instead'...
'of extraArgs.fig_filename']);
end
if isfield(extraArgs, 'target')
warning(['you wrote extraArgs.target instead of' ...
'extraArgs.targetFunction'])
extraArgs.targetFunction = extraArgs.target;
extraArgs = rmfield(extraArgs, 'target');
end
if isfield(extraArgs, 'targets')
warning(['you wrote extraArgs.targets instead of' ...
'extraArgs.targetFunction'])
extraArgs.targetFunction = extraArgs.targets;
extraArgs = rmfield(extraArgs, 'targets');
end
if isfield(extraArgs, 'obstacle')
extraArgs.obstacleFunction = extraArgs.obstacle;
warning(['you wrote extraArgs.obstacle instead of' ...
'extraArgs.obstacleFunction'])
extraArgs = rmfield(extraArgs, 'obstacle');
end
if isfield(extraArgs, 'obstacles')
extraArgs.obstacleFunction = extraArgs.obstacles;
warning(['you wrote extraArgs.obstacles instead of' ...
'extraArgs.obstacleFunction'])
extraArgs = rmfield(extraArgs, 'obstacles');
end
end
%% Extract the information from extraargs
% Quiet mode
if isfield(extraArgs, 'quiet') && extraArgs.quiet
fprintf('HJIPDE_solve running in quiet mode...\n')
quiet = true;
end
% Low memory mode
if isfield(extraArgs, 'lowMemory') && extraArgs.lowMemory
fprintf('HJIPDE_solve running in low memory mode...\n')
lowMemory = true;
% Save the output in reverse order
if isfield(extraArgs, 'flipOutput') && extraArgs.flipOutput
flipOutput = true;
end
end
% Only keep latest data (saves memory)
if isfield(extraArgs, 'keepLast') && extraArgs.keepLast
keepLast = true;
end
%---Extract the information about obstacles--------------------------------
obsMode = 'none';
if isfield(extraArgs, 'obstacleFunction')
obstacles = extraArgs.obstacleFunction;
% are obstacles moving or not?
if numDims(obstacles) == gDim
obsMode = 'static';
obstacle_i = obstacles;
elseif numDims(obstacles) == gDim + 1
obsMode = 'time-varying';
obstacle_i = obstacles(clns{:}, 1);
else
error('Inconsistent obstacle dimensions!')
end
% We always take the max between the data and the obstacles
% note that obstacles are negated. That's because if you define the
% obstacles using something like ShapeSphere, it sets it up as a
% target. To make it an obstacle we just negate that.
data0 = max(data0, -obstacle_i);
end
%---Extract the information about targets----------------------------------
targMode = 'none';
if isfield(extraArgs, 'targetFunction')
targets = extraArgs.targetFunction;
% is target function moving or not?
if numDims(targets) == gDim
targMode = 'static';
target_i = targets;
elseif numDims(targets) == gDim + 1
targMode = 'time-varying';
target_i = targets(clns{:}, 1);
else
error('Inconsistent target dimensions!')
end
end
%---Stopping Conditions----------------------------------------------------
% Check validity of stopInit if needed
if isfield(extraArgs, 'stopInit')
if ~isvector(extraArgs.stopInit) || gDim ~= length(extraArgs.stopInit)
error('stopInit must be a vector of length g.dim!')
end
end
if isfield(extraArgs,'stopSetInclude') || isfield(extraArgs,'stopSetIntersect')
if isfield(extraArgs,'stopSetInclude')
stopSet = extraArgs.stopSetInclude;
else
stopSet = extraArgs.stopSetIntersect;
end
if numDims(stopSet) ~= gDim || any(size(stopSet) ~= g.N')
error('Inconsistent stopSet dimensions!')
end
% Extract set of indices at which stopSet is negative
setInds = find(stopSet(:) < 0);
% Check validity of stopLevel if needed
if isfield(extraArgs, 'stopLevel')
stopLevel = extraArgs.stopLevel;
else
stopLevel = 0;
end
end
%% Visualization
if (isfield(extraArgs, 'visualize') && isstruct(extraArgs.visualize))...
|| (isfield(extraArgs, 'makeVideo') && extraArgs.makeVideo)
% Mark initial iteration, state that for the first plot we need
% lighting
timeCount = 0;
needLight = true;
%---Video Parameters---------------------------------------------------
% If we're making a video, set up the parameters
if isfield(extraArgs, 'makeVideo') && extraArgs.makeVideo
if ~isfield(extraArgs, 'videoFilename')
extraArgs.videoFilename = ...
[datestr(now,'YYYYMMDD_hhmmss') '.mp4'];
end
vout = VideoWriter(extraArgs.videoFilename,'MPEG-4');
vout.Quality = 100;
if isfield(extraArgs, 'frameRate')
vout.FrameRate = extraArgs.frameRate;
else
vout.FrameRate = 30;
end
try
vout.open;
catch
error('cannot open file for writing')
end
end
%---Projection Parameters----------------------------------------------
% Extract the information about plotData
plotDims = ones(gDim, 1);
projpt = [];
if isfield(extraArgs.visualize, 'plotData')
% Dimensions to visualize
% It will be an array of 1s and 0s with 1s means that dimension should
% be plotted.
plotDims = extraArgs.visualize.plotData.plotDims;
% Points to project other dimensions at. There should be an entry point
% corresponding to each 0 in plotDims.
projpt = extraArgs.visualize.plotData.projpt;
end
% Number of dimensions to be plotted and to be projected
pDims = nnz(plotDims);
projDims = length(projpt);
% Basic Checks
if (pDims > 4)
error('Currently plotting up to 3D is supported!');
end
%---Defaults-----------------------------------------------------------
if isfield(extraArgs, 'obstacleFunction') && isfield(extraArgs, 'visualize')
if ~isfield(extraArgs.visualize, 'obstacleSet')
extraArgs.visualize.obstacleSet = 1;
end
end
if isfield(extraArgs, 'targetFunction') && isfield(extraArgs, 'visualize')
if ~isfield(extraArgs.visualize, 'targetSet')
extraArgs.visualize.targetSet = 1;
end
end
% Set level set slice
if isfield(extraArgs.visualize, 'sliceLevel')
sliceLevel = extraArgs.visualize.sliceLevel;
else
sliceLevel = 0;
end
% Do we want to see every single plot at every single time step, or
% only the most recent one?
if isfield(extraArgs.visualize, 'deleteLastPlot')
deleteLastPlot = extraArgs.visualize.deleteLastPlot;
else
deleteLastPlot = false;
end
view3D = 0;
%---Perform Projections------------------------------------------------
% Project
if projDims == 0
gPlot = g;
dataPlot = data0;
if isfield(extraArgs, 'obstacleFunction')
obsPlot = obstacle_i;
end
if isfield(extraArgs, 'targetFunction')
targPlot = target_i;
end
else
% if projpt is a cell, project each dimensions separately. This
% allows us to take the union/intersection through some dimensions
% and to project at a particular slice through other dimensions.
if iscell(projpt)
idx = find(plotDims==0);
plotDimsTemp = ones(size(plotDims));
gPlot = g;
dataPlot = data0;
if isfield(extraArgs, 'obstacleFunction')
obsPlot = obstacle_i;
end
if isfield(extraArgs, 'targetFunction')
targPlot = target_i;
end
for ii = length(idx):-1:1
plotDimsTemp(idx(ii)) = 0;
if isfield(extraArgs, 'obstacleFunction')
[~, obsPlot] = proj(gPlot, obsPlot, ~plotDimsTemp,...
projpt{ii});
end
if isfield(extraArgs, 'targetFunction')
[~, targPlot] = proj(gPlot, targPlot, ...
~plotDimsTemp, projpt{ii});
end
[gPlot, dataPlot] = proj(gPlot, dataPlot, ~plotDimsTemp,...
projpt{ii});
plotDimsTemp = ones(1,gPlot.dim);
end
else
[gPlot, dataPlot] = proj(g, data0, ~plotDims, projpt);
if isfield(extraArgs, 'obstacleFunction')
[~, obsPlot] = proj(g, obstacle_i, ~plotDims, projpt);
end
if isfield(extraArgs, 'targetFunction')
[~, targPlot] = proj(g, target_i, ~plotDims, projpt);
end
end
end
%---Initialize Figure--------------------------------------------------
% Initialize the figure for visualization
if isfield(extraArgs.visualize,'figNum')
f = figure(extraArgs.visualize.figNum);
else
f = figure;
end
% Clear figure unless otherwise specified
if ~isfield(extraArgs.visualize,'holdOn')|| ~extraArgs.visualize.holdOn
clf
end
hold on
grid on
% Set defaults
eAT_visSetIm.sliceDim = gPlot.dim;
eAT_visSetIm.applyLight = false;
if isfield(extraArgs.visualize, 'lineWidth')
eAT_visSetIm.LineWidth = extraArgs.visualize.lineWidth;
eAO_visSetIm.LineWidth = extraArgs.visualize.lineWidth;
else
eAO_visSetIm.LineWidth = 2;
end
% If we're stopping once we hit an initial condition requirement, plot
% said requirement
if isfield(extraArgs, 'stopInit')
projectedInit = extraArgs.stopInit(logical(plotDims));
if nnz(plotDims) == 2
plot(projectedInit(1), projectedInit(2), 'b*')
elseif nnz(plotDims) == 3
plot3(projectedInit(1), projectedInit(2), projectedInit(3), 'b*')
end
end
%% Visualize Inital Value Function/Set
%---Visualize Initial Value Set----------------------------------------
if isfield(extraArgs.visualize, 'initialValueSet') &&...
extraArgs.visualize.initialValueSet
if ~isfield(extraArgs.visualize,'plotColorVS0')
extraArgs.visualize.plotColorVS0 = 'g';
end
extraOuts.hVS0 = visSetIm(...
gPlot, dataPlot, extraArgs.visualize.plotColorVS0,...
sliceLevel, eAT_visSetIm);
if isfield(extraArgs.visualize,'plotAlphaVS0')
extraOuts.hVS0.FaceAlpha = extraArgs.visualize.plotAlphaVS0;
end
end
%---Visualize Initial Value Function-----------------------------------
if isfield(extraArgs.visualize, 'initialValueFunction') &&...
extraArgs.visualize.initialValueFunction
% If we're making a 3D plot, mark so we know to view this at an
% angle appropriate for 3D
if gPlot.dim >= 2
view3D = 1;
end
% Set up default parameters
if ~isfield(extraArgs.visualize,'plotColorVF0')
extraArgs.visualize.plotColorVF0 = 'g';
end
if ~isfield(extraArgs.visualize,'plotAlphaVF0')
extraArgs.visualize.plotAlphaVF0 = .5;
end
% Visualize Initial Value function (hVF0)
[extraOuts.hVF0]= visFuncIm(gPlot,dataPlot,...
extraArgs.visualize.plotColorVF0,...
extraArgs.visualize.plotAlphaVF0);
end
%% Visualize Target Function/Set
%---Visualize Target Set-----------------------------------------------
if isfield(extraArgs.visualize, 'targetSet') ...
&& extraArgs.visualize.targetSet
if ~isfield(extraArgs.visualize,'plotColorTS')
extraArgs.visualize.plotColorTS = 'g';
end
extraOuts.hTS = visSetIm(gPlot, targPlot, ...
extraArgs.visualize.plotColorTS, sliceLevel, eAT_visSetIm);
if isfield(extraArgs.visualize,'plotAlphaTS')
extraOuts.hTS.FaceAlpha = extraArgs.visualize.plotAlphaTS;
end
end
%---Visualize Target Function------------------------------------------
if isfield(extraArgs.visualize, 'targetFunction') &&...
extraArgs.visualize.targetFunction
% If we're making a 3D plot, mark so we know to view this at an
% angle appropriate for 3D
if gPlot.dim >= 2
view3D = 1;
end
% Set up default parameters
if ~isfield(extraArgs.visualize,'plotColorTF')
extraArgs.visualize.plotColorTF = 'g';
end
if ~isfield(extraArgs.visualize,'plotAlphaTF')
extraArgs.visualize.plotAlphaTF = .5;
end
% Visualize Target function (hTF)
[extraOuts.hTF]= visFuncIm(gPlot,targPlot,...
extraArgs.visualize.plotColorTF,...
extraArgs.visualize.plotAlphaTF);
end
%% Visualize Obstacle Function/Set
%---Visualize Obstacle Set---------------------------------------------
if isfield(extraArgs.visualize, 'obstacleSet') ...
&& extraArgs.visualize.obstacleSet
if ~isfield(extraArgs.visualize,'plotColorOS')
extraArgs.visualize.plotColorOS = 'r';
end
% Visualize obstacle set (hOS)
extraOuts.hOS = visSetIm(gPlot, obsPlot, ...
extraArgs.visualize.plotColorOS, sliceLevel, eAO_visSetIm);
end
%---Visualize Obstacle Function----------------------------------------
if isfield(extraArgs.visualize, 'obstacleFunction') ...
&& extraArgs.visualize.obstacleFunction
% If we're making a 3D plot, mark so we know to view this at an
% angle appropriate for 3D
if gPlot.dim >= 2
view3D = 1;
end
% Set up default parameters
if ~isfield(extraArgs.visualize,'plotColorOF')
extraArgs.visualize.plotColorOF = 'r';
end
if ~isfield(extraArgs.visualize,'plotAlphaOF')
extraArgs.visualize.plotAlphaOF = .5;
end
% Visualize function
[extraOuts.hOF]= visFuncIm(gPlot,-obsPlot,...
extraArgs.visualize.plotColorOF,...
extraArgs.visualize.plotAlphaOF);
end
%% Visualize Value Function/Set
%---Visualize Value Set Heat Map---------------------------------------
if isfield(extraArgs.visualize, 'valueSetHeatMap') &&...
extraArgs.visualize.valueSetHeatMap
maxVal = max(abs(data0(:)));
clims = [-maxVal-1 maxVal+1];
extraOuts.hVSHeat = imagesc(...
gPlot.vs{1},gPlot.vs{2},dataPlot,clims);
if isfield(extraArgs.visualize,'colormap')
colormap(extraArgs.visualize.colormap)
else
cmapAutumn = colormap('autumn');
cmapCool = colormap('cool');
cmap(1:32,:) = cmapCool(64:-2:1,:);
cmap(33:64,:) = cmapAutumn(64:-2:1,:);
colormap(cmap);
end
colorbar
end
%---Visualize Value Set------------------------------------------------
if isfield(extraArgs.visualize, 'valueSet') &&...
extraArgs.visualize.valueSet
if ~isfield(extraArgs.visualize,'plotColorVS')
extraArgs.visualize.plotColorVS = 'b';
end
extraOuts.hVS = visSetIm(gPlot, dataPlot, ...
extraArgs.visualize.plotColorVS, sliceLevel, eAT_visSetIm);
end
%---Visualize Value Function-------------------------------------------
if isfield(extraArgs.visualize, 'valueFunction') && ...
extraArgs.visualize.valueFunction
% If we're making a 3D plot, mark so we know to view this at an
% angle appropriate for 3D
if gPlot.dim >= 2
view3D = 1;
end
% Set up default parameters
if ~isfield(extraArgs.visualize,'plotColorVF')
extraArgs.visualize.plotColorVF = 'b';
end
if ~isfield(extraArgs.visualize,'plotAlphaVF')
extraArgs.visualize.plotAlphaVF = .5;
end
% Visualize Value function (hVF)
[extraOuts.hVF]= visFuncIm(gPlot,dataPlot,...
extraArgs.visualize.plotColorVF,...
extraArgs.visualize.plotAlphaVF);
end
%% General Visualization Stuff
%---Set Angle, Lighting, axis, Labels, Title---------------------------
% Set Angle
if pDims >2 || view3D || isfield(extraArgs.visualize, 'viewAngle')
if isfield(extraArgs.visualize, 'viewAngle')
view(extraArgs.visualize.viewAngle)
else
view(30,10)
end
% Set Lighting
if needLight% && (gPlot.dim == 3)
lighting phong
c = camlight;
%need_light = false;
end
if isfield(extraArgs.visualize, 'camlightPosition')
c.Position = extraArgs.visualize.camlightPosition;
else
c.Position = [-30 -30 -30];
end
end
% Grid and axis
if isfield(extraArgs.visualize, 'viewGrid') && ...
~extraArgs.visualize.viewGrid
grid off
end
if isfield(extraArgs.visualize, 'viewAxis')
axis(extraArgs.visualize.viewAxis)
end
axis square
% Labels
if isfield(extraArgs.visualize, 'xTitle')
xlabel(extraArgs.visualize.xTitle, 'interpreter','latex')
end
if isfield(extraArgs.visualize, 'yTitle')
ylabel(extraArgs.visualize.yTitle,'interpreter','latex')
end
if isfield(extraArgs.visualize, 'zTitle')
zlabel(extraArgs.visualize.zTitle,'interpreter','latex')
end
title(['t = ' num2str(0) ' s'])
set(gcf,'Color','white')
if isfield(extraArgs.visualize, 'fontSize')
set(gca,'FontSize',extraArgs.visualize.fontSize)
end
if isfield(extraArgs.visualize, 'lineWidth')
set(gca,'LineWidth',extraArgs.visualize.lineWidth)
end
drawnow;
% If we're making a video, grab the frame
if isfield(extraArgs, 'makeVideo') && extraArgs.makeVideo
current_frame = getframe(gcf); %gca does just the plot
writeVideo(vout,current_frame);
end
% If we're saving each figure, do so now
if isfield(extraArgs.visualize, 'figFilename')
export_fig(sprintf('%s%d', extraArgs.visualize.figFilename, 0), '-png')
end
end
%% Extract dynamical system if needed
if isfield(schemeData, 'dynSys')
schemeData.hamFunc = @genericHam;
schemeData.partialFunc = @genericPartial;
end
stopConverge = false;
if isfield(extraArgs, 'stopConverge')
stopConverge = extraArgs.stopConverge;
if isfield(extraArgs, 'convergeThreshold')
convergeThreshold = extraArgs.convergeThreshold;
else
convergeThreshold = 1e-5;
end
end
stopConvergeTTR = false;
if isfield(extraArgs, 'stopConvergeTTR')
stopConvergeTTR = extraArgs.stopConvergeTTR;
if isfield(extraArgs, 'convergeThreshold')
convergeThresholdTTR = extraArgs.convergeThresholdTTR;
else
convergeThresholdTTR = 1e-5;
end
end
%% SchemeFunc and SchemeData
schemeFunc = @termLaxFriedrichs;
% Extract accuracy parameter o/w set default accuracy
accuracy = 'veryHigh';
if isfield(schemeData, 'accuracy')
accuracy = schemeData.accuracy;
end
%% Numerical approximation functions
dissType = 'global';
[schemeData.dissFunc, integratorFunc, schemeData.derivFunc] = ...
getNumericalFuncs(dissType, accuracy);
% if we're doing minWithZero or zero as the comp method, actually implement
% correctly using level set toolbox
if strcmp(compMethod, 'minWithZero') || strcmp(compMethod, 'zero')
schemeFunc = @termRestrictUpdate;
schemeData.innerFunc = @termLaxFriedrichs;
schemeData.innerData = schemeData;
schemeData.innerData = schemeData;
schemeData.positive = 0;
end
%% Time integration
integratorOptions = odeCFLset('factorCFL', 0.8, 'singleStep', 'on');
startTime = cputime;
%% Stochastic additive terms
if isfield(extraArgs, 'addGaussianNoiseStandardDeviation')
% We are taking all the previous scheme terms and adding noise to it
% Save all the previous terms as the deterministic component in detFunc
detFunc = schemeFunc;
detData = schemeData;
% The full computation scheme will include this added term so clear
% out the schemeFunc so we can pack everything back in later with the
% new stuff
clear schemeFunc schemeData;
% Create the Hessian term corresponding to white noise diffusion
stochasticFunc = @termTraceHessian;
stochasticData.grid = g;
stochasticData.L = extraArgs.addGaussianNoiseStandardDeviation';
stochasticData.R = extraArgs.addGaussianNoiseStandardDeviation;
stochasticData.hessianFunc = @hessianSecond;
% Add the (saved) deterministic terms and the (new) stochastic term
% together into the complete scheme
schemeFunc = @termSum;
schemeData.innerFunc = { detFunc; stochasticFunc };
schemeData.innerData = { detData; stochasticData };
end
%% Initialize PDE solution
data0size = size(data0);
if numDims(data0) == gDim
% New computation
if keepLast
data = data0;
elseif lowMemory
data = single(data0);
else
data = zeros([data0size(1:gDim) length(tau)]);
data(clns{:}, 1) = data0;
end
istart = 2;
elseif numDims(data0) == gDim + 1
% Continue an old computation
if keepLast
data = data0(clns{:}, data0size(end));
elseif lowMemory
data = single(data0(clns{:}, data0size(end)));
else
data = zeros([data0size(1:gDim) length(tau)]);
data(clns{:}, 1:data0size(end)) = data0;
end
% Start at custom starting index if specified
if isfield(extraArgs, 'istart')
istart = extraArgs.istart;
else
istart = data0size(end)+1;
end
else
error('Inconsistent initial condition dimension!')
end
if isfield(extraArgs,'ignoreBoundary') &&...
extraArgs.ignoreBoundary
[~, dataTrimmed] = truncateGrid(...
g, data0, g.min+4*g.dx, g.max-4*g.dx);
end
for i = istart:length(tau)
if ~quiet
fprintf('tau(i) = %f\n', tau(i))
end
%% Variable schemeData
if isfield(extraArgs, 'SDModFunc')
if isfield(extraArgs, 'SDModParams')
paramsIn = extraArgs.SDModParams;
else