]> SALOME platform Git repositories - plugins/netgenplugin.git/blob - src/NETGENPlugin/NETGENPlugin_NETGEN_3D_Remote.cxx
Salome HOME
Modifications for multinode parallelism
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_3D_Remote.cxx
1 // Copyright (C) 2007-2023  CEA, EDF, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //=============================================================================
24 // File      : NETGENPlugin_NETGEN_3D_Remote.cxx
25 // Created   : lundi 19 Septembre 2022
26 // Author    : Yoann AUDOUIN (CEA)
27 // Project   : SALOME
28 //=============================================================================
29 //
30 //
31 #include "NETGENPlugin_NETGEN_3D_Remote.hxx"
32
33 #include "NETGENPlugin_NETGEN_3D.hxx"
34
35 #include "NETGENPlugin_DriverParam.hxx"
36 #include "NETGENPlugin_Hypothesis.hxx"
37
38 #include "Utils_SALOME_Exception.hxx"
39
40 #include <SMESH_Gen.hxx>
41 #include <SMESH_Mesh.hxx>
42 #include <SMESH_ParallelMesh.hxx>
43 #include <SMESH_MesherHelper.hxx>
44 #include <SMESH_DriverShape.hxx>
45 #include <SMESH_DriverMesh.hxx>
46 #include <SMESHDS_Mesh.hxx>
47 #include <SMESH_MeshLocker.hxx>
48
49 #include <QString>
50 #include <QProcess>
51
52 #ifdef WIN32
53 #include <filesystem>
54 namespace fs = std::filesystem;
55 #else
56 #include <boost/filesystem.hpp>
57 namespace fs = boost::filesystem;
58 #endif
59
60 /*
61   Netgen include files
62 */
63
64 #ifndef OCCGEOMETRY
65 #define OCCGEOMETRY
66 #endif
67 #include <occgeom.hpp>
68
69 #ifdef NETGEN_V5
70 #include <ngexception.hpp>
71 #endif
72 #ifdef NETGEN_V6
73 #include <core/exception.hpp>
74 #endif
75
76 namespace nglib {
77 #include <nglib.h>
78 }
79 namespace netgen {
80
81   NETGENPLUGIN_DLL_HEADER
82   extern MeshingParameters mparam;
83
84   NETGENPLUGIN_DLL_HEADER
85   extern volatile multithreadt multithread;
86 }
87 using namespace nglib;
88
89 //=============================================================================
90 /*!
91  * Constructor
92  */
93 //=============================================================================
94
95 NETGENPlugin_NETGEN_3D_Remote::NETGENPlugin_NETGEN_3D_Remote(int hypId, SMESH_Gen * gen)
96   : NETGENPlugin_NETGEN_3D(hypId, gen)
97 {
98   _name = "NETGEN_3D_Remote";
99 }
100
101 //=============================================================================
102 /*!
103  * Destructor
104  */
105 //=============================================================================
106
107 NETGENPlugin_NETGEN_3D_Remote::~NETGENPlugin_NETGEN_3D_Remote()
108 {
109 }
110
111 /**
112  * @brief Fill the structure netgen_param with the information from the hypothesis
113  *
114  * @param hyp the hypothesis
115  * @param aParams the netgen_param structure
116  */
117 void NETGENPlugin_NETGEN_3D_Remote::fillParameters(const NETGENPlugin_Hypothesis* hyp, netgen_params &aParams)
118 {
119   aParams.maxh               = hyp->GetMaxSize();
120   aParams.minh               = hyp->GetMinSize();
121   aParams.segmentsperedge    = hyp->GetNbSegPerEdge();
122   aParams.grading            = hyp->GetGrowthRate();
123   aParams.curvaturesafety    = hyp->GetNbSegPerRadius();
124   aParams.secondorder        = hyp->GetSecondOrder() ? 1 : 0;
125   aParams.quad               = hyp->GetQuadAllowed() ? 1 : 0;
126   aParams.optimize           = hyp->GetOptimize();
127   aParams.fineness           = hyp->GetFineness();
128   aParams.uselocalh          = hyp->GetSurfaceCurvature();
129   aParams.merge_solids       = hyp->GetFuseEdges();
130   aParams.chordalError       = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
131   aParams.optsteps2d         = aParams.optimize ? hyp->GetNbSurfOptSteps() : 0;
132   aParams.optsteps3d         = aParams.optimize ? hyp->GetNbVolOptSteps()  : 0;
133   aParams.elsizeweight       = hyp->GetElemSizeWeight();
134   aParams.opterrpow          = hyp->GetWorstElemMeasure();
135   aParams.delaunay           = hyp->GetUseDelauney();
136   aParams.checkoverlap       = hyp->GetCheckOverlapping();
137   aParams.checkchartboundary = hyp->GetCheckChartBoundary();
138 #ifdef NETGEN_V6
139   // std::string
140   aParams.meshsizefilename = hyp->GetMeshSizeFile();
141   aParams.closeedgefac = 2;
142   aParams.nbThreads = hyp->GetNbThreads();
143 #else
144   // const char*
145   aParams.meshsizefilename = hyp->GetMeshSizeFile();
146   aParams.closeedgefac = 0;
147   aParams.nbThreads = 0;
148 #endif
149 }
150
151 //
152
153 /**
154  * @brief write in a binary file the orientation for each surface element of the mesh
155  *
156  * @param aMesh The mesh
157  * @param aShape the shape associated to the mesh
158  * @param output_file name of the binary file
159  */
160 void NETGENPlugin_NETGEN_3D_Remote::exportElementOrientation(SMESH_Mesh& aMesh,
161                                                       const TopoDS_Shape& aShape,
162                                                       const std::string output_file)
163 {
164   SMESH_MesherHelper helper(aMesh);
165   NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
166   SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
167   std::map<vtkIdType, bool> elemOrientation;
168
169   for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
170   {
171     const TopoDS_Shape& aShapeFace = exFa.Current();
172     int faceID = aMesh.GetMeshDS()->ShapeToIndex( aShapeFace );
173     bool isInternalFace = internals.isInternalShape( faceID );
174     bool isRev = false;
175     if ( !isInternalFace &&
176           helper.NbAncestors(aShapeFace, aMesh, aShape.ShapeType()) > 1 )
177       // IsReversedSubMesh() can work wrong on strongly curved faces,
178       // so we use it as less as possible
179       isRev = helper.IsReversedSubMesh( TopoDS::Face( aShapeFace ));
180
181     const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
182     if ( !aSubMeshDSFace ) continue;
183
184     SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
185     if ( _quadraticMesh &&
186           dynamic_cast< const SMESH_ProxyMesh::SubMesh*>( aSubMeshDSFace ))
187     {
188       // add medium nodes of proxy triangles to helper (#16843)
189       while ( iteratorElem->more() )
190         helper.AddTLinks( static_cast< const SMDS_MeshFace* >( iteratorElem->next() ));
191
192       iteratorElem = aSubMeshDSFace->GetElements();
193     }
194     while ( iteratorElem->more() ) // loop on elements on a geom face
195     {
196       // check mesh face
197       const SMDS_MeshElement* elem = iteratorElem->next();
198       if ( !elem )
199         error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
200       if ( elem->NbCornerNodes() != 3 )
201         error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
202       elemOrientation[elem->GetID()] = isRev;
203     } // loop on elements on a face
204   } // loop on faces of a SOLID or SHELL
205
206   {
207     std::ofstream df(output_file, ios::out|ios::binary);
208     int size=elemOrientation.size();
209
210     df.write((char*)&size, sizeof(int));
211     for(auto const& [id, orient]:elemOrientation){
212       df.write((char*)&id, sizeof(vtkIdType));
213       df.write((char*)&orient, sizeof(bool));
214     }
215   }
216 }
217
218 /**
219  * @brief Compute mesh associate to shape
220  *
221  * @param aMesh The mesh
222  * @param aShape The shape
223  * @return true fi there are some error
224  */
225 bool NETGENPlugin_NETGEN_3D_Remote::Compute(SMESH_Mesh&         aMesh,
226                                            const TopoDS_Shape& aShape)
227 {
228   {
229     SMESH_MeshLocker myLocker(&aMesh);
230     SMESH_Hypothesis::Hypothesis_Status hypStatus;
231     NETGENPlugin_NETGEN_3D::CheckHypothesis(aMesh, aShape, hypStatus);
232   }
233   SMESH_ParallelMesh& aParMesh = dynamic_cast<SMESH_ParallelMesh&>(aMesh);
234
235   // Temporary folder for run
236 #ifdef WIN32
237   fs::path tmp_folder = aParMesh.GetTmpFolder() / fs::path("Volume-%%%%-%%%%");
238 #else
239   fs::path tmp_folder = aParMesh.GetTmpFolder() / fs::unique_path(fs::path("Volume-%%%%-%%%%"));
240 #endif
241   fs::create_directories(tmp_folder);
242   // Using MESH2D generated after all triangles where created.
243   fs::path mesh_file=aParMesh.GetTmpFolder() / fs::path("Mesh2D.med");
244   fs::path element_orientation_file=tmp_folder / fs::path("element_orientation.dat");
245   fs::path new_element_file=tmp_folder / fs::path("new_elements.dat");
246   fs::path tmp_mesh_file=tmp_folder / fs::path("tmp_mesh.med");
247   // Not used kept for debug
248   //fs::path output_mesh_file=tmp_folder / fs::path("output_mesh.med");
249   fs::path shape_file=tmp_folder / fs::path("shape.brep");
250   fs::path param_file=tmp_folder / fs::path("netgen3d_param.txt");
251   fs::path log_file=tmp_folder / fs::path("run.log");
252   fs::path cmd_file=tmp_folder / fs::path("cmd.txt");
253   // TODO: See if we can retreived name from aMesh ?
254   std::string mesh_name = "MESH";
255
256   {
257     SMESH_MeshLocker myLocker(&aMesh);
258     //Writing Shape
259     SMESH_DriverShape::exportShape(shape_file.string(), aShape);
260
261     //Writing hypo
262     netgen_params aParams;
263     fillParameters(_hypParameters, aParams);
264
265     exportNetgenParams(param_file.string(), aParams);
266
267     // Exporting element orientation
268     exportElementOrientation(aMesh, aShape, element_orientation_file.string());
269   }
270
271   // Calling run_mesher
272   // Path to mesher script
273   fs::path mesher_launcher = fs::path(std::getenv("SMESH_ROOT_DIR"))/
274        fs::path("bin")/
275        fs::path("salome")/
276        fs::path("mesher_launcher.py");
277
278
279   std::string s_program="python3";
280   std::list<std::string> params;
281   params.push_back(mesher_launcher.string());
282   params.push_back("NETGEN3D");
283   params.push_back(mesh_file.string());
284   params.push_back(shape_file.string());
285   params.push_back(param_file.string());
286   params.push_back("--elem-orient-file=" + element_orientation_file.string());
287   params.push_back("--new-element-file=" + new_element_file.string());
288
289   // Parallelism method parameters
290   int method = aParMesh.GetParallelismMethod();
291   if(method == ParallelismMethod::MultiThread){
292     params.push_back("--method=local");
293   } else if (method == ParallelismMethod::MultiNode){
294     // TODO :See what parameters to handle in the end
295     params.push_back("--method=cluster");
296     params.push_back("--resource="+aParMesh.GetResource());
297     params.push_back("--wc-key="+aParMesh.GetWcKey());
298     params.push_back("--nb-proc=1");
299     params.push_back("--nb-proc-per-node="+to_string(aParMesh.GetNbProcPerNode()));
300     params.push_back("--nb-node="+to_string(aParMesh.GetNbNode()));
301   } else {
302     throw SALOME_Exception("Unknown parallelism method "+method);
303   }
304   std::string cmd = "";
305   cmd += s_program;
306   for(auto arg: params){
307     cmd += " " + arg;
308   }
309   MESSAGE("Running command: ");
310   MESSAGE(cmd);
311   // Writing command in cmd.log
312   {
313     std::ofstream flog(cmd_file.string());
314     flog << cmd << endl;
315   }
316
317   // Building arguments for QProcess
318   QString program = QString::fromStdString(s_program);
319   QStringList arguments;
320   for(auto arg : params){
321     arguments << arg.c_str();
322   }
323
324   QString out_file = log_file.string().c_str();
325   QProcess myProcess;
326   myProcess.setProcessChannelMode(QProcess::MergedChannels);
327   myProcess.setStandardOutputFile(out_file);
328
329   myProcess.start(program, arguments);
330   // Waiting for process to finish (argument -1 make it wait until the end of
331   // the process otherwise it just waits 30 seconds)
332   bool finished = myProcess.waitForFinished(-1);
333   int ret = myProcess.exitCode();
334
335   if(ret != 0 || !finished){
336     // Run crahed
337     std::string msg = "Issue with mesh_launcher: \n";
338     msg += "See log for more details: " + log_file.string() + "\n";
339     msg += cmd + "\n";
340     throw SALOME_Exception(msg);
341   }
342
343   {
344     SMESH_MeshLocker myLocker(&aMesh);
345     std::ifstream df(new_element_file.string(), ios::binary);
346
347     int Netgen_NbOfNodes;
348     int Netgen_NbOfNodesNew;
349     int Netgen_NbOfTetra;
350     double Netgen_point[3];
351     int    Netgen_tetrahedron[4];
352     int nodeID;
353
354     SMESH_MesherHelper helper(aMesh);
355     // This function is mandatory for setElementsOnShape to work
356     helper.IsQuadraticSubMesh(aShape);
357     helper.SetElementsOnShape( true );
358
359     // Number of nodes in intial mesh
360     df.read((char*) &Netgen_NbOfNodes, sizeof(int));
361     // Number of nodes added by netgen
362     df.read((char*) &Netgen_NbOfNodesNew, sizeof(int));
363
364     // Filling nodevec (correspondence netgen numbering mesh numbering)
365     vector< const SMDS_MeshNode* > nodeVec ( Netgen_NbOfNodesNew + 1 );
366     //vector<int> nodeTmpVec ( Netgen_NbOfNodesNew + 1 );
367     SMESHDS_Mesh * meshDS = helper.GetMeshDS();
368     for (int nodeIndex = 1 ; nodeIndex <= Netgen_NbOfNodes; ++nodeIndex )
369     {
370       //Id of the point
371       df.read((char*) &nodeID, sizeof(int));
372       nodeVec.at(nodeIndex) = meshDS->FindNode(nodeID);
373     }
374
375     // Add new points and update nodeVec
376     for (int nodeIndex = Netgen_NbOfNodes +1 ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
377     {
378       df.read((char *) &Netgen_point, sizeof(double)*3);
379
380       nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0],
381                                  Netgen_point[1],
382                                  Netgen_point[2]);
383     }
384
385     // Add tetrahedrons
386     df.read((char*) &Netgen_NbOfTetra, sizeof(int));
387
388     for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
389     {
390       df.read((char*) &Netgen_tetrahedron, sizeof(int)*4);
391       helper.AddVolume(
392                     nodeVec.at( Netgen_tetrahedron[0] ),
393                     nodeVec.at( Netgen_tetrahedron[1] ),
394                     nodeVec.at( Netgen_tetrahedron[2] ),
395                     nodeVec.at( Netgen_tetrahedron[3] ));
396     }
397   }
398
399   return true;
400 }
401
402 /**
403  * @brief Assign submeshes to compute
404  *
405  * @param aSubMesh submesh to add
406  */
407 void NETGENPlugin_NETGEN_3D_Remote::setSubMeshesToCompute(SMESH_subMesh * aSubMesh)
408 {
409   SMESH_MeshLocker myLocker(aSubMesh->GetFather());
410   SMESH_Algo::setSubMeshesToCompute(aSubMesh);
411 }