Salome HOME
Merge remote branch 'origin/master'
[modules/paravis.git] / src / Plugins / MEDReader / IO / vtkMEDReader.cxx
1 // Copyright (C) 2010-2015  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
24 #include "vtkMultiBlockDataSet.h"
25 #include "vtkInformation.h"
26 #include "vtkDataSetAttributes.h"
27 #include "vtkStringArray.h"
28 #include "vtkMutableDirectedGraph.h"
29 #include "vtkInformationStringKey.h"
30 //
31 #include "vtkUnsignedCharArray.h"
32 #include "vtkInformationVector.h"
33 #include "vtkSmartPointer.h"
34 #include "vtkVariantArray.h"
35 #include "vtkExecutive.h"
36 #include "vtkStreamingDemandDrivenPipeline.h"
37 #include "vtkMultiTimeStepAlgorithm.h"
38 #include "vtkUnstructuredGrid.h"
39 #include "vtkInformationQuadratureSchemeDefinitionVectorKey.h"
40 #include "vtkQuadratureSchemeDefinition.h"
41 #include "vtkPointData.h"
42 #include "vtkCellData.h"
43 #include "vtkCellType.h"
44 #include "vtkCellArray.h"
45 #include "vtkDoubleArray.h"
46 #include "vtkObjectFactory.h"
47 #ifdef MEDREADER_USE_MPI
48 #include "vtkMultiProcessController.h"
49 #endif
50
51 #include "MEDFileFieldRepresentationTree.hxx"
52
53 #include <map>
54 #include <string>
55 #include <vector>
56 #include <sstream>
57 #include <algorithm>
58
59 /*!
60  * This class stores properties in loading state mode (pvsm) when the MED file has not been read yet.
61  * The file is not read beacause FileName has not been informed yet ! So this class stores properties of vtkMEDReader instance that 
62  * owns it and wait the vtkMEDReader::SetFileName to apply properties afterwards.
63  */
64 class PropertyKeeper
65 {
66 public:
67   PropertyKeeper(vtkMEDReader *master):_master(master),IsGVActivated(false),GVValue(0),IsCMActivated(false),CMValue(0) { }
68   void assignPropertiesIfNeeded();
69   bool arePropertiesOnTreeToSetAfter() const;
70   //
71   void pushFieldStatusEntry(const char* name, int status);
72   void pushGenerateVectorsValue(int value);
73   void pushChangeModeValue(int value);
74   void pushTimesFlagsStatusEntry(const char* name, int status);
75 protected:
76   // pool of pairs to assign in SetFieldsStatus if needed. The use case is the load using pvsm.
77   std::vector< std::pair<std::string,int> > SetFieldsStatusPairs;
78   // generate vector
79   bool IsGVActivated;
80   int GVValue;
81   // change mode
82   bool IsCMActivated;
83   int CMValue;
84   //
85   std::vector< std::pair<std::string,int> > TimesFlagsStatusPairs;
86   vtkMEDReader *_master;
87 };
88
89 void PropertyKeeper::assignPropertiesIfNeeded()
90 {
91   if(!this->SetFieldsStatusPairs.empty())
92     {
93       for(std::vector< std::pair<std::string,int> >::const_iterator it=this->SetFieldsStatusPairs.begin();it!=this->SetFieldsStatusPairs.end();it++)
94         _master->SetFieldsStatus((*it).first.c_str(),(*it).second);
95       this->SetFieldsStatusPairs.clear();
96     }
97   if(!this->TimesFlagsStatusPairs.empty())
98     {
99       for(std::vector< std::pair<std::string,int> >::const_iterator it=this->TimesFlagsStatusPairs.begin();it!=this->TimesFlagsStatusPairs.end();it++)
100         _master->SetTimesFlagsStatus((*it).first.c_str(),(*it).second);
101       this->TimesFlagsStatusPairs.clear();
102     }
103   if(this->IsGVActivated)
104     {
105       _master->GenerateVectors(this->GVValue);
106       this->IsGVActivated=false;
107     }
108   if(this->IsCMActivated)
109     {
110       _master->ChangeMode(this->CMValue);
111       this->IsCMActivated=false;
112     }
113 }
114
115 void PropertyKeeper::pushFieldStatusEntry(const char* name, int status)
116 {
117   bool found(false);
118   for(std::vector< std::pair<std::string,int> >::const_iterator it=this->SetFieldsStatusPairs.begin();it!=this->SetFieldsStatusPairs.end() && !found;it++)
119     found=(*it).first==name;
120   if(!found)
121     this->SetFieldsStatusPairs.push_back(std::pair<std::string,int>(name,status));
122 }
123
124 void PropertyKeeper::pushTimesFlagsStatusEntry(const char* name, int status)
125 {
126   bool found(false);
127   for(std::vector< std::pair<std::string,int> >::const_iterator it=this->TimesFlagsStatusPairs.begin();it!=this->TimesFlagsStatusPairs.end() && !found;it++)
128     found=(*it).first==name;
129   if(!found)
130     this->TimesFlagsStatusPairs.push_back(std::pair<std::string,int>(name,status));
131 }
132
133 void PropertyKeeper::pushGenerateVectorsValue(int value)
134 {
135   this->IsGVActivated=true;
136   this->GVValue=value;
137 }
138
139 void PropertyKeeper::pushChangeModeValue(int value)
140 {
141   this->IsCMActivated=true;
142   this->CMValue=value;
143 }
144
145 bool PropertyKeeper::arePropertiesOnTreeToSetAfter() const
146 {
147   return !SetFieldsStatusPairs.empty();
148 }
149
150 class vtkMEDReader::vtkMEDReaderInternal
151 {
152
153 public:
154   vtkMEDReaderInternal(vtkMEDReader *master):TK(0),IsMEDOrSauv(true),IsStdOrMode(false),GenerateVect(false),SIL(0),LastLev0(-1),FirstCall0(2),PK(master),MyMTime(0)
155   {
156   }
157   
158   bool PluginStart0()
159   {
160     if(FirstCall0==0)
161       return false;
162     FirstCall0--;
163     return true;
164   }
165   
166   ~vtkMEDReaderInternal()
167   {
168     if(this->SIL)
169       this->SIL->Delete();
170   }
171 public:
172   MEDFileFieldRepresentationTree Tree;
173   TimeKeeper TK;
174   std::string FileName;
175   //when true the file is MED file. when false it is a Sauv file
176   bool IsMEDOrSauv;
177   //when false -> std, true -> mode. By default std (false).
178   bool IsStdOrMode;
179   //when false -> do nothing. When true cut off or extend to nbOfCompo=3 vector arrays.
180   bool GenerateVect;
181   std::string DftMeshName;
182   // Store the vtkMutableDirectedGraph that represents links between family, groups and cell types
183   vtkMutableDirectedGraph* SIL;
184   // store the lev0 id in Tree corresponding to the TIME_STEPS in the pipeline.
185   int LastLev0;
186   // The property keeper is usable only in pvsm mode.
187   PropertyKeeper PK;
188   int MyMTime;
189   std::set<std::string> _wonderful_set;// this set is used by SetFieldsStatus method to detect the fact that SetFieldsStatus has been called for all items ! Great Items are not sorted ! Why ?
190   std::map<std::string,bool> _wonderful_ref;// this map stores the state before a SetFieldsStatus status.
191 private:
192   unsigned char FirstCall0;
193 };
194
195 vtkStandardNewMacro(vtkMEDReader);
196
197 vtkMEDReader::vtkMEDReader():Internal(new vtkMEDReaderInternal(this))
198 {
199   this->SetNumberOfInputPorts(0);
200   this->SetNumberOfOutputPorts(1);
201 }
202
203 vtkMEDReader::~vtkMEDReader()
204 {
205   delete this->Internal;
206   this->Internal = 0;
207 }
208
209 void vtkMEDReader::Reload(int a)
210 {
211   if(a==0)
212     return;
213   std::cerr << "vtkMEDReader::Reload" << a << std::endl;
214   std::string fName((const char *)this->GetFileName());
215   delete this->Internal;
216   this->Internal=new vtkMEDReaderInternal(this);
217   this->SetFileName(fName.c_str());
218 }
219
220 int vtkMEDReader::GetServerModifTime()
221 {
222   if( !this->Internal )
223     return -1;
224   return this->Internal->MyMTime;
225 }
226
227 void vtkMEDReader::GenerateVectors(int val)
228 {
229   if ( !this->Internal )
230     return;
231   
232   if(this->Internal->FileName.empty())
233     {//pvsm mode
234       this->Internal->PK.pushGenerateVectorsValue(val);
235       return ;
236     }
237   //not pvsm mode (general case)
238   bool val2((bool)val);
239   if(val2!=this->Internal->GenerateVect)
240     {
241       this->Internal->GenerateVect=val2;
242       this->Modified();
243     }
244 }
245
246 void vtkMEDReader::ChangeMode(int newMode)
247 {
248   if ( !this->Internal )
249     return;
250   
251   if(this->Internal->FileName.empty())
252     {//pvsm mode
253       this->Internal->PK.pushChangeModeValue(newMode);
254       return ;
255     }
256   //not pvsm mode (general case)
257   this->Internal->IsStdOrMode=newMode!=0;
258   //std::cerr << "vtkMEDReader::ChangeMode : " << this->Internal->IsStdOrMode << std::endl;
259   this->Modified();
260 }
261
262 const char *vtkMEDReader::GetSeparator()
263 {
264   return MEDFileFieldRepresentationLeavesArrays::ZE_SEP;
265 }
266
267 void vtkMEDReader::SetFileName(const char *fname)
268 {
269   if(!this->Internal)
270     return;
271   try
272     {
273       this->Internal->FileName=fname;
274       std::size_t pos(this->Internal->FileName.find_last_of('.'));
275       if(pos!=std::string::npos)
276         {
277           std::string ext(this->Internal->FileName.substr(pos));
278           if(ext.find("sauv")!=std::string::npos)
279             this->Internal->IsMEDOrSauv=false;
280         }
281       if(this->Internal->Tree.getNumberOfLeavesArrays()==0)
282         {
283           int iPart(-1),nbOfParts(-1);
284 #ifdef MEDREADER_USE_MPI
285           vtkMultiProcessController *vmpc(vtkMultiProcessController::GetGlobalController());
286           if(vmpc)
287             {
288               iPart=vmpc->GetLocalProcessId();
289               nbOfParts=vmpc->GetNumberOfProcesses();
290             }
291 #endif
292           this->Internal->Tree.loadMainStructureOfFile(this->Internal->FileName.c_str(),this->Internal->IsMEDOrSauv,iPart,nbOfParts);
293           if(!this->Internal->PK.arePropertiesOnTreeToSetAfter())
294             this->Internal->Tree.activateTheFirst();//This line manually initialize the status of server (this) with the remote client.
295           this->Internal->TK.setMaxNumberOfTimeSteps(this->Internal->Tree.getMaxNumberOfTimeSteps());
296         }
297       this->Modified();
298       this->Internal->PK.assignPropertiesIfNeeded();
299     }
300   catch(INTERP_KERNEL::Exception& e)
301     {
302       delete this->Internal;
303       this->Internal=0;
304       std::ostringstream oss;
305       oss << "Exception has been thrown in vtkMEDReader::SetFileName : " << e.what() << std::endl;
306       if(this->HasObserver("ErrorEvent") )
307         this->InvokeEvent("ErrorEvent",const_cast<char *>(oss.str().c_str()));
308       else
309         vtkOutputWindowDisplayErrorText(const_cast<char *>(oss.str().c_str()));
310       vtkObject::BreakOnError();
311     }
312 }
313
314 char *vtkMEDReader::GetFileName()
315 {
316   if (!this->Internal)
317     return 0;
318   return const_cast<char *>(this->Internal->FileName.c_str());
319 }
320
321 int vtkMEDReader::RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector)
322 {
323   //std::cerr << "########################################## RequestInformation ##########################################" << std::endl;
324   if(!this->Internal)
325     return 0;
326   try
327     {
328       vtkInformation *outInfo(outputVector->GetInformationObject(0));
329       outInfo->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkMultiBlockDataSet");
330       this->UpdateSIL(outInfo);
331       //
332       bool dummy(false);
333       this->PublishTimeStepsIfNeeded(outInfo,dummy);
334     }
335   catch(INTERP_KERNEL::Exception& e)
336     {
337       std::ostringstream oss;
338       oss << "Exception has been thrown in vtkMEDReader::RequestInformation : " << e.what() << std::endl;
339       if(this->HasObserver("ErrorEvent") )
340         this->InvokeEvent("ErrorEvent",const_cast<char *>(oss.str().c_str()));
341       else
342         vtkOutputWindowDisplayErrorText(const_cast<char *>(oss.str().c_str()));
343       vtkObject::BreakOnError();
344       return 0;
345     }
346   return 1;
347 }
348
349 int vtkMEDReader::RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector)
350 {
351   //std::cerr << "########################################## RequestData        ##########################################";
352   if(!this->Internal)
353     return 0;
354   try
355     {
356       vtkInformation *outInfo(outputVector->GetInformationObject(0));
357       vtkMultiBlockDataSet *output(vtkMultiBlockDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())));
358       bool isUpdated(false);
359       double reqTS(0.);
360       if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()))
361         reqTS=outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP());
362       //std::cerr << reqTS << std::endl;
363       this->FillMultiBlockDataSetInstance(output,reqTS);
364       output->GetInformation()->Set(vtkDataObject::DATA_TIME_STEP(),reqTS);
365       this->UpdateSIL(outInfo);
366       //this->UpdateProgress((float) progress/((float) maxprogress-1));
367     }
368   catch(INTERP_KERNEL::Exception& e)
369     {
370       std::cerr << "Exception has been thrown in vtkMEDReader::RequestData : " << e.what() << std::endl;
371       return 0;
372     }
373   return 1;
374 }
375
376 void vtkMEDReader::SetFieldsStatus(const char* name, int status)
377 {
378   if( !this->Internal )
379     return;
380
381   //this->Internal->_wonderful_set.insert(name);
382   if(this->Internal->FileName.empty())
383     {//pvsm mode
384       this->Internal->PK.pushFieldStatusEntry(name,status);
385       return ;
386     }
387   if(this->Internal->_wonderful_set.empty())
388     this->Internal->_wonderful_ref=this->Internal->Tree.dumpState();// start of SetFieldsStatus serie -> store ref to compare at the end of the SetFieldsStatus serie.
389   this->Internal->_wonderful_set.insert(name);
390   //not pvsm mode (general case)
391   try
392     {
393       this->Internal->Tree.changeStatusOfAndUpdateToHaveCoherentVTKDataSet(this->Internal->Tree.getIdHavingZeName(name),status);
394       if(this->Internal->_wonderful_set.size()==GetNumberOfFieldsTreeArrays())
395         {
396           if(this->Internal->_wonderful_ref!=this->Internal->Tree.dumpState())
397             {
398               if(!this->Internal->PluginStart0())
399                 {
400                   this->Modified();
401                 }
402               this->Internal->MyMTime++;
403             }
404           this->Internal->_wonderful_set.clear();
405         }
406     }
407   catch(INTERP_KERNEL::Exception& e)
408     {
409       if(!this->Internal->FileName.empty())
410         {
411           std::cerr << "vtkMEDReader::SetFieldsStatus error : " << e.what() << " *** WITH STATUS=" << status << endl;
412           return ;
413         }
414     }
415 }
416
417 int vtkMEDReader::GetNumberOfFieldsTreeArrays()
418 {
419   if(!this->Internal)
420     return 0;
421   return this->Internal->Tree.getNumberOfLeavesArrays();
422   //std::cerr << "vtkMEDReader::GetNumberOfFieldsTreeArrays called ! " << ret << std::endl;
423 }
424
425 const char *vtkMEDReader::GetFieldsTreeArrayName(int index)
426 {
427   if(!this->Internal)
428     return 0;
429   return this->Internal->Tree.getNameOfC(index);
430   //std::cerr << "vtkMEDReader::GetFieldsTreeArrayName(" << index << ") called ! " << ret << std::endl;
431 }
432
433 int vtkMEDReader::GetFieldsTreeArrayStatus(const char *name)
434 {
435   if(!this->Internal)
436     return -1;
437
438   int zeId(this->Internal->Tree.getIdHavingZeName(name));
439   int ret(this->Internal->Tree.getStatusOf(zeId));
440   return ret;
441 }
442
443 void vtkMEDReader::SetTimesFlagsStatus(const char *name, int status)
444 {
445   if (!this->Internal)
446     return;
447   
448   if(this->Internal->FileName.empty())
449     {//pvsm mode
450       this->Internal->PK.pushTimesFlagsStatusEntry(name,status);
451       return ;
452     }
453   //not pvsm mode (general case)
454   int pos(0);
455   std::istringstream iss(name); iss >> pos;
456   this->Internal->TK.getTimesFlagArray()[pos].first=(bool)status;
457   if(pos==this->Internal->TK.getTimesFlagArray().size()-1)
458     if(!this->Internal->PluginStart0())
459       {
460         this->Modified();
461         //this->Internal->TK.printSelf(std::cerr);
462       }
463 }
464
465 int vtkMEDReader::GetNumberOfTimesFlagsArrays()
466 {
467   if(!this->Internal)
468     return 0;
469   return (int)this->Internal->TK.getTimesFlagArray().size();
470 }
471
472 const char *vtkMEDReader::GetTimesFlagsArrayName(int index)
473 {
474   return this->Internal->TK.getTimesFlagArray()[index].second.c_str();
475 }
476
477 int vtkMEDReader::GetTimesFlagsArrayStatus(const char *name)
478 {
479   if(!this->Internal)
480     return -1;
481   int pos(0);
482   std::istringstream iss(name); iss >> pos;
483   return (int)this->Internal->TK.getTimesFlagArray()[pos].first;
484 }
485
486 void vtkMEDReader::UpdateSIL(vtkInformation *info)
487 {
488   if(!this->Internal)
489       return;
490   vtkMutableDirectedGraph *sil(vtkMutableDirectedGraph::New());
491   std::string meshName(this->BuildSIL(sil));
492   if(meshName!=this->Internal->DftMeshName)
493     {
494       if(this->Internal->SIL)
495         this->Internal->SIL->Delete();
496       this->Internal->SIL=sil;
497       this->Internal->DftMeshName=meshName;
498       info->Set(vtkDataObject::SIL(),this->Internal->SIL);
499       //request->AppendUnique(vtkExecutive::KEYS_TO_COPY(),vtkDataObject::SIL());
500     }
501   else
502     {
503       sil->Delete();
504     }
505 }
506
507 /*!
508  * The returned string is the name of the mesh activated which groups and families are in \a sil.
509  */
510 std::string vtkMEDReader::BuildSIL(vtkMutableDirectedGraph* sil)
511 {
512   if (!this->Internal)
513     return std::string();
514   sil->Initialize();
515   vtkSmartPointer<vtkVariantArray> childEdge(vtkSmartPointer<vtkVariantArray>::New());
516   childEdge->InsertNextValue(0);
517   vtkSmartPointer<vtkVariantArray> crossEdge(vtkSmartPointer<vtkVariantArray>::New());
518   crossEdge->InsertNextValue(1);
519   // CrossEdge is an edge linking hierarchies.
520   vtkUnsignedCharArray* crossEdgesArray=vtkUnsignedCharArray::New();
521   crossEdgesArray->SetName("CrossEdges");
522   sil->GetEdgeData()->AddArray(crossEdgesArray);
523   crossEdgesArray->Delete();
524   std::vector<std::string> names;
525   // Now build the hierarchy.
526   vtkIdType rootId=sil->AddVertex();
527   names.push_back("SIL");
528   // Add global fields root
529   vtkIdType fieldsRoot(sil->AddChild(rootId,childEdge));
530   names.push_back("FieldsStatusTree");
531   this->Internal->Tree.feedSIL(sil,fieldsRoot,childEdge,names);
532   vtkIdType meshesFamsGrpsRoot(sil->AddChild(rootId,childEdge));
533   names.push_back("MeshesFamsGrps");
534   std::string dftMeshName(this->Internal->Tree.feedSILForFamsAndGrps(sil,meshesFamsGrpsRoot,childEdge,names));
535   // This array is used to assign names to nodes.
536   vtkStringArray *namesArray(vtkStringArray::New());
537   namesArray->SetName("Names");
538   namesArray->SetNumberOfTuples(sil->GetNumberOfVertices());
539   sil->GetVertexData()->AddArray(namesArray);
540   namesArray->Delete();
541   std::vector<std::string>::const_iterator iter;
542   vtkIdType cc;
543   for(cc=0, iter=names.begin(); iter!=names.end(); ++iter, ++cc)
544     namesArray->SetValue(cc,(*iter).c_str());
545   return dftMeshName;
546 }
547
548 double vtkMEDReader::PublishTimeStepsIfNeeded(vtkInformation *outInfo, bool& isUpdated)
549 {
550   if(!this->Internal)
551     return 0.0;
552
553   int lev0(-1);
554   std::vector<double> tsteps;
555   if(!this->Internal->IsStdOrMode)
556     tsteps=this->Internal->Tree.getTimeSteps(lev0,this->Internal->TK);
557   else
558     { tsteps.resize(1); tsteps[0]=0.; }
559   isUpdated=false;
560   if(lev0!=this->Internal->LastLev0)
561     {
562       isUpdated=true;
563       double timeRange[2];
564       timeRange[0]=tsteps.front();
565       timeRange[1]=tsteps.back();
566       outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(),&tsteps[0],tsteps.size());
567       outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(),timeRange,2);
568       this->Internal->LastLev0=lev0;
569     }
570   return tsteps.front();
571 }
572
573 void vtkMEDReader::FillMultiBlockDataSetInstance(vtkMultiBlockDataSet *output, double reqTS)
574 {
575   if( !this->Internal )
576     return;
577   std::string meshName;
578   vtkDataSet *ret(this->Internal->Tree.buildVTKInstance(this->Internal->IsStdOrMode,reqTS,meshName,this->Internal->TK));
579   if(this->Internal->GenerateVect)
580     {
581       vtkGenerateVectors::Operate(ret->GetPointData());
582       vtkGenerateVectors::Operate(ret->GetCellData());
583       vtkGenerateVectors::Operate(ret->GetFieldData());
584     }
585   output->SetBlock(0,ret);
586   ret->Delete();
587 }
588
589 void vtkMEDReader::PrintSelf(ostream& os, vtkIndent indent)
590 {
591   this->Superclass::PrintSelf(os, indent);
592 }