-
Notifications
You must be signed in to change notification settings - Fork 292
Expand file tree
/
Copy pathmmg_process.cpp
More file actions
executable file
·1558 lines (1268 loc) · 68.7 KB
/
Copy pathmmg_process.cpp
File metadata and controls
executable file
·1558 lines (1268 loc) · 68.7 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
// KRATOS __ __ _____ ____ _ _ ___ _ _ ____
// | \/ | ____/ ___|| | | |_ _| \ | |/ ___|
// | |\/| | _| \___ \| |_| || || \| | | _
// | | | | |___ ___) | _ || || |\ | |_| |
// |_| |_|_____|____/|_| |_|___|_| \_|\____| APPLICATION
//
// License: BSD License
// license: MeshingApplication/license.txt
//
// Main authors: Vicente Mataix Ferrandiz
//
// System includes
#include <set>
// External includes
// Project includes
#include "custom_processes/mmg/mmg_process.h"
#include "containers/model.h"
// We indlude the internal variable interpolation process
#include "custom_processes/nodal_values_interpolation_process.h"
#include "custom_processes/internal_variables_interpolation_process.h"
// Include the point locator
#include "utilities/binbased_fast_point_locator.h"
#include "utilities/parallel_utilities.h"
// Include the spatial containers needed for search
#include "spatial_containers/spatial_containers.h" // kd-tree
#include "includes/gid_io.h"
#include "includes/model_part_io.h"
/* The mappers includes */
#include "spaces/ublas_space.h"
#include "mappers/mapper_flags.h"
#include "factories/mapper_factory.h"
// NOTE: The following contains the license of the MMG library
/* =============================================================================
** Copyright (c) Bx INP/Inria/UBordeaux/UPMC, 2004- .
**
** mmg is free software: you can redistribute it and/or modify it
** under the terms of the GNU Lesser General Public License as published
** by the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** mmg is distributed in the hope that it will be useful, but WITHOUT
** ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
** FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
** License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License and of the GNU General Public License along with mmg (in
** files COPYING.LESSER and COPYING). If not, see
** <http://www.gnu.org/licenses/>. Please read their terms carefully and
** use this copy of the mmg distribution only if you accept them.
** =============================================================================
*/
namespace Kratos
{
#define DEFINE_MAPPER_FACTORY_SERIAL \
using SparseSpace = UblasSpace<double, boost::numeric::ublas::compressed_matrix<double>, boost::numeric::ublas::vector<double>>; \
using DenseSpace = UblasSpace<double, DenseMatrix<double>, DenseVector<double>>; \
using MapperFactoryType = MapperFactory<SparseSpace, DenseSpace>;
/************************************* CONSTRUCTOR *********************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
MmgProcess<TMMGLibrary>::MmgProcess(
ModelPart& rThisModelPart,
Parameters ThisParameters
):mrThisModelPart(rThisModelPart),
mThisParameters(ThisParameters)
{
const Parameters default_parameters = GetDefaultParameters();
mThisParameters.RecursivelyValidateAndAssignDefaults(default_parameters);
mFilename = mThisParameters["filename"].GetString();
mEchoLevel = mThisParameters["echo_level"].GetInt();
// The framework type
mFramework = ConvertFramework(mThisParameters["framework"].GetString());
// The discretization type
mDiscretization = ConvertDiscretization(mThisParameters["discretization_type"].GetString());
if (TMMGLibrary != MMGLibrary::MMGS) {
if (mDiscretization == DiscretizationOption::LAGRANGIAN && mFramework == FrameworkEulerLagrange::EULERIAN) {
mFramework = FrameworkEulerLagrange::LAGRANGIAN;
KRATOS_WARNING("MmgProcess") << "Inconsistent discretization and framework. Assigning LAGRANGIAN framework" << std::endl;
}
} else if (mDiscretization == DiscretizationOption::LAGRANGIAN) {
mDiscretization = DiscretizationOption::STANDARD;
KRATOS_WARNING("MmgProcess") << "Surface meshes not compatible with Lagrangian motion. Reassign to standard discretization" << std::endl;
}
// Checking isosurface flag
if (mDiscretization == DiscretizationOption::ISOSURFACE) {
mRemoveRegions = mThisParameters["isosurface_parameters"]["remove_internal_regions"].GetBool();
} else {
mRemoveRegions = false;
}
mpRefElement.clear();
mpRefCondition.clear();
}
template<MMGLibrary TMMGLibrary>
MmgProcess<TMMGLibrary>::MmgProcess(
ModelPart* pThisModelPart
) : mrThisModelPart(*pThisModelPart)
{
}
/*************************************** EXECUTE ***********************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgProcess<TMMGLibrary>::Execute()
{
KRATOS_TRY;
// We execute all the necessary steps
ExecuteInitialize();
ExecuteInitializeSolutionStep();
ExecuteFinalize();
KRATOS_CATCH("");
}
/***********************************************************************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgProcess<TMMGLibrary>::ExecuteInitialize()
{
KRATOS_TRY;
/* We print one important information message */
KRATOS_INFO_IF("MmgProcess", mEchoLevel > 0) << "We clone the first condition and element of each type (we will assume that each sub model part has just one kind of condition, in my opinion it is quite recommended to create more than one sub model part if you have more than one element or condition)" << std::endl;
// The conditions are re-created in the process
if( mRemoveRegions ) {
// Mark conditions from submodelparts
MarkConditionsSubmodelParts(mrThisModelPart);
// Remove not marked
auto& r_conditions_array = mrThisModelPart.Conditions();
block_for_each(r_conditions_array,
[&](Condition& rCondition) {
if (rCondition.IsNot(MARKER)) {
rCondition.Set(TO_ERASE, true);
}
});
mrThisModelPart.RemoveConditionsFromAllLevels(TO_ERASE); // In theory with RemoveConditions is enough
// Setting to erare on the auxiliar model part
if (mrThisModelPart.HasSubModelPart("AUXILIAR_ISOSURFACE_MODEL_PART")) {
VariableUtils().SetFlag(TO_ERASE, true, mrThisModelPart.GetSubModelPart("AUXILIAR_ISOSURFACE_MODEL_PART").Conditions());
}
// Reset flag
VariableUtils().ResetFlag(MARKER, mrThisModelPart.Conditions());
// Passing that info to logger
KRATOS_INFO("MmgProcess") << "Conditions were cleared" << std::endl;
}
/* We restart the MMG mesh and solution */
mMmgUtilities.SetEchoLevel(mEchoLevel);
mMmgUtilities.SetDiscretization(mDiscretization);
mMmgUtilities.SetRemoveRegions(mRemoveRegions);
mMmgUtilities.InitMesh();
KRATOS_CATCH("");
}
/***********************************************************************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgProcess<TMMGLibrary>::ExecuteBeforeSolutionLoop()
{
KRATOS_TRY;
KRATOS_CATCH("");
}
/***********************************************************************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgProcess<TMMGLibrary>::ExecuteInitializeSolutionStep()
{
KRATOS_TRY;
const bool safe_to_file = mThisParameters["save_external_files"].GetBool();
const bool optimization_mode = mThisParameters["advanced_parameters"]["mesh_optimization_only"].GetBool();
/* We print the original model part */
KRATOS_INFO_IF("", mEchoLevel > 0) <<
"//---------------------------------------------------//" << std::endl <<
"//--------------- BEFORE REMESHING ---------------//" << std::endl <<
"//---------------------------------------------------//" << std::endl <<
std::endl << mrThisModelPart << std::endl;
// We initialize the mesh and solution data
InitializeMeshData();
mMmgUtilities.SetMeshOptimizationModeParameter(optimization_mode);
// We retrieve the data form the Kratos model part to fill sol
if (mDiscretization == DiscretizationOption::ISOSURFACE) {
InitializeSolDataDistance();
}
// We load the metric field, unless optimization mode is enabled.
if (!optimization_mode) {
InitializeSolDataMetric();
}
// We set the displacement vector
if (mDiscretization == DiscretizationOption::LAGRANGIAN) {
InitializeDisplacementData();
}
// Check if the number of given entities match with mesh size
mMmgUtilities.CheckMeshData();
// Save to file
if (safe_to_file) SaveSolutionToFile(false);
// We execute the remeshing
ExecuteRemeshing();
/* We print the resulting model part */
KRATOS_INFO_IF("", mEchoLevel > 0) <<
"//---------------------------------------------------//" << std::endl <<
"//--------------- AFTER REMESHING ---------------//" << std::endl <<
"//---------------------------------------------------//" << std::endl <<
std::endl << mrThisModelPart << std::endl;
KRATOS_CATCH("");
}
/***********************************************************************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgProcess<TMMGLibrary>::ExecuteFinalizeSolutionStep()
{
KRATOS_TRY;
KRATOS_CATCH("");
}
/***********************************************************************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgProcess<TMMGLibrary>::ExecuteBeforeOutputStep()
{
KRATOS_TRY;
KRATOS_CATCH("");
}
/***********************************************************************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgProcess<TMMGLibrary>::ExecuteAfterOutputStep()
{
KRATOS_TRY;
KRATOS_CATCH("");
}
/***********************************************************************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgProcess<TMMGLibrary>::ExecuteFinalize()
{
KRATOS_TRY;
/* Save to file */
const bool save_to_file = mThisParameters["save_external_files"].GetBool();
if (GetMmgVersion() == "5.5" && mDiscretization == DiscretizationOption::ISOSURFACE && save_to_file) {
InitializeSolDataDistance();
SaveSolutionToFile(true);
}
// We release the memory
FreeMemory();
// Nodes not belonging to an element are removed
if(mRemoveRegions) {
CleanSuperfluousNodes();
CleanSuperfluousConditions();
}
// Save the mesh in an .mdpa format
const bool save_mdpa_file = mThisParameters["save_mdpa_file"].GetBool();
if(save_mdpa_file) OutputMdpa();
KRATOS_CATCH("");
}
/************************************* OPERATOR() **********************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgProcess<TMMGLibrary>::operator()()
{
Execute();
}
/***********************************************************************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgProcess<TMMGLibrary>::InitializeMeshData()
{
KRATOS_TRY;
// We create a list of submodelparts to later reassign flags after remesh
if (mThisParameters["preserve_flags"].GetBool()) {
mMmgUtilities.CreateAuxiliarSubModelPartForFlags(mrThisModelPart);
}
// The auxiliar color maps
ColorsMapType aux_ref_cond, aux_ref_elem;
// We initialize the mesh data with the given modelpart
const bool collapse_prisms_elements = mThisParameters["collapse_prisms_elements"].GetBool();
if (collapse_prisms_elements) {
CollapsePrismsToTriangles();
}
// Move mesh before remesh
if (mDiscretization == DiscretizationOption::LAGRANGIAN) { // TODO: Revert when dependency problem solved
NodesArrayType& r_nodes_array = mrThisModelPart.Nodes();
block_for_each(r_nodes_array,
[&](Node& rNode) {
noalias(rNode.GetInitialPosition().Coordinates()) = rNode.Coordinates();
});
}
// Actually generate mesh data
mMmgUtilities.GenerateMeshDataFromModelPart(mrThisModelPart, mColors, aux_ref_cond, aux_ref_elem, mFramework, collapse_prisms_elements);
// We copy the DOF from the first node (after we release, to avoid problem with previous conditions)
auto& r_nodes_array = mrThisModelPart.Nodes();
KRATOS_DEBUG_ERROR_IF(r_nodes_array.size() == 0) << "The model part considered has not nodes\n" << mrThisModelPart << std::endl;
const auto& r_old_dofs = r_nodes_array.begin()->GetDofs();
// Clear before assign new ones
mDofs.clear();
// Assign dofs
for (auto it_dof = r_old_dofs.begin(); it_dof != r_old_dofs.end(); ++it_dof)
mDofs.push_back(Kratos::make_unique<Node::DofType>(**it_dof));
for (auto it_dof = mDofs.begin(); it_dof != mDofs.end(); ++it_dof)
(**it_dof).FreeDof();
mrThisModelPart.Nodes().Unique();
mrThisModelPart.Conditions().Unique();
mrThisModelPart.Elements().Unique();
// Generate the maps of reference
mMmgUtilities.GenerateReferenceMaps(mrThisModelPart, aux_ref_cond, aux_ref_elem, mpRefCondition, mpRefElement);
KRATOS_CATCH("");
}
/***********************************************************************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgProcess<TMMGLibrary>::InitializeSolDataMetric()
{
KRATOS_TRY;
if (mDiscretization == DiscretizationOption::ISOSURFACE) {
// This will only run for version >= 5.5
if (mThisParameters["isosurface_parameters"]["use_metric_field"].GetBool())
mMmgUtilities.GenerateIsosurfaceMetricDataFromModelPart(mrThisModelPart);
} else {
// We initialize the solution data with the given modelpart
mMmgUtilities.GenerateSolDataFromModelPart(mrThisModelPart);
}
KRATOS_CATCH("");
}
/***********************************************************************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgProcess<TMMGLibrary>::InitializeSolDataDistance()
{
KRATOS_TRY;
////////* SOLUTION FILE for ISOSURFACE*////////
// Iterate in the nodes
auto& r_nodes_array = mrThisModelPart.Nodes();
const auto it_node_begin = r_nodes_array.begin();
// Set size of the solution
mMmgUtilities.SetSolSizeScalar(r_nodes_array.size() );
// GEtting variable for scalar filed
const std::string& r_isosurface_variable_name = mThisParameters["isosurface_parameters"]["isosurface_variable"].GetString();
const bool nonhistorical_variable = mThisParameters["isosurface_parameters"]["nonhistorical_variable"].GetBool();
const bool invert_value = mThisParameters["isosurface_parameters"]["invert_value"].GetBool();
const Variable<double>& r_scalar_variable = KratosComponents<Variable<double>>::Get(r_isosurface_variable_name);
// Auxiliary value
const double sign = invert_value ? -1.0 : 1.0;
double isosurface_value = 0.0;
// We iterate over the nodes
auto& r_mmg_utilities = mMmgUtilities;
IndexPartition<std::size_t>(r_nodes_array.size()).for_each(isosurface_value,
[&it_node_begin,&r_mmg_utilities,&r_scalar_variable,&r_isosurface_variable_name,&nonhistorical_variable,&sign](std::size_t i, double& isosurface_value) {
auto it_node = it_node_begin + i;
const bool old_entity = it_node->IsDefined(OLD_ENTITY) ? it_node->Is(OLD_ENTITY) : false;
if (!old_entity) {
if (nonhistorical_variable) {
KRATOS_DEBUG_ERROR_IF_NOT(it_node->Has(r_scalar_variable)) << r_isosurface_variable_name << " field not found as a non-historical variable " << std::endl;
// We get the isosurface value (non-historical variable)
isosurface_value = it_node->GetValue( r_scalar_variable );
} else {
KRATOS_DEBUG_ERROR_IF_NOT(it_node->SolutionStepsDataHas(r_scalar_variable)) << r_isosurface_variable_name << " field not found as a historical variable " << std::endl;
// We get the isosurface value (historical variable)
isosurface_value = it_node->FastGetSolutionStepValue( r_scalar_variable );
}
// We set the isosurface variable
r_mmg_utilities.SetMetricScalar(sign * isosurface_value, i + 1);
}
});
KRATOS_CATCH("");
}
/***********************************************************************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgProcess<TMMGLibrary>::InitializeDisplacementData()
{
KRATOS_TRY;
// We initialize the displacement data with the given modelpart
mMmgUtilities.GenerateDisplacementDataFromModelPart(mrThisModelPart);
KRATOS_CATCH("");
}
/***********************************************************************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgProcess<TMMGLibrary>::ExecuteRemeshing()
{
KRATOS_TRY;
// Getting the parameters
const bool save_to_file = mThisParameters["save_external_files"].GetBool();
// We initialize some values
const SizeType step_data_size = mrThisModelPart.GetNodalSolutionStepDataSize();
const SizeType buffer_size = mrThisModelPart.NodesBegin()->GetBufferSize();
mThisParameters["step_data_size"].SetInt(step_data_size);
mThisParameters["buffer_size"].SetInt(buffer_size);
KRATOS_INFO_IF("MmgProcess", mEchoLevel > 0) << "Step data size: " << step_data_size << " Buffer size: " << buffer_size << std::endl;
////////* MMG LIBRARY CALL *////////
KRATOS_INFO_IF("MmgProcess", mEchoLevel > 0) << "////////* MMG LIBRARY CALL *////////" << std::endl;
////////* EMPTY AND BACKUP THE MODEL PART *////////
Model& r_owner_model = mrThisModelPart.GetModel();
ModelPart& r_old_model_part = r_owner_model.CreateModelPart(mrThisModelPart.Name()+"_Old", mrThisModelPart.GetBufferSize());
const bool collapse_prisms_elements = mThisParameters["collapse_prisms_elements"].GetBool();
if (collapse_prisms_elements) {
ModelPart& r_auxiliary_model_part = mrThisModelPart.GetSubModelPart("AUXILIAR_COLLAPSED_PRISMS");
ModelPart& r_old_auxiliar_model_part = r_old_model_part.CreateSubModelPart("AUXILIAR_COLLAPSED_PRISMS");
r_old_auxiliar_model_part.AddNodes( r_auxiliary_model_part.NodesBegin(), r_auxiliary_model_part.NodesEnd() );
r_old_auxiliar_model_part.AddElements( r_auxiliary_model_part.ElementsBegin(), r_auxiliary_model_part.ElementsEnd() );
}
// Apply local entity parameters if there are any
if (mThisParameters["advanced_parameters"]["local_entity_parameters_list"].size() > 0) {
ApplyLocalParameters();
}
// Calling the library functions
if (mDiscretization == DiscretizationOption::ISOSURFACE) {
mMmgUtilities.MMGLibCallIsoSurface(mThisParameters);
} else {
mMmgUtilities.MMGLibCallMetric(mThisParameters);
}
/* Save to file */
if (save_to_file) {
if (GetMmgVersion() == "5.5") {
if (mDiscretization != DiscretizationOption::ISOSURFACE) {
SaveSolutionToFile(true);
}
} else {
SaveSolutionToFile(true);
}
}
// Some information
MMGMeshInfo<TMMGLibrary> mmg_mesh_info;
mMmgUtilities.PrintAndGetMmgMeshInfo(mmg_mesh_info);
// We clear the OLD_ENTITY flag
if (collapse_prisms_elements) {
for(auto& r_elem : mrThisModelPart.Elements()){
// We get the element geometry
const GeometryType& r_geometry = r_elem.GetGeometry();
if (r_geometry.GetGeometryType() == GeometryData::KratosGeometryType::Kratos_Prism3D6) {
r_elem.Reset(OLD_ENTITY);
for (auto& r_node : r_geometry)
r_node.Reset(OLD_ENTITY);
}
}
}
// First we empty the model part
auto& r_nodes_array = mrThisModelPart.Nodes();
block_for_each(r_nodes_array,
[&](Node& rNode) {
const bool old_entity = rNode.IsDefined(OLD_ENTITY) ? rNode.Is(OLD_ENTITY) : false;
if (!old_entity) {
rNode.Set(TO_ERASE, true);
}
});
r_old_model_part.AddNodes( mrThisModelPart.NodesBegin(), mrThisModelPart.NodesEnd() );
mrThisModelPart.RemoveNodesFromAllLevels(TO_ERASE);
auto& r_conditions_array = mrThisModelPart.Conditions();
block_for_each(r_conditions_array,
[&](Condition& rCondition) {
const bool old_entity = rCondition.IsDefined(OLD_ENTITY) ? rCondition.Is(OLD_ENTITY) : false;
if (!old_entity) {
rCondition.Set(TO_ERASE, true);
}
});
r_old_model_part.AddConditions( mrThisModelPart.ConditionsBegin(), mrThisModelPart.ConditionsEnd() );
mrThisModelPart.RemoveConditionsFromAllLevels(TO_ERASE);
auto& r_elements_array = mrThisModelPart.Elements();
block_for_each(r_elements_array,
[&](Element& rElement) {
const bool old_entity = rElement.IsDefined(OLD_ENTITY) ? rElement.Is(OLD_ENTITY) : false;
if (!old_entity) {
rElement.Set(TO_ERASE, true);
}
});
r_old_model_part.AddElements( mrThisModelPart.ElementsBegin(), mrThisModelPart.ElementsEnd() );
mrThisModelPart.RemoveElementsFromAllLevels(TO_ERASE);
/* Before create new mesh we reorder nodes, conditions and elements: */
mMmgUtilities.ReorderAllIds(mrThisModelPart);
// Writing the new mesh data on the model part
mMmgUtilities.WriteMeshDataToModelPart(mrThisModelPart, mColors, mDofs, mmg_mesh_info, mpRefCondition, mpRefElement);
// In case of prism collapse we extrapolate now (and later extrude)
if (collapse_prisms_elements) {
if (mThisParameters["interpolate_nodal_values"].GetBool()) {
/* We interpolate all the values */
ModelPart& r_old_auxiliar_model_part = r_old_model_part.GetSubModelPart("AUXILIAR_COLLAPSED_PRISMS");
ModelPart& r_auxiliary_model_part = mrThisModelPart.GetSubModelPart("AUXILIAR_COLLAPSED_PRISMS");
// Define mapper factory
DEFINE_MAPPER_FACTORY_SERIAL
if (MapperFactoryType::HasMapper("nearest_element") && mThisParameters["use_mapper_if_available"].GetBool()) {
KRATOS_INFO_IF("MmgProcess", mEchoLevel > 0) << "Using MappingApplication to interpolate values" << std::endl;
Parameters mapping_parameters = mThisParameters["mapping_parameters"];
auto p_mapper = MapperFactoryType::CreateMapper(r_old_auxiliar_model_part, r_auxiliary_model_part, mapping_parameters);
Kratos::Flags mapper_flags = Kratos::Flags();
const auto p_variables = r_old_auxiliar_model_part.Nodes().begin()->pGetVariablesList();
for(VariablesList::const_iterator it_variable = p_variables->begin(); it_variable != p_variables->end(); ++it_variable) {
const auto& r_variable_name = it_variable->Name();
if (KratosComponents<Variable<double>>::Has(r_variable_name)) {
const Variable<double>& r_variable = KratosComponents<Variable<double>>::Get(r_variable_name);
p_mapper->Map(r_variable, r_variable, mapper_flags);
} else if (KratosComponents<Variable<array_1d<double, 3>>>::Has(r_variable_name)) {
const Variable<array_1d<double, 3>>& r_variable = KratosComponents<Variable<array_1d<double, 3>>>::Get(r_variable_name);
p_mapper->Map(r_variable, r_variable, mapper_flags);
// } else if (KratosComponents<Variable<Vector>>::Has(r_variable_name)) { // TODO: Add to mapper
// const Variable<Vector>& r_variable = KratosComponents<Variable<Vector>>::Get(r_variable_name);
// p_mapper->Map(r_variable, r_variable, mapper_flags);
// } else if (KratosComponents<Variable<Matrix>>::Has(r_variable_name)) { // TODO: Add to mapper
// const Variable<Matrix>& r_variable = KratosComponents<Variable<Matrix>>::Get(r_variable_name);
// p_mapper->Map(r_variable, r_variable, mapper_flags);
} else {
KRATOS_WARNING("MmgProcess") << r_variable_name << " is a not compatible variable with Mapper class" << std::endl;
}
}
// Interpolate non-historical variables
if (mThisParameters["interpolate_non_historical"].GetBool()) {
mapper_flags.Set(MapperFlags::FROM_NON_HISTORICAL);
mapper_flags.Set(MapperFlags::TO_NON_HISTORICAL);
std::unordered_set<std::string> non_historical_variables;
NodalInterpolationFunctions::GetListNonHistoricalVariables(r_old_auxiliar_model_part, non_historical_variables);
for (auto& r_variable_name : non_historical_variables) {
if (KratosComponents<Variable<double>>::Has(r_variable_name)) {
const Variable<double>& r_variable = KratosComponents<Variable<double>>::Get(r_variable_name);
p_mapper->Map(r_variable, r_variable, mapper_flags);
} else if (KratosComponents<Variable<array_1d<double, 3>>>::Has(r_variable_name)) {
const Variable<array_1d<double, 3>>& r_variable = KratosComponents<Variable<array_1d<double, 3>>>::Get(r_variable_name);
p_mapper->Map(r_variable, r_variable, mapper_flags);
// } else if (KratosComponents<Variable<Vector>>::Has(r_variable_name)) { // TODO: Add to mapper
// const Variable<Vector>& r_variable = KratosComponents<Variable<Vector>>::Get(r_variable_name);
// p_mapper->Map(r_variable, r_variable, mapper_flags);
// } else if (KratosComponents<Variable<Matrix>>::Has(r_variable_name)) { // TODO: Add to mapper
// const Variable<Matrix>& r_variable = KratosComponents<Variable<Matrix>>::Get(r_variable_name);
// p_mapper->Map(r_variable, r_variable, mapper_flags);
} else {
KRATOS_WARNING("MmgProcess") << r_variable_name << " is a not compatible variable with Mapper class" << std::endl;
}
}
}
} else {
KRATOS_INFO_IF("MmgProcess", mEchoLevel > 0) << "Using NodalValuesInterpolationProcess to interpolate values" << std::endl;
Parameters interpolate_parameters = Parameters(R"({})" );
interpolate_parameters.AddValue("echo_level", mThisParameters["echo_level"]);
interpolate_parameters.AddValue("framework", mThisParameters["framework"]);
interpolate_parameters.AddValue("max_number_of_searchs", mThisParameters["max_number_of_searchs"]);
interpolate_parameters.AddValue("step_data_size", mThisParameters["step_data_size"]);
interpolate_parameters.AddValue("buffer_size", mThisParameters["buffer_size"]);
interpolate_parameters.AddValue("interpolate_non_historical", mThisParameters["interpolate_non_historical"]);
interpolate_parameters.AddValue("extrapolate_contour_values", mThisParameters["extrapolate_contour_values"]);
interpolate_parameters.AddValue("surface_elements", mThisParameters["surface_elements"]);
interpolate_parameters.AddValue("search_parameters", mThisParameters["search_parameters"]);
interpolate_parameters["surface_elements"].SetBool(true);
NodalValuesInterpolationProcess<Dimension> interpolate_nodal_values_process(r_old_auxiliar_model_part, r_auxiliary_model_part, interpolate_parameters);
interpolate_nodal_values_process.Execute();
}
}
// Reorder before extrude
mMmgUtilities.ReorderAllIds(mrThisModelPart);
/* Now we can extrude */
ExtrudeTrianglestoPrisms(r_old_model_part);
// Remove the auxiliar model part
mrThisModelPart.RemoveSubModelPart("AUXILIAR_COLLAPSED_PRISMS");
}
/* After that we reorder nodes, conditions and elements: */
mMmgUtilities.ReorderAllIds(mrThisModelPart);
/* We assign flags and clear the auxiliar model parts created to reassing the flags */
if (mThisParameters["preserve_flags"].GetBool()) {
mMmgUtilities.AssignAndClearAuxiliarSubModelPartForFlags(mrThisModelPart);
}
/* Unmoving the original mesh to be able to interpolate */
if (mFramework == FrameworkEulerLagrange::LAGRANGIAN) {
NodesArrayType& r_old_nodes_array = r_old_model_part.Nodes();
block_for_each(r_old_nodes_array,
[&](Node& rNode) {
noalias(rNode.Coordinates()) = rNode.GetInitialPosition().Coordinates();
});
}
// We create an auxiliar mesh for debugging purposes
if (mThisParameters["debug_result_mesh"].GetBool()) {
CreateDebugPrePostRemeshOutput(r_old_model_part);
}
if (mThisParameters["interpolate_nodal_values"].GetBool()) {
/* We interpolate all the values */
// Define mapper factory
DEFINE_MAPPER_FACTORY_SERIAL
if (MapperFactoryType::HasMapper("nearest_element") && mThisParameters["use_mapper_if_available"].GetBool()) {
KRATOS_INFO_IF("MmgProcess", mEchoLevel > 0) << "Using MappingApplication to interpolate values" << std::endl;
Parameters mapping_parameters = mThisParameters["mapping_parameters"];
auto p_mapper = MapperFactoryType::CreateMapper(r_old_model_part, mrThisModelPart, mapping_parameters);
Kratos::Flags mapper_flags = Kratos::Flags();
const auto p_variables = r_old_model_part.Nodes().begin()->pGetVariablesList();
for(VariablesList::const_iterator it_variable = p_variables->begin(); it_variable != p_variables->end(); ++it_variable) {
const auto& r_variable_name = it_variable->Name();
if (KratosComponents<Variable<double>>::Has(r_variable_name)) {
const Variable<double>& r_variable = KratosComponents<Variable<double>>::Get(r_variable_name);
p_mapper->Map(r_variable, r_variable, mapper_flags);
} else if (KratosComponents<Variable<array_1d<double, 3>>>::Has(r_variable_name)) {
const Variable<array_1d<double, 3>>& r_variable = KratosComponents<Variable<array_1d<double, 3>>>::Get(r_variable_name);
p_mapper->Map(r_variable, r_variable, mapper_flags);
// } else if (KratosComponents<Variable<Vector>>::Has(r_variable_name)) { // TODO: Add to mapper
// const Variable<Vector>& r_variable = KratosComponents<Variable<Vector>>::Get(r_variable_name);
// p_mapper->Map(r_variable, r_variable, mapper_flags);
// } else if (KratosComponents<Variable<Matrix>>::Has(r_variable_name)) { // TODO: Add to mapper
// const Variable<Matrix>& r_variable = KratosComponents<Variable<Matrix>>::Get(r_variable_name);
// p_mapper->Map(r_variable, r_variable, mapper_flags);
} else {
KRATOS_WARNING("MmgProcess") << r_variable_name << " is a not compatible variable with Mapper class" << std::endl;
}
}
// Interpolate non-historical variables
if (mThisParameters["interpolate_non_historical"].GetBool()) {
mapper_flags.Set(MapperFlags::FROM_NON_HISTORICAL);
mapper_flags.Set(MapperFlags::TO_NON_HISTORICAL);
std::unordered_set<std::string> non_historical_variables;
NodalInterpolationFunctions::GetListNonHistoricalVariables(r_old_model_part, non_historical_variables);
for (auto& r_variable_name : non_historical_variables) {
if (KratosComponents<Variable<double>>::Has(r_variable_name)) {
const Variable<double>& r_variable = KratosComponents<Variable<double>>::Get(r_variable_name);
p_mapper->Map(r_variable, r_variable, mapper_flags);
} else if (KratosComponents<Variable<array_1d<double, 3>>>::Has(r_variable_name)) {
const Variable<array_1d<double, 3>>& r_variable = KratosComponents<Variable<array_1d<double, 3>>>::Get(r_variable_name);
p_mapper->Map(r_variable, r_variable, mapper_flags);
// } else if (KratosComponents<Variable<Vector>>::Has(r_variable_name)) { // TODO: Add to mapper
// const Variable<Vector>& r_variable = KratosComponents<Variable<Vector>>::Get(r_variable_name);
// p_mapper->Map(r_variable, r_variable, mapper_flags);
// } else if (KratosComponents<Variable<Matrix>>::Has(r_variable_name)) { // TODO: Add to mapper
// const Variable<Matrix>& r_variable = KratosComponents<Variable<Matrix>>::Get(r_variable_name);
// p_mapper->Map(r_variable, r_variable, mapper_flags);
} else {
KRATOS_WARNING("MmgProcess") << r_variable_name << " is a not compatible variable with Mapper class" << std::endl;
}
}
}
} else {
KRATOS_INFO_IF("MmgProcess", mEchoLevel > 0) << "Using NodalValuesInterpolationProcess to interpolate values" << std::endl;
Parameters interpolate_parameters = Parameters(R"({})" );
interpolate_parameters.AddValue("echo_level", mThisParameters["echo_level"]);
interpolate_parameters.AddValue("framework", mThisParameters["framework"]);
interpolate_parameters.AddValue("max_number_of_searchs", mThisParameters["max_number_of_searchs"]);
interpolate_parameters.AddValue("step_data_size", mThisParameters["step_data_size"]);
interpolate_parameters.AddValue("buffer_size", mThisParameters["buffer_size"]);
interpolate_parameters.AddValue("interpolate_non_historical", mThisParameters["interpolate_non_historical"]);
interpolate_parameters.AddValue("extrapolate_contour_values", mThisParameters["extrapolate_contour_values"]);
interpolate_parameters.AddValue("surface_elements", mThisParameters["surface_elements"]);
interpolate_parameters.AddValue("search_parameters", mThisParameters["search_parameters"]);
if constexpr (TMMGLibrary == MMGLibrary::MMGS) interpolate_parameters["surface_elements"].SetBool(!collapse_prisms_elements);
NodalValuesInterpolationProcess<Dimension> interpolate_nodal_values_process(r_old_model_part, mrThisModelPart, interpolate_parameters);
interpolate_nodal_values_process.Execute();
}
}
/* We initialize elements and conditions */
if (mThisParameters["initialize_entities"].GetBool()) {
InitializeElementsAndConditions();
}
/* We do some operations related with the Lagrangian framework */
if (mFramework == FrameworkEulerLagrange::LAGRANGIAN) {
r_nodes_array = mrThisModelPart.Nodes();
if (mDiscretization == DiscretizationOption::STANDARD) {
// If we remesh during non linear iteration we just move to the previous displacement, to the last displacement otherwise
const IndexType step = mThisParameters["remesh_at_non_linear_iteration"].GetBool() ? 1 : 0;
/* We move the mesh */
block_for_each(r_nodes_array,
[&step](Node& rNode) {
noalias(rNode.Coordinates()) = rNode.GetInitialPosition().Coordinates();
noalias(rNode.Coordinates()) += rNode.FastGetSolutionStepValue(DISPLACEMENT, step);
});
} else if (mDiscretization == DiscretizationOption::LAGRANGIAN) {
/* We reset the displacement (the API already moved the mesh) */
const SizeType buffer_size = mrThisModelPart.GetBufferSize();
const array_1d<double, 3> zero_vector = ZeroVector(3);
block_for_each(r_nodes_array,
[&zero_vector,&buffer_size](Node& rNode) {
for (IndexType i_buffer = 0; i_buffer < buffer_size; ++i_buffer) {
noalias(rNode.FastGetSolutionStepValue(DISPLACEMENT, i_buffer)) = zero_vector;
}
});
}
/* We interpolate the internal variables */
InternalVariablesInterpolationProcess internal_variables_interpolation = InternalVariablesInterpolationProcess(r_old_model_part, mrThisModelPart, mThisParameters["internal_variables_parameters"]);
internal_variables_interpolation.Execute();
}
// We set to zero the variables contained on the elements and conditions
if (r_old_model_part.Conditions().size() > 0)
SetToZeroEntityData(mrThisModelPart.Conditions(), r_old_model_part.Conditions());
if (r_old_model_part.Elements().size() > 0)
SetToZeroEntityData(mrThisModelPart.Elements(), r_old_model_part.Elements());
// Finally remove old model part
r_owner_model.DeleteModelPart(mrThisModelPart.Name()+"_Old");
/* We clean conditions with duplicated geometries (this is an error on fluid simulations) */
if (mFramework == FrameworkEulerLagrange::EULERIAN) {
ClearConditionsDuplicatedGeometries();
}
// Writing the new solution data (metric) on the model part
mMmgUtilities.WriteSolDataToModelPart(mrThisModelPart);
// We clear the OLD_ENTITY flag
VariableUtils().ResetFlag(OLD_ENTITY, mrThisModelPart.Nodes());
VariableUtils().ResetFlag(OLD_ENTITY, mrThisModelPart.Conditions());
VariableUtils().ResetFlag(OLD_ENTITY, mrThisModelPart.Elements());
KRATOS_CATCH("");
}
/***********************************************************************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgProcess<TMMGLibrary>::InitializeElementsAndConditions()
{
KRATOS_TRY;
const auto& r_process_info = mrThisModelPart.GetProcessInfo();
// Iterate over conditions
block_for_each(mrThisModelPart.Conditions(),
[&r_process_info](Condition& rCondition) {
rCondition.Initialize(r_process_info);
});
// Iterate over elements
block_for_each(mrThisModelPart.Elements(),
[&r_process_info](Element& rElement) {
rElement.Initialize(r_process_info);
});
KRATOS_CATCH("");
}
/***********************************************************************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgProcess<TMMGLibrary>::ApplyLocalParameters() {
// Find colors with a unique submodelpart (size == 1)
std::unordered_map<std::string, IndexType> string_to_color;
for (auto& r_color : mColors) {
if (r_color.second.size() == 1) {
string_to_color[r_color.second[0]] = r_color.first;
}
}
// Count number of parameters given by the user
const auto parameter_array = mThisParameters["advanced_parameters"]["local_entity_parameters_list"];
IndexType n_parameters = parameter_array.size();
for (auto& parameter_settings : parameter_array) {
n_parameters += parameter_settings["model_part_name_list"].size();
}
// Set the number of tags references on which you will impose local parameters
mMmgUtilities.SetNumberOfLocalParameters(n_parameters);
// For each local parameter, set the type of the entity on which the parameter will
// apply (triangle or tetra), the reference of these entities and the hmin, hmax and
// hausdorff values to apply
for (auto parameter_settings : parameter_array) {
for (auto model_part_name_object : parameter_settings["model_part_name_list"])
{
KRATOS_ERROR_IF_NOT(parameter_settings.Has("hmin")) << "hmin is missing in the local entity parameters list";
const double hmin = parameter_settings["hmin"].GetDouble();
KRATOS_ERROR_IF_NOT(parameter_settings.Has("hmax")) << "hmax is missing in the local entity parameters list";
const double hmax = parameter_settings["hmax"].GetDouble();
KRATOS_ERROR_IF_NOT(parameter_settings.Has("hausdorff_value")) << "hausdorff is missing in the local entity parameters list";
const double hausdorff = parameter_settings["hausdorff_value"].GetDouble();
const auto model_part_name = model_part_name_object.GetString();
KRATOS_ERROR_IF(string_to_color.find(model_part_name) == string_to_color.end()) << "model_part_name " << model_part_name << " is not found in the colors list";
const IndexType color = string_to_color[model_part_name];
mMmgUtilities.SetLocalParameter(color, hmin, hmax, hausdorff);
}
}
}
/***********************************************************************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgProcess<TMMGLibrary>::SaveSolutionToFile(const bool PostOutput)
{
KRATOS_TRY;
/* GET RESULTS */
const int step = mrThisModelPart.GetProcessInfo()[STEP];
const std::string file_name = mFilename + "_step=" + std::to_string(step) + (PostOutput ? ".o" : "");
// Automatically save the mesh
mMmgUtilities.OutputMesh(file_name);
// Automatically save the solution
mMmgUtilities.OutputSol(file_name);
// The current displacement
if (mDiscretization == DiscretizationOption::LAGRANGIAN) {
mMmgUtilities.OutputDisplacement(file_name);
}
if (mThisParameters["save_colors_files"].GetBool()) {
// Output the reference files
mMmgUtilities.OutputReferenceEntitities(file_name, mpRefCondition, mpRefElement);
// Writing the colors to a JSON
AssignUniqueModelPartCollectionTagUtility::WriteTagsToJson(file_name, mColors);
}
KRATOS_CATCH("");
}
/***********************************************************************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgProcess<TMMGLibrary>::FreeMemory()
{
KRATOS_TRY;
// Free the MMG structures
mMmgUtilities.FreeAll();
// Free reference std::unordered_map
mpRefElement.clear();
mpRefCondition.clear();
// Clear the colors
mColors.clear();
KRATOS_CATCH("");
}
/***********************************************************************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgProcess<TMMGLibrary>::OutputMdpa()
{
KRATOS_TRY;
std::ofstream output_file;
ModelPartIO model_part_io("output", IO::WRITE);
model_part_io.WriteModelPart(mrThisModelPart);
KRATOS_CATCH("");
}
/***********************************************************************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgProcess<TMMGLibrary>::CollapsePrismsToTriangles()
{
KRATOS_TRY;
// Connectivity map
std::unordered_map<IndexType, IndexType> thickness_connectivity_map;
std::unordered_map<IndexType, std::vector<IndexType>> transversal_connectivity_map;
// Now we iterate over the elements to create a connectivity map
ElementsArrayType& r_elements_array = mrThisModelPart.Elements();
const auto it_elem_begin = r_elements_array.begin();
// Node counter
const SizeType total_number_of_nodes = mrThisModelPart.GetRootModelPart().NumberOfNodes(); // Nodes must be ordered
const SizeType total_number_of_elements = mrThisModelPart.GetRootModelPart().NumberOfElements(); // Elements must be ordered
for(IndexType i = 0; i < r_elements_array.size(); ++i){
const auto it_elem = it_elem_begin + i;
// We get the element geometry
const GeometryType& r_geometry = it_elem->GetGeometry();
if (r_geometry.GetGeometryType() == GeometryData::KratosGeometryType::Kratos_Prism3D6) {
it_elem->Set(OLD_ENTITY, true); // This must be removed later
for (auto& r_node : r_geometry)