Salome HOME
9d6d49cc284c3c5a0f4b06c7eaa08907db7a180d
[plugins/ghs3dprlplugin.git] / src / tepal2med / tetrahpc2med.cxx
1 // Copyright (C) 2007-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
20 // ---
21 // File   : tetrahpc2med.cxx
22 // Author : Christian VAN WAMBEKE (CEA) 
23 // ---
24 //
25 /*
26 ** prog principal de ghs3dprl
27 */
28
29 #include <stdio.h> /* printf clrscr fopen fread fwrite fclose */
30 #include <string>
31 #include <cstring>
32 #include <cstdlib>
33 #include <iostream>
34 #include <sstream>
35 #include <fstream>
36 #include <vector>
37 #ifndef WIN32
38 #include <unistd.h>
39 #endif
40
41 #include <qstring.h>
42
43 #include <QXmlSimpleReader>
44 #include <QXmlInputSource>
45 #include <QApplication>
46
47 #include "ghs3dprl_msg_parser.h"
48 #include "dlg_ghs3dmain.h"
49
50 #ifdef WIN32
51 #include <io.h>
52 #include <windows.h>
53 #define F_OK 0
54 #endif
55
56 //#include "MEDMEM_Exception.hxx"
57 //#include "MEDMEM_define.hxx"
58
59 #include <med.h>
60 //#include <med_config.h>
61 //#include <med_utils.h>
62 //#include <med_misc.h>
63
64 //************************************
65 med_idt ouvre_fichier_MED(char *fichier,int verbose)
66 {
67   med_idt fid = 0;
68   med_err ret = 0;
69   med_int majeur,mineur,release;
70
71   /* on regarde si le fichier existe */
72   ret = (int) access(fichier,F_OK);
73   if (ret < 0) return fid;
74
75   /* on regarde s'il s'agit d'un fichier au format HDF5 */
76   med_bool hdfok,medok;
77   ret = MEDfileCompatibility(fichier,&hdfok,&medok);
78   if (ret < 0){
79      std::cerr<<"File "<<fichier<<" not MED or HDF V5 formatted\n";
80      return fid;
81   }
82
83   /* Quelle version de MED est utilise par mdump ? */
84   MEDlibraryNumVersion(&majeur,&mineur,&release);
85   if (verbose>0)fprintf(stdout,"\nReading %s with MED V%d.%d.%d",
86                         fichier,majeur,mineur,release);
87
88   /* Ouverture du fichier MED en lecture seule */
89   fid = MEDfileOpen(fichier,MED_ACC_RDONLY);
90   if (ret < 0) return fid;
91
92   MEDfileNumVersionRd(fid, &majeur, &mineur, &release);
93   if (majeur < 2 || majeur == 2 && mineur < 2) {
94     fprintf(stderr,"File %s from MED V%d.%d.%d not assumed\n",
95                    fichier,majeur,mineur,release);
96     //" version est ant�ieure �la version 2.2";
97     ret = MEDfileClose(fid);
98     fid=0; }
99   else {
100     if (verbose>0)fprintf(stdout,", file from MED V%d.%d.%d\n",majeur,mineur,release); }
101
102   return fid;
103 }
104
105 //************************************
106 bool ReadFileMED(QString nomfilemed,ghs3dprl_mesh_wrap *mymailw)
107 {
108    med_err ret;
109    med_idt fid=0;
110    med_int i,j,sdim,mdim,nmaa,edim,majeur_lu,mineur_lu,release_lu,nprofils,nstep;
111    med_mesh_type type_maillage;
112    char dtunit[MED_SNAME_SIZE+1];
113    char axisname[MED_SNAME_SIZE+1];
114    char axisunit[MED_SNAME_SIZE*3+1];
115    med_sorting_type sortingtype;
116    med_axis_type axistype;
117    int numero=1;
118    QString key,tmp;
119    med_bool chan;
120    med_bool tran;
121    
122    //version qt3
123    char* chaine = (char*)malloc((nomfilemed.length()+1)*sizeof(char));
124    strncpy(chaine,nomfilemed.toLatin1().constData(),nomfilemed.length()+1);
125    //std::cout<<"*** ReadFileMED *** "<<chaine<<"\n";
126
127    fid=ouvre_fichier_MED(chaine,mymailw->verbose);
128    free(chaine);
129    if (fid == 0) {
130       std::cerr<<"Problem opening file "<<nomfilemed.toLatin1().constData()<<"\n";
131       return false;
132    }
133
134    nmaa = MEDnMesh(fid);
135    if (nmaa <= 0){
136       std::cerr<<"No meshes in "<<nomfilemed.toLatin1().constData()<<"\n";
137       ret = MEDfileClose(fid);
138       return false;
139    }
140    if (nmaa > 1) std::cout<<"More than one mesh in "<<nomfilemed.toLatin1().constData()<<", first one taken\n";
141    ret = MEDmeshInfo(fid,numero,mymailw->nommaa,&sdim,&mdim,&type_maillage,mymailw->maillage_description,
142                         dtunit,&sortingtype,&nstep,&axistype,axisname,axisunit);
143    if (ret < 0){
144       std::cerr<<"Problem MEDmeshInfo in "<<nomfilemed.toLatin1().constData()<<"\n";
145       ret = MEDfileClose(fid);
146       return false;
147    }
148    //changed with version med: a triangles mesh in 3d is dim 2 now and 3 before 2014
149    if (mdim != 2 && mdim != 3){
150       std::cerr<<"Problem mesh dimension should be 2 or 3: "<<mdim<<"\n";
151       ret = MEDfileClose(fid);
152       return false;
153    }
154    if (sdim != 3){
155       std::cerr<<"Problem space dimension should be 3: "<<sdim<<"\n";
156       ret = MEDfileClose(fid);
157       return false;
158    }
159    if (type_maillage != MED_UNSTRUCTURED_MESH){
160       std::cerr<<"Problem type mesh should be MED_NON_STRUCTURE: "<<type_maillage<<std::endl;
161       ret = MEDfileClose(fid);
162       return false;
163    }
164
165    //lecture nb de noeuds
166    //cf med-3.0.0_install/share/doc/html/maillage_utilisateur.html
167    med_int nnoe=MEDmeshnEntity(fid,mymailw->nommaa,MED_NO_DT,MED_NO_IT,
168       MED_NODE,MED_NO_GEOTYPE,MED_COORDINATE,MED_NO_CMODE,&chan,&tran);
169               //(med_geometrie_element)0,(med_connectivite)0);
170    if (nnoe<1){
171       std::cerr<<"Problem number of Vertices < 1\n";
172       ret = MEDfileClose(fid);
173       return false;
174    }
175
176    //nombre d'objets MED : mailles, faces, aretes , ... 
177    med_int nmailles[MED_N_CELL_GEO],nbtria3;
178    med_int nfaces[MED_N_FACE_GEO];
179    med_int naretes[MED_N_EDGE_FIXED_GEO],nbseg2;
180    //med_int nmailles[MED_NBR_GEOMETRIE_MAILLE],nbtria3;
181    //med_int nfaces[MED_NBR_GEOMETRIE_FACE];
182    //med_int naretes[MED_NBR_GEOMETRIE_ARETE],nbseg2;
183    //polygones et polyedres familles equivalences joints
184    med_int nmpolygones,npolyedres,nfpolygones,nfam,nequ,njnt;
185
186    //Combien de mailles, faces ou aretes pour chaque type geometrique ?
187    /*for (i=0;i<MED_NBR_GEOMETRIE_MAILLE;i++){
188       nmailles[i]=MEDnEntMaa(fid,mymailw->nommaa,MED_CONN,MED_MAILLE,typmai[i],typ_con);
189       //lecture_nombre_mailles_standards(fid,nommaa,typmai[i],typ_con,i);
190       if (mymailw->verbose>6) std::cout<<"NumberOf"<<nommai[i]<<"="<<nmailles[i]<<std::endl;
191    }*/
192    
193    nbtria3=MEDmeshnEntity(fid,mymailw->nommaa,MED_NO_DT,MED_NO_IT,
194       MED_CELL,MED_TRIA3,MED_CONNECTIVITY,MED_NODAL,&chan,&tran);
195    nbseg2=MEDmeshnEntity(fid,mymailw->nommaa,MED_NO_DT,MED_NO_IT,
196       MED_CELL,MED_SEG2,MED_CONNECTIVITY,MED_NODAL,&chan,&tran);
197
198    //combien de familles ?
199    nfam=MEDnFamily(fid,mymailw->nommaa);
200    if (mymailw->verbose>2) {
201       std::cout<<"\nNumberOfFamilies="<<nfam<<std::endl;
202       std::cout<<"NumberOfVertices="<<nnoe<<std::endl;
203       std::cout<<"NumberOfMED_SEG2="<<nbseg2<<std::endl;
204       std::cout<<"NumberOfMED_TRIA3="<<nbtria3<<"\n\n";
205    }
206    if (nbtria3<3){
207       std::cerr<<"Problem number of MED_TRIA3 < 3, not a skin of a volume\n";
208       ret = MEDfileClose(fid);
209       return false;
210    }
211
212 med_int ifamdelete=0,idelete;
213 std::vector<med_int> famdelete = std::vector<med_int>(nfam);
214 {
215   med_int ngro;
216   char *gro;
217   char nomfam[MED_NAME_SIZE+1];
218   med_int numfam;
219   char str1[MED_COMMENT_SIZE+1];
220   char str2[MED_LNAME_SIZE+1];
221   med_err ret = 0;
222   
223   for (i=0;i<nfam;i++) famdelete[i]=0;
224   for (i=0;i<nfam;i++) {
225
226     //nombre de groupes
227     ngro = MEDnFamilyGroup(fid,mymailw->nommaa,i+1);
228     if (ngro < 0){
229        std::cerr<<"Problem reading number of groups of family\n";
230        continue;
231     }
232
233     //atributs obsolete MED3
234     //allocation memoire par exces
235     gro = (char*) malloc(MED_LNAME_SIZE*(ngro+1));
236     
237     ret = MEDfamilyInfo(fid,mymailw->nommaa,i+1,nomfam,&numfam,gro);
238     if (ret < 0){
239        std::cerr<<"Problem reading informations of family\n";
240        continue;
241     }
242
243     if (mymailw->verbose>8) {
244      std::cout<<"Family "<<numfam<<" have "<<ngro<<" groups\n";
245      //affichage des resultats
246      for (j=0;j<ngro;j++) {
247       if (j==0) std::cout<<"  Groups :\n";
248       strncpy(str2,gro+j*MED_LNAME_SIZE,MED_LNAME_SIZE);
249       str2[MED_LNAME_SIZE] = '\0';
250       fprintf(stdout,"    name = %s\n",str2);
251      }
252      if (i==nfam-1) std::cout<<std::endl;
253     }
254     QString sfam,sgro;
255     sfam=sfam.sprintf("%d",numfam);
256     idelete=0;
257     for (j=0;j<ngro;j++){
258        strncpy(str2,gro+j*MED_LNAME_SIZE,MED_LNAME_SIZE);
259        str2[MED_LNAME_SIZE]='\0';
260        sgro=str2;
261        if (sgro.contains(mymailw->deletegroups)>0) {
262           //std::cout<<"idelete++ "<<sgro<<std::endl;
263           idelete++;
264        }
265     }
266
267     if (idelete==ngro && ngro>0) { //only delete family whith all delete groups
268        //std::cout<<"famdelete++ "<<numfam<<" "<<ifamdelete<<" "<<ngro<<std::endl;
269        famdelete[ifamdelete]=numfam;
270        ifamdelete++;
271     }
272
273     else {
274      for (j=0;j<ngro;j++){
275        strncpy(str2,gro+j*MED_LNAME_SIZE,MED_LNAME_SIZE);
276        str2[MED_LNAME_SIZE]='\0';
277        sgro=str2;
278        QRegExp qgroup=QRegExp("Group_Of_All",Qt::CaseSensitive,QRegExp::RegExp);
279        if (sgro.contains(mymailw->deletegroups)==0){
280           if (sgro.contains(qgroup)>0) {
281              sgro="Skin_"+sgro; //pas sur que ce soit pertinent
282           }
283           if (mymailw->verbose>8) std::cout<<"families.add("<<sfam.toLatin1().constData()<<
284                                         ","<<sgro.toLatin1().constData()<<")\n";
285           mymailw->families.add(sfam,sgro);
286        }
287        else {
288           //sgro="Skin_"+sgro; //pas sur que ce soit pertinent
289           //std::cout<<"--deletegroups matches \""<<sfam<<","<<sgro<<"\"\n";
290           if (mymailw->verbose>3) std::cout<<"--deletegroups matches \""<<
291                                         sgro.toLatin1().constData()<<
292                                         "\" in family "<<numfam<<std::endl;
293        }
294      }
295     }
296     
297     /*for (j=0;j<ngro;j++){
298        strncpy(str2,gro+j*MED_LNAME_SIZE,MED_LNAME_SIZE);
299        str2[MED_LNAME_SIZE]='\0';
300        sgro=str2;
301        //std::cout<<"families.add("<<sfam<<","<<sgro<<")\n";
302        if (sgro.contains(mymailw->deletegroups)==0){
303           //sgro="Skin_"+sgro; //pas sur que ce soit pertinent
304           std::cout<<"families.add("<<sfam<<","<<sgro<<")\n";
305           mymailw->families.add(sfam,sgro);
306        }
307        else {
308           std::cout<<"--deletegroups matches \""<<sgro<<"\"\n";
309           famdelete[ifamdelete]=numfam
310           ifamdelete++;
311        }
312     }*/
313
314     //on libere la memoire
315     free(gro);
316   }
317 }
318
319 //std::cout<<"famdelete"; for (j=0;j<ifamdelete;j++) std::cout<<" "<<famdelete[j]; std::cout<<std::endl;
320
321 if (mymailw->verbose>3){
322    std::cout<<"\nFamiliesAndGroupsOf "<<nomfilemed.toLatin1().constData()<<std::endl;
323    mymailw->families.write();
324 }
325    /* Allocations memoires */
326    /* table des coordonnees profil : (space dimension * nombre de noeuds ) */
327    med_float *coo=new med_float[nnoe*sdim];
328    /* table des numeros de familles des noeuds profil : (nombre de noeuds) */
329    med_int *famnodesskin=new med_int[nnoe];
330    //med_int *pfltab=new med_int[1]; //inutilise car on lit tout 
331    //lecture des noeuds : coordonnees
332    ret=MEDmeshNodeCoordinateRd(fid,mymailw->nommaa,MED_NO_DT,MED_NO_IT,MED_FULL_INTERLACE,coo);
333           //mdim,coo,mode_coo,MED_ALL,pfltab,0,&rep,mymailw->nomcoo,mymailw->unicoo);
334    if (ret < 0){
335       std::cerr<<"Problem reading nodes\n";
336       ret = MEDfileClose(fid);
337       //return false;
338    }
339    ret=MEDmeshEntityFamilyNumberRd(fid,mymailw->nommaa,MED_NO_DT,MED_NO_IT,MED_NODE,MED_NONE,famnodesskin);
340       //famnodesskin,nnoe,MED_NOEUD,(med_geometrie_element) 0);
341    if (ret < 0){
342       std::cerr<<"Problem reading families of nodes\n";
343       ret = MEDfileClose(fid);
344       return false;
345    }
346    if (mymailw->verbose>9) {
347      std::cout<<"\nVertices: no x y z family\n";
348      for (i=0;i<nnoe*mdim;i=i+3) {
349       fprintf(stdout,"%5d %13.5e %13.5e %13.5e %5d \n",
350           (i/3+1), coo[i], coo[i+1], coo[i+2], famnodesskin[i/3]);
351      } 
352      std::cout<<std::endl;
353    }
354
355    med_int *conn2=new med_int[nbseg2*2];
356    ret=MEDmeshElementConnectivityRd(fid,mymailw->nommaa,MED_NO_DT,MED_NO_IT,
357            MED_CELL,MED_SEG2,MED_NODAL,MED_FULL_INTERLACE,conn2);
358             //mdim,conn2,mode_coo,pfltab,0,MED_MAILLE,MED_SEG2,MED_NOD);
359    if (ret < 0){
360       std::cerr<<"Problem reading MED_SEG2\n";
361       ret = MEDfileClose(fid);
362       //return false;
363    }
364    med_int *famseg2skin=new med_int[nbseg2];
365    ret=MEDmeshEntityFamilyNumberRd(fid,mymailw->nommaa,MED_NO_DT,MED_NO_IT,MED_CELL,MED_SEG2,famseg2skin);
366       //MEDfamLire(fid,mymailw->nommaa,famseg2skin,nbseg2,MED_MAILLE,MED_SEG2);
367    if (ret < 0){
368       std::cerr<<"Problem reading families of MED_SEG2\n";
369       ret = MEDfileClose(fid);
370       return false;
371    }
372    if (mymailw->verbose>9) {
373      std::cout<<"\nConnectivity MED_SEG2: no node1 node2 family\n";
374      for (i=0;i<nbseg2*2;i=i+2) {
375       fprintf(stdout,"%5d %5d %5d %5d \n",
376           (i/2+1), conn2[i], conn2[i+1], famseg2skin[i/2]);
377      } 
378      std::cout<<std::endl;
379    }
380    //std::cout<<"\ncvw1 conn nbtria3 "<<nbtria3<<"dt "<<MED_NO_DT<<"it "<<MED_NO_IT<<"cell "<<MED_CELL<<"tria3 "<<MED_TRIA3<<std::endl;
381    med_int *conn3=new med_int[nbtria3*3];
382    ret=MEDmeshElementConnectivityRd(fid,mymailw->nommaa,MED_NO_DT,MED_NO_IT,
383            MED_CELL,MED_TRIA3,MED_NODAL,MED_FULL_INTERLACE,conn3);
384            //MEDconnLire(fid,mymailw->nommaa,mdim,conn3,mode_coo,pfltab,0,MED_MAILLE,MED_TRIA3,MED_NOD);
385    if (ret < 0){
386       std::cerr<<"Problem reading MED_TRIA3\n";
387       ret = MEDfileClose(fid);
388       //return false;
389    }
390    med_int *famtria3skin=new med_int[nbtria3];
391    ret=MEDmeshEntityFamilyNumberRd(fid,mymailw->nommaa,MED_NO_DT,MED_NO_IT,MED_CELL,MED_TRIA3,famtria3skin);
392         //MEDfamLire(fid,mymailw->nommaa,famtria3skin,nbtria3,MED_MAILLE,MED_TRIA3);
393    if (ret < 0){
394       std::cerr<<"Problem reading families of MED_TRIA3\n";
395       ret = MEDfileClose(fid);
396       return false;
397    }
398    if (mymailw->verbose>9) {
399      std::cout<<"\nConnectivity MED_TRIA3: no node1 node2 node3 family\n";
400      for (i=0;i<nbtria3*3;i=i+3) {
401       fprintf(stdout,"%5d %5d %5d %5d %5d \n",
402           (i/3+1), conn3[i], conn3[i+1], conn3[i+2], famtria3skin[i/3]);
403      } 
404      std::cout<<std::endl;
405    }
406
407   /*liberation memoire?
408   delete[] coo;
409   delete[] nomnoe;
410   delete[] numnoe;
411   delete[] nufano;*/
412
413   if (ifamdelete>0) {
414    //std::cout<<"!!!!!!!!nodes "<<famnodesskin[0]<<" "<<nnoe<<famdelete[1]<<std::endl;
415    for (i=0;i<nnoe;i++) {
416     for (j=0;j<ifamdelete;j++) {
417       if (famnodesskin[i]==famdelete[j]) {
418        //std::cout<<"nodes "<<famnodesskin[i]<<" "<<i<<" "<<famdelete[j]<<std::endl;
419        famnodesskin[i]=0; }
420     }
421    }
422    for (i=0;i<nbseg2;i++) {
423     for (j=0;j<ifamdelete;j++) {
424       if (famseg2skin[i]==famdelete[j]) famseg2skin[i]=0;
425     }
426    }
427    for (i=0;i<nbtria3;i++) {
428     for (j=0;j<ifamdelete;j++) {
429       if (famtria3skin[i]==famdelete[j]) famtria3skin[i]=0;
430     }
431    }
432   }
433    //stocks data for future use 
434    CVWtab *montab;
435    bool ok;
436
437    montab=new CVWtab(nnoe*mdim,coo);
438    tmp="SKIN_VERTICES_COORDINATES";
439    ok=mymailw->insert_key(tmp,montab);
440
441    montab=new CVWtab(nnoe,famnodesskin);
442    tmp="SKIN_VERTICES_FAMILIES";
443    ok=mymailw->insert_key(tmp,montab);
444    
445    montab=new CVWtab(nbseg2*2,conn2);
446    tmp="SKIN_SEG2_CONNECTIVITIES";
447    ok=mymailw->insert_key(tmp,montab);
448
449    montab=new CVWtab(nbtria3,famseg2skin);
450    tmp="SKIN_SEG2_FAMILIES";
451    ok=mymailw->insert_key(tmp,montab);
452
453    montab=new CVWtab(nbtria3*3,conn3);
454    tmp="SKIN_TRIA3_CONNECTIVITIES";
455    ok=mymailw->insert_key(tmp,montab);
456
457    montab=new CVWtab(nbtria3,famtria3skin);
458    tmp="SKIN_TRIA3_FAMILIES";
459    ok=mymailw->insert_key(tmp,montab);
460
461    //if (mymailw->verbose>6) ok=mymailw->list_keys_mesh_wrap();
462
463    ret = MEDfileClose(fid);
464    if (ret < 0){
465       std::cerr<<"Problem closing "<<nomfilemed.toLatin1().constData()<<"\n";
466       return false;
467    }
468    return true;
469 }
470
471
472 //************************************
473 int main(int argc, char *argv[])
474 {
475    bool ok;
476    int i,nb,nbfiles,limit_swap,nbelem_limit_swap,limit_swap_defaut,verbose;
477    QString path,pathini,casename,casenamemed,fileskinmed,
478            tmp,cmd,format,format_tetra,
479            test,menu,launchtetra,background,deletegroups,
480            ToMergeSubdomains,ToTagSubdomains,ToOutputInterfaces,ToDiscardSubdomains,
481            version="V3.0 (MED3+tetra-hpc)";
482    
483    char *chelp=NULL,
484         *ccasename=NULL,
485         *cnumber=NULL,
486         *cmedname=NULL,
487         *climitswap=NULL,
488         *cverbose=NULL,
489         *ctest=NULL,
490         *cmenu=NULL,
491         *claunchtetra=NULL,
492         *cToMergeSubdomains=NULL,
493         *cToTagSubdomains=NULL,
494         *cToOutputInterfaces=NULL,
495         *cToDiscardSubdomains=NULL,
496         *cbackground=NULL,
497         *cdeletegroups=NULL;
498
499    for (i = 0; i < argc; i++){
500       if (!strncmp (argv[i], "--help", sizeof ("--help"))) chelp = &(argv[i][0]);
501       else if (!strncmp (argv[i], "--casename=", sizeof ("--casename"))) ccasename = &(argv[i][sizeof ("--casename")]);
502       else if (!strncmp (argv[i], "--number=", sizeof ("--number"))) cnumber = &(argv[i][sizeof ("--number")]);
503       else if (!strncmp (argv[i], "--medname=", sizeof ("--medname"))) cmedname = &(argv[i][sizeof ("--medname")]);
504       else if (!strncmp (argv[i], "--limitswap=", sizeof ("--limitswap"))) climitswap = &(argv[i][sizeof ("--limitswap")]);
505       else if (!strncmp (argv[i], "--verbose=", sizeof ("--verbose"))) cverbose = &(argv[i][sizeof ("--verbose")]);
506       else if (!strncmp (argv[i], "--test=", sizeof ("--test"))) ctest = &(argv[i][sizeof ("--test")]);
507       else if (!strncmp (argv[i], "--menu=", sizeof ("--menu"))) cmenu = &(argv[i][sizeof ("--menu")]);
508       else if (!strncmp (argv[i], "--launchtetra=", sizeof ("--launchtetra"))) claunchtetra = &(argv[i][sizeof ("--launchtetra")]);
509       else if (!strncmp (argv[i], "--merge_subdomains=", sizeof ("--merge_subdomains"))) cToMergeSubdomains = &(argv[i][sizeof ("--")]);
510       else if (!strncmp (argv[i], "--tag_subdomains=", sizeof ("--tag_subdomains"))) cToTagSubdomains = &(argv[i][sizeof ("--")]);
511       else if (!strncmp (argv[i], "--output_interfaces=", sizeof ("--output_interfaces"))) cToOutputInterfaces = &(argv[i][sizeof ("--")]);
512       else if (!strncmp (argv[i], "--discard_subdomains=", sizeof ("--discard_subdomains"))) cToDiscardSubdomains = &(argv[i][sizeof ("--")]);
513       else if (!strncmp (argv[i], "--background=", sizeof ("--background"))) cbackground = &(argv[i][sizeof ("--background")]);
514       else if (!strncmp (argv[i], "--deletegroups=", sizeof ("--deletegroups"))) cdeletegroups = &(argv[i][sizeof ("--deletegroups")]);
515       }
516
517    if (argc < 2 || chelp){
518       std::cout<<"tetrahpc2med "<<version.toLatin1().constData()<<" Available options:\n"
519       "   --help               : produces this help message\n"<<
520       "   --casename           : path and name of input tetrahpc2med files which are\n"<<
521       "                           - output files of GHS3DPRL_Plugin .mesh\n"<<
522       "                           - output file of GHS3DPRL_Plugin casename_skin.med (optional)\n"<<
523       "                          with initial skin and its initial groups\n"<<
524       "   --number             : number of partitions\n"<<
525       "   --medname            : path and name of output MED files\n"<<
526       "   --limitswap          : max size of working cpu memory (Mo) (before swapping on .temp files)\n"<<
527       "   --verbose            : trace of execution (0->6)\n"<<
528       "   --test               : more tests about joints, before generation of output files\n"<<
529       "   --menu               : a GUI menu for option number\n"<<
530       "   --launchtetra        : also launch tetra-hpc on files casename.mesh and option number\n"<<
531       "   --merge_subdomains   : merge the subdomains into one mesh and write the output .mesh(b) file\n"<<
532       "   --tag_subdomains     : use the parallel subdomain index as tag into the merged output mesh\n"<<
533       "                            to identify the parallel subdomains (used in combination with the merge_subdomains option)\n"<<
534       "   --output_interfaces  : write the parallel subdomains interface triangles into the merged output mesh\n"<<
535       "                            (used in combination with the merge_subdomains option)\n"<<
536       "   --discard_subdomains : discard the parallel subdomains informations output (mesh, global numbering and interfaces)\n"<<
537       "   --background         : force background mode from launch tetra-hpc and generation of final MED files (big meshes)\n"<<
538       "   --deletegroups       : regular expression (see QRegExp) which matches unwanted groups in final MED files\n"<<
539       "                            (try --deletegroups=\"(\\bJOINT)\"\n"<<
540       "                            (try --deletegroups=\"(\\bAll_Nodes|\\bAll_Faces)\"\n"<<
541       "                            (try --deletegroups=\"((\\bAll_|\\bNew_)(N|F|T))\"\n";
542       std::cout<<"example:\n   tetrahpcl2med --casename=/tmp/GHS3DPRL --number=2 --medname=DOMAIN "<<
543                  "--limitswap=1000 --verbose=0 --test=yes --menu=no --launchtetra=no\n\n";
544       return 1;  //no output files
545    }
546    
547    if (!ccasename){
548       std::cerr<<"--casename: a path/name is expected\n\n";
549       return 1;
550    }
551    casename=ccasename;
552    if (!cnumber){
553       std::cerr<<"--number: an integer is expected\n\n";
554       return 1;
555    }
556    tmp=cnumber;
557    nbfiles=tmp.toLong(&ok,10);
558    if (!ok){
559       std::cerr<<"--number: an integer is expected\n\n";
560       return 1;
561    }
562    if (nbfiles<=0){
563       std::cerr<<"--number: a positive integer is expected\n\n";
564       return 1;
565    }
566    if (nbfiles>2048){ //delirium in 2014
567       std::cerr<<"--number: a positive integer <= 2048 is expected\n\n";
568       return 1;
569    }
570    if (!cmedname) cmedname=ccasename;
571    casenamemed=cmedname;
572    limit_swap_defaut=1000; //1000Mo
573    limit_swap=limit_swap_defaut;
574    if (climitswap){
575       tmp=climitswap;
576       limit_swap=tmp.toLong(&ok,10);
577       if (!ok){
578          std::cerr<<"--limitswap: an integer is expected. try 1000\n\n";
579          return 1;
580       }
581       if (limit_swap<1 || limit_swap>32000){
582          std::cerr<<"--limitswap: [1->32000] expected. try 1000\n\n";
583          return 1;
584       }
585    }
586    //default 1GOctet/8(for float)
587    nbelem_limit_swap=limit_swap*1000000; //100%
588    CVWtab::memorymax=nbelem_limit_swap;
589
590    verbose=1; //default
591    if (cverbose){
592       tmp=cverbose;
593       verbose=tmp.toLong(&ok,10);
594       if (!ok){
595          std::cerr<<"--verbose: an integer is expected\n\n";
596          return 1;
597       }
598       if (verbose<0){
599          std::cerr<<"--verbose: a positive integer is expected\n\n";
600          return 1;
601       }
602    }
603
604    test="no"; //default
605    if (ctest){
606       tmp=ctest;
607       if (tmp=="yes") test="yes";
608    }
609
610    menu="no"; //default
611    if (cmenu){
612       tmp=cmenu;
613       if (tmp=="yes") menu="yes";
614    }
615
616    launchtetra="no"; //default
617    if (claunchtetra){
618       tmp=claunchtetra;
619       if (tmp=="yes") launchtetra="yes";
620    }
621
622    ToMergeSubdomains="no"; //default
623    if (cToMergeSubdomains){
624       tmp=cToMergeSubdomains;
625       if (tmp=="yes") ToMergeSubdomains="yes";
626    }
627
628    ToTagSubdomains="no"; //default
629    if (cToTagSubdomains){
630       tmp=cToTagSubdomains;
631       if (tmp=="yes") ToTagSubdomains="yes";
632    }
633
634    ToOutputInterfaces="no"; //default
635    if (cToOutputInterfaces){
636       tmp=cToOutputInterfaces;
637       if (tmp=="yes") ToOutputInterfaces="yes";
638    }
639
640    ToDiscardSubdomains="no"; //default
641    if (cToDiscardSubdomains){
642       tmp=cToDiscardSubdomains;
643       if (tmp=="yes") ToDiscardSubdomains="yes";
644    }
645
646    background="no"; //default
647    if (cbackground){
648       tmp=cbackground;
649       if (tmp=="yes") background="yes";
650    }
651
652
653    // We must always have an application
654    if (menu=="yes") {
655     QApplication a(argc,argv);
656     dlg_ghs3dmain *m = new dlg_ghs3dmain();
657     m->setWindowTitle("tetrahpc2med 3.0");
658     m->show();
659     a.exec();
660     if ( m->result() == QDialog::Accepted ) {
661       std::cout<<"parameters "<<m->KeepFiles()<<" "<<m->NbPart()<<std::endl;
662       nbfiles=m->NbPart();
663     }
664     else {
665       return 1;
666     }
667     delete m;
668    }
669
670    int n=casenamemed.count('/');
671    if (n>0)
672       path=casenamemed.section('/',-n-1,-2)+"/";
673    else
674       path="./";
675       casenamemed=casenamemed.section('/',-1);
676    if (casenamemed.length()>20){
677       std::cerr<<"--medname truncated (no more 20 characters)"<<std::endl;
678       casenamemed.truncate(20);
679    }
680
681    n=casename.count('/');
682    if (n>0)
683       pathini=casename.section('/',-n-1,-2)+"/";
684    else
685       pathini="./";
686       casename=casename.section('/',-1);
687    if (casename.length()>20){
688       std::cerr<<"--casename truncated (no more 20 characters)"<<std::endl;
689       casename.truncate(20);
690    }
691
692    /*std::cout<<"CaseNameMed="<<casenamemed<<std::endl;
693    std::cout<<"PathMed="<<path<<std::endl;*/
694
695    deletegroups="(\\bxyz)"; //default improbable name
696    if (cdeletegroups){
697       deletegroups=cdeletegroups;
698    }
699    
700    //verbose=5;
701    if (verbose>0)
702    std::cout<<"tetrahpc2med "<<version.toLatin1().constData()<<" parameters:"<<
703          "\n   --casename="<<pathini.toLatin1().constData()<<casename.toLatin1().constData()<<
704          "\n   --number="<<nbfiles<<
705          "\n   --medname="<<path.toLatin1().constData()<<casenamemed.toLatin1().constData()<<
706          "\n   --limitswap="<<limit_swap<<
707          "\n   --verbose="<<verbose<<
708          "\n   --test="<<test.toLatin1().constData()<<
709          "\n   --menu="<<menu.toLatin1().constData()<<
710          "\n   --launchtetra="<<launchtetra.toLatin1().constData()<<
711          "\n   --merge_subdomains="<<ToMergeSubdomains.toLatin1().constData()<<
712          "\n   --tag_subdomains="<<ToTagSubdomains.toLatin1().constData()<<
713          "\n   --output_interfaces="<<ToOutputInterfaces.toLatin1().constData()<<
714          "\n   --discard_subdomains="<<ToDiscardSubdomains.toLatin1().constData()<<
715          "\n   --background="<<background.toLatin1().constData()<<
716          "\n   --deletegroups=\""<<deletegroups.toLatin1().constData()<<"\"\n";
717    
718    //utile si appel par plugin ghs3dprl sur big meshes et tetrahpc sur plusieurs jours
719 #ifndef WIN32
720    if (background=="yes"){
721       pid_t pid = fork();
722       if (pid > 0) {
723          //Process father
724          exit(0); //temporary ok for plugin
725       }
726       //process children
727       //On rend le fils independant de tout terminal
728       //from here everything in background: tetrahpc AND generation of final MED files
729       setsid();
730       system("sleep 10");  //for debug
731    }
732 #else
733    printf("background mode is not supported on win32 platform !\n");
734 #endif
735
736    //"tetrahpc -f exemple1 -n 4"
737    if (launchtetra=="yes"){
738       //tetra_hpc.exe --help
739       //mpirun -n 3 mg-tetra_hpc.exe --in GHS3DPRL.mesh --out TOTO.mesh
740       
741       //direct mpirun cause problem: invalid
742       //cmd="mpirun -n "+cmd.sprintf("%d",nbfiles)+" mg-tetra_hpc.exe --in "+
743       
744       //call tetra_hpc.bash is script which assumes mpirun after compilation openmpi etc...
745       cmd="mg-tetra_hpc.bash -n "+cmd.sprintf("%d",nbfiles)+" --in "+
746           pathini+casename+".mesh --out "+
747           pathini+casename+".mesh"+
748           " --merge_subdomains "+ToMergeSubdomains+
749           " --tag_subdomains "+ToTagSubdomains+
750           " --output_interfaces "+ToOutputInterfaces+
751           " --discard_subdomains "+ToDiscardSubdomains+
752           " > "+path+"tetrahpc.log";
753       std::cout<<"\nlaunchtetra command: background="<<cbackground<<
754                  "\n      "<<cmd.toLatin1().constData()<<std::endl;
755       system(cmd.toLatin1().constData()); // run
756       //sometimes it is better to wait flushing files on slow filesystem...
757       system("sleep 3");
758    }
759    ghs3dprl_mesh_wrap *mymailw=new ghs3dprl_mesh_wrap;
760    //no constructor, later maybe
761    mymailw->nbfiles=0;
762    mymailw->nbfilestot=nbfiles;
763    //for huge cases big array swap in huge binary files
764    mymailw->nbelem_limit_swap=nbelem_limit_swap;
765    mymailw->verbose=verbose;
766    mymailw->casename=casename;
767    mymailw->medname=casenamemed;
768    mymailw->path=path;
769    mymailw->pathini=pathini;
770    mymailw->deletegroups=QRegExp(deletegroups,Qt::CaseSensitive,QRegExp::RegExp);
771    ghs3dprl_msg_parser handler;
772    //constructor later maybe
773    //handler.verbose=true;
774    handler.mailw=mymailw;
775    mymailw->families.no=1;
776    //std::cout<<"coucou1 "<<mymailw->families.no<<std::endl;
777    //mymailw->families.add(casename,casenamemed);
778    format=format.sprintf("%d",nbfiles);
779    int nbf=format.length();
780    format=format.sprintf(".%%0%dd.%%0%dd",nbf,nbf);
781    format_tetra=".%05d";
782    if (verbose>10)std::cout<<"format "<<format.toLatin1().constData()<<std::endl;
783    if (verbose>10)std::cout<<"format_tetra "<<format_tetra.toLatin1().constData()<<std::endl;
784    mymailw->format=format;
785    mymailw->format_tetra=format_tetra;
786    mymailw->for_tetrahpc=true; //to know what files to read: .noboite or .mesh
787    
788    //something like "/home/wambeke/tmp/GHS3DPRL_skin.med"
789    fileskinmed=pathini+casename+"_skin.med";
790    //fileskinmed="/home/wambeke/tmp/GHS3DPRL_skin.med";
791    /*for debug
792    {
793    char ctmp[fileskinmed.length()+1] ; strcpy(ctmp,fileskinmed);
794    int res=dumpMED(&ctmp[0],1);
795    }*/
796    int ret = access(fileskinmed.toLatin1().constData(),F_OK); //on regarde si le fichier existe
797    if (ret >= 0) {
798       ok=ReadFileMED(fileskinmed,mymailw); }
799    else {
800       if (verbose>0)std::cout<<"Initial skin file <"<<fileskinmed.toLatin1().constData()<<"> does not exist\n"; }
801    
802
803 //if test quickly read all files before (or only small files)
804  if (test=="yes"){
805    if (verbose>0) std::cout<<"\nReading output files of tetrahpc as input files of tetrahpc2med...\n";
806    //only read beginning of files .xxxxx.mesh
807    //supposed big files big arrays so only see first lines
808    mymailw->nbfiles=0;
809    for (int i=1; i<=nbfiles; i++){
810       mymailw->nofile=i;
811       tmp=pathini+casename+tmp.sprintf(format_tetra.toLatin1().constData(),i)+".mesh";
812       if (verbose>0) std::cout<<"FileName="<<tmp.toLatin1().constData()<<std::endl;
813       ok=mymailw->TestExistingFileMESHnew(tmp);
814    }
815    if (verbose>0)
816       std::cout<<"NumberOfFilesMESHTested="<<mymailw->nbfiles<<": ok\n\n";
817    if (mymailw->nbfiles != nbfiles){
818       std::cerr<<"NumberOfFiles != NumberOfFilesTested is unexpected\n\n";
819       return 1;
820    }
821  }  //end if test
822  
823    ok=mymailw->Write_MEDfiles_v2(true); //deletekeys=true
824    
825    nb=mymailw->remove_all_keys_mesh_wrap();
826    if (verbose>3)std::cout<<"***remove_all_key_mesh_wrap*** "<<nb<<" keys removed\n";
827    if (verbose>0)std::cout<<std::endl<<"===end of "<<argv[0]<<"==="<<std::endl;
828
829    //for debug
830    //int res=dumpMED("/home/wambeke/tmp/DOMAIN_1.med",1);
831
832    return 0; //ok
833 }