-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathde_parametric_heat_conduction_greedy.cpp
More file actions
1317 lines (1161 loc) · 46.9 KB
/
Copy pathde_parametric_heat_conduction_greedy.cpp
File metadata and controls
1317 lines (1161 loc) · 46.9 KB
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
/******************************************************************************
*
* Copyright (c) 2013-2024, Lawrence Livermore National Security, LLC
* and other libROM project developers. See the top-level COPYRIGHT
* file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
*
*****************************************************************************/
// libROM MFEM Example: Greedy Parametric_Heat_Conduction with Differential Evolution (adapted from ex16p.cpp)
//
// Compile with: make de_parametric_heat_conduction_greedy
//
// =================================================================================
//
// In these examples, the radius of the interface between different initial temperatures, the
// alpha coefficient, and two center location variables are modified. First, a database of local
// DMDs is built in a greedy fashion within a certain radius, alpha, and center location parameter
// range. Then, a target FOM is built at a certain parameter point. Finally, this parameter point
// is treated as unknown and differential evolution (an iterative optimization algorithm that minimizes
// a cost function without the use of gradients) is run within some parameter range and automatically
// converges to the same parameter point where the target FOM was built.
//
// In this example, the optimization objective of the differential evolution (DE) algorithm is to minimize
// the relative difference between the final solution of the parametric DMD and the target FOM solution.
// The relative difference is minimized by adjusting the parameter point (radius, alpha, and center
// location) where the parametric DMD is built until some parameter point is found where the relative
// difference is at a global minimum. DE optimizes this problem by maintaining a population of
// candidate parameters and iteratively creating new candidate parameters by combining existing ones and
// storing whichever parameter set's final solution has the smallest relative difference. Thus, given an
// unknown solution and a database of local DMDs, DE is able to estimate the parameters of this unknown
// solution.
//
// For Parametric DMD with differential evolution (radius & alpha & cx & cy):
// rm -rf parameters.txt
// rm -rf de_parametric_heat_conduction_greedy_*
// mpirun -np 8 de_parametric_heat_conduction_greedy -build_database -rdim 16 -greedy-param-size 5 -greedysubsize 2 -greedyconvsize 3 -greedyreldifftol 0.01 (Create DMDs in a greedy fashion at different training points)
// mpirun -np 8 de_parametric_heat_conduction_greedy -r 0.2 -cx 0.2 -cy 0.2 -visit (Compute target FOM)
// mpirun -np 8 de_parametric_heat_conduction_greedy -r 0.2 -cx 0.2 -cy 0.2 -visit -de -de_f 0.9 -de_cr 0.9 -de_ps 50 -de_min_iter 10 -de_max_iter 100 -de_ct 0.001 (Run interpolative differential evolution to see if target FOM can be matched)
//
// =================================================================================
//
// Description: This example solves a time dependent nonlinear heat equation
// problem of the form du/dt = C(u), with a non-linear diffusion
// operator C(u) = \nabla \cdot (\kappa + \alpha u) \nabla u.
//
// The example demonstrates the use of nonlinear operators (the
// class ConductionOperator defining C(u)), as well as their
// implicit time integration. Note that implementing the method
// ConductionOperator::ImplicitSolve is the only requirement for
// high-order implicit (SDIRK) time integration. Optional saving
// with ADIOS2 (adios2.readthedocs.io) is also illustrated.
#include "mfem.hpp"
#include "algo/DMD.h"
#include "algo/DifferentialEvolution.h"
#include "algo/greedy/GreedyRandomSampler.h"
#include "linalg/Vector.h"
#include <cmath>
#include <cfloat>
#include <fstream>
#include <iostream>
#include "utils/CSVDatabase.h"
#ifndef _WIN32
#include <sys/stat.h> // mkdir
#else
#include <direct.h> // _mkdir
#define mkdir(dir, mode) _mkdir(dir)
#endif
using std::vector;
using std::cout;
using std::endl;
using std::flush;
using std::max;
using std::min;
using std::to_string;
using std::ifstream;
using std::ofstream;
using std::ostringstream;
using std::setfill;
using std::setw;
using namespace mfem;
/** After spatial discretization, the conduction model can be written as:
*
* du/dt = M^{-1}(-Ku)
*
* where u is the vector representing the temperature, M is the mass matrix,
* and K is the diffusion operator with diffusivity depending on u:
* (\kappa + \alpha u).
*
* Class ConductionOperator represents the right-hand side of the above ODE.
*/
class ConductionOperator : public TimeDependentOperator
{
protected:
ParFiniteElementSpace &fespace;
Array<int> ess_tdof_list; // this list remains empty for pure Neumann b.c.
ParBilinearForm *M;
ParBilinearForm *K;
HypreParMatrix Mmat;
HypreParMatrix Kmat;
HypreParMatrix *T; // T = M + dt K
double current_dt;
CGSolver M_solver; // Krylov solver for inverting the mass matrix M
HypreSmoother M_prec; // Preconditioner for the mass matrix M
CGSolver T_solver; // Implicit solver for T = M + dt K
HypreSmoother T_prec; // Preconditioner for the implicit solver
double alpha, kappa;
mutable Vector z; // auxiliary vector
public:
ConductionOperator(ParFiniteElementSpace &f, double alpha, double kappa,
const Vector &u);
virtual void Mult(const Vector &u, Vector &du_dt) const;
/** Solve the Backward-Euler equation: k = f(u + dt*k, t), for the unknown k.
This is the only requirement for high-order SDIRK implicit integration.*/
virtual void ImplicitSolve(const double dt, const Vector &u, Vector &k);
/// Update the diffusion BilinearForm K using the given true-dof vector `u`.
void SetParameters(const Vector &u);
virtual ~ConductionOperator();
};
double InitialTemperature(const Vector &x);
int num_procs, myid;
const char *mesh_file = "../data/star.mesh";
int ser_ref_levels = 2;
int par_ref_levels = 1;
int order = 2;
int ode_solver_type = 3;
double t_final = 0.5;
double dt = 1.0e-2;
double alpha = 1.0e-2;
double kappa = 0.5;
double closest_rbf_val = 0.9;
int rdim = -1;
bool offline = false;
bool online = false;
bool build_database = false;
bool calc_err_indicator = false;
bool de = false;
double greedy_param_space_radius_min = 0.1;
double greedy_param_space_radius_max = 0.3;
double greedy_param_space_alpha_min = 0.1;
double greedy_param_space_alpha_max = 0.1;
double greedy_param_space_cx_min = 0.1;
double greedy_param_space_cx_max = 0.3;
double greedy_param_space_cy_min = 0.1;
double greedy_param_space_cy_max = 0.3;
int greedy_param_space_size = 8;
double greedy_relative_diff_tol = 0.01;
int greedy_subset_size = 2;
int greedy_convergence_subset_size = 3;
bool visualization = false;
bool visit = false;
int vis_steps = 5;
bool adios2 = false;
const char *baseoutputname = "";
int precision = 16;
double radius = 0.5;
double cx = 0.0;
double cy = 0.0;
double de_min_radius = -DBL_MAX;
double de_min_alpha = -DBL_MAX;
double de_min_cx = -DBL_MAX;
double de_min_cy = -DBL_MAX;
double de_max_radius = DBL_MAX;
double de_max_alpha = DBL_MAX;
double de_max_cx = DBL_MAX;
double de_max_cy = DBL_MAX;
double target_radius = radius;
double target_alpha = alpha;
double target_cx = cx;
double target_cy = cy;
double de_F = 0.8;
double de_CR = 0.9;
int de_PS = 50;
int de_min_iter = 10;
int de_max_iter = 100;
double de_ct = 0.001;
CAROM::GreedySampler* greedy_sampler = NULL;
Vector* true_solution_u = NULL;
double tot_true_solution_u_norm = 0.0;
double simulation()
{
// 6. Read the serial mesh from the given mesh file on all processors. We can
// handle triangular, quadrilateral, tetrahedral and hexahedral meshes
// with the same code.
Mesh *mesh = new Mesh(mesh_file, 1, 1);
int dim = mesh->Dimension();
// 7. Define the ODE solver used for time integration. Several implicit
// singly diagonal implicit Runge-Kutta (SDIRK) methods, as well as
// explicit Runge-Kutta methods are available.
ODESolver *ode_solver;
switch (ode_solver_type)
{
// Implicit L-stable methods
case 1:
ode_solver = new BackwardEulerSolver;
break;
case 2:
ode_solver = new SDIRK23Solver(2);
break;
case 3:
ode_solver = new SDIRK33Solver;
break;
// Explicit methods
case 11:
ode_solver = new ForwardEulerSolver;
break;
case 12:
ode_solver = new RK2Solver(0.5);
break; // midpoint method
case 13:
ode_solver = new RK3SSPSolver;
break;
case 14:
ode_solver = new RK4Solver;
break;
case 15:
ode_solver = new GeneralizedAlphaSolver(0.5);
break;
// Implicit A-stable methods (not L-stable)
case 22:
ode_solver = new ImplicitMidpointSolver;
break;
case 23:
ode_solver = new SDIRK23Solver;
break;
case 24:
ode_solver = new SDIRK34Solver;
break;
default:
cout << "Unknown ODE solver type: " << ode_solver_type << '\n';
delete mesh;
return 3;
}
// 8. Refine the mesh in serial to increase the resolution. In this example
// we do 'ser_ref_levels' of uniform refinement, where 'ser_ref_levels' is
// a command-line parameter.
for (int lev = 0; lev < ser_ref_levels; lev++)
{
mesh->UniformRefinement();
}
// 9. Define a parallel mesh by a partitioning of the serial mesh. Refine
// this mesh further in parallel to increase the resolution. Once the
// parallel mesh is defined, the serial mesh can be deleted.
ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);
delete mesh;
for (int lev = 0; lev < par_ref_levels; lev++)
{
pmesh->UniformRefinement();
}
// 10. Define the vector finite element space representing the current and the
// initial temperature, u_ref.
H1_FECollection fe_coll(order, dim);
ParFiniteElementSpace fespace(pmesh, &fe_coll);
int fe_size = fespace.GlobalTrueVSize();
if (!de && !online && myid == 0)
{
cout << "Number of temperature unknowns: " << fe_size << endl;
}
ParGridFunction u_gf(&fespace);
// 11. Set the initial conditions for u. All boundaries are considered
// natural.
FunctionCoefficient u_0(InitialTemperature);
u_gf.ProjectCoefficient(u_0);
Vector u;
u_gf.GetTrueDofs(u);
// 12. Initialize the conduction operator and the VisIt visualization.
ConductionOperator oper(fespace, alpha, kappa, u);
u_gf.SetFromTrueDofs(u);
if (!de && !online)
{
ostringstream mesh_name, sol_name;
mesh_name << "de_parametric_heat_conduction_greedy_" << to_string(
radius) << "_"
<< to_string(alpha) << "_" << to_string(cx) << "_" << to_string(cy)
<< "-mesh." << setfill('0') << setw(6) << myid;
sol_name << "de_parametric_heat_conduction_greedy_" << to_string(
radius) << "_"
<< to_string(alpha) << "_" << to_string(cx) << "_" << to_string(cy)
<< "-init." << setfill('0') << setw(6) << myid;
ofstream omesh(mesh_name.str().c_str());
omesh.precision(precision);
pmesh->Print(omesh);
ofstream osol(sol_name.str().c_str());
osol.precision(precision);
u_gf.Save(osol);
}
VisItDataCollection visit_dc("DE_Parametric_Heat_Conduction_Greedy_" +
to_string(radius) + "_" + to_string(alpha) + "_" + to_string(cx) + "_" +
to_string(cy), pmesh);
visit_dc.RegisterField("temperature", &u_gf);
if (!de && !online && visit)
{
visit_dc.SetCycle(0);
visit_dc.SetTime(0.0);
visit_dc.Save();
}
// Optionally output a BP (binary pack) file using ADIOS2. This can be
// visualized with the ParaView VTX reader.
#ifdef MFEM_USE_ADIOS2
ADIOS2DataCollection* adios2_dc = NULL;
if (adios2)
{
std::string postfix(mesh_file);
postfix.erase(0, std::string("../data/").size() );
postfix += "_o" + std::to_string(order);
postfix += "_solver" + std::to_string(ode_solver_type);
const std::string collection_name = "de_parametric_heat_conduction_greedy-p-" +
postfix + ".bp";
adios2_dc = new ADIOS2DataCollection(MPI_COMM_WORLD, collection_name, pmesh);
adios2_dc->SetParameter("SubStreams", std::to_string(num_procs/2) );
adios2_dc->RegisterField("temperature", &u_gf);
adios2_dc->SetCycle(0);
adios2_dc->SetTime(0.0);
adios2_dc->Save();
}
#endif
socketstream sout;
if (visualization)
{
char vishost[] = "localhost";
int visport = 19916;
sout.open(vishost, visport);
sout << "parallel " << num_procs << " " << myid << endl;
int good = sout.good(), all_good;
MPI_Allreduce(&good, &all_good, 1, MPI_INT, MPI_MIN, pmesh->GetComm());
if (!all_good)
{
sout.close();
visualization = false;
if (myid == 0)
{
cout << "Unable to connect to GLVis server at "
<< vishost << ':' << visport << endl;
cout << "GLVis visualization disabled.\n";
}
}
else
{
sout.precision(precision);
sout << "solution\n" << *pmesh << u_gf;
sout << flush;
}
}
StopWatch fom_timer, dmd_training_timer, dmd_prediction_timer;
fom_timer.Start();
// 13. Perform time-integration (looping over the time iterations, ti, with a
// time-step dt).
ode_solver->Init(oper);
double t = 0.0;
vector<double> ts;
CAROM::Vector* init = NULL;
CAROM::CSVDatabase csv_db;
fom_timer.Stop();
std::unique_ptr<CAROM::DMD> dmd_u;
// 14. If in offline mode, create DMD object and take initial sample.
if (offline)
{
dmd_training_timer.Start();
u_gf.SetFromTrueDofs(u);
dmd_u.reset(new CAROM::DMD(u.Size(), dt));
dmd_u->takeSample(u.GetData(), t);
if (myid == 0)
{
std::cout << "Taking snapshot at: " << t << std::endl;
}
dmd_training_timer.Stop();
}
// 14. If in de or online mode, save the initial vector.
if (de || online)
{
u_gf.SetFromTrueDofs(u);
init = new CAROM::Vector(u.GetData(), u.Size(), true);
}
else
{
// 14. If in calc_err_indicator mode, load the current DMD database,
// and create a parametric DMD object at the current set of parameters.
if (calc_err_indicator)
{
init = new CAROM::Vector(u.GetData(), u.Size(), true);
std::fstream fin("parameters.txt", std::ios_base::in);
double curr_param;
std::vector<std::string> dmd_paths;
std::vector<CAROM::Vector> param_vectors;
while (fin >> curr_param)
{
double curr_radius = curr_param;
fin >> curr_param;
double curr_alpha = curr_param;
fin >> curr_param;
double curr_cx = curr_param;
fin >> curr_param;
double curr_cy = curr_param;
dmd_paths.push_back(to_string(curr_radius) + "_" +
to_string(curr_alpha) + "_" + to_string(curr_cx) + "_" +
to_string(curr_cy));
CAROM::Vector param_vector(4, false);
param_vector(0) = curr_radius;
param_vector(1) = curr_alpha;
param_vector(2) = curr_cx;
param_vector(3) = curr_cy;
param_vectors.push_back(param_vector);
}
fin.close();
if (dmd_paths.size() > 1)
{
CAROM::Vector desired_param(4, false);
desired_param(0) = radius;
desired_param(1) = alpha;
desired_param(2) = cx;
desired_param(3) = cy;
dmd_training_timer.Start();
CAROM::getParametricDMD(dmd_u, param_vectors, dmd_paths, desired_param,
"G", "LS", closest_rbf_val);
}
else
{
dmd_u.reset(new CAROM::DMD(dmd_paths[0]));
}
dmd_u->projectInitialCondition(*init);
dmd_training_timer.Stop();
// For the error indicator, load in the DMD predicted solution 10
// steps before t_final, then run the FOM for the last 10 steps and
// compare the final FOM solution to the DMD predicted solution.
t = t_final - 10.0 * dt;
std::shared_ptr<CAROM::Vector> carom_tf_u_minus_some = dmd_u->predict(t);
Vector tf_u_minus_some(carom_tf_u_minus_some->getData(),
carom_tf_u_minus_some->dim());
u = tf_u_minus_some;
u_gf.SetFromTrueDofs(u);
}
ts.push_back(t);
// 15. Iterate through the time loop.
bool last_step = false;
for (int ti = 1; !last_step; ti++)
{
fom_timer.Start();
if (t + dt >= t_final - dt/2)
{
last_step = true;
}
ode_solver->Step(u, t, dt);
fom_timer.Stop();
if (offline)
{
dmd_training_timer.Start();
u_gf.SetFromTrueDofs(u);
dmd_u->takeSample(u.GetData(), t);
if (myid == 0)
{
std::cout << "Taking snapshot at: " << t << std::endl;
}
dmd_training_timer.Stop();
}
ts.push_back(t);
if (last_step || (ti % vis_steps) == 0)
{
if (myid == 0)
{
cout << "step " << ti << ", t = " << t << endl;
}
u_gf.SetFromTrueDofs(u);
if (visualization)
{
sout << "parallel " << num_procs << " " << myid << "\n";
sout << "solution\n" << *pmesh << u_gf << flush;
}
if (!de && !online && visit)
{
visit_dc.SetCycle(ti);
visit_dc.SetTime(t);
visit_dc.Save();
}
#ifdef MFEM_USE_ADIOS2
if (adios2)
{
adios2_dc->SetCycle(ti);
adios2_dc->SetTime(t);
adios2_dc->Save();
}
#endif
}
oper.SetParameters(u);
}
if (!build_database && myid == 0)
{
std::ofstream outFile("ts.txt");
for (int i = 0; i < ts.size(); i++)
{
outFile << ts[i] << "\n";
}
}
#ifdef MFEM_USE_ADIOS2
if (adios2)
{
delete adios2_dc;
}
#endif
// 16. Save the final solution in parallel. This output can be viewed later
// using GLVis: "glvis -np <np> -m de_parametric_heat_conduction_greedy-mesh -g de_parametric_heat_conduction_greedy-final".
{
ostringstream sol_name;
sol_name << "de_parametric_heat_conduction_greedy_" << to_string(
radius) << "_"
<< to_string(alpha) << "_" << to_string(cx) << "_" << to_string(cy)
<< "-final." << setfill('0') << setw(6) << myid;
ofstream osol(sol_name.str().c_str());
osol.precision(precision);
u.Print(osol, 1);
}
}
double rel_diff = 0.0;
// 17. If in de or online mode, create the parametric DMD.
if (de || online)
{
std::fstream fin("parameters.txt", std::ios_base::in);
double curr_param;
std::vector<std::string> dmd_paths;
std::vector<CAROM::Vector> param_vectors;
while (fin >> curr_param)
{
double curr_radius = curr_param;
fin >> curr_param;
double curr_alpha = curr_param;
fin >> curr_param;
double curr_cx = curr_param;
fin >> curr_param;
double curr_cy = curr_param;
dmd_paths.push_back(to_string(curr_radius) + "_" +
to_string(curr_alpha) + "_" + to_string(curr_cx) + "_" +
to_string(curr_cy));
CAROM::Vector param_vector(4, false);
param_vector(0) = curr_radius;
param_vector(1) = curr_alpha;
param_vector(2) = curr_cx;
param_vector(3) = curr_cy;
param_vectors.push_back(param_vector);
}
fin.close();
CAROM::Vector desired_param(4, false);
desired_param(0) = radius;
desired_param(1) = alpha;
desired_param(2) = cx;
desired_param(3) = cy;
dmd_training_timer.Start();
CAROM::getParametricDMD(dmd_u, param_vectors, dmd_paths, desired_param,
"G", "LS", closest_rbf_val);
dmd_u->projectInitialCondition(*init);
dmd_training_timer.Stop();
}
if (offline || de || calc_err_indicator)
{
// 17. If in offline mode, save the DMD object.
if (offline)
{
if (myid == 0)
{
std::cout << "Creating DMD with rdim: " << rdim << std::endl;
}
dmd_training_timer.Start();
dmd_u->train(rdim);
dmd_training_timer.Stop();
dmd_u->save(to_string(radius) + "_" + to_string(alpha) + "_" +
to_string(cx) + "_" + to_string(cy));
if (myid == 0)
{
std::ofstream fout;
fout.open("parameters.txt", std::ios::app);
fout << radius << " " << alpha << " " << cx << " " << cy << std::endl;
fout.close();
}
}
// 18. Compare the DMD solution to the FOM solution.
if (de)
{
if (true_solution_u == NULL)
{
ifstream solution_file;
ostringstream sol_name;
ostringstream target_name;
sol_name << "de_parametric_heat_conduction_greedy_" << to_string(
target_radius) << "_"
<< to_string(target_alpha) << "_" << to_string(target_cx) << "_" << to_string(
target_cy)
<< "-final." << setfill('0') << setw(6) << myid;
solution_file.open(sol_name.str().c_str());
true_solution_u = new Vector(u.Size());
true_solution_u->Load(solution_file, u.Size());
solution_file.close();
tot_true_solution_u_norm = sqrt(InnerProduct(MPI_COMM_WORLD,
*true_solution_u, *true_solution_u));
}
}
else
{
if (true_solution_u == NULL)
{
true_solution_u = new Vector(u.Size());
*true_solution_u = u.GetData();
tot_true_solution_u_norm = sqrt(InnerProduct(MPI_COMM_WORLD,
*true_solution_u, *true_solution_u));
}
}
std::shared_ptr<CAROM::Vector> result_u = dmd_u->predict(t_final);
Vector dmd_solution_u(result_u->getData(), result_u->dim());
Vector diff_u(true_solution_u->Size());
subtract(dmd_solution_u, *true_solution_u, diff_u);
double tot_diff_norm_u = sqrt(InnerProduct(MPI_COMM_WORLD, diff_u, diff_u));
rel_diff = tot_diff_norm_u / tot_true_solution_u_norm;
if (myid == 0)
{
std::cout << "Rel. diff. of DMD temp. (u) at t_final at radius " << radius <<
", alpha " << alpha << ", cx " << cx << ", cy " << cy << ": "
<< rel_diff << std::endl;
}
if (!de && myid == 0)
{
printf("Elapsed time for training DMD: %e second\n",
dmd_training_timer.RealTime());
}
}
else if (online)
{
std::ifstream infile("ts.txt");
std::string str;
while (std::getline(infile, str))
{
// Line contains string of length > 0 then save it in vector
if(str.size() > 0)
{
ts.push_back(std::stod(str));
}
}
infile.close();
dmd_prediction_timer.Start();
// 14. Predict the state at t_final using DMD.
if (myid == 0)
{
std::cout << "Predicting temperature using DMD at: " << ts[0] << std::endl;
}
std::shared_ptr<CAROM::Vector> result_u = dmd_u->predict(ts[0]);
Vector initial_dmd_solution_u(result_u->getData(), result_u->dim());
u_gf.SetFromTrueDofs(initial_dmd_solution_u);
VisItDataCollection dmd_visit_dc("DMD_DE_Parametric_Heat_Conduction_Greedy_" +
to_string(radius) + "_" + to_string(alpha) + "_" +
to_string(cx) + "_" + to_string(cy), pmesh);
dmd_visit_dc.RegisterField("temperature", &u_gf);
if (visit)
{
dmd_visit_dc.SetCycle(0);
dmd_visit_dc.SetTime(0.0);
dmd_visit_dc.Save();
}
if (visit)
{
for (int i = 1; i < ts.size(); i++)
{
if (i == ts.size() - 1 || (i % vis_steps) == 0)
{
result_u = dmd_u->predict(ts[i]);
if (myid == 0)
{
std::cout << "Predicting temperature using DMD at: " << ts[i] << std::endl;
}
Vector dmd_solution_u(result_u->getData(), result_u->dim());
u_gf.SetFromTrueDofs(dmd_solution_u);
dmd_visit_dc.SetCycle(i);
dmd_visit_dc.SetTime(ts[i]);
dmd_visit_dc.Save();
}
}
}
dmd_prediction_timer.Stop();
result_u = dmd_u->predict(t_final);
// 15. Calculate the relative error between the DMD final solution and the true solution.
Vector dmd_solution_u(result_u->getData(), result_u->dim());
Vector diff_u(true_solution_u->Size());
subtract(dmd_solution_u, *true_solution_u, diff_u);
double tot_diff_norm_u = sqrt(InnerProduct(MPI_COMM_WORLD, diff_u, diff_u));
double tot_true_solution_u_norm = sqrt(InnerProduct(MPI_COMM_WORLD,
*true_solution_u, *true_solution_u));
if (myid == 0)
{
std::cout << "Relative error of DMD temperature (u) at t_final: "
<< t_final << " is " << tot_diff_norm_u / tot_true_solution_u_norm << std::endl;
printf("Elapsed time for predicting DMD: %e second\n",
dmd_prediction_timer.RealTime());
}
}
// 19. Calculate the relative error as commanded by the greedy algorithm.
if (offline)
{
if (myid == 0) std::cout << "The relative error is: " << rel_diff <<
std::endl;
greedy_sampler->setPointRelativeError(rel_diff);
}
// 20. Or calculate the error indicator as commanded by the greedy algorithm.
else if (calc_err_indicator)
{
if (myid == 0) std::cout << "The error indicator is: " << rel_diff << std::endl;
greedy_sampler->setPointErrorIndicator(rel_diff, 1);
}
if (!de && !online && myid == 0)
{
printf("Elapsed time for solving FOM: %e second\n", fom_timer.RealTime());
}
// 21. Free the used memory.
delete ode_solver;
delete pmesh;
return rel_diff;
}
class RelativeDifferenceCostFunction : public CAROM::IOptimizable
{
public:
RelativeDifferenceCostFunction(unsigned int dims) :
m_dim(dims)
{
}
double EvaluateCost(std::vector<double> & inputs) const override
{
radius = inputs[0];
alpha = inputs[1];
cx = inputs[2];
cy = inputs[3];
return simulation();
}
unsigned int NumberOfParameters() const override
{
return m_dim;
}
std::vector<Constraints> GetConstraints() const override
{
std::fstream fin("parameters.txt", std::ios_base::in);
double curr_param;
bool first_line = true;
double min_radius = 0.0;
double max_radius = 0.0;
double min_alpha = 0.0;
double max_alpha = 0.0;
double min_cx = 0.0;
double max_cx = 0.0;
double min_cy = 0.0;
double max_cy = 0.0;
while (fin >> curr_param)
{
double curr_radius = curr_param;
fin >> curr_param;
double curr_alpha = curr_param;
fin >> curr_param;
double curr_cx = curr_param;
fin >> curr_param;
double curr_cy = curr_param;
if (first_line)
{
min_radius = curr_radius;
max_radius = curr_radius;
min_alpha = curr_alpha;
max_alpha = curr_alpha;
min_cx = curr_cx;
max_cx = curr_cx;
min_cy = curr_cy;
max_cy = curr_cy;
first_line = false;
}
else
{
min_radius = min(curr_radius, min_radius);
max_radius = max(curr_radius, max_radius);
min_alpha = min(curr_alpha, min_alpha);
max_alpha = max(curr_alpha, max_alpha);
min_cx = min(curr_cx, min_cx);
max_cx = max(curr_cx, max_cx);
min_cy = min(curr_cy, min_cy);
max_cy = max(curr_cy, max_cy);
}
}
fin.close();
if (de_min_radius != -DBL_MAX) min_radius = de_min_radius;
if (de_min_alpha != -DBL_MAX) min_alpha = de_min_alpha;
if (de_min_cx != -DBL_MAX) min_cx = de_min_cx;
if (de_min_cy != -DBL_MAX) min_cy = de_min_cy;
if (de_max_radius != DBL_MAX) max_radius = de_max_radius;
if (de_max_alpha != DBL_MAX) max_alpha = de_max_alpha;
if (de_max_cx != DBL_MAX) max_cx = de_max_cx;
if (de_max_cy != DBL_MAX) max_cy = de_max_cy;
MFEM_VERIFY(min_radius <= max_radius, "Radius DE range is invalid.");
MFEM_VERIFY(min_alpha <= max_alpha, "Alpha DE range is invalid.");
MFEM_VERIFY(min_cx <= max_cx, "cx DE range is invalid.");
MFEM_VERIFY(min_cy <= max_cy, "cy DE range is invalid.");
if (myid == 0) cout << "DE radius range is: " << min_radius << " to " <<
max_radius << endl;
if (myid == 0) cout << "DE alpha range is: " << min_alpha << " to " << max_alpha
<< endl;
if (myid == 0) cout << "DE cx range is: " << min_cx << " to " << max_cx << endl;
if (myid == 0) cout << "DE cy range is: " << min_cy << " to " << max_cy << endl;
std::vector<Constraints> constr(NumberOfParameters());
constr[0] = Constraints(min_radius, max_radius, true);
constr[1] = Constraints(min_alpha, max_alpha, true);
constr[2] = Constraints(min_cx, max_cx, true);
constr[3] = Constraints(min_cy, max_cy, true);
return constr;
}
private:
unsigned int m_dim;
};
int main(int argc, char *argv[])
{
// 1. Initialize MPI.
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
cout.precision(precision);
// 2. Parse command-line options.
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&ser_ref_levels, "-rs", "--refine-serial",
"Number of times to refine the mesh uniformly in serial.");
args.AddOption(&par_ref_levels, "-rp", "--refine-parallel",
"Number of times to refine the mesh uniformly in parallel.");
args.AddOption(&order, "-o", "--order",
"Order (degree) of the finite elements.");
args.AddOption(&ode_solver_type, "-s", "--ode-solver",
"ODE solver: 1 - Backward Euler, 2 - SDIRK2, 3 - SDIRK3,\n\t"
"\t 11 - Forward Euler, 12 - RK2, 13 - RK3 SSP, 14 - RK4.");
args.AddOption(&t_final, "-tf", "--t-final",
"Final time; start time is 0.");
args.AddOption(&dt, "-dt", "--time-step",
"Time step.");
args.AddOption(&alpha, "-a", "--alpha",
"Alpha coefficient.");
args.AddOption(&kappa, "-k", "--kappa",
"Kappa coefficient offset.");
args.AddOption(&radius, "-r", "--radius",
"Radius of the interface of initial temperature.");
args.AddOption(&cx, "-cx", "--cx",
"Center offset in the x direction.");
args.AddOption(&cy, "-cy", "--cy",
"Center offset in the y direction.");
args.AddOption(&de_min_radius, "-de_min_r", "--de_min_radius",
"DE min radius.");
args.AddOption(&de_max_radius, "-de_max_r", "--de_max_radius",
"DE max radius.");
args.AddOption(&de_min_alpha, "-de_min_a", "--de_min_alpha",
"DE min alpha.");
args.AddOption(&de_max_alpha, "-de_max_a", "--de_max_alpha",
"DE max alpha.");
args.AddOption(&de_min_cx, "-de_min_cx", "--de_min_cx",
"DE min cx.");
args.AddOption(&de_max_cx, "-de_max_cx", "--de_max_cx",
"DE max cx.");
args.AddOption(&de_min_cy, "-de_min_cy", "--de_min_cy",
"DE min cy.");
args.AddOption(&de_max_cy, "-de_max_cy", "--de_max_cy",
"DE max cy.");
args.AddOption(&de_F, "-de_f", "--de_f",
"DE F.");
args.AddOption(&de_CR, "-de_cr", "--de_cr",
"DE CR.");
args.AddOption(&de_PS, "-de_ps", "--de_ps",
"DE Population size.");
args.AddOption(&de_min_iter, "-de_min_iter", "--de_min_iter",
"DE Minimum number of iterations.");
args.AddOption(&de_max_iter, "-de_max_iter", "--de_max_iter",
"DE Maximum number of iterations.");
args.AddOption(&de_ct, "-de_ct", "--de_ct",
"DE Cost threshold.");
args.AddOption(&greedy_param_space_radius_min, "-greedy-param-radius-min",
"--greedy-param-radius-min",
"The minimum radius value of the parameter point space.");
args.AddOption(&greedy_param_space_radius_max, "-greedy-param-radius-max",
"--greedy-param-radius-max",
"The maximum radius value of the parameter point space.");
args.AddOption(&greedy_param_space_alpha_min, "-greedy-param-alpha-min",
"--greedy-param-alpha-min",