Salome HOME
Copyright update 2022
[modules/paravis.git] / src / Plugins / MEDReader / plugin / MEDReaderIO / vtkMEDReader.cxx
1 // Copyright (C) 2010-2022  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19 // Author : Anthony Geay
20
21 #include "vtkMEDReader.h"
22 #include "vtkGenerateVectors.h"
23 #include "MEDUtilities.hxx"
24
25 #include "vtkCellArray.h"
26 #include "vtkCellData.h"
27 #include "vtkCellType.h"
28 #include "vtkDataSetAttributes.h"
29 #include "vtkDataArraySelection.h"
30 #include "vtkDoubleArray.h"
31 #include "vtkExecutive.h"
32 #include "vtkInformation.h"
33 #include "vtkInformationDataObjectMetaDataKey.h"
34 #include "vtkInformationDoubleVectorKey.h"
35 #include "vtkInformationQuadratureSchemeDefinitionVectorKey.h"
36 #include "vtkInformationStringKey.h"
37 #include "vtkInformationVector.h"
38 #include "vtkMultiBlockDataSet.h"
39 #include "vtkMultiTimeStepAlgorithm.h"
40 #include "vtkMutableDirectedGraph.h"
41 #include "vtkObjectFactory.h"
42 #include "vtkPointData.h"
43 #include "vtkQuadratureSchemeDefinition.h"
44 #include "vtkSmartPointer.h"
45 #include "vtkStreamingDemandDrivenPipeline.h"
46 #include "vtkStringArray.h"
47 #include "vtkUnsignedCharArray.h"
48 #include "vtkUnstructuredGrid.h"
49 #include "vtkVariantArray.h"
50
51 #ifdef MEDREADER_USE_MPI
52 #include "vtkMultiProcessController.h"
53 #include "vtkPUnstructuredGridGhostCellsGenerator.h"
54 #endif
55
56 #include "MEDFileFieldRepresentationTree.hxx"
57
58 #include <map>
59 #include <string>
60 #include <vector>
61 #include <sstream>
62 #include <algorithm>
63
64 class vtkMEDReader::vtkMEDReaderInternal
65 {
66
67 public:
68   vtkMEDReaderInternal(vtkMEDReader *master):TK(0),IsStdOrMode(false),GenerateVect(false),SIL(0),LastLev0(-1),GCGCP(true)
69   {
70   }
71
72   ~vtkMEDReaderInternal()
73   {
74     if(this->SIL)
75       this->SIL->Delete();
76   }
77 public:
78   MEDFileFieldRepresentationTree Tree;
79   vtkNew<vtkDataArraySelection> FieldSelection;
80   vtkNew<vtkDataArraySelection> TimeFlagSelection;
81
82   TimeKeeper TK;
83   std::string FileName;
84   //when false -> std, true -> mode. By default std (false).
85   bool IsStdOrMode;
86   //when false -> do nothing. When true cut off or extend to nbOfCompo=3 vector arrays.
87   bool GenerateVect;
88   std::string DftMeshName;
89   // Store the vtkMutableDirectedGraph that represents links between family, groups and cell types
90   vtkMutableDirectedGraph* SIL;
91   // store the lev0 id in Tree corresponding to the TIME_STEPS in the pipeline.
92   int LastLev0;
93   bool GCGCP;
94 };
95
96 vtkStandardNewMacro(vtkMEDReader)
97
98 // vtkInformationKeyMacro(vtkMEDReader, META_DATA, DataObjectMetaData); // Here we need to customize vtkMEDReader::META_DATA method
99 // start of overload of vtkInformationKeyMacro
100 static vtkInformationDataObjectMetaDataKey *vtkMEDReader_META_DATA=new vtkInformationDataObjectMetaDataKey("META_DATA","vtkMEDReader");
101
102 vtkInformationDataObjectMetaDataKey *vtkMEDReader::META_DATA()  
103 {
104   static const char ZE_KEY[]="vtkMEDReader::META_DATA";
105   vtkInformationDataObjectMetaDataKey *ret(vtkMEDReader_META_DATA);
106   MEDCoupling::GlobalDict *gd(MEDCoupling::GlobalDict::GetInstance());
107   if(!gd->hasKey(ZE_KEY))
108     {// here META_DATA is put on global var to be exchanged with other filters without dependancy of MEDReader. Please do not change ZE_KEY !
109       std::ostringstream oss; oss << ret;
110       gd->setKeyValue(ZE_KEY,oss.str());
111     }
112   return ret;
113 }
114
115 static vtkInformationGaussDoubleVectorKey *vtkMEDReader_GAUSS_DATA=new vtkInformationGaussDoubleVectorKey("GAUSS_DATA","vtkMEDReader");
116
117 vtkInformationGaussDoubleVectorKey *vtkMEDReader::GAUSS_DATA()  
118 {
119   static const char ZE_KEY[]="vtkMEDReader::GAUSS_DATA";
120   vtkInformationGaussDoubleVectorKey *ret(vtkMEDReader_GAUSS_DATA);
121   MEDCoupling::GlobalDict *gd(MEDCoupling::GlobalDict::GetInstance());
122   if(!gd->hasKey(ZE_KEY))
123     {// here META_DATA is put on global var to be exchanged with other filters without dependancy of MEDReader. Please do not change ZE_KEY !
124       vtkInformationDoubleVectorKey *ret2(ret);
125       std::ostringstream oss; oss << ret2;
126       gd->setKeyValue(ZE_KEY,oss.str());
127     }
128   return ret;
129 }
130 // end of overload of vtkInformationKeyMacro
131
132 vtkMEDReader::vtkMEDReader():Internal(new vtkMEDReaderInternal(this))
133 {
134   this->SetNumberOfInputPorts(0);
135   this->SetNumberOfOutputPorts(1);
136 }
137
138 vtkMEDReader::~vtkMEDReader()
139 {
140   delete this->Internal;
141   this->Internal = 0;
142 }
143
144 void vtkMEDReader::Reload()
145 {
146   std::string fName((const char *)this->GetFileName());
147   delete this->Internal;
148   this->Internal=new vtkMEDReaderInternal(this);
149   this->SetFileName(fName.c_str());
150 }
151
152 void vtkMEDReader::GenerateVectors(int val)
153 {
154   if ( !this->Internal )
155     return;
156   
157   bool val2((bool)val);
158   if(val2!=this->Internal->GenerateVect)
159     {
160       this->Internal->GenerateVect=val2;
161       this->Modified();
162     }
163 }
164
165 void vtkMEDReader::ChangeMode(int newMode)
166 {
167   if ( !this->Internal )
168     return;
169   
170   this->Internal->IsStdOrMode=newMode!=0;
171   this->Modified();
172 }
173
174 void vtkMEDReader::GhostCellGeneratorCallForPara(int gcgcp)
175 {
176   if ( !this->Internal )
177     return;
178   
179   bool newVal(gcgcp!=0);
180   if(newVal!=this->Internal->GCGCP)
181     {
182       this->Internal->GCGCP=newVal;
183       this->Modified();
184     }
185 }
186
187 const char *vtkMEDReader::GetSeparator()
188 {
189   return MEDFileFieldRepresentationLeavesArrays::ZE_SEP;
190 }
191
192 void vtkMEDReader::SetFileName(const char *fname)
193 {
194   if(!this->Internal)
195     return;
196   try
197     {
198       this->Internal->FileName=fname;
199       this->Modified();
200     }
201   catch(INTERP_KERNEL::Exception& e)
202     {
203       delete this->Internal;
204       this->Internal=0;
205       std::ostringstream oss;
206       oss << "Exception has been thrown in vtkMEDReader::SetFileName : " << e.what() << std::endl;
207       if(this->HasObserver("ErrorEvent") )
208         this->InvokeEvent("ErrorEvent",const_cast<char *>(oss.str().c_str()));
209       else
210         vtkOutputWindowDisplayErrorText(const_cast<char *>(oss.str().c_str()));
211       vtkObject::BreakOnError();
212     }
213 }
214
215 char *vtkMEDReader::GetFileName()
216 {
217   if (!this->Internal)
218     return 0;
219   return const_cast<char *>(this->Internal->FileName.c_str());
220 }
221
222 int vtkMEDReader::RequestInformation(vtkInformation *request, vtkInformationVector ** /*inputVector*/, vtkInformationVector *outputVector)
223 {
224 //  std::cout << "########################################## vtkMEDReader::RequestInformation ##########################################" << std::endl;
225   if(!this->Internal)
226     return 0;
227   try
228     {
229       // Process file meta data
230       if(this->Internal->Tree.getNumberOfLeavesArrays()==0)
231         {
232           int iPart(-1),nbOfParts(-1);
233 #ifdef MEDREADER_USE_MPI
234           vtkMultiProcessController *vmpc(vtkMultiProcessController::GetGlobalController());
235           if(vmpc)
236             {
237               iPart=vmpc->GetLocalProcessId();
238               nbOfParts=vmpc->GetNumberOfProcesses();
239             }
240 #endif
241           this->Internal->Tree.loadMainStructureOfFile(this->Internal->FileName.c_str(),iPart,nbOfParts);
242           
243           // Leaves
244           this->Internal->Tree.activateTheFirst();//This line manually initialize the status of server (this) with the remote client.
245           for (int idLeaveArray = 0; idLeaveArray < this->Internal->Tree.getNumberOfLeavesArrays(); idLeaveArray++)
246           {
247             std::string name = this->Internal->Tree.getNameOf(idLeaveArray);
248             bool status = this->Internal->Tree.getStatusOf(idLeaveArray);
249             this->Internal->FieldSelection->AddArray(name.c_str(), status);
250           }
251         }
252
253       // Time flags
254       this->Internal->TK.setMaxNumberOfTimeSteps(this->Internal->Tree.getMaxNumberOfTimeSteps());
255       auto timeFlagsArray = this->Internal->TK.getTimesFlagArray();
256       for (int idTimeFlag = 0; idTimeFlag < timeFlagsArray.size() ; idTimeFlag++)
257       {
258         std::string name = timeFlagsArray[idTimeFlag].second;
259         bool status = timeFlagsArray[idTimeFlag].first;
260         this->Internal->TimeFlagSelection->AddArray(name.c_str(), status);
261       }
262
263       // Make sure internal model are synchronized
264       /// So the SIL is up to date
265       int nArrays = this->Internal->FieldSelection->GetNumberOfArrays();
266       for(int i = nArrays - 1; i >= 0; i--)
267       {
268         try
269         {
270         this->Internal->Tree.changeStatusOfAndUpdateToHaveCoherentVTKDataSet(
271           this->Internal->Tree.getIdHavingZeName(this->Internal->FieldSelection->GetArrayName(i)),
272           this->Internal->FieldSelection->GetArraySetting(i));
273         }
274         catch(INTERP_KERNEL::Exception& e)
275         {
276           // Remove the incorrect array
277           this->Internal->FieldSelection->RemoveArrayByIndex(i);
278         }
279       }
280
281 //      request->Print(cout);
282       vtkInformation *outInfo(outputVector->GetInformationObject(0));
283       outInfo->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkMultiBlockDataSet");
284       this->UpdateSIL(request, outInfo);
285
286       // Set the meta data graph as a meta data key in the information
287       // That's all that is needed to transfer it along the pipeline
288       outInfo->Set(vtkMEDReader::META_DATA(),this->Internal->SIL);
289
290       bool dummy(false);
291       this->PublishTimeStepsIfNeeded(outInfo,dummy);
292     }
293   catch(INTERP_KERNEL::Exception& e)
294     {
295       std::ostringstream oss;
296       oss << "Exception has been thrown in vtkMEDReader::RequestInformation : " << e.what() << std::endl;
297       if(this->HasObserver("ErrorEvent") )
298         this->InvokeEvent("ErrorEvent",const_cast<char *>(oss.str().c_str()));
299       else
300         vtkOutputWindowDisplayErrorText(const_cast<char *>(oss.str().c_str()));
301       vtkObject::BreakOnError();
302       return 0;
303     }
304   return 1;
305 }
306
307 int vtkMEDReader::RequestData(vtkInformation *request, vtkInformationVector ** /*inputVector*/, vtkInformationVector *outputVector)
308 {
309 //  std::cout << "########################################## vtkMEDReader::RequestData ##########################################" << std::endl;
310   if(!this->Internal)
311     return 0;
312   try
313   {
314       for(int i = 0; i < this->Internal->FieldSelection->GetNumberOfArrays(); i++)
315       {
316         this->Internal->Tree.changeStatusOfAndUpdateToHaveCoherentVTKDataSet(
317           this->Internal->Tree.getIdHavingZeName(this->Internal->FieldSelection->GetArrayName(i)), 
318           this->Internal->FieldSelection->GetArraySetting(i));
319       }
320           
321       auto& timeFlagsArray = this->Internal->TK.getTimesFlagArray();
322       if (timeFlagsArray.size() != this->Internal->TimeFlagSelection->GetNumberOfArrays())
323       {
324         throw INTERP_KERNEL::Exception("Unexpected size of TimeFlagSelection");
325       }
326       for(int i = 0; i < this->Internal->TimeFlagSelection->GetNumberOfArrays(); i++)
327       {
328         timeFlagsArray[i] = std::make_pair(this->Internal->TimeFlagSelection->GetArraySetting(i), 
329           this->Internal->TimeFlagSelection->GetArrayName(i));
330       }
331
332 //      request->Print(cout);
333       vtkInformation *outInfo(outputVector->GetInformationObject(0));
334       vtkMultiBlockDataSet *output(vtkMultiBlockDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())));
335       //bool isUpdated(false); // todo: unused
336       double reqTS(0.);
337       if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()))
338         reqTS=outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP());
339       ExportedTinyInfo ti;
340 #ifndef MEDREADER_USE_MPI
341       this->FillMultiBlockDataSetInstance(output,reqTS,&ti);
342 #else
343       if(this->Internal->GCGCP)
344         {
345           vtkSmartPointer<vtkPUnstructuredGridGhostCellsGenerator> gcg(vtkSmartPointer<vtkPUnstructuredGridGhostCellsGenerator>::New());
346           {
347             vtkDataSet *ret(RetrieveDataSetAtTime(reqTS,&ti));
348             gcg->SetInputData(ret);
349             ret->Delete();
350           }
351           gcg->SetUseGlobalPointIds(true);
352           gcg->SetBuildIfRequired(false);
353           gcg->Update();
354           output->SetBlock(0,gcg->GetOutput());
355         }
356       else
357         this->FillMultiBlockDataSetInstance(output,reqTS,&ti);
358 #endif
359       if(!ti.empty())
360         {
361           const std::vector<double>& data(ti.getData());
362           outInfo->Set(vtkMEDReader::GAUSS_DATA(),&data[0],(int)data.size());
363           request->Append(vtkExecutive::KEYS_TO_COPY(),vtkMEDReader::GAUSS_DATA());// Thank you to SciberQuest and DIPOLE_CENTER ! Don't understand why ! In RequestInformation it does not work !
364         }
365       output->GetInformation()->Set(vtkDataObject::DATA_TIME_STEP(),reqTS);
366       // Is it really needed ? TODO
367       this->UpdateSIL(request, outInfo);
368     }
369   catch(INTERP_KERNEL::Exception& e)
370     {
371       std::cerr << "Exception has been thrown in vtkMEDReader::RequestData : " << e.what() << std::endl;
372       return 0;
373     }
374   return 1;
375 }
376
377 //------------------------------------------------------------------------------
378 int vtkMEDReader::GetNumberOfFieldsTreeArrays()
379 {
380   return this->Internal->FieldSelection->GetNumberOfArrays();
381 }
382
383 //------------------------------------------------------------------------------
384 const char* vtkMEDReader::GetFieldsTreeArrayName(int index)
385 {
386   return this->Internal->FieldSelection->GetArrayName(index);
387 }
388
389 //------------------------------------------------------------------------------
390 int vtkMEDReader::GetFieldsTreeArrayStatus(const char* name)
391 {
392   return this->Internal->FieldSelection->ArrayIsEnabled(name);
393 }
394
395 //------------------------------------------------------------------------------
396 void vtkMEDReader::SetFieldsStatus(const char* name, int status)
397 {
398   if (this->GetFieldsTreeArrayStatus(name) != status)
399   {
400     if (status)
401     {
402       this->Internal->FieldSelection->EnableArray(name);
403     }
404     else
405     {
406       this->Internal->FieldSelection->DisableArray(name);
407     }
408     this->Modified();
409   }
410 }
411
412 //------------------------------------------------------------------------------
413 int vtkMEDReader::GetNumberOfTimesFlagsArrays()
414 {
415   return this->Internal->TimeFlagSelection->GetNumberOfArrays();
416 }
417
418 //------------------------------------------------------------------------------
419 const char* vtkMEDReader::GetTimesFlagsArrayName(int index)
420 {
421   return this->Internal->TimeFlagSelection->GetArrayName(index);
422 }
423
424 //------------------------------------------------------------------------------
425 int vtkMEDReader::GetTimesFlagsArrayStatus(const char* name)
426 {
427   return this->Internal->TimeFlagSelection->ArrayIsEnabled(name);
428 }
429
430 //------------------------------------------------------------------------------
431 void vtkMEDReader::SetTimesFlagsStatus(const char* name, int status)
432 {
433   if (this->GetTimesFlagsArrayStatus(name) != status)
434   {
435     if (status)
436     {
437       this->Internal->TimeFlagSelection->EnableArray(name);
438     }
439     else
440     {
441       this->Internal->TimeFlagSelection->DisableArray(name);
442     }
443     this->Modified();
444   }
445 }
446
447 void vtkMEDReader::UpdateSIL(vtkInformation* /*request*/, vtkInformation * /*info*/)
448 {
449   if(!this->Internal)
450       return;
451   std::string meshName(this->Internal->Tree.getActiveMeshName());
452   if(!this->Internal->SIL || meshName!=this->Internal->DftMeshName)
453     {
454       vtkMutableDirectedGraph *sil(vtkMutableDirectedGraph::New());
455       this->BuildSIL(sil);
456       if(this->Internal->SIL)
457         this->Internal->SIL->Delete();
458       this->Internal->SIL=sil;
459       this->Internal->DftMeshName=meshName;
460     }
461 }
462
463 /*!
464  * The returned string is the name of the mesh activated which groups and families are in \a sil.
465  */
466 std::string vtkMEDReader::BuildSIL(vtkMutableDirectedGraph* sil)
467 {
468   if (!this->Internal)
469     return std::string();
470   sil->Initialize();
471   vtkSmartPointer<vtkVariantArray> childEdge(vtkSmartPointer<vtkVariantArray>::New());
472   childEdge->InsertNextValue(0);
473   vtkSmartPointer<vtkVariantArray> crossEdge(vtkSmartPointer<vtkVariantArray>::New());
474   crossEdge->InsertNextValue(1);
475   // CrossEdge is an edge linking hierarchies.
476   vtkUnsignedCharArray* crossEdgesArray=vtkUnsignedCharArray::New();
477   crossEdgesArray->SetName("CrossEdges");
478   sil->GetEdgeData()->AddArray(crossEdgesArray);
479   crossEdgesArray->Delete();
480   std::vector<std::string> names;
481   // Now build the hierarchy.
482   vtkIdType rootId=sil->AddVertex();
483   names.push_back("SIL");
484   // Add global fields root
485   vtkIdType fieldsRoot(sil->AddChild(rootId,childEdge));
486   names.push_back("FieldsStatusTree");
487   this->Internal->Tree.feedSIL(sil,fieldsRoot,childEdge,names);
488   vtkIdType meshesFamsGrpsRoot(sil->AddChild(rootId,childEdge));
489   names.push_back("MeshesFamsGrps");
490   std::string dftMeshName(this->Internal->Tree.feedSILForFamsAndGrps(sil,meshesFamsGrpsRoot,childEdge,names));
491   // This array is used to assign names to nodes.
492   vtkStringArray *namesArray(vtkStringArray::New());
493   namesArray->SetName("Names");
494   namesArray->SetNumberOfTuples(sil->GetNumberOfVertices());
495   sil->GetVertexData()->AddArray(namesArray);
496   namesArray->Delete();
497   std::vector<std::string>::const_iterator iter;
498   vtkIdType cc;
499   for(cc=0, iter=names.begin(); iter!=names.end(); ++iter, ++cc)
500     namesArray->SetValue(cc,(*iter).c_str());
501   return dftMeshName;
502 }
503
504 double vtkMEDReader::PublishTimeStepsIfNeeded(vtkInformation *outInfo, bool& isUpdated)
505 {
506   if(!this->Internal)
507     return 0.0;
508
509   int lev0(-1);
510   std::vector<double> tsteps;
511   if(!this->Internal->IsStdOrMode)
512     tsteps=this->Internal->Tree.getTimeSteps(lev0,this->Internal->TK);
513   else
514     { tsteps.resize(1); tsteps[0]=0.; }
515   isUpdated=false;
516   if(lev0!=this->Internal->LastLev0)
517     {
518       isUpdated=true;
519       double timeRange[2];
520       timeRange[0]=tsteps.front();
521       timeRange[1]=tsteps.back();
522       outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(),&tsteps[0],(int)tsteps.size());
523       outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(),timeRange,2);
524       this->Internal->LastLev0=lev0;
525     }
526   return tsteps.front();
527 }
528
529 void vtkMEDReader::FillMultiBlockDataSetInstance(vtkMultiBlockDataSet *output, double reqTS, ExportedTinyInfo *internalInfo)
530 {
531   if( !this->Internal )
532     return;
533   vtkDataSet *ret(RetrieveDataSetAtTime(reqTS,internalInfo));
534   output->SetBlock(0,ret);
535   ret->Delete();
536 }
537
538 vtkDataSet *vtkMEDReader::RetrieveDataSetAtTime(double reqTS, ExportedTinyInfo *internalInfo)
539 {
540   if( !this->Internal )
541     return 0;
542   std::string meshName;
543   vtkDataSet *ret(this->Internal->Tree.buildVTKInstance(this->Internal->IsStdOrMode,reqTS,meshName,this->Internal->TK,internalInfo));
544   if(this->Internal->GenerateVect)
545     {
546       vtkGenerateVectors::Operate(ret->GetPointData());
547       vtkGenerateVectors::Operate(ret->GetCellData());
548       vtkGenerateVectors::Operate(ret->GetFieldData());
549       // The operations above have potentially created new arrays -> This breaks the optimization of StaticMesh that expects the same field arrays over time.
550       // To enforce the cache recomputation declare modification of mesh.
551       //vtkGenerateVectors::ChangeMeshTimeToUpdateCache(ret);
552     }
553   return ret;
554 }
555
556 void vtkMEDReader::PrintSelf(ostream& os, vtkIndent indent)
557 {
558   this->Superclass::PrintSelf(os, indent);
559 }